repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
quantopian/empyrical | empyrical/stats.py | up_capture | def up_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is positive
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_re... | python | def up_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is positive
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_re... | [
"def",
"up_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"up",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"capture",
",",
"*",
"*",
"kwargs",
")"
] | Compute the capture ratio for periods when the benchmark return is positive
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
No... | [
"Compute",
"the",
"capture",
"ratio",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"positive"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1549-L1580 | train |
quantopian/empyrical | empyrical/stats.py | down_capture | def down_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_... | python | def down_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_... | [
"def",
"down_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"capture",
",",
"*",
"*",
"kwargs",
")"
] | Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
No... | [
"Compute",
"the",
"capture",
"ratio",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"negative"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1583-L1614 | train |
quantopian/empyrical | empyrical/stats.py | up_down_capture | def up_down_capture(returns, factor_returns, **kwargs):
"""
Computes the ratio of up_capture to down_capture.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_re... | python | def up_down_capture(returns, factor_returns, **kwargs):
"""
Computes the ratio of up_capture to down_capture.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_re... | [
"def",
"up_down_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"(",
"up_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
"/",
"down_capture",
"(",
"returns",
",",
"factor_returns",
... | Computes the ratio of up_capture to down_capture.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the... | [
"Computes",
"the",
"ratio",
"of",
"up_capture",
"to",
"down_capture",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1617-L1645 | train |
quantopian/empyrical | empyrical/stats.py | up_alpha_beta | def up_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is positive.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
float
Alpha.
float
Beta.
"""
return up(returns, fac... | python | def up_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is positive.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
float
Alpha.
float
Beta.
"""
return up(returns, fac... | [
"def",
"up_alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"up",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"alpha_beta_aligned",
",",
"*",
"*",
"kwargs",
")"
] | Computes alpha and beta for periods when the benchmark return is positive.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
float
Alpha.
float
Beta. | [
"Computes",
"alpha",
"and",
"beta",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"positive",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1648-L1663 | train |
quantopian/empyrical | empyrical/stats.py | down_alpha_beta | def down_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is negative.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
alpha : float
beta : float
"""
return down(returns, factor_return... | python | def down_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is negative.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
alpha : float
beta : float
"""
return down(returns, factor_return... | [
"def",
"down_alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"alpha_beta_aligned",
",",
"*",
"*",
"kwargs",
")"
] | Computes alpha and beta for periods when the benchmark return is negative.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
alpha : float
beta : float | [
"Computes",
"alpha",
"and",
"beta",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"negative",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1666-L1679 | train |
quantopian/empyrical | empyrical/utils.py | roll | def roll(*args, **kwargs):
"""
Calculates a given statistic across a rolling time period.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optiona... | python | def roll(*args, **kwargs):
"""
Calculates a given statistic across a rolling time period.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optiona... | [
"def",
"roll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
".",
"pop",
"(",
"'function'",
")",
"window",
"=",
"kwargs",
".",
"pop",
"(",
"'window'",
")",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"raise",
"Va... | Calculates a given statistic across a rolling time period.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark re... | [
"Calculates",
"a",
"given",
"statistic",
"across",
"a",
"rolling",
"time",
"period",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L78-L118 | train |
quantopian/empyrical | empyrical/utils.py | up | def up(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only positive factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_retu... | python | def up(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only positive factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_retu... | [
"def",
"up",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
".",
"pop",
"(",
"'function'",
")",
"returns",
"=",
"returns",
"[",
"factor_returns",
">",
"0",
"]",
"factor_returns",
"=",
"factor_returns",
"[... | Calculates a given statistic filtering only positive factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
... | [
"Calculates",
"a",
"given",
"statistic",
"filtering",
"only",
"positive",
"factor",
"return",
"periods",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L121-L144 | train |
quantopian/empyrical | empyrical/utils.py | down | def down(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only negative factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_re... | python | def down(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only negative factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_re... | [
"def",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
".",
"pop",
"(",
"'function'",
")",
"returns",
"=",
"returns",
"[",
"factor_returns",
"<",
"0",
"]",
"factor_returns",
"=",
"factor_returns",
... | Calculates a given statistic filtering only negative factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
... | [
"Calculates",
"a",
"given",
"statistic",
"filtering",
"only",
"negative",
"factor",
"return",
"periods",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L147-L170 | train |
quantopian/empyrical | empyrical/utils.py | get_treasury_yield | def get_treasury_yield(start=None, end=None, period='3MO'):
"""
Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
... | python | def get_treasury_yield(start=None, end=None, period='3MO'):
"""
Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
... | [
"def",
"get_treasury_yield",
"(",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"period",
"=",
"'3MO'",
")",
":",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"'1/1/1970'",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"_1_bday_ago",
"(",
")",... | Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
period : {'1MO', '3MO', '6MO', 1'... | [
"Load",
"treasury",
"yields",
"from",
"FRED",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L379-L409 | train |
quantopian/empyrical | empyrical/utils.py | default_returns_func | def default_returns_func(symbol, start=None, end=None):
"""
Gets returns for a symbol.
Queries Yahoo Finance. Attempts to cache SPY.
Parameters
----------
symbol : str
Ticker symbol, e.g. APPL.
start : date, optional
Earliest date to fetch data for.
Defaults to earli... | python | def default_returns_func(symbol, start=None, end=None):
"""
Gets returns for a symbol.
Queries Yahoo Finance. Attempts to cache SPY.
Parameters
----------
symbol : str
Ticker symbol, e.g. APPL.
start : date, optional
Earliest date to fetch data for.
Defaults to earli... | [
"def",
"default_returns_func",
"(",
"symbol",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"'1/1/1970'",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"_1_bday_ago",
"(",
")",
"start",
"=... | Gets returns for a symbol.
Queries Yahoo Finance. Attempts to cache SPY.
Parameters
----------
symbol : str
Ticker symbol, e.g. APPL.
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to ... | [
"Gets",
"returns",
"for",
"a",
"symbol",
".",
"Queries",
"Yahoo",
"Finance",
".",
"Attempts",
"to",
"cache",
"SPY",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L452-L495 | train |
quantopian/empyrical | empyrical/perf_attrib.py | perf_attrib | def perf_attrib(returns,
positions,
factor_returns,
factor_loadings):
"""
Attributes the performance of a returns stream to a set of risk factors.
Performance attribution determines how much each risk factor, e.g.,
momentum, the technology sector, etc., c... | python | def perf_attrib(returns,
positions,
factor_returns,
factor_loadings):
"""
Attributes the performance of a returns stream to a set of risk factors.
Performance attribution determines how much each risk factor, e.g.,
momentum, the technology sector, etc., c... | [
"def",
"perf_attrib",
"(",
"returns",
",",
"positions",
",",
"factor_returns",
",",
"factor_loadings",
")",
":",
"risk_exposures_portfolio",
"=",
"compute_exposures",
"(",
"positions",
",",
"factor_loadings",
")",
"perf_attrib_by_factor",
"=",
"risk_exposures_portfolio",
... | Attributes the performance of a returns stream to a set of risk factors.
Performance attribution determines how much each risk factor, e.g.,
momentum, the technology sector, etc., contributed to total returns, as
well as the daily exposure to each of the risk factors. The returns that
can be attributed... | [
"Attributes",
"the",
"performance",
"of",
"a",
"returns",
"stream",
"to",
"a",
"set",
"of",
"risk",
"factors",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/perf_attrib.py#L4-L97 | train |
quantopian/empyrical | empyrical/perf_attrib.py | compute_exposures | def compute_exposures(positions, factor_loadings):
"""
Compute daily risk factor exposures.
Parameters
----------
positions: pd.Series
A series of holdings as percentages indexed by date and ticker.
- Examples:
dt ticker
2017-01-01 AAPL 0.41758... | python | def compute_exposures(positions, factor_loadings):
"""
Compute daily risk factor exposures.
Parameters
----------
positions: pd.Series
A series of holdings as percentages indexed by date and ticker.
- Examples:
dt ticker
2017-01-01 AAPL 0.41758... | [
"def",
"compute_exposures",
"(",
"positions",
",",
"factor_loadings",
")",
":",
"risk_exposures",
"=",
"factor_loadings",
".",
"multiply",
"(",
"positions",
",",
"axis",
"=",
"'rows'",
")",
"return",
"risk_exposures",
".",
"groupby",
"(",
"level",
"=",
"'dt'",
... | Compute daily risk factor exposures.
Parameters
----------
positions: pd.Series
A series of holdings as percentages indexed by date and ticker.
- Examples:
dt ticker
2017-01-01 AAPL 0.417582
TLT 0.010989
... | [
"Compute",
"daily",
"risk",
"factor",
"exposures",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/perf_attrib.py#L100-L141 | train |
pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.has_pending | def has_pending(self):
"""Return True if there are pending test items.
This indicates that collection has finished and nodes are still
processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.workqueue:
return True
f... | python | def has_pending(self):
"""Return True if there are pending test items.
This indicates that collection has finished and nodes are still
processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.workqueue:
return True
f... | [
"def",
"has_pending",
"(",
"self",
")",
":",
"if",
"self",
".",
"workqueue",
":",
"return",
"True",
"for",
"assigned_unit",
"in",
"self",
".",
"assigned_work",
".",
"values",
"(",
")",
":",
"if",
"self",
".",
"_pending_of",
"(",
"assigned_unit",
")",
">"... | Return True if there are pending test items.
This indicates that collection has finished and nodes are still
processing test items, so this can be thought of as
"the scheduler is active". | [
"Return",
"True",
"if",
"there",
"are",
"pending",
"test",
"items",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L133-L147 | train |
pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.add_node | def add_node(self, node):
"""Add a new node to the scheduler.
From now on the node will be assigned work units to be executed.
Called by the ``DSession.worker_workerready`` hook when it successfully
bootstraps a new node.
"""
assert node not in self.assigned_work
... | python | def add_node(self, node):
"""Add a new node to the scheduler.
From now on the node will be assigned work units to be executed.
Called by the ``DSession.worker_workerready`` hook when it successfully
bootstraps a new node.
"""
assert node not in self.assigned_work
... | [
"def",
"add_node",
"(",
"self",
",",
"node",
")",
":",
"assert",
"node",
"not",
"in",
"self",
".",
"assigned_work",
"self",
".",
"assigned_work",
"[",
"node",
"]",
"=",
"OrderedDict",
"(",
")"
] | Add a new node to the scheduler.
From now on the node will be assigned work units to be executed.
Called by the ``DSession.worker_workerready`` hook when it successfully
bootstraps a new node. | [
"Add",
"a",
"new",
"node",
"to",
"the",
"scheduler",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L149-L158 | train |
pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.remove_node | def remove_node(self, node):
"""Remove a node from the scheduler.
This should be called either when the node crashed or at shutdown time.
In the former case any pending items assigned to the node will be
re-scheduled.
Called by the hooks:
- ``DSession.worker_workerfini... | python | def remove_node(self, node):
"""Remove a node from the scheduler.
This should be called either when the node crashed or at shutdown time.
In the former case any pending items assigned to the node will be
re-scheduled.
Called by the hooks:
- ``DSession.worker_workerfini... | [
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"workload",
"=",
"self",
".",
"assigned_work",
".",
"pop",
"(",
"node",
")",
"if",
"not",
"self",
".",
"_pending_of",
"(",
"workload",
")",
":",
"return",
"None",
"# The node crashed, identify test th... | Remove a node from the scheduler.
This should be called either when the node crashed or at shutdown time.
In the former case any pending items assigned to the node will be
re-scheduled.
Called by the hooks:
- ``DSession.worker_workerfinished``.
- ``DSession.worker_erro... | [
"Remove",
"a",
"node",
"from",
"the",
"scheduler",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L160-L199 | train |
pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.add_node_collection | def add_node_collection(self, node, collection):
"""Add the collected test items from a node.
The collection is stored in the ``.registered_collections`` dictionary.
Called by the hook:
- ``DSession.worker_collectionfinish``.
"""
# Check that add_node() was called on ... | python | def add_node_collection(self, node, collection):
"""Add the collected test items from a node.
The collection is stored in the ``.registered_collections`` dictionary.
Called by the hook:
- ``DSession.worker_collectionfinish``.
"""
# Check that add_node() was called on ... | [
"def",
"add_node_collection",
"(",
"self",
",",
"node",
",",
"collection",
")",
":",
"# Check that add_node() was called on the node before",
"assert",
"node",
"in",
"self",
".",
"assigned_work",
"# A new node has been added later, perhaps an original one died.",
"if",
"self",
... | Add the collected test items from a node.
The collection is stored in the ``.registered_collections`` dictionary.
Called by the hook:
- ``DSession.worker_collectionfinish``. | [
"Add",
"the",
"collected",
"test",
"items",
"from",
"a",
"node",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L201-L231 | train |
pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling._assign_work_unit | def _assign_work_unit(self, node):
"""Assign a work unit to a node."""
assert self.workqueue
# Grab a unit of work
scope, work_unit = self.workqueue.popitem(last=False)
# Keep track of the assigned work
assigned_to_node = self.assigned_work.setdefault(node, default=Orde... | python | def _assign_work_unit(self, node):
"""Assign a work unit to a node."""
assert self.workqueue
# Grab a unit of work
scope, work_unit = self.workqueue.popitem(last=False)
# Keep track of the assigned work
assigned_to_node = self.assigned_work.setdefault(node, default=Orde... | [
"def",
"_assign_work_unit",
"(",
"self",
",",
"node",
")",
":",
"assert",
"self",
".",
"workqueue",
"# Grab a unit of work",
"scope",
",",
"work_unit",
"=",
"self",
".",
"workqueue",
".",
"popitem",
"(",
"last",
"=",
"False",
")",
"# Keep track of the assigned w... | Assign a work unit to a node. | [
"Assign",
"a",
"work",
"unit",
"to",
"a",
"node",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L246-L265 | train |
pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling._pending_of | def _pending_of(self, workload):
"""Return the number of pending tests in a workload."""
pending = sum(list(scope.values()).count(False) for scope in workload.values())
return pending | python | def _pending_of(self, workload):
"""Return the number of pending tests in a workload."""
pending = sum(list(scope.values()).count(False) for scope in workload.values())
return pending | [
"def",
"_pending_of",
"(",
"self",
",",
"workload",
")",
":",
"pending",
"=",
"sum",
"(",
"list",
"(",
"scope",
".",
"values",
"(",
")",
")",
".",
"count",
"(",
"False",
")",
"for",
"scope",
"in",
"workload",
".",
"values",
"(",
")",
")",
"return",... | Return the number of pending tests in a workload. | [
"Return",
"the",
"number",
"of",
"pending",
"tests",
"in",
"a",
"workload",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L291-L294 | train |
pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling._reschedule | def _reschedule(self, node):
"""Maybe schedule new items on the node.
If there are any globally pending work units left then this will check
if the given node should be given any more tests.
"""
# Do not add more work to a node shutting down
if node.shutting_down:
... | python | def _reschedule(self, node):
"""Maybe schedule new items on the node.
If there are any globally pending work units left then this will check
if the given node should be given any more tests.
"""
# Do not add more work to a node shutting down
if node.shutting_down:
... | [
"def",
"_reschedule",
"(",
"self",
",",
"node",
")",
":",
"# Do not add more work to a node shutting down",
"if",
"node",
".",
"shutting_down",
":",
"return",
"# Check that more work is available",
"if",
"not",
"self",
".",
"workqueue",
":",
"node",
".",
"shutdown",
... | Maybe schedule new items on the node.
If there are any globally pending work units left then this will check
if the given node should be given any more tests. | [
"Maybe",
"schedule",
"new",
"items",
"on",
"the",
"node",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L296-L320 | train |
pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.schedule | def schedule(self):
"""Initiate distribution of the test collection.
Initiate scheduling of the items across the nodes. If this gets called
again later it behaves the same as calling ``._reschedule()`` on all
nodes so that newly added nodes will start to be used.
If ``.collect... | python | def schedule(self):
"""Initiate distribution of the test collection.
Initiate scheduling of the items across the nodes. If this gets called
again later it behaves the same as calling ``._reschedule()`` on all
nodes so that newly added nodes will start to be used.
If ``.collect... | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"# Initial distribution already happened, reschedule on all nodes",
"if",
"self",
".",
"collection",
"is",
"not",
"None",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",... | Initiate distribution of the test collection.
Initiate scheduling of the items across the nodes. If this gets called
again later it behaves the same as calling ``._reschedule()`` on all
nodes so that newly added nodes will start to be used.
If ``.collection_is_completed`` is True, thi... | [
"Initiate",
"distribution",
"of",
"the",
"test",
"collection",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L322-L380 | train |
pytest-dev/pytest-xdist | xdist/scheduler/each.py | EachScheduling.schedule | def schedule(self):
"""Schedule the test items on the nodes
If the node's pending list is empty it is a new node which
needs to run all the tests. If the pending list is already
populated (by ``.add_node_collection()``) then it replaces a
dead node and we only need to run those... | python | def schedule(self):
"""Schedule the test items on the nodes
If the node's pending list is empty it is a new node which
needs to run all the tests. If the pending list is already
populated (by ``.add_node_collection()``) then it replaces a
dead node and we only need to run those... | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"for",
"node",
",",
"pending",
"in",
"self",
".",
"node2pending",
".",
"items",
"(",
")",
":",
"if",
"node",
"in",
"self",
".",
"_started",
":",
"continue",
"if",... | Schedule the test items on the nodes
If the node's pending list is empty it is a new node which
needs to run all the tests. If the pending list is already
populated (by ``.add_node_collection()``) then it replaces a
dead node and we only need to run those tests. | [
"Schedule",
"the",
"test",
"items",
"on",
"the",
"nodes"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/each.py#L114-L132 | train |
pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.has_pending | def has_pending(self):
"""Return True if there are pending test items
This indicates that collection has finished and nodes are
still processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.pending:
return True
for p... | python | def has_pending(self):
"""Return True if there are pending test items
This indicates that collection has finished and nodes are
still processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.pending:
return True
for p... | [
"def",
"has_pending",
"(",
"self",
")",
":",
"if",
"self",
".",
"pending",
":",
"return",
"True",
"for",
"pending",
"in",
"self",
".",
"node2pending",
".",
"values",
"(",
")",
":",
"if",
"pending",
":",
"return",
"True",
"return",
"False"
] | Return True if there are pending test items
This indicates that collection has finished and nodes are
still processing test items, so this can be thought of as
"the scheduler is active". | [
"Return",
"True",
"if",
"there",
"are",
"pending",
"test",
"items"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L96-L108 | train |
pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.check_schedule | def check_schedule(self, node, duration=0):
"""Maybe schedule new items on the node
If there are any globally pending nodes left then this will
check if the given node should be given any more tests. The
``duration`` of the last test is optionally used as a
heuristic to influen... | python | def check_schedule(self, node, duration=0):
"""Maybe schedule new items on the node
If there are any globally pending nodes left then this will
check if the given node should be given any more tests. The
``duration`` of the last test is optionally used as a
heuristic to influen... | [
"def",
"check_schedule",
"(",
"self",
",",
"node",
",",
"duration",
"=",
"0",
")",
":",
"if",
"node",
".",
"shutting_down",
":",
"return",
"if",
"self",
".",
"pending",
":",
"# how many nodes do we have?",
"num_nodes",
"=",
"len",
"(",
"self",
".",
"node2p... | Maybe schedule new items on the node
If there are any globally pending nodes left then this will
check if the given node should be given any more tests. The
``duration`` of the last test is optionally used as a
heuristic to influence how many tests the node is assigned. | [
"Maybe",
"schedule",
"new",
"items",
"on",
"the",
"node"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L154-L184 | train |
pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.remove_node | def remove_node(self, node):
"""Remove a node from the scheduler
This should be called either when the node crashed or at
shutdown time. In the former case any pending items assigned
to the node will be re-scheduled. Called by the
``DSession.worker_workerfinished`` and
... | python | def remove_node(self, node):
"""Remove a node from the scheduler
This should be called either when the node crashed or at
shutdown time. In the former case any pending items assigned
to the node will be re-scheduled. Called by the
``DSession.worker_workerfinished`` and
... | [
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"pending",
"=",
"self",
".",
"node2pending",
".",
"pop",
"(",
"node",
")",
"if",
"not",
"pending",
":",
"return",
"# The node crashed, reassing pending items",
"crashitem",
"=",
"self",
".",
"collection... | Remove a node from the scheduler
This should be called either when the node crashed or at
shutdown time. In the former case any pending items assigned
to the node will be re-scheduled. Called by the
``DSession.worker_workerfinished`` and
``DSession.worker_errordown`` hooks.
... | [
"Remove",
"a",
"node",
"from",
"the",
"scheduler"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L186-L208 | train |
pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.schedule | def schedule(self):
"""Initiate distribution of the test collection
Initiate scheduling of the items across the nodes. If this
gets called again later it behaves the same as calling
``.check_schedule()`` on all nodes so that newly added nodes
will start to be used.
Thi... | python | def schedule(self):
"""Initiate distribution of the test collection
Initiate scheduling of the items across the nodes. If this
gets called again later it behaves the same as calling
``.check_schedule()`` on all nodes so that newly added nodes
will start to be used.
Thi... | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"# Initial distribution already happened, reschedule on all nodes",
"if",
"self",
".",
"collection",
"is",
"not",
"None",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",... | Initiate distribution of the test collection
Initiate scheduling of the items across the nodes. If this
gets called again later it behaves the same as calling
``.check_schedule()`` on all nodes so that newly added nodes
will start to be used.
This is called by the ``DSession.w... | [
"Initiate",
"distribution",
"of",
"the",
"test",
"collection"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L210-L254 | train |
pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling._check_nodes_have_same_collection | def _check_nodes_have_same_collection(self):
"""Return True if all nodes have collected the same items.
If collections differ, this method returns False while logging
the collection differences and posting collection errors to
pytest_collectreport hook.
"""
node_collecti... | python | def _check_nodes_have_same_collection(self):
"""Return True if all nodes have collected the same items.
If collections differ, this method returns False while logging
the collection differences and posting collection errors to
pytest_collectreport hook.
"""
node_collecti... | [
"def",
"_check_nodes_have_same_collection",
"(",
"self",
")",
":",
"node_collection_items",
"=",
"list",
"(",
"self",
".",
"node2collection",
".",
"items",
"(",
")",
")",
"first_node",
",",
"col",
"=",
"node_collection_items",
"[",
"0",
"]",
"same_collection",
"... | Return True if all nodes have collected the same items.
If collections differ, this method returns False while logging
the collection differences and posting collection errors to
pytest_collectreport hook. | [
"Return",
"True",
"if",
"all",
"nodes",
"have",
"collected",
"the",
"same",
"items",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L263-L286 | train |
pytest-dev/pytest-xdist | xdist/dsession.py | DSession.loop_once | def loop_once(self):
"""Process one callback from one of the workers."""
while 1:
if not self._active_nodes:
# If everything has died stop looping
self.triggershutdown()
raise RuntimeError("Unexpectedly no active workers available")
... | python | def loop_once(self):
"""Process one callback from one of the workers."""
while 1:
if not self._active_nodes:
# If everything has died stop looping
self.triggershutdown()
raise RuntimeError("Unexpectedly no active workers available")
... | [
"def",
"loop_once",
"(",
"self",
")",
":",
"while",
"1",
":",
"if",
"not",
"self",
".",
"_active_nodes",
":",
"# If everything has died stop looping",
"self",
".",
"triggershutdown",
"(",
")",
"raise",
"RuntimeError",
"(",
"\"Unexpectedly no active workers available\"... | Process one callback from one of the workers. | [
"Process",
"one",
"callback",
"from",
"one",
"of",
"the",
"workers",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L121-L140 | train |
pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_workerready | def worker_workerready(self, node, workerinfo):
"""Emitted when a node first starts up.
This adds the node to the scheduler, nodes continue with
collection without any further input.
"""
node.workerinfo = workerinfo
node.workerinfo["id"] = node.gateway.id
node.wo... | python | def worker_workerready(self, node, workerinfo):
"""Emitted when a node first starts up.
This adds the node to the scheduler, nodes continue with
collection without any further input.
"""
node.workerinfo = workerinfo
node.workerinfo["id"] = node.gateway.id
node.wo... | [
"def",
"worker_workerready",
"(",
"self",
",",
"node",
",",
"workerinfo",
")",
":",
"node",
".",
"workerinfo",
"=",
"workerinfo",
"node",
".",
"workerinfo",
"[",
"\"id\"",
"]",
"=",
"node",
".",
"gateway",
".",
"id",
"node",
".",
"workerinfo",
"[",
"\"sp... | Emitted when a node first starts up.
This adds the node to the scheduler, nodes continue with
collection without any further input. | [
"Emitted",
"when",
"a",
"node",
"first",
"starts",
"up",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L146-L163 | train |
pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_workerfinished | def worker_workerfinished(self, node):
"""Emitted when node executes its pytest_sessionfinish hook.
Removes the node from the scheduler.
The node might not be in the scheduler if it had not emitted
workerready before shutdown was triggered.
"""
self.config.hook.pytest_t... | python | def worker_workerfinished(self, node):
"""Emitted when node executes its pytest_sessionfinish hook.
Removes the node from the scheduler.
The node might not be in the scheduler if it had not emitted
workerready before shutdown was triggered.
"""
self.config.hook.pytest_t... | [
"def",
"worker_workerfinished",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_testnodedown",
"(",
"node",
"=",
"node",
",",
"error",
"=",
"None",
")",
"if",
"node",
".",
"workeroutput",
"[",
"\"exitstatus\"",
"]",
"... | Emitted when node executes its pytest_sessionfinish hook.
Removes the node from the scheduler.
The node might not be in the scheduler if it had not emitted
workerready before shutdown was triggered. | [
"Emitted",
"when",
"node",
"executes",
"its",
"pytest_sessionfinish",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L165-L181 | train |
pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_errordown | def worker_errordown(self, node, error):
"""Emitted by the WorkerController when a node dies."""
self.config.hook.pytest_testnodedown(node=node, error=error)
try:
crashitem = self.sched.remove_node(node)
except KeyError:
pass
else:
if crashitem... | python | def worker_errordown(self, node, error):
"""Emitted by the WorkerController when a node dies."""
self.config.hook.pytest_testnodedown(node=node, error=error)
try:
crashitem = self.sched.remove_node(node)
except KeyError:
pass
else:
if crashitem... | [
"def",
"worker_errordown",
"(",
"self",
",",
"node",
",",
"error",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_testnodedown",
"(",
"node",
"=",
"node",
",",
"error",
"=",
"error",
")",
"try",
":",
"crashitem",
"=",
"self",
".",
"sched",
... | Emitted by the WorkerController when a node dies. | [
"Emitted",
"by",
"the",
"WorkerController",
"when",
"a",
"node",
"dies",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L183-L208 | train |
pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_collectionfinish | def worker_collectionfinish(self, node, ids):
"""worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler t... | python | def worker_collectionfinish(self, node, ids):
"""worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler t... | [
"def",
"worker_collectionfinish",
"(",
"self",
",",
"node",
",",
"ids",
")",
":",
"if",
"self",
".",
"shuttingdown",
":",
"return",
"self",
".",
"config",
".",
"hook",
".",
"pytest_xdist_node_collection_finished",
"(",
"node",
"=",
"node",
",",
"ids",
"=",
... | worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler to schedule the collected items. When initiating
... | [
"worker",
"has",
"finished",
"test",
"collection",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L210-L236 | train |
pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_logstart | def worker_logstart(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logstart hook."""
self.config.hook.pytest_runtest_logstart(nodeid=nodeid, location=location) | python | def worker_logstart(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logstart hook."""
self.config.hook.pytest_runtest_logstart(nodeid=nodeid, location=location) | [
"def",
"worker_logstart",
"(",
"self",
",",
"node",
",",
"nodeid",
",",
"location",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_runtest_logstart",
"(",
"nodeid",
"=",
"nodeid",
",",
"location",
"=",
"location",
")"
] | Emitted when a node calls the pytest_runtest_logstart hook. | [
"Emitted",
"when",
"a",
"node",
"calls",
"the",
"pytest_runtest_logstart",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L238-L240 | train |
pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_logfinish | def worker_logfinish(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logfinish hook."""
self.config.hook.pytest_runtest_logfinish(nodeid=nodeid, location=location) | python | def worker_logfinish(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logfinish hook."""
self.config.hook.pytest_runtest_logfinish(nodeid=nodeid, location=location) | [
"def",
"worker_logfinish",
"(",
"self",
",",
"node",
",",
"nodeid",
",",
"location",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_runtest_logfinish",
"(",
"nodeid",
"=",
"nodeid",
",",
"location",
"=",
"location",
")"
] | Emitted when a node calls the pytest_runtest_logfinish hook. | [
"Emitted",
"when",
"a",
"node",
"calls",
"the",
"pytest_runtest_logfinish",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L242-L244 | train |
pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_collectreport | def worker_collectreport(self, node, rep):
"""Emitted when a node calls the pytest_collectreport hook.
Because we only need the report when there's a failure/skip, as optimization
we only expect to receive failed/skipped reports from workers (#330).
"""
assert not rep.passed
... | python | def worker_collectreport(self, node, rep):
"""Emitted when a node calls the pytest_collectreport hook.
Because we only need the report when there's a failure/skip, as optimization
we only expect to receive failed/skipped reports from workers (#330).
"""
assert not rep.passed
... | [
"def",
"worker_collectreport",
"(",
"self",
",",
"node",
",",
"rep",
")",
":",
"assert",
"not",
"rep",
".",
"passed",
"self",
".",
"_failed_worker_collectreport",
"(",
"node",
",",
"rep",
")"
] | Emitted when a node calls the pytest_collectreport hook.
Because we only need the report when there's a failure/skip, as optimization
we only expect to receive failed/skipped reports from workers (#330). | [
"Emitted",
"when",
"a",
"node",
"calls",
"the",
"pytest_collectreport",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L260-L267 | train |
pytest-dev/pytest-xdist | xdist/dsession.py | DSession._clone_node | def _clone_node(self, node):
"""Return new node based on an existing one.
This is normally for when a node dies, this will copy the spec
of the existing node and create a new one with a new id. The
new node will have been setup so it will start calling the
"worker_*" hooks and ... | python | def _clone_node(self, node):
"""Return new node based on an existing one.
This is normally for when a node dies, this will copy the spec
of the existing node and create a new one with a new id. The
new node will have been setup so it will start calling the
"worker_*" hooks and ... | [
"def",
"_clone_node",
"(",
"self",
",",
"node",
")",
":",
"spec",
"=",
"node",
".",
"gateway",
".",
"spec",
"spec",
".",
"id",
"=",
"None",
"self",
".",
"nodemanager",
".",
"group",
".",
"allocate_id",
"(",
"spec",
")",
"node",
"=",
"self",
".",
"n... | Return new node based on an existing one.
This is normally for when a node dies, this will copy the spec
of the existing node and create a new one with a new id. The
new node will have been setup so it will start calling the
"worker_*" hooks and do work soon. | [
"Return",
"new",
"node",
"based",
"on",
"an",
"existing",
"one",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L279-L292 | train |
pytest-dev/pytest-xdist | xdist/workermanage.py | NodeManager.rsync_roots | def rsync_roots(self, gateway):
"""Rsync the set of roots to the node's gateway cwd."""
if self.roots:
for root in self.roots:
self.rsync(gateway, root, **self.rsyncoptions) | python | def rsync_roots(self, gateway):
"""Rsync the set of roots to the node's gateway cwd."""
if self.roots:
for root in self.roots:
self.rsync(gateway, root, **self.rsyncoptions) | [
"def",
"rsync_roots",
"(",
"self",
",",
"gateway",
")",
":",
"if",
"self",
".",
"roots",
":",
"for",
"root",
"in",
"self",
".",
"roots",
":",
"self",
".",
"rsync",
"(",
"gateway",
",",
"root",
",",
"*",
"*",
"self",
".",
"rsyncoptions",
")"
] | Rsync the set of roots to the node's gateway cwd. | [
"Rsync",
"the",
"set",
"of",
"roots",
"to",
"the",
"node",
"s",
"gateway",
"cwd",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L53-L57 | train |
pytest-dev/pytest-xdist | xdist/workermanage.py | NodeManager._getrsyncoptions | def _getrsyncoptions(self):
"""Get options to be passed for rsync."""
ignores = list(self.DEFAULT_IGNORES)
ignores += self.config.option.rsyncignore
ignores += self.config.getini("rsyncignore")
return {"ignores": ignores, "verbose": self.config.option.verbose} | python | def _getrsyncoptions(self):
"""Get options to be passed for rsync."""
ignores = list(self.DEFAULT_IGNORES)
ignores += self.config.option.rsyncignore
ignores += self.config.getini("rsyncignore")
return {"ignores": ignores, "verbose": self.config.option.verbose} | [
"def",
"_getrsyncoptions",
"(",
"self",
")",
":",
"ignores",
"=",
"list",
"(",
"self",
".",
"DEFAULT_IGNORES",
")",
"ignores",
"+=",
"self",
".",
"config",
".",
"option",
".",
"rsyncignore",
"ignores",
"+=",
"self",
".",
"config",
".",
"getini",
"(",
"\"... | Get options to be passed for rsync. | [
"Get",
"options",
"to",
"be",
"passed",
"for",
"rsync",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L109-L115 | train |
pytest-dev/pytest-xdist | xdist/workermanage.py | WorkerController.sendcommand | def sendcommand(self, name, **kwargs):
""" send a named parametrized command to the other side. """
self.log("sending command %s(**%s)" % (name, kwargs))
self.channel.send((name, kwargs)) | python | def sendcommand(self, name, **kwargs):
""" send a named parametrized command to the other side. """
self.log("sending command %s(**%s)" % (name, kwargs))
self.channel.send((name, kwargs)) | [
"def",
"sendcommand",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"log",
"(",
"\"sending command %s(**%s)\"",
"%",
"(",
"name",
",",
"kwargs",
")",
")",
"self",
".",
"channel",
".",
"send",
"(",
"(",
"name",
",",
"kwargs... | send a named parametrized command to the other side. | [
"send",
"a",
"named",
"parametrized",
"command",
"to",
"the",
"other",
"side",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L284-L287 | train |
pytest-dev/pytest-xdist | xdist/workermanage.py | WorkerController.process_from_remote | def process_from_remote(self, eventcall): # noqa too complex
""" this gets called for each object we receive from
the other side and if the channel closes.
Note that channel callbacks run in the receiver
thread of execnet gateways - we need to
avoid raising exce... | python | def process_from_remote(self, eventcall): # noqa too complex
""" this gets called for each object we receive from
the other side and if the channel closes.
Note that channel callbacks run in the receiver
thread of execnet gateways - we need to
avoid raising exce... | [
"def",
"process_from_remote",
"(",
"self",
",",
"eventcall",
")",
":",
"# noqa too complex",
"try",
":",
"if",
"eventcall",
"==",
"self",
".",
"ENDMARK",
":",
"err",
"=",
"self",
".",
"channel",
".",
"_getremoteerror",
"(",
")",
"if",
"not",
"self",
".",
... | this gets called for each object we receive from
the other side and if the channel closes.
Note that channel callbacks run in the receiver
thread of execnet gateways - we need to
avoid raising exceptions or doing heavy work. | [
"this",
"gets",
"called",
"for",
"each",
"object",
"we",
"receive",
"from",
"the",
"other",
"side",
"and",
"if",
"the",
"channel",
"closes",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L293-L367 | train |
pytest-dev/pytest-xdist | xdist/report.py | report_collection_diff | def report_collection_diff(from_collection, to_collection, from_id, to_id):
"""Report the collected test difference between two nodes.
:returns: detailed message describing the difference between the given
collections, or None if they are equal.
"""
if from_collection == to_collection:
retu... | python | def report_collection_diff(from_collection, to_collection, from_id, to_id):
"""Report the collected test difference between two nodes.
:returns: detailed message describing the difference between the given
collections, or None if they are equal.
"""
if from_collection == to_collection:
retu... | [
"def",
"report_collection_diff",
"(",
"from_collection",
",",
"to_collection",
",",
"from_id",
",",
"to_id",
")",
":",
"if",
"from_collection",
"==",
"to_collection",
":",
"return",
"None",
"diff",
"=",
"unified_diff",
"(",
"from_collection",
",",
"to_collection",
... | Report the collected test difference between two nodes.
:returns: detailed message describing the difference between the given
collections, or None if they are equal. | [
"Report",
"the",
"collected",
"test",
"difference",
"between",
"two",
"nodes",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/report.py#L5-L21 | train |
ivelum/djangoql | djangoql/queryset.py | apply_search | def apply_search(queryset, search, schema=None):
"""
Applies search written in DjangoQL mini-language to given queryset
"""
ast = DjangoQLParser().parse(search)
schema = schema or DjangoQLSchema
schema_instance = schema(queryset.model)
schema_instance.validate(ast)
return queryset.filter... | python | def apply_search(queryset, search, schema=None):
"""
Applies search written in DjangoQL mini-language to given queryset
"""
ast = DjangoQLParser().parse(search)
schema = schema or DjangoQLSchema
schema_instance = schema(queryset.model)
schema_instance.validate(ast)
return queryset.filter... | [
"def",
"apply_search",
"(",
"queryset",
",",
"search",
",",
"schema",
"=",
"None",
")",
":",
"ast",
"=",
"DjangoQLParser",
"(",
")",
".",
"parse",
"(",
"search",
")",
"schema",
"=",
"schema",
"or",
"DjangoQLSchema",
"schema_instance",
"=",
"schema",
"(",
... | Applies search written in DjangoQL mini-language to given queryset | [
"Applies",
"search",
"written",
"in",
"DjangoQL",
"mini",
"-",
"language",
"to",
"given",
"queryset"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/queryset.py#L32-L40 | train |
ivelum/djangoql | djangoql/schema.py | DjangoQLField.get_options | def get_options(self):
"""
Override this method to provide custom suggestion options
"""
choices = self._field_choices()
if choices:
return [c[1] for c in choices]
else:
return self.model.objects.\
order_by(self.name).\
... | python | def get_options(self):
"""
Override this method to provide custom suggestion options
"""
choices = self._field_choices()
if choices:
return [c[1] for c in choices]
else:
return self.model.objects.\
order_by(self.name).\
... | [
"def",
"get_options",
"(",
"self",
")",
":",
"choices",
"=",
"self",
".",
"_field_choices",
"(",
")",
"if",
"choices",
":",
"return",
"[",
"c",
"[",
"1",
"]",
"for",
"c",
"in",
"choices",
"]",
"else",
":",
"return",
"self",
".",
"model",
".",
"obje... | Override this method to provide custom suggestion options | [
"Override",
"this",
"method",
"to",
"provide",
"custom",
"suggestion",
"options"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L55-L65 | train |
ivelum/djangoql | djangoql/schema.py | DjangoQLField.get_lookup_value | def get_lookup_value(self, value):
"""
Override this method to convert displayed values to lookup values
"""
choices = self._field_choices()
if choices:
if isinstance(value, list):
return [c[0] for c in choices if c[1] in value]
else:
... | python | def get_lookup_value(self, value):
"""
Override this method to convert displayed values to lookup values
"""
choices = self._field_choices()
if choices:
if isinstance(value, list):
return [c[0] for c in choices if c[1] in value]
else:
... | [
"def",
"get_lookup_value",
"(",
"self",
",",
"value",
")",
":",
"choices",
"=",
"self",
".",
"_field_choices",
"(",
")",
"if",
"choices",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"[",
"c",
"[",
"0",
"]",
"for",
"c",
"... | Override this method to convert displayed values to lookup values | [
"Override",
"this",
"method",
"to",
"convert",
"displayed",
"values",
"to",
"lookup",
"values"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L73-L85 | train |
ivelum/djangoql | djangoql/schema.py | DjangoQLField.get_operator | def get_operator(self, operator):
"""
Get a comparison suffix to be used in Django ORM & inversion flag for it
:param operator: string, DjangoQL comparison operator
:return: (suffix, invert) - a tuple with 2 values:
suffix - suffix to be used in ORM query, for example '__gt'... | python | def get_operator(self, operator):
"""
Get a comparison suffix to be used in Django ORM & inversion flag for it
:param operator: string, DjangoQL comparison operator
:return: (suffix, invert) - a tuple with 2 values:
suffix - suffix to be used in ORM query, for example '__gt'... | [
"def",
"get_operator",
"(",
"self",
",",
"operator",
")",
":",
"op",
"=",
"{",
"'='",
":",
"''",
",",
"'>'",
":",
"'__gt'",
",",
"'>='",
":",
"'__gte'",
",",
"'<'",
":",
"'__lt'",
",",
"'<='",
":",
"'__lte'",
",",
"'~'",
":",
"'__icontains'",
",",
... | Get a comparison suffix to be used in Django ORM & inversion flag for it
:param operator: string, DjangoQL comparison operator
:return: (suffix, invert) - a tuple with 2 values:
suffix - suffix to be used in ORM query, for example '__gt' for '>'
invert - boolean, True if this co... | [
"Get",
"a",
"comparison",
"suffix",
"to",
"be",
"used",
"in",
"Django",
"ORM",
"&",
"inversion",
"flag",
"for",
"it"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L87-L112 | train |
ivelum/djangoql | djangoql/schema.py | DjangoQLSchema.introspect | def introspect(self, model, exclude=()):
"""
Start with given model and recursively walk through its relationships.
Returns a dict with all model labels and their fields found.
"""
result = {}
open_set = deque([model])
closed_set = list(exclude)
while op... | python | def introspect(self, model, exclude=()):
"""
Start with given model and recursively walk through its relationships.
Returns a dict with all model labels and their fields found.
"""
result = {}
open_set = deque([model])
closed_set = list(exclude)
while op... | [
"def",
"introspect",
"(",
"self",
",",
"model",
",",
"exclude",
"=",
"(",
")",
")",
":",
"result",
"=",
"{",
"}",
"open_set",
"=",
"deque",
"(",
"[",
"model",
"]",
")",
"closed_set",
"=",
"list",
"(",
"exclude",
")",
"while",
"open_set",
":",
"mode... | Start with given model and recursively walk through its relationships.
Returns a dict with all model labels and their fields found. | [
"Start",
"with",
"given",
"model",
"and",
"recursively",
"walk",
"through",
"its",
"relationships",
"."
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L332-L365 | train |
ivelum/djangoql | djangoql/schema.py | DjangoQLSchema.get_fields | def get_fields(self, model):
"""
By default, returns all field names of a given model.
Override this method to limit field options. You can either return a
plain list of field names from it, like ['id', 'name'], or call
.super() and exclude unwanted fields from its result.
... | python | def get_fields(self, model):
"""
By default, returns all field names of a given model.
Override this method to limit field options. You can either return a
plain list of field names from it, like ['id', 'name'], or call
.super() and exclude unwanted fields from its result.
... | [
"def",
"get_fields",
"(",
"self",
",",
"model",
")",
":",
"return",
"sorted",
"(",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"model",
".",
"_meta",
".",
"get_fields",
"(",
")",
"if",
"f",
".",
"name",
"!=",
"'password'",
"]",
")"
] | By default, returns all field names of a given model.
Override this method to limit field options. You can either return a
plain list of field names from it, like ['id', 'name'], or call
.super() and exclude unwanted fields from its result. | [
"By",
"default",
"returns",
"all",
"field",
"names",
"of",
"a",
"given",
"model",
"."
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L367-L377 | train |
ivelum/djangoql | djangoql/schema.py | DjangoQLSchema.validate | def validate(self, node):
"""
Validate DjangoQL AST tree vs. current schema
"""
assert isinstance(node, Node)
if isinstance(node.operator, Logical):
self.validate(node.left)
self.validate(node.right)
return
assert isinstance(node.left, ... | python | def validate(self, node):
"""
Validate DjangoQL AST tree vs. current schema
"""
assert isinstance(node, Node)
if isinstance(node.operator, Logical):
self.validate(node.left)
self.validate(node.right)
return
assert isinstance(node.left, ... | [
"def",
"validate",
"(",
"self",
",",
"node",
")",
":",
"assert",
"isinstance",
"(",
"node",
",",
"Node",
")",
"if",
"isinstance",
"(",
"node",
".",
"operator",
",",
"Logical",
")",
":",
"self",
".",
"validate",
"(",
"node",
".",
"left",
")",
"self",
... | Validate DjangoQL AST tree vs. current schema | [
"Validate",
"DjangoQL",
"AST",
"tree",
"vs",
".",
"current",
"schema"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L454-L479 | train |
ivelum/djangoql | djangoql/lexer.py | DjangoQLLexer.find_column | def find_column(self, t):
"""
Returns token position in current text, starting from 1
"""
cr = max(self.text.rfind(l, 0, t.lexpos) for l in self.line_terminators)
if cr == -1:
return t.lexpos + 1
return t.lexpos - cr | python | def find_column(self, t):
"""
Returns token position in current text, starting from 1
"""
cr = max(self.text.rfind(l, 0, t.lexpos) for l in self.line_terminators)
if cr == -1:
return t.lexpos + 1
return t.lexpos - cr | [
"def",
"find_column",
"(",
"self",
",",
"t",
")",
":",
"cr",
"=",
"max",
"(",
"self",
".",
"text",
".",
"rfind",
"(",
"l",
",",
"0",
",",
"t",
".",
"lexpos",
")",
"for",
"l",
"in",
"self",
".",
"line_terminators",
")",
"if",
"cr",
"==",
"-",
... | Returns token position in current text, starting from 1 | [
"Returns",
"token",
"position",
"in",
"current",
"text",
"starting",
"from",
"1"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/lexer.py#L40-L47 | train |
aiogram/aiogram | aiogram/dispatcher/filters/filters.py | execute_filter | async def execute_filter(filter_: FilterObj, args):
"""
Helper for executing filter
:param filter_:
:param args:
:return:
"""
if filter_.is_async:
return await filter_.filter(*args, **filter_.kwargs)
else:
return filter_.filter(*args, **filter_.kwargs) | python | async def execute_filter(filter_: FilterObj, args):
"""
Helper for executing filter
:param filter_:
:param args:
:return:
"""
if filter_.is_async:
return await filter_.filter(*args, **filter_.kwargs)
else:
return filter_.filter(*args, **filter_.kwargs) | [
"async",
"def",
"execute_filter",
"(",
"filter_",
":",
"FilterObj",
",",
"args",
")",
":",
"if",
"filter_",
".",
"is_async",
":",
"return",
"await",
"filter_",
".",
"filter",
"(",
"*",
"args",
",",
"*",
"*",
"filter_",
".",
"kwargs",
")",
"else",
":",
... | Helper for executing filter
:param filter_:
:param args:
:return: | [
"Helper",
"for",
"executing",
"filter"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L47-L58 | train |
aiogram/aiogram | aiogram/dispatcher/filters/filters.py | check_filters | async def check_filters(filters: typing.Iterable[FilterObj], args):
"""
Check list of filters
:param filters:
:param args:
:return:
"""
data = {}
if filters is not None:
for filter_ in filters:
f = await execute_filter(filter_, args)
if not f:
... | python | async def check_filters(filters: typing.Iterable[FilterObj], args):
"""
Check list of filters
:param filters:
:param args:
:return:
"""
data = {}
if filters is not None:
for filter_ in filters:
f = await execute_filter(filter_, args)
if not f:
... | [
"async",
"def",
"check_filters",
"(",
"filters",
":",
"typing",
".",
"Iterable",
"[",
"FilterObj",
"]",
",",
"args",
")",
":",
"data",
"=",
"{",
"}",
"if",
"filters",
"is",
"not",
"None",
":",
"for",
"filter_",
"in",
"filters",
":",
"f",
"=",
"await"... | Check list of filters
:param filters:
:param args:
:return: | [
"Check",
"list",
"of",
"filters"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L61-L77 | train |
aiogram/aiogram | aiogram/dispatcher/filters/filters.py | AbstractFilter.validate | def validate(cls, full_config: typing.Dict[str, typing.Any]) -> typing.Optional[typing.Dict[str, typing.Any]]:
"""
Validate and parse config.
This method will be called by the filters factory when you bind this filter.
Must be overridden.
:param full_config: dict with arguments... | python | def validate(cls, full_config: typing.Dict[str, typing.Any]) -> typing.Optional[typing.Dict[str, typing.Any]]:
"""
Validate and parse config.
This method will be called by the filters factory when you bind this filter.
Must be overridden.
:param full_config: dict with arguments... | [
"def",
"validate",
"(",
"cls",
",",
"full_config",
":",
"typing",
".",
"Dict",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
")",
"->",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Dict",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
"]",
":",
"pa... | Validate and parse config.
This method will be called by the filters factory when you bind this filter.
Must be overridden.
:param full_config: dict with arguments passed to handler registrar
:return: Current filter config | [
"Validate",
"and",
"parse",
"config",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L136-L146 | train |
aiogram/aiogram | aiogram/dispatcher/filters/filters.py | AndFilter.check | async def check(self, *args):
"""
All filters must return a positive result
:param args:
:return:
"""
data = {}
for target in self.targets:
result = await target(*args)
if not result:
return False
if isinstance(... | python | async def check(self, *args):
"""
All filters must return a positive result
:param args:
:return:
"""
data = {}
for target in self.targets:
result = await target(*args)
if not result:
return False
if isinstance(... | [
"async",
"def",
"check",
"(",
"self",
",",
"*",
"args",
")",
":",
"data",
"=",
"{",
"}",
"for",
"target",
"in",
"self",
".",
"targets",
":",
"result",
"=",
"await",
"target",
"(",
"*",
"args",
")",
"if",
"not",
"result",
":",
"return",
"False",
"... | All filters must return a positive result
:param args:
:return: | [
"All",
"filters",
"must",
"return",
"a",
"positive",
"result"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L247-L263 | train |
aiogram/aiogram | examples/broadcast_example.py | send_message | async def send_message(user_id: int, text: str, disable_notification: bool = False) -> bool:
"""
Safe messages sender
:param user_id:
:param text:
:param disable_notification:
:return:
"""
try:
await bot.send_message(user_id, text, disable_notification=disable_notification)
... | python | async def send_message(user_id: int, text: str, disable_notification: bool = False) -> bool:
"""
Safe messages sender
:param user_id:
:param text:
:param disable_notification:
:return:
"""
try:
await bot.send_message(user_id, text, disable_notification=disable_notification)
... | [
"async",
"def",
"send_message",
"(",
"user_id",
":",
"int",
",",
"text",
":",
"str",
",",
"disable_notification",
":",
"bool",
"=",
"False",
")",
"->",
"bool",
":",
"try",
":",
"await",
"bot",
".",
"send_message",
"(",
"user_id",
",",
"text",
",",
"dis... | Safe messages sender
:param user_id:
:param text:
:param disable_notification:
:return: | [
"Safe",
"messages",
"sender"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/broadcast_example.py#L26-L52 | train |
aiogram/aiogram | aiogram/types/message.py | Message.get_full_command | def get_full_command(self):
"""
Split command and args
:return: tuple of (command, args)
"""
if self.is_command():
command, _, args = self.text.partition(' ')
return command, args | python | def get_full_command(self):
"""
Split command and args
:return: tuple of (command, args)
"""
if self.is_command():
command, _, args = self.text.partition(' ')
return command, args | [
"def",
"get_full_command",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_command",
"(",
")",
":",
"command",
",",
"_",
",",
"args",
"=",
"self",
".",
"text",
".",
"partition",
"(",
"' '",
")",
"return",
"command",
",",
"args"
] | Split command and args
:return: tuple of (command, args) | [
"Split",
"command",
"and",
"args"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L156-L164 | train |
aiogram/aiogram | aiogram/types/message.py | Message.get_command | def get_command(self, pure=False):
"""
Get command from message
:return:
"""
command = self.get_full_command()
if command:
command = command[0]
if pure:
command, _, _ = command[1:].partition('@')
return command | python | def get_command(self, pure=False):
"""
Get command from message
:return:
"""
command = self.get_full_command()
if command:
command = command[0]
if pure:
command, _, _ = command[1:].partition('@')
return command | [
"def",
"get_command",
"(",
"self",
",",
"pure",
"=",
"False",
")",
":",
"command",
"=",
"self",
".",
"get_full_command",
"(",
")",
"if",
"command",
":",
"command",
"=",
"command",
"[",
"0",
"]",
"if",
"pure",
":",
"command",
",",
"_",
",",
"_",
"="... | Get command from message
:return: | [
"Get",
"command",
"from",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L166-L177 | train |
aiogram/aiogram | aiogram/types/message.py | Message.parse_entities | def parse_entities(self, as_html=True):
"""
Text or caption formatted as HTML or Markdown.
:return: str
"""
text = self.text or self.caption
if text is None:
raise TypeError("This message doesn't have any text.")
quote_fn = md.quote_html if as_html ... | python | def parse_entities(self, as_html=True):
"""
Text or caption formatted as HTML or Markdown.
:return: str
"""
text = self.text or self.caption
if text is None:
raise TypeError("This message doesn't have any text.")
quote_fn = md.quote_html if as_html ... | [
"def",
"parse_entities",
"(",
"self",
",",
"as_html",
"=",
"True",
")",
":",
"text",
"=",
"self",
".",
"text",
"or",
"self",
".",
"caption",
"if",
"text",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"This message doesn't have any text.\"",
")",
"quote_fn... | Text or caption formatted as HTML or Markdown.
:return: str | [
"Text",
"or",
"caption",
"formatted",
"as",
"HTML",
"or",
"Markdown",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L189-L231 | train |
aiogram/aiogram | aiogram/types/message.py | Message.url | def url(self) -> str:
"""
Get URL for the message
:return: str
"""
if self.chat.type not in [ChatType.SUPER_GROUP, ChatType.CHANNEL]:
raise TypeError('Invalid chat type!')
elif not self.chat.username:
raise TypeError('This chat does not have @user... | python | def url(self) -> str:
"""
Get URL for the message
:return: str
"""
if self.chat.type not in [ChatType.SUPER_GROUP, ChatType.CHANNEL]:
raise TypeError('Invalid chat type!')
elif not self.chat.username:
raise TypeError('This chat does not have @user... | [
"def",
"url",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"chat",
".",
"type",
"not",
"in",
"[",
"ChatType",
".",
"SUPER_GROUP",
",",
"ChatType",
".",
"CHANNEL",
"]",
":",
"raise",
"TypeError",
"(",
"'Invalid chat type!'",
")",
"elif",
"not"... | Get URL for the message
:return: str | [
"Get",
"URL",
"for",
"the",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L252-L263 | train |
aiogram/aiogram | aiogram/types/message.py | Message.link | def link(self, text, as_html=True) -> str:
"""
Generate URL for using in text messages with HTML or MD parse mode
:param text: link label
:param as_html: generate as HTML
:return: str
"""
try:
url = self.url
except TypeError: # URL is not acc... | python | def link(self, text, as_html=True) -> str:
"""
Generate URL for using in text messages with HTML or MD parse mode
:param text: link label
:param as_html: generate as HTML
:return: str
"""
try:
url = self.url
except TypeError: # URL is not acc... | [
"def",
"link",
"(",
"self",
",",
"text",
",",
"as_html",
"=",
"True",
")",
"->",
"str",
":",
"try",
":",
"url",
"=",
"self",
".",
"url",
"except",
"TypeError",
":",
"# URL is not accessible",
"if",
"as_html",
":",
"return",
"md",
".",
"quote_html",
"("... | Generate URL for using in text messages with HTML or MD parse mode
:param text: link label
:param as_html: generate as HTML
:return: str | [
"Generate",
"URL",
"for",
"using",
"in",
"text",
"messages",
"with",
"HTML",
"or",
"MD",
"parse",
"mode"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L265-L282 | train |
aiogram/aiogram | aiogram/types/message.py | Message.answer | async def answer(self, text, parse_mode=None, disable_web_page_preview=None,
disable_notification=None, reply_markup=None, reply=False) -> Message:
"""
Answer to this message
:param text: str
:param parse_mode: str
:param disable_web_page_preview: bool
... | python | async def answer(self, text, parse_mode=None, disable_web_page_preview=None,
disable_notification=None, reply_markup=None, reply=False) -> Message:
"""
Answer to this message
:param text: str
:param parse_mode: str
:param disable_web_page_preview: bool
... | [
"async",
"def",
"answer",
"(",
"self",
",",
"text",
",",
"parse_mode",
"=",
"None",
",",
"disable_web_page_preview",
"=",
"None",
",",
"disable_notification",
"=",
"None",
",",
"reply_markup",
"=",
"None",
",",
"reply",
"=",
"False",
")",
"->",
"Message",
... | Answer to this message
:param text: str
:param parse_mode: str
:param disable_web_page_preview: bool
:param disable_notification: bool
:param reply_markup:
:param reply: fill 'reply_to_message_id'
:return: :class:`aiogram.types.Message` | [
"Answer",
"to",
"this",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L284-L302 | train |
aiogram/aiogram | aiogram/types/message.py | Message.answer_photo | async def answer_photo(self, photo: typing.Union[base.InputFile, base.String],
caption: typing.Union[base.String, None] = None,
disable_notification: typing.Union[base.Boolean, None] = None,
reply_markup=None, reply=False) -> Message:
... | python | async def answer_photo(self, photo: typing.Union[base.InputFile, base.String],
caption: typing.Union[base.String, None] = None,
disable_notification: typing.Union[base.Boolean, None] = None,
reply_markup=None, reply=False) -> Message:
... | [
"async",
"def",
"answer_photo",
"(",
"self",
",",
"photo",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"InputFile",
",",
"base",
".",
"String",
"]",
",",
"caption",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"String",
",",
"None",
"]",
"=",
... | Use this method to send photos.
Source: https://core.telegram.org/bots/api#sendphoto
:param photo: Photo to send.
:type photo: :obj:`typing.Union[base.InputFile, base.String]`
:param caption: Photo caption (may also be used when resending photos by file_id), 0-200 characters
:t... | [
"Use",
"this",
"method",
"to",
"send",
"photos",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L304-L329 | train |
aiogram/aiogram | aiogram/types/message.py | Message.forward | async def forward(self, chat_id, disable_notification=None) -> Message:
"""
Forward this message
:param chat_id:
:param disable_notification:
:return:
"""
return await self.bot.forward_message(chat_id, self.chat.id, self.message_id, disable_notification) | python | async def forward(self, chat_id, disable_notification=None) -> Message:
"""
Forward this message
:param chat_id:
:param disable_notification:
:return:
"""
return await self.bot.forward_message(chat_id, self.chat.id, self.message_id, disable_notification) | [
"async",
"def",
"forward",
"(",
"self",
",",
"chat_id",
",",
"disable_notification",
"=",
"None",
")",
"->",
"Message",
":",
"return",
"await",
"self",
".",
"bot",
".",
"forward_message",
"(",
"chat_id",
",",
"self",
".",
"chat",
".",
"id",
",",
"self",
... | Forward this message
:param chat_id:
:param disable_notification:
:return: | [
"Forward",
"this",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L1322-L1330 | train |
aiogram/aiogram | aiogram/types/message.py | Message.delete | async def delete(self):
"""
Delete this message
:return: bool
"""
return await self.bot.delete_message(self.chat.id, self.message_id) | python | async def delete(self):
"""
Delete this message
:return: bool
"""
return await self.bot.delete_message(self.chat.id, self.message_id) | [
"async",
"def",
"delete",
"(",
"self",
")",
":",
"return",
"await",
"self",
".",
"bot",
".",
"delete_message",
"(",
"self",
".",
"chat",
".",
"id",
",",
"self",
".",
"message_id",
")"
] | Delete this message
:return: bool | [
"Delete",
"this",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L1470-L1476 | train |
aiogram/aiogram | aiogram/utils/callback_data.py | CallbackData.new | def new(self, *args, **kwargs) -> str:
"""
Generate callback data
:param args:
:param kwargs:
:return:
"""
args = list(args)
data = [self.prefix]
for part in self._part_names:
value = kwargs.pop(part, None)
if value is No... | python | def new(self, *args, **kwargs) -> str:
"""
Generate callback data
:param args:
:param kwargs:
:return:
"""
args = list(args)
data = [self.prefix]
for part in self._part_names:
value = kwargs.pop(part, None)
if value is No... | [
"def",
"new",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"args",
"=",
"list",
"(",
"args",
")",
"data",
"=",
"[",
"self",
".",
"prefix",
"]",
"for",
"part",
"in",
"self",
".",
"_part_names",
":",
"value",
"="... | Generate callback data
:param args:
:param kwargs:
:return: | [
"Generate",
"callback",
"data"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/callback_data.py#L44-L81 | train |
aiogram/aiogram | examples/webhook_example.py | cmd_id | async def cmd_id(message: types.Message):
"""
Return info about user.
"""
if message.reply_to_message:
target = message.reply_to_message.from_user
chat = message.chat
elif message.forward_from and message.chat.type == ChatType.PRIVATE:
target = message.forward_from
ch... | python | async def cmd_id(message: types.Message):
"""
Return info about user.
"""
if message.reply_to_message:
target = message.reply_to_message.from_user
chat = message.chat
elif message.forward_from and message.chat.type == ChatType.PRIVATE:
target = message.forward_from
ch... | [
"async",
"def",
"cmd_id",
"(",
"message",
":",
"types",
".",
"Message",
")",
":",
"if",
"message",
".",
"reply_to_message",
":",
"target",
"=",
"message",
".",
"reply_to_message",
".",
"from_user",
"chat",
"=",
"message",
".",
"chat",
"elif",
"message",
".... | Return info about user. | [
"Return",
"info",
"about",
"user",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/webhook_example.py#L83-L113 | train |
aiogram/aiogram | examples/webhook_example.py | on_shutdown | async def on_shutdown(app):
"""
Graceful shutdown. This method is recommended by aiohttp docs.
"""
# Remove webhook.
await bot.delete_webhook()
# Close Redis connection.
await dp.storage.close()
await dp.storage.wait_closed() | python | async def on_shutdown(app):
"""
Graceful shutdown. This method is recommended by aiohttp docs.
"""
# Remove webhook.
await bot.delete_webhook()
# Close Redis connection.
await dp.storage.close()
await dp.storage.wait_closed() | [
"async",
"def",
"on_shutdown",
"(",
"app",
")",
":",
"# Remove webhook.",
"await",
"bot",
".",
"delete_webhook",
"(",
")",
"# Close Redis connection.",
"await",
"dp",
".",
"storage",
".",
"close",
"(",
")",
"await",
"dp",
".",
"storage",
".",
"wait_closed",
... | Graceful shutdown. This method is recommended by aiohttp docs. | [
"Graceful",
"shutdown",
".",
"This",
"method",
"is",
"recommended",
"by",
"aiohttp",
"docs",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/webhook_example.py#L149-L158 | train |
aiogram/aiogram | aiogram/types/input_file.py | InputFile.from_url | def from_url(cls, url, filename=None, chunk_size=CHUNK_SIZE):
"""
Download file from URL
Manually is not required action. You can send urls instead!
:param url: target URL
:param filename: optional. set custom file name
:param chunk_size:
:return: InputFile
... | python | def from_url(cls, url, filename=None, chunk_size=CHUNK_SIZE):
"""
Download file from URL
Manually is not required action. You can send urls instead!
:param url: target URL
:param filename: optional. set custom file name
:param chunk_size:
:return: InputFile
... | [
"def",
"from_url",
"(",
"cls",
",",
"url",
",",
"filename",
"=",
"None",
",",
"chunk_size",
"=",
"CHUNK_SIZE",
")",
":",
"pipe",
"=",
"_WebPipe",
"(",
"url",
",",
"chunk_size",
"=",
"chunk_size",
")",
"if",
"filename",
"is",
"None",
":",
"filename",
"=... | Download file from URL
Manually is not required action. You can send urls instead!
:param url: target URL
:param filename: optional. set custom file name
:param chunk_size:
:return: InputFile | [
"Download",
"file",
"from",
"URL"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/input_file.py#L101-L117 | train |
aiogram/aiogram | aiogram/types/input_file.py | InputFile.save | def save(self, filename, chunk_size=CHUNK_SIZE):
"""
Write file to disk
:param filename:
:param chunk_size:
"""
with open(filename, 'wb') as fp:
while True:
# Chunk writer
data = self.file.read(chunk_size)
if no... | python | def save(self, filename, chunk_size=CHUNK_SIZE):
"""
Write file to disk
:param filename:
:param chunk_size:
"""
with open(filename, 'wb') as fp:
while True:
# Chunk writer
data = self.file.read(chunk_size)
if no... | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"chunk_size",
"=",
"CHUNK_SIZE",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"fp",
":",
"while",
"True",
":",
"# Chunk writer",
"data",
"=",
"self",
".",
"file",
".",
"read",
"(... | Write file to disk
:param filename:
:param chunk_size: | [
"Write",
"file",
"to",
"disk"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/input_file.py#L119-L138 | train |
aiogram/aiogram | aiogram/types/force_reply.py | ForceReply.create | def create(cls, selective: typing.Optional[base.Boolean] = None):
"""
Create new force reply
:param selective:
:return:
"""
return cls(selective=selective) | python | def create(cls, selective: typing.Optional[base.Boolean] = None):
"""
Create new force reply
:param selective:
:return:
"""
return cls(selective=selective) | [
"def",
"create",
"(",
"cls",
",",
"selective",
":",
"typing",
".",
"Optional",
"[",
"base",
".",
"Boolean",
"]",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"selective",
"=",
"selective",
")"
] | Create new force reply
:param selective:
:return: | [
"Create",
"new",
"force",
"reply"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/force_reply.py#L29-L36 | train |
aiogram/aiogram | examples/finite_state_machine_example.py | cancel_handler | async def cancel_handler(message: types.Message, state: FSMContext, raw_state: Optional[str] = None):
"""
Allow user to cancel any action
"""
if raw_state is None:
return
# Cancel state and inform user about it
await state.finish()
# And remove keyboard (just in case)
await mess... | python | async def cancel_handler(message: types.Message, state: FSMContext, raw_state: Optional[str] = None):
"""
Allow user to cancel any action
"""
if raw_state is None:
return
# Cancel state and inform user about it
await state.finish()
# And remove keyboard (just in case)
await mess... | [
"async",
"def",
"cancel_handler",
"(",
"message",
":",
"types",
".",
"Message",
",",
"state",
":",
"FSMContext",
",",
"raw_state",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"if",
"raw_state",
"is",
"None",
":",
"return",
"# Cancel state and ... | Allow user to cancel any action | [
"Allow",
"user",
"to",
"cancel",
"any",
"action"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/finite_state_machine_example.py#L44-L54 | train |
aiogram/aiogram | examples/finite_state_machine_example.py | process_name | async def process_name(message: types.Message, state: FSMContext):
"""
Process user name
"""
async with state.proxy() as data:
data['name'] = message.text
await Form.next()
await message.reply("How old are you?") | python | async def process_name(message: types.Message, state: FSMContext):
"""
Process user name
"""
async with state.proxy() as data:
data['name'] = message.text
await Form.next()
await message.reply("How old are you?") | [
"async",
"def",
"process_name",
"(",
"message",
":",
"types",
".",
"Message",
",",
"state",
":",
"FSMContext",
")",
":",
"async",
"with",
"state",
".",
"proxy",
"(",
")",
"as",
"data",
":",
"data",
"[",
"'name'",
"]",
"=",
"message",
".",
"text",
"aw... | Process user name | [
"Process",
"user",
"name"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/finite_state_machine_example.py#L58-L66 | train |
aiogram/aiogram | examples/middleware_and_antiflood.py | rate_limit | def rate_limit(limit: int, key=None):
"""
Decorator for configuring rate limit and key in different functions.
:param limit:
:param key:
:return:
"""
def decorator(func):
setattr(func, 'throttling_rate_limit', limit)
if key:
setattr(func, 'throttling_key', key)
... | python | def rate_limit(limit: int, key=None):
"""
Decorator for configuring rate limit and key in different functions.
:param limit:
:param key:
:return:
"""
def decorator(func):
setattr(func, 'throttling_rate_limit', limit)
if key:
setattr(func, 'throttling_key', key)
... | [
"def",
"rate_limit",
"(",
"limit",
":",
"int",
",",
"key",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"setattr",
"(",
"func",
",",
"'throttling_rate_limit'",
",",
"limit",
")",
"if",
"key",
":",
"setattr",
"(",
"func",
",",
"'t... | Decorator for configuring rate limit and key in different functions.
:param limit:
:param key:
:return: | [
"Decorator",
"for",
"configuring",
"rate",
"limit",
"and",
"key",
"in",
"different",
"functions",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/middleware_and_antiflood.py#L21-L36 | train |
aiogram/aiogram | examples/middleware_and_antiflood.py | ThrottlingMiddleware.on_process_message | async def on_process_message(self, message: types.Message, data: dict):
"""
This handler is called when dispatcher receives a message
:param message:
"""
# Get current handler
handler = current_handler.get()
# Get dispatcher from context
dispatcher = Dis... | python | async def on_process_message(self, message: types.Message, data: dict):
"""
This handler is called when dispatcher receives a message
:param message:
"""
# Get current handler
handler = current_handler.get()
# Get dispatcher from context
dispatcher = Dis... | [
"async",
"def",
"on_process_message",
"(",
"self",
",",
"message",
":",
"types",
".",
"Message",
",",
"data",
":",
"dict",
")",
":",
"# Get current handler",
"handler",
"=",
"current_handler",
".",
"get",
"(",
")",
"# Get dispatcher from context",
"dispatcher",
... | This handler is called when dispatcher receives a message
:param message: | [
"This",
"handler",
"is",
"called",
"when",
"dispatcher",
"receives",
"a",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/middleware_and_antiflood.py#L49-L76 | train |
aiogram/aiogram | examples/middleware_and_antiflood.py | ThrottlingMiddleware.message_throttled | async def message_throttled(self, message: types.Message, throttled: Throttled):
"""
Notify user only on first exceed and notify about unlocking only on last exceed
:param message:
:param throttled:
"""
handler = current_handler.get()
dispatcher = Dispatcher.get_... | python | async def message_throttled(self, message: types.Message, throttled: Throttled):
"""
Notify user only on first exceed and notify about unlocking only on last exceed
:param message:
:param throttled:
"""
handler = current_handler.get()
dispatcher = Dispatcher.get_... | [
"async",
"def",
"message_throttled",
"(",
"self",
",",
"message",
":",
"types",
".",
"Message",
",",
"throttled",
":",
"Throttled",
")",
":",
"handler",
"=",
"current_handler",
".",
"get",
"(",
")",
"dispatcher",
"=",
"Dispatcher",
".",
"get_current",
"(",
... | Notify user only on first exceed and notify about unlocking only on last exceed
:param message:
:param throttled: | [
"Notify",
"user",
"only",
"on",
"first",
"exceed",
"and",
"notify",
"about",
"unlocking",
"only",
"on",
"last",
"exceed"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/middleware_and_antiflood.py#L78-L107 | train |
aiogram/aiogram | aiogram/utils/auth_widget.py | generate_hash | def generate_hash(data: dict, token: str) -> str:
"""
Generate secret hash
:param data:
:param token:
:return:
"""
secret = hashlib.sha256()
secret.update(token.encode('utf-8'))
sorted_params = collections.OrderedDict(sorted(data.items()))
msg = '\n'.join("{}={}".format(k, v) fo... | python | def generate_hash(data: dict, token: str) -> str:
"""
Generate secret hash
:param data:
:param token:
:return:
"""
secret = hashlib.sha256()
secret.update(token.encode('utf-8'))
sorted_params = collections.OrderedDict(sorted(data.items()))
msg = '\n'.join("{}={}".format(k, v) fo... | [
"def",
"generate_hash",
"(",
"data",
":",
"dict",
",",
"token",
":",
"str",
")",
"->",
"str",
":",
"secret",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"secret",
".",
"update",
"(",
"token",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"sorted_params",
"="... | Generate secret hash
:param data:
:param token:
:return: | [
"Generate",
"secret",
"hash"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/auth_widget.py#L12-L24 | train |
aiogram/aiogram | aiogram/utils/auth_widget.py | check_token | def check_token(data: dict, token: str) -> bool:
"""
Validate auth token
:param data:
:param token:
:return:
"""
param_hash = data.get('hash', '') or ''
return param_hash == generate_hash(data, token) | python | def check_token(data: dict, token: str) -> bool:
"""
Validate auth token
:param data:
:param token:
:return:
"""
param_hash = data.get('hash', '') or ''
return param_hash == generate_hash(data, token) | [
"def",
"check_token",
"(",
"data",
":",
"dict",
",",
"token",
":",
"str",
")",
"->",
"bool",
":",
"param_hash",
"=",
"data",
".",
"get",
"(",
"'hash'",
",",
"''",
")",
"or",
"''",
"return",
"param_hash",
"==",
"generate_hash",
"(",
"data",
",",
"toke... | Validate auth token
:param data:
:param token:
:return: | [
"Validate",
"auth",
"token"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/auth_widget.py#L27-L36 | train |
aiogram/aiogram | aiogram/dispatcher/filters/factory.py | FiltersFactory.resolve | def resolve(self, event_handler, *custom_filters, **full_config
) -> typing.List[typing.Union[typing.Callable, AbstractFilter]]:
"""
Resolve filters to filters-set
:param event_handler:
:param custom_filters:
:param full_config:
:return:
"""
... | python | def resolve(self, event_handler, *custom_filters, **full_config
) -> typing.List[typing.Union[typing.Callable, AbstractFilter]]:
"""
Resolve filters to filters-set
:param event_handler:
:param custom_filters:
:param full_config:
:return:
"""
... | [
"def",
"resolve",
"(",
"self",
",",
"event_handler",
",",
"*",
"custom_filters",
",",
"*",
"*",
"full_config",
")",
"->",
"typing",
".",
"List",
"[",
"typing",
".",
"Union",
"[",
"typing",
".",
"Callable",
",",
"AbstractFilter",
"]",
"]",
":",
"filters_s... | Resolve filters to filters-set
:param event_handler:
:param custom_filters:
:param full_config:
:return: | [
"Resolve",
"filters",
"to",
"filters",
"-",
"set"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/factory.py#L41-L57 | train |
aiogram/aiogram | aiogram/dispatcher/filters/factory.py | FiltersFactory._resolve_registered | def _resolve_registered(self, event_handler, full_config) -> typing.Generator:
"""
Resolve registered filters
:param event_handler:
:param full_config:
:return:
"""
for record in self._registered:
filter_ = record.resolve(self._dispatcher, event_handl... | python | def _resolve_registered(self, event_handler, full_config) -> typing.Generator:
"""
Resolve registered filters
:param event_handler:
:param full_config:
:return:
"""
for record in self._registered:
filter_ = record.resolve(self._dispatcher, event_handl... | [
"def",
"_resolve_registered",
"(",
"self",
",",
"event_handler",
",",
"full_config",
")",
"->",
"typing",
".",
"Generator",
":",
"for",
"record",
"in",
"self",
".",
"_registered",
":",
"filter_",
"=",
"record",
".",
"resolve",
"(",
"self",
".",
"_dispatcher"... | Resolve registered filters
:param event_handler:
:param full_config:
:return: | [
"Resolve",
"registered",
"filters"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/factory.py#L59-L73 | train |
aiogram/aiogram | aiogram/types/auth_widget_data.py | AuthWidgetData.parse | def parse(cls, request: web.Request) -> AuthWidgetData:
"""
Parse request as Telegram auth widget data.
:param request:
:return: :obj:`AuthWidgetData`
:raise: :obj:`aiohttp.web.HTTPBadRequest`
"""
try:
query = dict(request.query)
query['id... | python | def parse(cls, request: web.Request) -> AuthWidgetData:
"""
Parse request as Telegram auth widget data.
:param request:
:return: :obj:`AuthWidgetData`
:raise: :obj:`aiohttp.web.HTTPBadRequest`
"""
try:
query = dict(request.query)
query['id... | [
"def",
"parse",
"(",
"cls",
",",
"request",
":",
"web",
".",
"Request",
")",
"->",
"AuthWidgetData",
":",
"try",
":",
"query",
"=",
"dict",
"(",
"request",
".",
"query",
")",
"query",
"[",
"'id'",
"]",
"=",
"int",
"(",
"query",
"[",
"'id'",
"]",
... | Parse request as Telegram auth widget data.
:param request:
:return: :obj:`AuthWidgetData`
:raise: :obj:`aiohttp.web.HTTPBadRequest` | [
"Parse",
"request",
"as",
"Telegram",
"auth",
"widget",
"data",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/auth_widget_data.py#L19-L35 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | _check_ip | def _check_ip(ip: str) -> bool:
"""
Check IP in range
:param ip:
:return:
"""
address = ipaddress.IPv4Address(ip)
return address in allowed_ips | python | def _check_ip(ip: str) -> bool:
"""
Check IP in range
:param ip:
:return:
"""
address = ipaddress.IPv4Address(ip)
return address in allowed_ips | [
"def",
"_check_ip",
"(",
"ip",
":",
"str",
")",
"->",
"bool",
":",
"address",
"=",
"ipaddress",
".",
"IPv4Address",
"(",
"ip",
")",
"return",
"address",
"in",
"allowed_ips"
] | Check IP in range
:param ip:
:return: | [
"Check",
"IP",
"in",
"range"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L39-L47 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | allow_ip | def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]):
"""
Allow ip address.
:param ips:
:return:
"""
for ip in ips:
if isinstance(ip, ipaddress.IPv4Address):
allowed_ips.add(ip)
elif isinstance(ip, str):
allowed_ips.add(ipad... | python | def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]):
"""
Allow ip address.
:param ips:
:return:
"""
for ip in ips:
if isinstance(ip, ipaddress.IPv4Address):
allowed_ips.add(ip)
elif isinstance(ip, str):
allowed_ips.add(ipad... | [
"def",
"allow_ip",
"(",
"*",
"ips",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"ipaddress",
".",
"IPv4Network",
",",
"ipaddress",
".",
"IPv4Address",
"]",
")",
":",
"for",
"ip",
"in",
"ips",
":",
"if",
"isinstance",
"(",
"ip",
",",
"ipaddress",
".... | Allow ip address.
:param ips:
:return: | [
"Allow",
"ip",
"address",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L50-L65 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | configure_app | def configure_app(dispatcher, app: web.Application, path=DEFAULT_WEB_PATH, route_name=DEFAULT_ROUTE_NAME):
"""
You can prepare web.Application for working with webhook handler.
:param dispatcher: Dispatcher instance
:param app: :class:`aiohttp.web.Application`
:param path: Path to your webhook.
... | python | def configure_app(dispatcher, app: web.Application, path=DEFAULT_WEB_PATH, route_name=DEFAULT_ROUTE_NAME):
"""
You can prepare web.Application for working with webhook handler.
:param dispatcher: Dispatcher instance
:param app: :class:`aiohttp.web.Application`
:param path: Path to your webhook.
... | [
"def",
"configure_app",
"(",
"dispatcher",
",",
"app",
":",
"web",
".",
"Application",
",",
"path",
"=",
"DEFAULT_WEB_PATH",
",",
"route_name",
"=",
"DEFAULT_ROUTE_NAME",
")",
":",
"app",
".",
"router",
".",
"add_route",
"(",
"'*'",
",",
"path",
",",
"Webh... | You can prepare web.Application for working with webhook handler.
:param dispatcher: Dispatcher instance
:param app: :class:`aiohttp.web.Application`
:param path: Path to your webhook.
:param route_name: Name of webhook handler route
:return: | [
"You",
"can",
"prepare",
"web",
".",
"Application",
"for",
"working",
"with",
"webhook",
"handler",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L278-L289 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.get_dispatcher | def get_dispatcher(self):
"""
Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher`
"""
dp = self.request.app[BOT_DISPATCHER_KEY]
try:
from aiogram import Bot, Dispatcher
Dispatcher.set_current(dp)
Bot.set_curre... | python | def get_dispatcher(self):
"""
Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher`
"""
dp = self.request.app[BOT_DISPATCHER_KEY]
try:
from aiogram import Bot, Dispatcher
Dispatcher.set_current(dp)
Bot.set_curre... | [
"def",
"get_dispatcher",
"(",
"self",
")",
":",
"dp",
"=",
"self",
".",
"request",
".",
"app",
"[",
"BOT_DISPATCHER_KEY",
"]",
"try",
":",
"from",
"aiogram",
"import",
"Bot",
",",
"Dispatcher",
"Dispatcher",
".",
"set_current",
"(",
"dp",
")",
"Bot",
"."... | Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher` | [
"Get",
"Dispatcher",
"instance",
"from",
"environment"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L93-L106 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.parse_update | async def parse_update(self, bot):
"""
Read update from stream and deserialize it.
:param bot: bot instance. You an get it from Dispatcher
:return: :class:`aiogram.types.Update`
"""
data = await self.request.json()
update = types.Update(**data)
return upd... | python | async def parse_update(self, bot):
"""
Read update from stream and deserialize it.
:param bot: bot instance. You an get it from Dispatcher
:return: :class:`aiogram.types.Update`
"""
data = await self.request.json()
update = types.Update(**data)
return upd... | [
"async",
"def",
"parse_update",
"(",
"self",
",",
"bot",
")",
":",
"data",
"=",
"await",
"self",
".",
"request",
".",
"json",
"(",
")",
"update",
"=",
"types",
".",
"Update",
"(",
"*",
"*",
"data",
")",
"return",
"update"
] | Read update from stream and deserialize it.
:param bot: bot instance. You an get it from Dispatcher
:return: :class:`aiogram.types.Update` | [
"Read",
"update",
"from",
"stream",
"and",
"deserialize",
"it",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L108-L117 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.post | async def post(self):
"""
Process POST request
if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook.
Otherwise do nothing (return 'ok')
:return: :class:`aiohttp.web.Response`
"""
self.validate_ip()
... | python | async def post(self):
"""
Process POST request
if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook.
Otherwise do nothing (return 'ok')
:return: :class:`aiohttp.web.Response`
"""
self.validate_ip()
... | [
"async",
"def",
"post",
"(",
"self",
")",
":",
"self",
".",
"validate_ip",
"(",
")",
"# context.update_state({'CALLER': WEBHOOK,",
"# WEBHOOK_CONNECTION: True,",
"# WEBHOOK_REQUEST: self.request})",
"dispatcher",
"=",
"self",
".",
"ge... | Process POST request
if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook.
Otherwise do nothing (return 'ok')
:return: :class:`aiohttp.web.Response` | [
"Process",
"POST",
"request"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L119-L148 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.process_update | async def process_update(self, update):
"""
Need respond in less than 60 seconds in to webhook.
So... If you respond greater than 55 seconds webhook automatically respond 'ok'
and execute callback response via simple HTTP request.
:param update:
:return:
"""
... | python | async def process_update(self, update):
"""
Need respond in less than 60 seconds in to webhook.
So... If you respond greater than 55 seconds webhook automatically respond 'ok'
and execute callback response via simple HTTP request.
:param update:
:return:
"""
... | [
"async",
"def",
"process_update",
"(",
"self",
",",
"update",
")",
":",
"dispatcher",
"=",
"self",
".",
"get_dispatcher",
"(",
")",
"loop",
"=",
"dispatcher",
".",
"loop",
"# Analog of `asyncio.wait_for` but without cancelling task",
"waiter",
"=",
"loop",
".",
"c... | Need respond in less than 60 seconds in to webhook.
So... If you respond greater than 55 seconds webhook automatically respond 'ok'
and execute callback response via simple HTTP request.
:param update:
:return: | [
"Need",
"respond",
"in",
"less",
"than",
"60",
"seconds",
"in",
"to",
"webhook",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L158-L194 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.respond_via_request | def respond_via_request(self, task):
"""
Handle response after 55 second.
:param task:
:return:
"""
warn(f"Detected slow response into webhook. "
f"(Greater than {RESPONSE_TIMEOUT} seconds)\n"
f"Recommended to use 'async_task' decorator from Dis... | python | def respond_via_request(self, task):
"""
Handle response after 55 second.
:param task:
:return:
"""
warn(f"Detected slow response into webhook. "
f"(Greater than {RESPONSE_TIMEOUT} seconds)\n"
f"Recommended to use 'async_task' decorator from Dis... | [
"def",
"respond_via_request",
"(",
"self",
",",
"task",
")",
":",
"warn",
"(",
"f\"Detected slow response into webhook. \"",
"f\"(Greater than {RESPONSE_TIMEOUT} seconds)\\n\"",
"f\"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.\"",
",",
"Timeou... | Handle response after 55 second.
:param task:
:return: | [
"Handle",
"response",
"after",
"55",
"second",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L196-L219 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.get_response | def get_response(self, results):
"""
Get response object from results.
:param results: list
:return:
"""
if results is None:
return None
for result in itertools.chain.from_iterable(results):
if isinstance(result, BaseResponse):
... | python | def get_response(self, results):
"""
Get response object from results.
:param results: list
:return:
"""
if results is None:
return None
for result in itertools.chain.from_iterable(results):
if isinstance(result, BaseResponse):
... | [
"def",
"get_response",
"(",
"self",
",",
"results",
")",
":",
"if",
"results",
"is",
"None",
":",
"return",
"None",
"for",
"result",
"in",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"results",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
... | Get response object from results.
:param results: list
:return: | [
"Get",
"response",
"object",
"from",
"results",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L221-L232 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.check_ip | def check_ip(self):
"""
Check client IP. Accept requests only from telegram servers.
:return:
"""
# For reverse proxy (nginx)
forwarded_for = self.request.headers.get('X-Forwarded-For', None)
if forwarded_for:
return forwarded_for, _check_ip(forwarded... | python | def check_ip(self):
"""
Check client IP. Accept requests only from telegram servers.
:return:
"""
# For reverse proxy (nginx)
forwarded_for = self.request.headers.get('X-Forwarded-For', None)
if forwarded_for:
return forwarded_for, _check_ip(forwarded... | [
"def",
"check_ip",
"(",
"self",
")",
":",
"# For reverse proxy (nginx)",
"forwarded_for",
"=",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'X-Forwarded-For'",
",",
"None",
")",
"if",
"forwarded_for",
":",
"return",
"forwarded_for",
",",
"_check_ip"... | Check client IP. Accept requests only from telegram servers.
:return: | [
"Check",
"client",
"IP",
".",
"Accept",
"requests",
"only",
"from",
"telegram",
"servers",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L234-L252 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | WebhookRequestHandler.validate_ip | def validate_ip(self):
"""
Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts.
"""
if self.request.app.get('_check_ip', False):
ip_address, accept = self.check_ip()
if not accept:
raise web.HTTPUnauthorized() | python | def validate_ip(self):
"""
Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts.
"""
if self.request.app.get('_check_ip', False):
ip_address, accept = self.check_ip()
if not accept:
raise web.HTTPUnauthorized() | [
"def",
"validate_ip",
"(",
"self",
")",
":",
"if",
"self",
".",
"request",
".",
"app",
".",
"get",
"(",
"'_check_ip'",
",",
"False",
")",
":",
"ip_address",
",",
"accept",
"=",
"self",
".",
"check_ip",
"(",
")",
"if",
"not",
"accept",
":",
"raise",
... | Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts. | [
"Check",
"ip",
"if",
"that",
"is",
"needed",
".",
"Raise",
"web",
".",
"HTTPUnauthorized",
"for",
"not",
"allowed",
"hosts",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L254-L261 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | BaseResponse.cleanup | def cleanup(self) -> typing.Dict:
"""
Cleanup response after preparing. Remove empty fields.
:return: response parameters dict
"""
return {k: v for k, v in self.prepare().items() if v is not None} | python | def cleanup(self) -> typing.Dict:
"""
Cleanup response after preparing. Remove empty fields.
:return: response parameters dict
"""
return {k: v for k, v in self.prepare().items() if v is not None} | [
"def",
"cleanup",
"(",
"self",
")",
"->",
"typing",
".",
"Dict",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"prepare",
"(",
")",
".",
"items",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"}"
] | Cleanup response after preparing. Remove empty fields.
:return: response parameters dict | [
"Cleanup",
"response",
"after",
"preparing",
".",
"Remove",
"empty",
"fields",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L327-L333 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | BaseResponse.execute_response | async def execute_response(self, bot):
"""
Use this method if you want to execute response as simple HTTP request.
:param bot: Bot instance.
:return:
"""
method_name = helper.HelperMode.apply(self.method, helper.HelperMode.snake_case)
method = getattr(bot, method... | python | async def execute_response(self, bot):
"""
Use this method if you want to execute response as simple HTTP request.
:param bot: Bot instance.
:return:
"""
method_name = helper.HelperMode.apply(self.method, helper.HelperMode.snake_case)
method = getattr(bot, method... | [
"async",
"def",
"execute_response",
"(",
"self",
",",
"bot",
")",
":",
"method_name",
"=",
"helper",
".",
"HelperMode",
".",
"apply",
"(",
"self",
".",
"method",
",",
"helper",
".",
"HelperMode",
".",
"snake_case",
")",
"method",
"=",
"getattr",
"(",
"bo... | Use this method if you want to execute response as simple HTTP request.
:param bot: Bot instance.
:return: | [
"Use",
"this",
"method",
"if",
"you",
"want",
"to",
"execute",
"response",
"as",
"simple",
"HTTP",
"request",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L351-L362 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | ReplyToMixin.reply | def reply(self, message: typing.Union[int, types.Message]):
"""
Reply to message
:param message: :obj:`int` or :obj:`types.Message`
:return: self
"""
setattr(self, 'reply_to_message_id', message.message_id if isinstance(message, types.Message) else message)
retu... | python | def reply(self, message: typing.Union[int, types.Message]):
"""
Reply to message
:param message: :obj:`int` or :obj:`types.Message`
:return: self
"""
setattr(self, 'reply_to_message_id', message.message_id if isinstance(message, types.Message) else message)
retu... | [
"def",
"reply",
"(",
"self",
",",
"message",
":",
"typing",
".",
"Union",
"[",
"int",
",",
"types",
".",
"Message",
"]",
")",
":",
"setattr",
"(",
"self",
",",
"'reply_to_message_id'",
",",
"message",
".",
"message_id",
"if",
"isinstance",
"(",
"message"... | Reply to message
:param message: :obj:`int` or :obj:`types.Message`
:return: self | [
"Reply",
"to",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L382-L390 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | ReplyToMixin.to | def to(self, target: typing.Union[types.Message, types.Chat, types.base.Integer, types.base.String]):
"""
Send to chat
:param target: message or chat or id
:return:
"""
if isinstance(target, types.Message):
chat_id = target.chat.id
elif isinstance(tar... | python | def to(self, target: typing.Union[types.Message, types.Chat, types.base.Integer, types.base.String]):
"""
Send to chat
:param target: message or chat or id
:return:
"""
if isinstance(target, types.Message):
chat_id = target.chat.id
elif isinstance(tar... | [
"def",
"to",
"(",
"self",
",",
"target",
":",
"typing",
".",
"Union",
"[",
"types",
".",
"Message",
",",
"types",
".",
"Chat",
",",
"types",
".",
"base",
".",
"Integer",
",",
"types",
".",
"base",
".",
"String",
"]",
")",
":",
"if",
"isinstance",
... | Send to chat
:param target: message or chat or id
:return: | [
"Send",
"to",
"chat"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L392-L409 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | SendMessage.write | def write(self, *text, sep=' '):
"""
Write text to response
:param text:
:param sep:
:return:
"""
self.text += markdown.text(*text, sep)
return self | python | def write(self, *text, sep=' '):
"""
Write text to response
:param text:
:param sep:
:return:
"""
self.text += markdown.text(*text, sep)
return self | [
"def",
"write",
"(",
"self",
",",
"*",
"text",
",",
"sep",
"=",
"' '",
")",
":",
"self",
".",
"text",
"+=",
"markdown",
".",
"text",
"(",
"*",
"text",
",",
"sep",
")",
"return",
"self"
] | Write text to response
:param text:
:param sep:
:return: | [
"Write",
"text",
"to",
"response"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L524-L533 | train |
aiogram/aiogram | aiogram/dispatcher/webhook.py | ForwardMessage.message | def message(self, message: types.Message):
"""
Select target message
:param message:
:return:
"""
setattr(self, 'from_chat_id', message.chat.id)
setattr(self, 'message_id', message.message_id)
return self | python | def message(self, message: types.Message):
"""
Select target message
:param message:
:return:
"""
setattr(self, 'from_chat_id', message.chat.id)
setattr(self, 'message_id', message.message_id)
return self | [
"def",
"message",
"(",
"self",
",",
"message",
":",
"types",
".",
"Message",
")",
":",
"setattr",
"(",
"self",
",",
"'from_chat_id'",
",",
"message",
".",
"chat",
".",
"id",
")",
"setattr",
"(",
"self",
",",
"'message_id'",
",",
"message",
".",
"messag... | Select target message
:param message:
:return: | [
"Select",
"target",
"message"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L575-L584 | train |
aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.check_address | def check_address(cls, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> (typing.Union[str, int], typing.Union[str, int]):
"""
In all storage's methods chat or user is always required.
If one of them is not pro... | python | def check_address(cls, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None) -> (typing.Union[str, int], typing.Union[str, int]):
"""
In all storage's methods chat or user is always required.
If one of them is not pro... | [
"def",
"check_address",
"(",
"cls",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
")",... | In all storage's methods chat or user is always required.
If one of them is not provided, you have to set missing value based on the provided one.
This method performs the check described above.
:param chat:
:param user:
:return: | [
"In",
"all",
"storage",
"s",
"methods",
"chat",
"or",
"user",
"is",
"always",
"required",
".",
"If",
"one",
"of",
"them",
"is",
"not",
"provided",
"you",
"have",
"to",
"set",
"missing",
"value",
"based",
"on",
"the",
"provided",
"one",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L41-L61 | train |
aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.get_data | async def get_data(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
default: typing.Optional[typing.Dict] = None) -> typing.Dict:
"""
Get state-data for user in chat. Return `default` if no... | python | async def get_data(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
default: typing.Optional[typing.Dict] = None) -> typing.Dict:
"""
Get state-data for user in chat. Return `default` if no... | [
"async",
"def",
"get_data",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",... | Get state-data for user in chat. Return `default` if no data is provided in storage.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param default:
:return: | [
"Get",
"state",
"-",
"data",
"for",
"user",
"in",
"chat",
".",
"Return",
"default",
"if",
"no",
"data",
"is",
"provided",
"in",
"storage",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L80-L95 | train |
aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.update_data | async def update_data(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
data: typing.Dict = None,
**kwargs):
"""
Update data for user in chat
You ... | python | async def update_data(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
data: typing.Dict = None,
**kwargs):
"""
Update data for user in chat
You ... | [
"async",
"def",
"update_data",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"Non... | Update data for user in chat
You can use data parameter or|and kwargs.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param data:
:param chat:
:param user:
:param kwargs:
:retur... | [
"Update",
"data",
"for",
"user",
"in",
"chat"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L129-L148 | train |
aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.reset_state | async def reset_state(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
with_data: typing.Optional[bool] = True):
"""
Reset state for user in chat.
You may desire to use thi... | python | async def reset_state(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
with_data: typing.Optional[bool] = True):
"""
Reset state for user in chat.
You may desire to use thi... | [
"async",
"def",
"reset_state",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"Non... | Reset state for user in chat.
You may desire to use this method when finishing conversations.
Chat or user is always required. If one of this is not presented,
you have to set missing value based on the provided one.
:param chat:
:param user:
:param with_data:
:... | [
"Reset",
"state",
"for",
"user",
"in",
"chat",
".",
"You",
"may",
"desire",
"to",
"use",
"this",
"method",
"when",
"finishing",
"conversations",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L165-L184 | train |
aiogram/aiogram | aiogram/dispatcher/storage.py | BaseStorage.finish | async def finish(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None):
"""
Finish conversation for user in chat.
Chat or user is always required. If one of them is not provided,
you have to set missing v... | python | async def finish(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None):
"""
Finish conversation for user in chat.
Chat or user is always required. If one of them is not provided,
you have to set missing v... | [
"async",
"def",
"finish",
"(",
"self",
",",
"*",
",",
"chat",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
",",
"user",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
",",
"None",
"]",
"=",
"None",
... | Finish conversation for user in chat.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param chat:
:param user:
:return: | [
"Finish",
"conversation",
"for",
"user",
"in",
"chat",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/storage.py#L186-L199 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.