id
int32 0
252k
| 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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
5,800 | tyarkoni/pliers | pliers/diagnostics/diagnostics.py | correlation_matrix | def correlation_matrix(df):
'''
Returns a pandas DataFrame with the pair-wise correlations of the columns.
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
columns = df.columns.tolist()
corr = pd.DataFrame(
np.corrcoef(df, rowvar=0), columns=columns, index=columns)
return corr | python | def correlation_matrix(df):
'''
Returns a pandas DataFrame with the pair-wise correlations of the columns.
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
columns = df.columns.tolist()
corr = pd.DataFrame(
np.corrcoef(df, rowvar=0), columns=columns, index=columns)
return corr | [
"def",
"correlation_matrix",
"(",
"df",
")",
":",
"columns",
"=",
"df",
".",
"columns",
".",
"tolist",
"(",
")",
"corr",
"=",
"pd",
".",
"DataFrame",
"(",
"np",
".",
"corrcoef",
"(",
"df",
",",
"rowvar",
"=",
"0",
")",
",",
"columns",
"=",
"columns",
",",
"index",
"=",
"columns",
")",
"return",
"corr"
] | Returns a pandas DataFrame with the pair-wise correlations of the columns.
Args:
df: pandas DataFrame with columns to run diagnostics on | [
"Returns",
"a",
"pandas",
"DataFrame",
"with",
"the",
"pair",
"-",
"wise",
"correlations",
"of",
"the",
"columns",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/diagnostics/diagnostics.py#L12-L22 |
5,801 | tyarkoni/pliers | pliers/diagnostics/diagnostics.py | eigenvalues | def eigenvalues(df):
'''
Returns a pandas Series with eigenvalues of the correlation matrix.
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
corr = np.corrcoef(df, rowvar=0)
eigvals = np.linalg.eigvals(corr)
return pd.Series(eigvals, df.columns, name='Eigenvalue') | python | def eigenvalues(df):
'''
Returns a pandas Series with eigenvalues of the correlation matrix.
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
corr = np.corrcoef(df, rowvar=0)
eigvals = np.linalg.eigvals(corr)
return pd.Series(eigvals, df.columns, name='Eigenvalue') | [
"def",
"eigenvalues",
"(",
"df",
")",
":",
"corr",
"=",
"np",
".",
"corrcoef",
"(",
"df",
",",
"rowvar",
"=",
"0",
")",
"eigvals",
"=",
"np",
".",
"linalg",
".",
"eigvals",
"(",
"corr",
")",
"return",
"pd",
".",
"Series",
"(",
"eigvals",
",",
"df",
".",
"columns",
",",
"name",
"=",
"'Eigenvalue'",
")"
] | Returns a pandas Series with eigenvalues of the correlation matrix.
Args:
df: pandas DataFrame with columns to run diagnostics on | [
"Returns",
"a",
"pandas",
"Series",
"with",
"eigenvalues",
"of",
"the",
"correlation",
"matrix",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/diagnostics/diagnostics.py#L25-L34 |
5,802 | tyarkoni/pliers | pliers/diagnostics/diagnostics.py | condition_indices | def condition_indices(df):
'''
Returns a pandas Series with condition indices of the df columns.
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
eigvals = eigenvalues(df)
cond_idx = np.sqrt(eigvals.max() / eigvals)
return pd.Series(cond_idx, df.columns, name='Condition index') | python | def condition_indices(df):
'''
Returns a pandas Series with condition indices of the df columns.
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
eigvals = eigenvalues(df)
cond_idx = np.sqrt(eigvals.max() / eigvals)
return pd.Series(cond_idx, df.columns, name='Condition index') | [
"def",
"condition_indices",
"(",
"df",
")",
":",
"eigvals",
"=",
"eigenvalues",
"(",
"df",
")",
"cond_idx",
"=",
"np",
".",
"sqrt",
"(",
"eigvals",
".",
"max",
"(",
")",
"/",
"eigvals",
")",
"return",
"pd",
".",
"Series",
"(",
"cond_idx",
",",
"df",
".",
"columns",
",",
"name",
"=",
"'Condition index'",
")"
] | Returns a pandas Series with condition indices of the df columns.
Args:
df: pandas DataFrame with columns to run diagnostics on | [
"Returns",
"a",
"pandas",
"Series",
"with",
"condition",
"indices",
"of",
"the",
"df",
"columns",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/diagnostics/diagnostics.py#L37-L46 |
5,803 | tyarkoni/pliers | pliers/diagnostics/diagnostics.py | mahalanobis_distances | def mahalanobis_distances(df, axis=0):
'''
Returns a pandas Series with Mahalanobis distances for each sample on the
axis.
Note: does not work well when # of observations < # of dimensions
Will either return NaN in answer
or (in the extreme case) fail with a Singular Matrix LinAlgError
Args:
df: pandas DataFrame with columns to run diagnostics on
axis: 0 to find outlier rows, 1 to find outlier columns
'''
df = df.transpose() if axis == 1 else df
means = df.mean()
try:
inv_cov = np.linalg.inv(df.cov())
except LinAlgError:
return pd.Series([np.NAN] * len(df.index), df.index,
name='Mahalanobis')
dists = []
for i, sample in df.iterrows():
dists.append(mahalanobis(sample, means, inv_cov))
return pd.Series(dists, df.index, name='Mahalanobis') | python | def mahalanobis_distances(df, axis=0):
'''
Returns a pandas Series with Mahalanobis distances for each sample on the
axis.
Note: does not work well when # of observations < # of dimensions
Will either return NaN in answer
or (in the extreme case) fail with a Singular Matrix LinAlgError
Args:
df: pandas DataFrame with columns to run diagnostics on
axis: 0 to find outlier rows, 1 to find outlier columns
'''
df = df.transpose() if axis == 1 else df
means = df.mean()
try:
inv_cov = np.linalg.inv(df.cov())
except LinAlgError:
return pd.Series([np.NAN] * len(df.index), df.index,
name='Mahalanobis')
dists = []
for i, sample in df.iterrows():
dists.append(mahalanobis(sample, means, inv_cov))
return pd.Series(dists, df.index, name='Mahalanobis') | [
"def",
"mahalanobis_distances",
"(",
"df",
",",
"axis",
"=",
"0",
")",
":",
"df",
"=",
"df",
".",
"transpose",
"(",
")",
"if",
"axis",
"==",
"1",
"else",
"df",
"means",
"=",
"df",
".",
"mean",
"(",
")",
"try",
":",
"inv_cov",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"df",
".",
"cov",
"(",
")",
")",
"except",
"LinAlgError",
":",
"return",
"pd",
".",
"Series",
"(",
"[",
"np",
".",
"NAN",
"]",
"*",
"len",
"(",
"df",
".",
"index",
")",
",",
"df",
".",
"index",
",",
"name",
"=",
"'Mahalanobis'",
")",
"dists",
"=",
"[",
"]",
"for",
"i",
",",
"sample",
"in",
"df",
".",
"iterrows",
"(",
")",
":",
"dists",
".",
"append",
"(",
"mahalanobis",
"(",
"sample",
",",
"means",
",",
"inv_cov",
")",
")",
"return",
"pd",
".",
"Series",
"(",
"dists",
",",
"df",
".",
"index",
",",
"name",
"=",
"'Mahalanobis'",
")"
] | Returns a pandas Series with Mahalanobis distances for each sample on the
axis.
Note: does not work well when # of observations < # of dimensions
Will either return NaN in answer
or (in the extreme case) fail with a Singular Matrix LinAlgError
Args:
df: pandas DataFrame with columns to run diagnostics on
axis: 0 to find outlier rows, 1 to find outlier columns | [
"Returns",
"a",
"pandas",
"Series",
"with",
"Mahalanobis",
"distances",
"for",
"each",
"sample",
"on",
"the",
"axis",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/diagnostics/diagnostics.py#L63-L87 |
5,804 | tyarkoni/pliers | pliers/diagnostics/diagnostics.py | Diagnostics.summary | def summary(self, stdout=True, plot=False):
'''
Displays diagnostics to the user
Args:
stdout (bool): print results to the console
plot (bool): use Seaborn to plot results
'''
if stdout:
print('Collinearity summary:')
print(pd.concat([self.results['Eigenvalues'],
self.results['ConditionIndices'],
self.results['VIFs'],
self.results['CorrelationMatrix']],
axis=1))
print('Outlier summary:')
print(self.results['RowMahalanobisDistances'])
print(self.results['ColumnMahalanobisDistances'])
print('Validity summary:')
print(self.results['Variances'])
if plot:
verify_dependencies('seaborn')
for key, result in self.results.items():
if key == 'CorrelationMatrix':
ax = plt.axes()
sns.heatmap(result, cmap='Blues', ax=ax)
ax.set_title(key)
sns.plt.show()
else:
result.plot(kind='bar', title=key)
plt.show() | python | def summary(self, stdout=True, plot=False):
'''
Displays diagnostics to the user
Args:
stdout (bool): print results to the console
plot (bool): use Seaborn to plot results
'''
if stdout:
print('Collinearity summary:')
print(pd.concat([self.results['Eigenvalues'],
self.results['ConditionIndices'],
self.results['VIFs'],
self.results['CorrelationMatrix']],
axis=1))
print('Outlier summary:')
print(self.results['RowMahalanobisDistances'])
print(self.results['ColumnMahalanobisDistances'])
print('Validity summary:')
print(self.results['Variances'])
if plot:
verify_dependencies('seaborn')
for key, result in self.results.items():
if key == 'CorrelationMatrix':
ax = plt.axes()
sns.heatmap(result, cmap='Blues', ax=ax)
ax.set_title(key)
sns.plt.show()
else:
result.plot(kind='bar', title=key)
plt.show() | [
"def",
"summary",
"(",
"self",
",",
"stdout",
"=",
"True",
",",
"plot",
"=",
"False",
")",
":",
"if",
"stdout",
":",
"print",
"(",
"'Collinearity summary:'",
")",
"print",
"(",
"pd",
".",
"concat",
"(",
"[",
"self",
".",
"results",
"[",
"'Eigenvalues'",
"]",
",",
"self",
".",
"results",
"[",
"'ConditionIndices'",
"]",
",",
"self",
".",
"results",
"[",
"'VIFs'",
"]",
",",
"self",
".",
"results",
"[",
"'CorrelationMatrix'",
"]",
"]",
",",
"axis",
"=",
"1",
")",
")",
"print",
"(",
"'Outlier summary:'",
")",
"print",
"(",
"self",
".",
"results",
"[",
"'RowMahalanobisDistances'",
"]",
")",
"print",
"(",
"self",
".",
"results",
"[",
"'ColumnMahalanobisDistances'",
"]",
")",
"print",
"(",
"'Validity summary:'",
")",
"print",
"(",
"self",
".",
"results",
"[",
"'Variances'",
"]",
")",
"if",
"plot",
":",
"verify_dependencies",
"(",
"'seaborn'",
")",
"for",
"key",
",",
"result",
"in",
"self",
".",
"results",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"'CorrelationMatrix'",
":",
"ax",
"=",
"plt",
".",
"axes",
"(",
")",
"sns",
".",
"heatmap",
"(",
"result",
",",
"cmap",
"=",
"'Blues'",
",",
"ax",
"=",
"ax",
")",
"ax",
".",
"set_title",
"(",
"key",
")",
"sns",
".",
"plt",
".",
"show",
"(",
")",
"else",
":",
"result",
".",
"plot",
"(",
"kind",
"=",
"'bar'",
",",
"title",
"=",
"key",
")",
"plt",
".",
"show",
"(",
")"
] | Displays diagnostics to the user
Args:
stdout (bool): print results to the console
plot (bool): use Seaborn to plot results | [
"Displays",
"diagnostics",
"to",
"the",
"user"
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/diagnostics/diagnostics.py#L128-L161 |
5,805 | tyarkoni/pliers | pliers/graph.py | Graph.add_nodes | def add_nodes(self, nodes, parent=None, mode='horizontal'):
''' Adds one or more nodes to the current graph.
Args:
nodes (list): A list of nodes to add. Each element must be one of
the following:
* A dict containing keyword args to pass onto to the Node init.
* An iterable containing 1 - 3 elements. The first element is
mandatory, and specifies the Transformer at that node. The
second element (optional) is an iterable of child nodes
(specified in the same format). The third element
(optional) is a string giving the (unique) name of the
node.
* A Node instance.
* A Transformer instance.
parent (Node): Optional parent node (i.e., the node containing the
pliers Transformer from which the to-be-created nodes receive
their inputs).
mode (str): Indicates the direction with which to add the new nodes
* horizontal: the nodes should each be added as a child of the
'parent' argument (or a Graph root by default).
* vertical: the nodes should each be added in sequence with
the first node being the child of the 'parnet' argument
(a Graph root by default) and each subsequent node being
the child of the previous node in the list.
'''
for n in nodes:
node_args = self._parse_node_args(n)
if mode == 'horizontal':
self.add_node(parent=parent, **node_args)
elif mode == 'vertical':
parent = self.add_node(parent=parent, return_node=True,
**node_args)
else:
raise ValueError("Invalid mode for adding nodes to a graph:"
"%s" % mode) | python | def add_nodes(self, nodes, parent=None, mode='horizontal'):
''' Adds one or more nodes to the current graph.
Args:
nodes (list): A list of nodes to add. Each element must be one of
the following:
* A dict containing keyword args to pass onto to the Node init.
* An iterable containing 1 - 3 elements. The first element is
mandatory, and specifies the Transformer at that node. The
second element (optional) is an iterable of child nodes
(specified in the same format). The third element
(optional) is a string giving the (unique) name of the
node.
* A Node instance.
* A Transformer instance.
parent (Node): Optional parent node (i.e., the node containing the
pliers Transformer from which the to-be-created nodes receive
their inputs).
mode (str): Indicates the direction with which to add the new nodes
* horizontal: the nodes should each be added as a child of the
'parent' argument (or a Graph root by default).
* vertical: the nodes should each be added in sequence with
the first node being the child of the 'parnet' argument
(a Graph root by default) and each subsequent node being
the child of the previous node in the list.
'''
for n in nodes:
node_args = self._parse_node_args(n)
if mode == 'horizontal':
self.add_node(parent=parent, **node_args)
elif mode == 'vertical':
parent = self.add_node(parent=parent, return_node=True,
**node_args)
else:
raise ValueError("Invalid mode for adding nodes to a graph:"
"%s" % mode) | [
"def",
"add_nodes",
"(",
"self",
",",
"nodes",
",",
"parent",
"=",
"None",
",",
"mode",
"=",
"'horizontal'",
")",
":",
"for",
"n",
"in",
"nodes",
":",
"node_args",
"=",
"self",
".",
"_parse_node_args",
"(",
"n",
")",
"if",
"mode",
"==",
"'horizontal'",
":",
"self",
".",
"add_node",
"(",
"parent",
"=",
"parent",
",",
"*",
"*",
"node_args",
")",
"elif",
"mode",
"==",
"'vertical'",
":",
"parent",
"=",
"self",
".",
"add_node",
"(",
"parent",
"=",
"parent",
",",
"return_node",
"=",
"True",
",",
"*",
"*",
"node_args",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid mode for adding nodes to a graph:\"",
"\"%s\"",
"%",
"mode",
")"
] | Adds one or more nodes to the current graph.
Args:
nodes (list): A list of nodes to add. Each element must be one of
the following:
* A dict containing keyword args to pass onto to the Node init.
* An iterable containing 1 - 3 elements. The first element is
mandatory, and specifies the Transformer at that node. The
second element (optional) is an iterable of child nodes
(specified in the same format). The third element
(optional) is a string giving the (unique) name of the
node.
* A Node instance.
* A Transformer instance.
parent (Node): Optional parent node (i.e., the node containing the
pliers Transformer from which the to-be-created nodes receive
their inputs).
mode (str): Indicates the direction with which to add the new nodes
* horizontal: the nodes should each be added as a child of the
'parent' argument (or a Graph root by default).
* vertical: the nodes should each be added in sequence with
the first node being the child of the 'parnet' argument
(a Graph root by default) and each subsequent node being
the child of the previous node in the list. | [
"Adds",
"one",
"or",
"more",
"nodes",
"to",
"the",
"current",
"graph",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L107-L144 |
5,806 | tyarkoni/pliers | pliers/graph.py | Graph.add_node | def add_node(self, transformer, name=None, children=None, parent=None,
parameters={}, return_node=False):
''' Adds a node to the current graph.
Args:
transformer (str, Transformer): The pliers Transformer to use at
the to-be-added node. Either a case-insensitive string giving
the name of a Transformer class, or an initialized Transformer
instance.
name (str): Optional name to give this Node.
children (list): Optional list of child nodes (i.e., nodes to pass
the to-be-added node's Transformer output to).
parent (Node): Optional node from which the to-be-added Node
receives its input.
parameters (dict): Optional keyword arguments to pass onto the
Transformer initialized at this Node if a string is passed to
the 'transformer' argument. Ignored if an already-initialized
Transformer is passed.
return_node (bool): If True, returns the initialized Node instance.
Returns:
The initialized Node instance if return_node is True,
None otherwise.
'''
node = Node(transformer, name, **parameters)
self.nodes[node.id] = node
if parent is None:
self.roots.append(node)
else:
parent = self.nodes[parent.id]
parent.add_child(node)
if children is not None:
self.add_nodes(children, parent=node)
if return_node:
return node | python | def add_node(self, transformer, name=None, children=None, parent=None,
parameters={}, return_node=False):
''' Adds a node to the current graph.
Args:
transformer (str, Transformer): The pliers Transformer to use at
the to-be-added node. Either a case-insensitive string giving
the name of a Transformer class, or an initialized Transformer
instance.
name (str): Optional name to give this Node.
children (list): Optional list of child nodes (i.e., nodes to pass
the to-be-added node's Transformer output to).
parent (Node): Optional node from which the to-be-added Node
receives its input.
parameters (dict): Optional keyword arguments to pass onto the
Transformer initialized at this Node if a string is passed to
the 'transformer' argument. Ignored if an already-initialized
Transformer is passed.
return_node (bool): If True, returns the initialized Node instance.
Returns:
The initialized Node instance if return_node is True,
None otherwise.
'''
node = Node(transformer, name, **parameters)
self.nodes[node.id] = node
if parent is None:
self.roots.append(node)
else:
parent = self.nodes[parent.id]
parent.add_child(node)
if children is not None:
self.add_nodes(children, parent=node)
if return_node:
return node | [
"def",
"add_node",
"(",
"self",
",",
"transformer",
",",
"name",
"=",
"None",
",",
"children",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"parameters",
"=",
"{",
"}",
",",
"return_node",
"=",
"False",
")",
":",
"node",
"=",
"Node",
"(",
"transformer",
",",
"name",
",",
"*",
"*",
"parameters",
")",
"self",
".",
"nodes",
"[",
"node",
".",
"id",
"]",
"=",
"node",
"if",
"parent",
"is",
"None",
":",
"self",
".",
"roots",
".",
"append",
"(",
"node",
")",
"else",
":",
"parent",
"=",
"self",
".",
"nodes",
"[",
"parent",
".",
"id",
"]",
"parent",
".",
"add_child",
"(",
"node",
")",
"if",
"children",
"is",
"not",
"None",
":",
"self",
".",
"add_nodes",
"(",
"children",
",",
"parent",
"=",
"node",
")",
"if",
"return_node",
":",
"return",
"node"
] | Adds a node to the current graph.
Args:
transformer (str, Transformer): The pliers Transformer to use at
the to-be-added node. Either a case-insensitive string giving
the name of a Transformer class, or an initialized Transformer
instance.
name (str): Optional name to give this Node.
children (list): Optional list of child nodes (i.e., nodes to pass
the to-be-added node's Transformer output to).
parent (Node): Optional node from which the to-be-added Node
receives its input.
parameters (dict): Optional keyword arguments to pass onto the
Transformer initialized at this Node if a string is passed to
the 'transformer' argument. Ignored if an already-initialized
Transformer is passed.
return_node (bool): If True, returns the initialized Node instance.
Returns:
The initialized Node instance if return_node is True,
None otherwise. | [
"Adds",
"a",
"node",
"to",
"the",
"current",
"graph",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L154-L192 |
5,807 | tyarkoni/pliers | pliers/graph.py | Graph.run | def run(self, stim, merge=True, **merge_kwargs):
''' Executes the graph by calling all Transformers in sequence.
Args:
stim (str, Stim, list): One or more valid inputs to any
Transformer's 'transform' call.
merge (bool): If True, all results are merged into a single pandas
DataFrame before being returned. If False, a list of
ExtractorResult objects is returned (one per Extractor/Stim
combination).
merge_kwargs: Optional keyword arguments to pass onto the
merge_results() call.
'''
results = list(chain(*[self.run_node(n, stim) for n in self.roots]))
results = list(flatten(results))
self._results = results # For use in plotting
return merge_results(results, **merge_kwargs) if merge else results | python | def run(self, stim, merge=True, **merge_kwargs):
''' Executes the graph by calling all Transformers in sequence.
Args:
stim (str, Stim, list): One or more valid inputs to any
Transformer's 'transform' call.
merge (bool): If True, all results are merged into a single pandas
DataFrame before being returned. If False, a list of
ExtractorResult objects is returned (one per Extractor/Stim
combination).
merge_kwargs: Optional keyword arguments to pass onto the
merge_results() call.
'''
results = list(chain(*[self.run_node(n, stim) for n in self.roots]))
results = list(flatten(results))
self._results = results # For use in plotting
return merge_results(results, **merge_kwargs) if merge else results | [
"def",
"run",
"(",
"self",
",",
"stim",
",",
"merge",
"=",
"True",
",",
"*",
"*",
"merge_kwargs",
")",
":",
"results",
"=",
"list",
"(",
"chain",
"(",
"*",
"[",
"self",
".",
"run_node",
"(",
"n",
",",
"stim",
")",
"for",
"n",
"in",
"self",
".",
"roots",
"]",
")",
")",
"results",
"=",
"list",
"(",
"flatten",
"(",
"results",
")",
")",
"self",
".",
"_results",
"=",
"results",
"# For use in plotting",
"return",
"merge_results",
"(",
"results",
",",
"*",
"*",
"merge_kwargs",
")",
"if",
"merge",
"else",
"results"
] | Executes the graph by calling all Transformers in sequence.
Args:
stim (str, Stim, list): One or more valid inputs to any
Transformer's 'transform' call.
merge (bool): If True, all results are merged into a single pandas
DataFrame before being returned. If False, a list of
ExtractorResult objects is returned (one per Extractor/Stim
combination).
merge_kwargs: Optional keyword arguments to pass onto the
merge_results() call. | [
"Executes",
"the",
"graph",
"by",
"calling",
"all",
"Transformers",
"in",
"sequence",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L194-L210 |
5,808 | tyarkoni/pliers | pliers/graph.py | Graph.run_node | def run_node(self, node, stim):
''' Executes the Transformer at a specific node.
Args:
node (str, Node): If a string, the name of the Node in the current
Graph. Otherwise the Node instance to execute.
stim (str, stim, list): Any valid input to the Transformer stored
at the target node.
'''
if isinstance(node, string_types):
node = self.nodes[node]
result = node.transformer.transform(stim)
if node.is_leaf():
return listify(result)
stim = result
# If result is a generator, the first child will destroy the
# iterable, so cache via list conversion
if len(node.children) > 1 and isgenerator(stim):
stim = list(stim)
return list(chain(*[self.run_node(c, stim) for c in node.children])) | python | def run_node(self, node, stim):
''' Executes the Transformer at a specific node.
Args:
node (str, Node): If a string, the name of the Node in the current
Graph. Otherwise the Node instance to execute.
stim (str, stim, list): Any valid input to the Transformer stored
at the target node.
'''
if isinstance(node, string_types):
node = self.nodes[node]
result = node.transformer.transform(stim)
if node.is_leaf():
return listify(result)
stim = result
# If result is a generator, the first child will destroy the
# iterable, so cache via list conversion
if len(node.children) > 1 and isgenerator(stim):
stim = list(stim)
return list(chain(*[self.run_node(c, stim) for c in node.children])) | [
"def",
"run_node",
"(",
"self",
",",
"node",
",",
"stim",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"string_types",
")",
":",
"node",
"=",
"self",
".",
"nodes",
"[",
"node",
"]",
"result",
"=",
"node",
".",
"transformer",
".",
"transform",
"(",
"stim",
")",
"if",
"node",
".",
"is_leaf",
"(",
")",
":",
"return",
"listify",
"(",
"result",
")",
"stim",
"=",
"result",
"# If result is a generator, the first child will destroy the",
"# iterable, so cache via list conversion",
"if",
"len",
"(",
"node",
".",
"children",
")",
">",
"1",
"and",
"isgenerator",
"(",
"stim",
")",
":",
"stim",
"=",
"list",
"(",
"stim",
")",
"return",
"list",
"(",
"chain",
"(",
"*",
"[",
"self",
".",
"run_node",
"(",
"c",
",",
"stim",
")",
"for",
"c",
"in",
"node",
".",
"children",
"]",
")",
")"
] | Executes the Transformer at a specific node.
Args:
node (str, Node): If a string, the name of the Node in the current
Graph. Otherwise the Node instance to execute.
stim (str, stim, list): Any valid input to the Transformer stored
at the target node. | [
"Executes",
"the",
"Transformer",
"at",
"a",
"specific",
"node",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L214-L235 |
5,809 | tyarkoni/pliers | pliers/graph.py | Graph.draw | def draw(self, filename, color=True):
''' Render a plot of the graph via pygraphviz.
Args:
filename (str): Path to save the generated image to.
color (bool): If True, will color graph nodes based on their type,
otherwise will draw a black-and-white graph.
'''
verify_dependencies(['pgv'])
if not hasattr(self, '_results'):
raise RuntimeError("Graph cannot be drawn before it is executed. "
"Try calling run() first.")
g = pgv.AGraph(directed=True)
g.node_attr['colorscheme'] = 'set312'
for elem in self._results:
if not hasattr(elem, 'history'):
continue
log = elem.history
while log:
# Configure nodes
source_from = log.parent[6] if log.parent else ''
s_node = hash((source_from, log[2]))
s_color = stim_list.index(log[2])
s_color = s_color % 12 + 1
t_node = hash((log[6], log[7]))
t_style = 'filled,' if color else ''
t_style += 'dotted' if log.implicit else ''
if log[6].endswith('Extractor'):
t_color = '#0082c8'
elif log[6].endswith('Filter'):
t_color = '#e6194b'
else:
t_color = '#3cb44b'
r_node = hash((log[6], log[5]))
r_color = stim_list.index(log[5])
r_color = r_color % 12 + 1
# Add nodes
if color:
g.add_node(s_node, label=log[2], shape='ellipse',
style='filled', fillcolor=s_color)
g.add_node(t_node, label=log[6], shape='box',
style=t_style, fillcolor=t_color)
g.add_node(r_node, label=log[5], shape='ellipse',
style='filled', fillcolor=r_color)
else:
g.add_node(s_node, label=log[2], shape='ellipse')
g.add_node(t_node, label=log[6], shape='box',
style=t_style)
g.add_node(r_node, label=log[5], shape='ellipse')
# Add edges
g.add_edge(s_node, t_node, style=t_style)
g.add_edge(t_node, r_node, style=t_style)
log = log.parent
g.draw(filename, prog='dot') | python | def draw(self, filename, color=True):
''' Render a plot of the graph via pygraphviz.
Args:
filename (str): Path to save the generated image to.
color (bool): If True, will color graph nodes based on their type,
otherwise will draw a black-and-white graph.
'''
verify_dependencies(['pgv'])
if not hasattr(self, '_results'):
raise RuntimeError("Graph cannot be drawn before it is executed. "
"Try calling run() first.")
g = pgv.AGraph(directed=True)
g.node_attr['colorscheme'] = 'set312'
for elem in self._results:
if not hasattr(elem, 'history'):
continue
log = elem.history
while log:
# Configure nodes
source_from = log.parent[6] if log.parent else ''
s_node = hash((source_from, log[2]))
s_color = stim_list.index(log[2])
s_color = s_color % 12 + 1
t_node = hash((log[6], log[7]))
t_style = 'filled,' if color else ''
t_style += 'dotted' if log.implicit else ''
if log[6].endswith('Extractor'):
t_color = '#0082c8'
elif log[6].endswith('Filter'):
t_color = '#e6194b'
else:
t_color = '#3cb44b'
r_node = hash((log[6], log[5]))
r_color = stim_list.index(log[5])
r_color = r_color % 12 + 1
# Add nodes
if color:
g.add_node(s_node, label=log[2], shape='ellipse',
style='filled', fillcolor=s_color)
g.add_node(t_node, label=log[6], shape='box',
style=t_style, fillcolor=t_color)
g.add_node(r_node, label=log[5], shape='ellipse',
style='filled', fillcolor=r_color)
else:
g.add_node(s_node, label=log[2], shape='ellipse')
g.add_node(t_node, label=log[6], shape='box',
style=t_style)
g.add_node(r_node, label=log[5], shape='ellipse')
# Add edges
g.add_edge(s_node, t_node, style=t_style)
g.add_edge(t_node, r_node, style=t_style)
log = log.parent
g.draw(filename, prog='dot') | [
"def",
"draw",
"(",
"self",
",",
"filename",
",",
"color",
"=",
"True",
")",
":",
"verify_dependencies",
"(",
"[",
"'pgv'",
"]",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_results'",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Graph cannot be drawn before it is executed. \"",
"\"Try calling run() first.\"",
")",
"g",
"=",
"pgv",
".",
"AGraph",
"(",
"directed",
"=",
"True",
")",
"g",
".",
"node_attr",
"[",
"'colorscheme'",
"]",
"=",
"'set312'",
"for",
"elem",
"in",
"self",
".",
"_results",
":",
"if",
"not",
"hasattr",
"(",
"elem",
",",
"'history'",
")",
":",
"continue",
"log",
"=",
"elem",
".",
"history",
"while",
"log",
":",
"# Configure nodes",
"source_from",
"=",
"log",
".",
"parent",
"[",
"6",
"]",
"if",
"log",
".",
"parent",
"else",
"''",
"s_node",
"=",
"hash",
"(",
"(",
"source_from",
",",
"log",
"[",
"2",
"]",
")",
")",
"s_color",
"=",
"stim_list",
".",
"index",
"(",
"log",
"[",
"2",
"]",
")",
"s_color",
"=",
"s_color",
"%",
"12",
"+",
"1",
"t_node",
"=",
"hash",
"(",
"(",
"log",
"[",
"6",
"]",
",",
"log",
"[",
"7",
"]",
")",
")",
"t_style",
"=",
"'filled,'",
"if",
"color",
"else",
"''",
"t_style",
"+=",
"'dotted'",
"if",
"log",
".",
"implicit",
"else",
"''",
"if",
"log",
"[",
"6",
"]",
".",
"endswith",
"(",
"'Extractor'",
")",
":",
"t_color",
"=",
"'#0082c8'",
"elif",
"log",
"[",
"6",
"]",
".",
"endswith",
"(",
"'Filter'",
")",
":",
"t_color",
"=",
"'#e6194b'",
"else",
":",
"t_color",
"=",
"'#3cb44b'",
"r_node",
"=",
"hash",
"(",
"(",
"log",
"[",
"6",
"]",
",",
"log",
"[",
"5",
"]",
")",
")",
"r_color",
"=",
"stim_list",
".",
"index",
"(",
"log",
"[",
"5",
"]",
")",
"r_color",
"=",
"r_color",
"%",
"12",
"+",
"1",
"# Add nodes",
"if",
"color",
":",
"g",
".",
"add_node",
"(",
"s_node",
",",
"label",
"=",
"log",
"[",
"2",
"]",
",",
"shape",
"=",
"'ellipse'",
",",
"style",
"=",
"'filled'",
",",
"fillcolor",
"=",
"s_color",
")",
"g",
".",
"add_node",
"(",
"t_node",
",",
"label",
"=",
"log",
"[",
"6",
"]",
",",
"shape",
"=",
"'box'",
",",
"style",
"=",
"t_style",
",",
"fillcolor",
"=",
"t_color",
")",
"g",
".",
"add_node",
"(",
"r_node",
",",
"label",
"=",
"log",
"[",
"5",
"]",
",",
"shape",
"=",
"'ellipse'",
",",
"style",
"=",
"'filled'",
",",
"fillcolor",
"=",
"r_color",
")",
"else",
":",
"g",
".",
"add_node",
"(",
"s_node",
",",
"label",
"=",
"log",
"[",
"2",
"]",
",",
"shape",
"=",
"'ellipse'",
")",
"g",
".",
"add_node",
"(",
"t_node",
",",
"label",
"=",
"log",
"[",
"6",
"]",
",",
"shape",
"=",
"'box'",
",",
"style",
"=",
"t_style",
")",
"g",
".",
"add_node",
"(",
"r_node",
",",
"label",
"=",
"log",
"[",
"5",
"]",
",",
"shape",
"=",
"'ellipse'",
")",
"# Add edges",
"g",
".",
"add_edge",
"(",
"s_node",
",",
"t_node",
",",
"style",
"=",
"t_style",
")",
"g",
".",
"add_edge",
"(",
"t_node",
",",
"r_node",
",",
"style",
"=",
"t_style",
")",
"log",
"=",
"log",
".",
"parent",
"g",
".",
"draw",
"(",
"filename",
",",
"prog",
"=",
"'dot'",
")"
] | Render a plot of the graph via pygraphviz.
Args:
filename (str): Path to save the generated image to.
color (bool): If True, will color graph nodes based on their type,
otherwise will draw a black-and-white graph. | [
"Render",
"a",
"plot",
"of",
"the",
"graph",
"via",
"pygraphviz",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L237-L298 |
5,810 | tyarkoni/pliers | pliers/graph.py | Graph.to_json | def to_json(self):
''' Returns the JSON representation of this graph. '''
roots = []
for r in self.roots:
roots.append(r.to_json())
return {'roots': roots} | python | def to_json(self):
''' Returns the JSON representation of this graph. '''
roots = []
for r in self.roots:
roots.append(r.to_json())
return {'roots': roots} | [
"def",
"to_json",
"(",
"self",
")",
":",
"roots",
"=",
"[",
"]",
"for",
"r",
"in",
"self",
".",
"roots",
":",
"roots",
".",
"append",
"(",
"r",
".",
"to_json",
"(",
")",
")",
"return",
"{",
"'roots'",
":",
"roots",
"}"
] | Returns the JSON representation of this graph. | [
"Returns",
"the",
"JSON",
"representation",
"of",
"this",
"graph",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L300-L305 |
5,811 | tyarkoni/pliers | pliers/utils/base.py | flatten | def flatten(l):
''' Flatten an iterable. '''
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, string_types):
for sub in flatten(el):
yield sub
else:
yield el | python | def flatten(l):
''' Flatten an iterable. '''
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, string_types):
for sub in flatten(el):
yield sub
else:
yield el | [
"def",
"flatten",
"(",
"l",
")",
":",
"for",
"el",
"in",
"l",
":",
"if",
"isinstance",
"(",
"el",
",",
"collections",
".",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"el",
",",
"string_types",
")",
":",
"for",
"sub",
"in",
"flatten",
"(",
"el",
")",
":",
"yield",
"sub",
"else",
":",
"yield",
"el"
] | Flatten an iterable. | [
"Flatten",
"an",
"iterable",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/utils/base.py#L20-L27 |
5,812 | tyarkoni/pliers | pliers/utils/base.py | set_iterable_type | def set_iterable_type(obj):
''' Returns either a generator or a list depending on config-level
settings. Should be used to wrap almost every internal iterable return.
Also inspects elements recursively in the case of list returns, to
ensure that there are no nested generators. '''
if not isiterable(obj):
return obj
if config.get_option('use_generators'):
return obj if isgenerator(obj) else (i for i in obj)
else:
return [set_iterable_type(i) for i in obj] | python | def set_iterable_type(obj):
''' Returns either a generator or a list depending on config-level
settings. Should be used to wrap almost every internal iterable return.
Also inspects elements recursively in the case of list returns, to
ensure that there are no nested generators. '''
if not isiterable(obj):
return obj
if config.get_option('use_generators'):
return obj if isgenerator(obj) else (i for i in obj)
else:
return [set_iterable_type(i) for i in obj] | [
"def",
"set_iterable_type",
"(",
"obj",
")",
":",
"if",
"not",
"isiterable",
"(",
"obj",
")",
":",
"return",
"obj",
"if",
"config",
".",
"get_option",
"(",
"'use_generators'",
")",
":",
"return",
"obj",
"if",
"isgenerator",
"(",
"obj",
")",
"else",
"(",
"i",
"for",
"i",
"in",
"obj",
")",
"else",
":",
"return",
"[",
"set_iterable_type",
"(",
"i",
")",
"for",
"i",
"in",
"obj",
"]"
] | Returns either a generator or a list depending on config-level
settings. Should be used to wrap almost every internal iterable return.
Also inspects elements recursively in the case of list returns, to
ensure that there are no nested generators. | [
"Returns",
"either",
"a",
"generator",
"or",
"a",
"list",
"depending",
"on",
"config",
"-",
"level",
"settings",
".",
"Should",
"be",
"used",
"to",
"wrap",
"almost",
"every",
"internal",
"iterable",
"return",
".",
"Also",
"inspects",
"elements",
"recursively",
"in",
"the",
"case",
"of",
"list",
"returns",
"to",
"ensure",
"that",
"there",
"are",
"no",
"nested",
"generators",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/utils/base.py#L55-L66 |
5,813 | tyarkoni/pliers | pliers/utils/base.py | isgenerator | def isgenerator(obj):
''' Returns True if object is a generator, or a generator wrapped by a
tqdm object. '''
return isinstance(obj, GeneratorType) or (hasattr(obj, 'iterable') and
isinstance(getattr(obj, 'iterable'), GeneratorType)) | python | def isgenerator(obj):
''' Returns True if object is a generator, or a generator wrapped by a
tqdm object. '''
return isinstance(obj, GeneratorType) or (hasattr(obj, 'iterable') and
isinstance(getattr(obj, 'iterable'), GeneratorType)) | [
"def",
"isgenerator",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"GeneratorType",
")",
"or",
"(",
"hasattr",
"(",
"obj",
",",
"'iterable'",
")",
"and",
"isinstance",
"(",
"getattr",
"(",
"obj",
",",
"'iterable'",
")",
",",
"GeneratorType",
")",
")"
] | Returns True if object is a generator, or a generator wrapped by a
tqdm object. | [
"Returns",
"True",
"if",
"object",
"is",
"a",
"generator",
"or",
"a",
"generator",
"wrapped",
"by",
"a",
"tqdm",
"object",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/utils/base.py#L85-L89 |
5,814 | tyarkoni/pliers | pliers/utils/base.py | progress_bar_wrapper | def progress_bar_wrapper(iterable, **kwargs):
''' Wrapper that applies tqdm progress bar conditional on config settings.
'''
return tqdm(iterable, **kwargs) if (config.get_option('progress_bar')
and not isinstance(iterable, tqdm)) else iterable | python | def progress_bar_wrapper(iterable, **kwargs):
''' Wrapper that applies tqdm progress bar conditional on config settings.
'''
return tqdm(iterable, **kwargs) if (config.get_option('progress_bar')
and not isinstance(iterable, tqdm)) else iterable | [
"def",
"progress_bar_wrapper",
"(",
"iterable",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"tqdm",
"(",
"iterable",
",",
"*",
"*",
"kwargs",
")",
"if",
"(",
"config",
".",
"get_option",
"(",
"'progress_bar'",
")",
"and",
"not",
"isinstance",
"(",
"iterable",
",",
"tqdm",
")",
")",
"else",
"iterable"
] | Wrapper that applies tqdm progress bar conditional on config settings. | [
"Wrapper",
"that",
"applies",
"tqdm",
"progress",
"bar",
"conditional",
"on",
"config",
"settings",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/utils/base.py#L92-L96 |
5,815 | tyarkoni/pliers | pliers/stimuli/video.py | VideoFrameCollectionStim.get_frame | def get_frame(self, index):
''' Get video frame at the specified index.
Args:
index (int): Positional index of the desired frame.
'''
frame_num = self.frame_index[index]
onset = float(frame_num) / self.fps
if index < self.n_frames - 1:
next_frame_num = self.frame_index[index + 1]
end = float(next_frame_num) / self.fps
else:
end = float(self.duration)
duration = end - onset if end > onset else 0.0
return VideoFrameStim(self, frame_num,
data=self.clip.get_frame(onset),
duration=duration) | python | def get_frame(self, index):
''' Get video frame at the specified index.
Args:
index (int): Positional index of the desired frame.
'''
frame_num = self.frame_index[index]
onset = float(frame_num) / self.fps
if index < self.n_frames - 1:
next_frame_num = self.frame_index[index + 1]
end = float(next_frame_num) / self.fps
else:
end = float(self.duration)
duration = end - onset if end > onset else 0.0
return VideoFrameStim(self, frame_num,
data=self.clip.get_frame(onset),
duration=duration) | [
"def",
"get_frame",
"(",
"self",
",",
"index",
")",
":",
"frame_num",
"=",
"self",
".",
"frame_index",
"[",
"index",
"]",
"onset",
"=",
"float",
"(",
"frame_num",
")",
"/",
"self",
".",
"fps",
"if",
"index",
"<",
"self",
".",
"n_frames",
"-",
"1",
":",
"next_frame_num",
"=",
"self",
".",
"frame_index",
"[",
"index",
"+",
"1",
"]",
"end",
"=",
"float",
"(",
"next_frame_num",
")",
"/",
"self",
".",
"fps",
"else",
":",
"end",
"=",
"float",
"(",
"self",
".",
"duration",
")",
"duration",
"=",
"end",
"-",
"onset",
"if",
"end",
">",
"onset",
"else",
"0.0",
"return",
"VideoFrameStim",
"(",
"self",
",",
"frame_num",
",",
"data",
"=",
"self",
".",
"clip",
".",
"get_frame",
"(",
"onset",
")",
",",
"duration",
"=",
"duration",
")"
] | Get video frame at the specified index.
Args:
index (int): Positional index of the desired frame. | [
"Get",
"video",
"frame",
"at",
"the",
"specified",
"index",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/stimuli/video.py#L94-L114 |
5,816 | tyarkoni/pliers | pliers/stimuli/video.py | VideoFrameCollectionStim.save | def save(self, path):
''' Save source video to file.
Args:
path (str): Filename to save to.
Notes: Saves entire source video to file, not just currently selected
frames.
'''
# IMPORTANT WARNING: saves entire source video
self.clip.write_videofile(path, audio_fps=self.clip.audio.fps) | python | def save(self, path):
''' Save source video to file.
Args:
path (str): Filename to save to.
Notes: Saves entire source video to file, not just currently selected
frames.
'''
# IMPORTANT WARNING: saves entire source video
self.clip.write_videofile(path, audio_fps=self.clip.audio.fps) | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"# IMPORTANT WARNING: saves entire source video",
"self",
".",
"clip",
".",
"write_videofile",
"(",
"path",
",",
"audio_fps",
"=",
"self",
".",
"clip",
".",
"audio",
".",
"fps",
")"
] | Save source video to file.
Args:
path (str): Filename to save to.
Notes: Saves entire source video to file, not just currently selected
frames. | [
"Save",
"source",
"video",
"to",
"file",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/stimuli/video.py#L125-L135 |
5,817 | tyarkoni/pliers | pliers/stimuli/video.py | VideoStim.get_frame | def get_frame(self, index=None, onset=None):
''' Overrides the default behavior by giving access to the onset
argument.
Args:
index (int): Positional index of the desired frame.
onset (float): Onset (in seconds) of the desired frame.
'''
if onset:
index = int(onset * self.fps)
return super(VideoStim, self).get_frame(index) | python | def get_frame(self, index=None, onset=None):
''' Overrides the default behavior by giving access to the onset
argument.
Args:
index (int): Positional index of the desired frame.
onset (float): Onset (in seconds) of the desired frame.
'''
if onset:
index = int(onset * self.fps)
return super(VideoStim, self).get_frame(index) | [
"def",
"get_frame",
"(",
"self",
",",
"index",
"=",
"None",
",",
"onset",
"=",
"None",
")",
":",
"if",
"onset",
":",
"index",
"=",
"int",
"(",
"onset",
"*",
"self",
".",
"fps",
")",
"return",
"super",
"(",
"VideoStim",
",",
"self",
")",
".",
"get_frame",
"(",
"index",
")"
] | Overrides the default behavior by giving access to the onset
argument.
Args:
index (int): Positional index of the desired frame.
onset (float): Onset (in seconds) of the desired frame. | [
"Overrides",
"the",
"default",
"behavior",
"by",
"giving",
"access",
"to",
"the",
"onset",
"argument",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/stimuli/video.py#L159-L170 |
5,818 | tyarkoni/pliers | pliers/utils/updater.py | hash_data | def hash_data(data, blocksize=65536):
"""" Hashes list of data, strings or data """
data = pickle.dumps(data)
hasher = hashlib.sha1()
hasher.update(data)
return hasher.hexdigest() | python | def hash_data(data, blocksize=65536):
"""" Hashes list of data, strings or data """
data = pickle.dumps(data)
hasher = hashlib.sha1()
hasher.update(data)
return hasher.hexdigest() | [
"def",
"hash_data",
"(",
"data",
",",
"blocksize",
"=",
"65536",
")",
":",
"data",
"=",
"pickle",
".",
"dumps",
"(",
"data",
")",
"hasher",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"hasher",
".",
"update",
"(",
"data",
")",
"return",
"hasher",
".",
"hexdigest",
"(",
")"
] | Hashes list of data, strings or data | [
"Hashes",
"list",
"of",
"data",
"strings",
"or",
"data"
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/utils/updater.py#L13-L20 |
5,819 | tyarkoni/pliers | pliers/utils/updater.py | check_updates | def check_updates(transformers, datastore=None, stimuli=None):
""" Run transformers through a battery of stimuli, and check if output has
changed. Store results in csv file for comparison.
Args:
transformers (list): A list of tuples of transformer names and
dictionary of parameters to instantiate with (or empty dict).
datastore (str): Filepath of CSV file with results. Stored in home dir
by default.
stimuli (list): List of stimuli file paths to extract from. If None,
use test data.
"""
# Find datastore file
datastore = datastore or expanduser('~/.pliers_updates')
prior_data = pd.read_csv(datastore) if exists(datastore) else None
# Load stimuli
stimuli = stimuli or glob.glob(
join(dirname(realpath(__file__)), '../tests/data/image/CC0/*'))
stimuli = load_stims(stimuli)
# Get transformers
loaded_transformers = {get_transformer(name, **params): (name, params)
for name, params in transformers}
# Transform stimuli
results = pd.DataFrame({'time_extracted': [datetime.datetime.now()]})
for trans in loaded_transformers.keys():
for stim in stimuli:
if trans._stim_matches_input_types(stim):
res = trans.transform(stim)
try: # Add iterable
res = [getattr(res, '_data', res.data) for r in res]
except TypeError:
res = getattr(res, '_data', res.data)
res = hash_data(res)
results["{}.{}".format(trans.__hash__(), stim.name)] = [res]
# Check for mismatches
mismatches = []
if prior_data is not None:
last = prior_data[
prior_data.time_extracted == prior_data.time_extracted.max()]. \
iloc[0].drop('time_extracted')
for label, value in results.iteritems():
old = last.get(label)
new = value.values[0]
if old is not None:
if isinstance(new, str):
if new != old:
mismatches.append(label)
elif not np.isclose(old, new):
mismatches.append(label)
results = prior_data.append(results)
results.to_csv(datastore, index=False)
# Get corresponding transformer name and parameters
def get_trans(hash_tr):
for obj, attr in loaded_transformers.items():
if str(obj.__hash__()) == hash_tr:
return attr
delta_t = set([m.split('.')[0] for m in mismatches])
delta_t = [get_trans(dt) for dt in delta_t]
return {'transformers': delta_t, 'mismatches': mismatches} | python | def check_updates(transformers, datastore=None, stimuli=None):
""" Run transformers through a battery of stimuli, and check if output has
changed. Store results in csv file for comparison.
Args:
transformers (list): A list of tuples of transformer names and
dictionary of parameters to instantiate with (or empty dict).
datastore (str): Filepath of CSV file with results. Stored in home dir
by default.
stimuli (list): List of stimuli file paths to extract from. If None,
use test data.
"""
# Find datastore file
datastore = datastore or expanduser('~/.pliers_updates')
prior_data = pd.read_csv(datastore) if exists(datastore) else None
# Load stimuli
stimuli = stimuli or glob.glob(
join(dirname(realpath(__file__)), '../tests/data/image/CC0/*'))
stimuli = load_stims(stimuli)
# Get transformers
loaded_transformers = {get_transformer(name, **params): (name, params)
for name, params in transformers}
# Transform stimuli
results = pd.DataFrame({'time_extracted': [datetime.datetime.now()]})
for trans in loaded_transformers.keys():
for stim in stimuli:
if trans._stim_matches_input_types(stim):
res = trans.transform(stim)
try: # Add iterable
res = [getattr(res, '_data', res.data) for r in res]
except TypeError:
res = getattr(res, '_data', res.data)
res = hash_data(res)
results["{}.{}".format(trans.__hash__(), stim.name)] = [res]
# Check for mismatches
mismatches = []
if prior_data is not None:
last = prior_data[
prior_data.time_extracted == prior_data.time_extracted.max()]. \
iloc[0].drop('time_extracted')
for label, value in results.iteritems():
old = last.get(label)
new = value.values[0]
if old is not None:
if isinstance(new, str):
if new != old:
mismatches.append(label)
elif not np.isclose(old, new):
mismatches.append(label)
results = prior_data.append(results)
results.to_csv(datastore, index=False)
# Get corresponding transformer name and parameters
def get_trans(hash_tr):
for obj, attr in loaded_transformers.items():
if str(obj.__hash__()) == hash_tr:
return attr
delta_t = set([m.split('.')[0] for m in mismatches])
delta_t = [get_trans(dt) for dt in delta_t]
return {'transformers': delta_t, 'mismatches': mismatches} | [
"def",
"check_updates",
"(",
"transformers",
",",
"datastore",
"=",
"None",
",",
"stimuli",
"=",
"None",
")",
":",
"# Find datastore file",
"datastore",
"=",
"datastore",
"or",
"expanduser",
"(",
"'~/.pliers_updates'",
")",
"prior_data",
"=",
"pd",
".",
"read_csv",
"(",
"datastore",
")",
"if",
"exists",
"(",
"datastore",
")",
"else",
"None",
"# Load stimuli",
"stimuli",
"=",
"stimuli",
"or",
"glob",
".",
"glob",
"(",
"join",
"(",
"dirname",
"(",
"realpath",
"(",
"__file__",
")",
")",
",",
"'../tests/data/image/CC0/*'",
")",
")",
"stimuli",
"=",
"load_stims",
"(",
"stimuli",
")",
"# Get transformers",
"loaded_transformers",
"=",
"{",
"get_transformer",
"(",
"name",
",",
"*",
"*",
"params",
")",
":",
"(",
"name",
",",
"params",
")",
"for",
"name",
",",
"params",
"in",
"transformers",
"}",
"# Transform stimuli",
"results",
"=",
"pd",
".",
"DataFrame",
"(",
"{",
"'time_extracted'",
":",
"[",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"]",
"}",
")",
"for",
"trans",
"in",
"loaded_transformers",
".",
"keys",
"(",
")",
":",
"for",
"stim",
"in",
"stimuli",
":",
"if",
"trans",
".",
"_stim_matches_input_types",
"(",
"stim",
")",
":",
"res",
"=",
"trans",
".",
"transform",
"(",
"stim",
")",
"try",
":",
"# Add iterable",
"res",
"=",
"[",
"getattr",
"(",
"res",
",",
"'_data'",
",",
"res",
".",
"data",
")",
"for",
"r",
"in",
"res",
"]",
"except",
"TypeError",
":",
"res",
"=",
"getattr",
"(",
"res",
",",
"'_data'",
",",
"res",
".",
"data",
")",
"res",
"=",
"hash_data",
"(",
"res",
")",
"results",
"[",
"\"{}.{}\"",
".",
"format",
"(",
"trans",
".",
"__hash__",
"(",
")",
",",
"stim",
".",
"name",
")",
"]",
"=",
"[",
"res",
"]",
"# Check for mismatches",
"mismatches",
"=",
"[",
"]",
"if",
"prior_data",
"is",
"not",
"None",
":",
"last",
"=",
"prior_data",
"[",
"prior_data",
".",
"time_extracted",
"==",
"prior_data",
".",
"time_extracted",
".",
"max",
"(",
")",
"]",
".",
"iloc",
"[",
"0",
"]",
".",
"drop",
"(",
"'time_extracted'",
")",
"for",
"label",
",",
"value",
"in",
"results",
".",
"iteritems",
"(",
")",
":",
"old",
"=",
"last",
".",
"get",
"(",
"label",
")",
"new",
"=",
"value",
".",
"values",
"[",
"0",
"]",
"if",
"old",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"new",
",",
"str",
")",
":",
"if",
"new",
"!=",
"old",
":",
"mismatches",
".",
"append",
"(",
"label",
")",
"elif",
"not",
"np",
".",
"isclose",
"(",
"old",
",",
"new",
")",
":",
"mismatches",
".",
"append",
"(",
"label",
")",
"results",
"=",
"prior_data",
".",
"append",
"(",
"results",
")",
"results",
".",
"to_csv",
"(",
"datastore",
",",
"index",
"=",
"False",
")",
"# Get corresponding transformer name and parameters",
"def",
"get_trans",
"(",
"hash_tr",
")",
":",
"for",
"obj",
",",
"attr",
"in",
"loaded_transformers",
".",
"items",
"(",
")",
":",
"if",
"str",
"(",
"obj",
".",
"__hash__",
"(",
")",
")",
"==",
"hash_tr",
":",
"return",
"attr",
"delta_t",
"=",
"set",
"(",
"[",
"m",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"for",
"m",
"in",
"mismatches",
"]",
")",
"delta_t",
"=",
"[",
"get_trans",
"(",
"dt",
")",
"for",
"dt",
"in",
"delta_t",
"]",
"return",
"{",
"'transformers'",
":",
"delta_t",
",",
"'mismatches'",
":",
"mismatches",
"}"
] | Run transformers through a battery of stimuli, and check if output has
changed. Store results in csv file for comparison.
Args:
transformers (list): A list of tuples of transformer names and
dictionary of parameters to instantiate with (or empty dict).
datastore (str): Filepath of CSV file with results. Stored in home dir
by default.
stimuli (list): List of stimuli file paths to extract from. If None,
use test data. | [
"Run",
"transformers",
"through",
"a",
"battery",
"of",
"stimuli",
"and",
"check",
"if",
"output",
"has",
"changed",
".",
"Store",
"results",
"in",
"csv",
"file",
"for",
"comparison",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/utils/updater.py#L23-L95 |
5,820 | open-homeautomation/miflora | demo.py | scan | def scan(args):
"""Scan for sensors."""
backend = _get_backend(args)
print('Scanning for 10 seconds...')
devices = miflora_scanner.scan(backend, 10)
print('Found {} devices:'.format(len(devices)))
for device in devices:
print(' {}'.format(device)) | python | def scan(args):
"""Scan for sensors."""
backend = _get_backend(args)
print('Scanning for 10 seconds...')
devices = miflora_scanner.scan(backend, 10)
print('Found {} devices:'.format(len(devices)))
for device in devices:
print(' {}'.format(device)) | [
"def",
"scan",
"(",
"args",
")",
":",
"backend",
"=",
"_get_backend",
"(",
"args",
")",
"print",
"(",
"'Scanning for 10 seconds...'",
")",
"devices",
"=",
"miflora_scanner",
".",
"scan",
"(",
"backend",
",",
"10",
")",
"print",
"(",
"'Found {} devices:'",
".",
"format",
"(",
"len",
"(",
"devices",
")",
")",
")",
"for",
"device",
"in",
"devices",
":",
"print",
"(",
"' {}'",
".",
"format",
"(",
"device",
")",
")"
] | Scan for sensors. | [
"Scan",
"for",
"sensors",
"."
] | 916606e7edc70bdc017dfbe681bc81771e0df7f3 | https://github.com/open-homeautomation/miflora/blob/916606e7edc70bdc017dfbe681bc81771e0df7f3/demo.py#L37-L44 |
5,821 | open-homeautomation/miflora | demo.py | _get_backend | def _get_backend(args):
"""Extract the backend class from the command line arguments."""
if args.backend == 'gatttool':
backend = GatttoolBackend
elif args.backend == 'bluepy':
backend = BluepyBackend
elif args.backend == 'pygatt':
backend = PygattBackend
else:
raise Exception('unknown backend: {}'.format(args.backend))
return backend | python | def _get_backend(args):
"""Extract the backend class from the command line arguments."""
if args.backend == 'gatttool':
backend = GatttoolBackend
elif args.backend == 'bluepy':
backend = BluepyBackend
elif args.backend == 'pygatt':
backend = PygattBackend
else:
raise Exception('unknown backend: {}'.format(args.backend))
return backend | [
"def",
"_get_backend",
"(",
"args",
")",
":",
"if",
"args",
".",
"backend",
"==",
"'gatttool'",
":",
"backend",
"=",
"GatttoolBackend",
"elif",
"args",
".",
"backend",
"==",
"'bluepy'",
":",
"backend",
"=",
"BluepyBackend",
"elif",
"args",
".",
"backend",
"==",
"'pygatt'",
":",
"backend",
"=",
"PygattBackend",
"else",
":",
"raise",
"Exception",
"(",
"'unknown backend: {}'",
".",
"format",
"(",
"args",
".",
"backend",
")",
")",
"return",
"backend"
] | Extract the backend class from the command line arguments. | [
"Extract",
"the",
"backend",
"class",
"from",
"the",
"command",
"line",
"arguments",
"."
] | 916606e7edc70bdc017dfbe681bc81771e0df7f3 | https://github.com/open-homeautomation/miflora/blob/916606e7edc70bdc017dfbe681bc81771e0df7f3/demo.py#L47-L57 |
5,822 | open-homeautomation/miflora | demo.py | list_backends | def list_backends(_):
"""List all available backends."""
backends = [b.__name__ for b in available_backends()]
print('\n'.join(backends)) | python | def list_backends(_):
"""List all available backends."""
backends = [b.__name__ for b in available_backends()]
print('\n'.join(backends)) | [
"def",
"list_backends",
"(",
"_",
")",
":",
"backends",
"=",
"[",
"b",
".",
"__name__",
"for",
"b",
"in",
"available_backends",
"(",
")",
"]",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"backends",
")",
")"
] | List all available backends. | [
"List",
"all",
"available",
"backends",
"."
] | 916606e7edc70bdc017dfbe681bc81771e0df7f3 | https://github.com/open-homeautomation/miflora/blob/916606e7edc70bdc017dfbe681bc81771e0df7f3/demo.py#L60-L63 |
5,823 | open-homeautomation/miflora | miflora/miflora_scanner.py | scan | def scan(backend, timeout=10):
"""Scan for miflora devices.
Note: this must be run as root!
"""
result = []
for (mac, name) in backend.scan_for_devices(timeout):
if (name is not None and name.lower() in VALID_DEVICE_NAMES) or \
mac is not None and mac.upper().startswith(DEVICE_PREFIX):
result.append(mac.upper())
return result | python | def scan(backend, timeout=10):
"""Scan for miflora devices.
Note: this must be run as root!
"""
result = []
for (mac, name) in backend.scan_for_devices(timeout):
if (name is not None and name.lower() in VALID_DEVICE_NAMES) or \
mac is not None and mac.upper().startswith(DEVICE_PREFIX):
result.append(mac.upper())
return result | [
"def",
"scan",
"(",
"backend",
",",
"timeout",
"=",
"10",
")",
":",
"result",
"=",
"[",
"]",
"for",
"(",
"mac",
",",
"name",
")",
"in",
"backend",
".",
"scan_for_devices",
"(",
"timeout",
")",
":",
"if",
"(",
"name",
"is",
"not",
"None",
"and",
"name",
".",
"lower",
"(",
")",
"in",
"VALID_DEVICE_NAMES",
")",
"or",
"mac",
"is",
"not",
"None",
"and",
"mac",
".",
"upper",
"(",
")",
".",
"startswith",
"(",
"DEVICE_PREFIX",
")",
":",
"result",
".",
"append",
"(",
"mac",
".",
"upper",
"(",
")",
")",
"return",
"result"
] | Scan for miflora devices.
Note: this must be run as root! | [
"Scan",
"for",
"miflora",
"devices",
"."
] | 916606e7edc70bdc017dfbe681bc81771e0df7f3 | https://github.com/open-homeautomation/miflora/blob/916606e7edc70bdc017dfbe681bc81771e0df7f3/miflora/miflora_scanner.py#L10-L20 |
5,824 | open-homeautomation/miflora | miflora/miflora_poller.py | MiFloraPoller.parameter_value | def parameter_value(self, parameter, read_cached=True):
"""Return a value of one of the monitored paramaters.
This method will try to retrieve the data from cache and only
request it by bluetooth if no cached value is stored or the cache is
expired.
This behaviour can be overwritten by the "read_cached" parameter.
"""
# Special handling for battery attribute
if parameter == MI_BATTERY:
return self.battery_level()
# Use the lock to make sure the cache isn't updated multiple times
with self.lock:
if (read_cached is False) or \
(self._last_read is None) or \
(datetime.now() - self._cache_timeout > self._last_read):
self.fill_cache()
else:
_LOGGER.debug("Using cache (%s < %s)",
datetime.now() - self._last_read,
self._cache_timeout)
if self.cache_available() and (len(self._cache) == 16):
return self._parse_data()[parameter]
else:
raise BluetoothBackendException("Could not read data from Mi Flora sensor %s" % self._mac) | python | def parameter_value(self, parameter, read_cached=True):
"""Return a value of one of the monitored paramaters.
This method will try to retrieve the data from cache and only
request it by bluetooth if no cached value is stored or the cache is
expired.
This behaviour can be overwritten by the "read_cached" parameter.
"""
# Special handling for battery attribute
if parameter == MI_BATTERY:
return self.battery_level()
# Use the lock to make sure the cache isn't updated multiple times
with self.lock:
if (read_cached is False) or \
(self._last_read is None) or \
(datetime.now() - self._cache_timeout > self._last_read):
self.fill_cache()
else:
_LOGGER.debug("Using cache (%s < %s)",
datetime.now() - self._last_read,
self._cache_timeout)
if self.cache_available() and (len(self._cache) == 16):
return self._parse_data()[parameter]
else:
raise BluetoothBackendException("Could not read data from Mi Flora sensor %s" % self._mac) | [
"def",
"parameter_value",
"(",
"self",
",",
"parameter",
",",
"read_cached",
"=",
"True",
")",
":",
"# Special handling for battery attribute",
"if",
"parameter",
"==",
"MI_BATTERY",
":",
"return",
"self",
".",
"battery_level",
"(",
")",
"# Use the lock to make sure the cache isn't updated multiple times",
"with",
"self",
".",
"lock",
":",
"if",
"(",
"read_cached",
"is",
"False",
")",
"or",
"(",
"self",
".",
"_last_read",
"is",
"None",
")",
"or",
"(",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"_cache_timeout",
">",
"self",
".",
"_last_read",
")",
":",
"self",
".",
"fill_cache",
"(",
")",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Using cache (%s < %s)\"",
",",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"_last_read",
",",
"self",
".",
"_cache_timeout",
")",
"if",
"self",
".",
"cache_available",
"(",
")",
"and",
"(",
"len",
"(",
"self",
".",
"_cache",
")",
"==",
"16",
")",
":",
"return",
"self",
".",
"_parse_data",
"(",
")",
"[",
"parameter",
"]",
"else",
":",
"raise",
"BluetoothBackendException",
"(",
"\"Could not read data from Mi Flora sensor %s\"",
"%",
"self",
".",
"_mac",
")"
] | Return a value of one of the monitored paramaters.
This method will try to retrieve the data from cache and only
request it by bluetooth if no cached value is stored or the cache is
expired.
This behaviour can be overwritten by the "read_cached" parameter. | [
"Return",
"a",
"value",
"of",
"one",
"of",
"the",
"monitored",
"paramaters",
"."
] | 916606e7edc70bdc017dfbe681bc81771e0df7f3 | https://github.com/open-homeautomation/miflora/blob/916606e7edc70bdc017dfbe681bc81771e0df7f3/miflora/miflora_poller.py#L115-L141 |
5,825 | halcy/Mastodon.py | mastodon/Mastodon.py | parse_version_string | def parse_version_string(version_string):
"""Parses a semver version string, stripping off "rc" stuff if present."""
string_parts = version_string.split(".")
version_parts = [
int(re.match("([0-9]*)", string_parts[0]).group(0)),
int(re.match("([0-9]*)", string_parts[1]).group(0)),
int(re.match("([0-9]*)", string_parts[2]).group(0))
]
return version_parts | python | def parse_version_string(version_string):
"""Parses a semver version string, stripping off "rc" stuff if present."""
string_parts = version_string.split(".")
version_parts = [
int(re.match("([0-9]*)", string_parts[0]).group(0)),
int(re.match("([0-9]*)", string_parts[1]).group(0)),
int(re.match("([0-9]*)", string_parts[2]).group(0))
]
return version_parts | [
"def",
"parse_version_string",
"(",
"version_string",
")",
":",
"string_parts",
"=",
"version_string",
".",
"split",
"(",
"\".\"",
")",
"version_parts",
"=",
"[",
"int",
"(",
"re",
".",
"match",
"(",
"\"([0-9]*)\"",
",",
"string_parts",
"[",
"0",
"]",
")",
".",
"group",
"(",
"0",
")",
")",
",",
"int",
"(",
"re",
".",
"match",
"(",
"\"([0-9]*)\"",
",",
"string_parts",
"[",
"1",
"]",
")",
".",
"group",
"(",
"0",
")",
")",
",",
"int",
"(",
"re",
".",
"match",
"(",
"\"([0-9]*)\"",
",",
"string_parts",
"[",
"2",
"]",
")",
".",
"group",
"(",
"0",
")",
")",
"]",
"return",
"version_parts"
] | Parses a semver version string, stripping off "rc" stuff if present. | [
"Parses",
"a",
"semver",
"version",
"string",
"stripping",
"off",
"rc",
"stuff",
"if",
"present",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L42-L50 |
5,826 | halcy/Mastodon.py | mastodon/Mastodon.py | bigger_version | def bigger_version(version_string_a, version_string_b):
"""Returns the bigger version of two version strings."""
major_a, minor_a, patch_a = parse_version_string(version_string_a)
major_b, minor_b, patch_b = parse_version_string(version_string_b)
if major_a > major_b:
return version_string_a
elif major_a == major_b and minor_a > minor_b:
return version_string_a
elif major_a == major_b and minor_a == minor_b and patch_a > patch_b:
return version_string_a
return version_string_b | python | def bigger_version(version_string_a, version_string_b):
"""Returns the bigger version of two version strings."""
major_a, minor_a, patch_a = parse_version_string(version_string_a)
major_b, minor_b, patch_b = parse_version_string(version_string_b)
if major_a > major_b:
return version_string_a
elif major_a == major_b and minor_a > minor_b:
return version_string_a
elif major_a == major_b and minor_a == minor_b and patch_a > patch_b:
return version_string_a
return version_string_b | [
"def",
"bigger_version",
"(",
"version_string_a",
",",
"version_string_b",
")",
":",
"major_a",
",",
"minor_a",
",",
"patch_a",
"=",
"parse_version_string",
"(",
"version_string_a",
")",
"major_b",
",",
"minor_b",
",",
"patch_b",
"=",
"parse_version_string",
"(",
"version_string_b",
")",
"if",
"major_a",
">",
"major_b",
":",
"return",
"version_string_a",
"elif",
"major_a",
"==",
"major_b",
"and",
"minor_a",
">",
"minor_b",
":",
"return",
"version_string_a",
"elif",
"major_a",
"==",
"major_b",
"and",
"minor_a",
"==",
"minor_b",
"and",
"patch_a",
">",
"patch_b",
":",
"return",
"version_string_a",
"return",
"version_string_b"
] | Returns the bigger version of two version strings. | [
"Returns",
"the",
"bigger",
"version",
"of",
"two",
"version",
"strings",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L52-L63 |
5,827 | halcy/Mastodon.py | mastodon/Mastodon.py | api_version | def api_version(created_ver, last_changed_ver, return_value_ver):
"""Version check decorator. Currently only checks Bigger Than."""
def api_min_version_decorator(function):
def wrapper(function, self, *args, **kwargs):
if not self.version_check_mode == "none":
if self.version_check_mode == "created":
version = created_ver
else:
version = bigger_version(last_changed_ver, return_value_ver)
major, minor, patch = parse_version_string(version)
if major > self.mastodon_major:
raise MastodonVersionError("Version check failed (Need version " + version + ")")
elif major == self.mastodon_major and minor > self.mastodon_minor:
print(self.mastodon_minor)
raise MastodonVersionError("Version check failed (Need version " + version + ")")
elif major == self.mastodon_major and minor == self.mastodon_minor and patch > self.mastodon_patch:
raise MastodonVersionError("Version check failed (Need version " + version + ", patch is " + str(self.mastodon_patch) + ")")
return function(self, *args, **kwargs)
function.__doc__ = function.__doc__ + "\n\n *Added: Mastodon v" + created_ver + ", last changed: Mastodon v" + last_changed_ver + "*"
return decorate(function, wrapper)
return api_min_version_decorator | python | def api_version(created_ver, last_changed_ver, return_value_ver):
"""Version check decorator. Currently only checks Bigger Than."""
def api_min_version_decorator(function):
def wrapper(function, self, *args, **kwargs):
if not self.version_check_mode == "none":
if self.version_check_mode == "created":
version = created_ver
else:
version = bigger_version(last_changed_ver, return_value_ver)
major, minor, patch = parse_version_string(version)
if major > self.mastodon_major:
raise MastodonVersionError("Version check failed (Need version " + version + ")")
elif major == self.mastodon_major and minor > self.mastodon_minor:
print(self.mastodon_minor)
raise MastodonVersionError("Version check failed (Need version " + version + ")")
elif major == self.mastodon_major and minor == self.mastodon_minor and patch > self.mastodon_patch:
raise MastodonVersionError("Version check failed (Need version " + version + ", patch is " + str(self.mastodon_patch) + ")")
return function(self, *args, **kwargs)
function.__doc__ = function.__doc__ + "\n\n *Added: Mastodon v" + created_ver + ", last changed: Mastodon v" + last_changed_ver + "*"
return decorate(function, wrapper)
return api_min_version_decorator | [
"def",
"api_version",
"(",
"created_ver",
",",
"last_changed_ver",
",",
"return_value_ver",
")",
":",
"def",
"api_min_version_decorator",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"function",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"version_check_mode",
"==",
"\"none\"",
":",
"if",
"self",
".",
"version_check_mode",
"==",
"\"created\"",
":",
"version",
"=",
"created_ver",
"else",
":",
"version",
"=",
"bigger_version",
"(",
"last_changed_ver",
",",
"return_value_ver",
")",
"major",
",",
"minor",
",",
"patch",
"=",
"parse_version_string",
"(",
"version",
")",
"if",
"major",
">",
"self",
".",
"mastodon_major",
":",
"raise",
"MastodonVersionError",
"(",
"\"Version check failed (Need version \"",
"+",
"version",
"+",
"\")\"",
")",
"elif",
"major",
"==",
"self",
".",
"mastodon_major",
"and",
"minor",
">",
"self",
".",
"mastodon_minor",
":",
"print",
"(",
"self",
".",
"mastodon_minor",
")",
"raise",
"MastodonVersionError",
"(",
"\"Version check failed (Need version \"",
"+",
"version",
"+",
"\")\"",
")",
"elif",
"major",
"==",
"self",
".",
"mastodon_major",
"and",
"minor",
"==",
"self",
".",
"mastodon_minor",
"and",
"patch",
">",
"self",
".",
"mastodon_patch",
":",
"raise",
"MastodonVersionError",
"(",
"\"Version check failed (Need version \"",
"+",
"version",
"+",
"\", patch is \"",
"+",
"str",
"(",
"self",
".",
"mastodon_patch",
")",
"+",
"\")\"",
")",
"return",
"function",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"function",
".",
"__doc__",
"=",
"function",
".",
"__doc__",
"+",
"\"\\n\\n *Added: Mastodon v\"",
"+",
"created_ver",
"+",
"\", last changed: Mastodon v\"",
"+",
"last_changed_ver",
"+",
"\"*\"",
"return",
"decorate",
"(",
"function",
",",
"wrapper",
")",
"return",
"api_min_version_decorator"
] | Version check decorator. Currently only checks Bigger Than. | [
"Version",
"check",
"decorator",
".",
"Currently",
"only",
"checks",
"Bigger",
"Than",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L65-L85 |
5,828 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.verify_minimum_version | def verify_minimum_version(self, version_str):
"""
Update version info from server and verify that at least the specified version is present.
Returns True if version requirement is satisfied, False if not.
"""
self.retrieve_mastodon_version()
major, minor, patch = parse_version_string(version_str)
if major > self.mastodon_major:
return False
elif major == self.mastodon_major and minor > self.mastodon_minor:
return False
elif major == self.mastodon_major and minor == self.mastodon_minor and patch > self.mastodon_patch:
return False
return True | python | def verify_minimum_version(self, version_str):
"""
Update version info from server and verify that at least the specified version is present.
Returns True if version requirement is satisfied, False if not.
"""
self.retrieve_mastodon_version()
major, minor, patch = parse_version_string(version_str)
if major > self.mastodon_major:
return False
elif major == self.mastodon_major and minor > self.mastodon_minor:
return False
elif major == self.mastodon_major and minor == self.mastodon_minor and patch > self.mastodon_patch:
return False
return True | [
"def",
"verify_minimum_version",
"(",
"self",
",",
"version_str",
")",
":",
"self",
".",
"retrieve_mastodon_version",
"(",
")",
"major",
",",
"minor",
",",
"patch",
"=",
"parse_version_string",
"(",
"version_str",
")",
"if",
"major",
">",
"self",
".",
"mastodon_major",
":",
"return",
"False",
"elif",
"major",
"==",
"self",
".",
"mastodon_major",
"and",
"minor",
">",
"self",
".",
"mastodon_minor",
":",
"return",
"False",
"elif",
"major",
"==",
"self",
".",
"mastodon_major",
"and",
"minor",
"==",
"self",
".",
"mastodon_minor",
"and",
"patch",
">",
"self",
".",
"mastodon_patch",
":",
"return",
"False",
"return",
"True"
] | Update version info from server and verify that at least the specified version is present.
Returns True if version requirement is satisfied, False if not. | [
"Update",
"version",
"info",
"from",
"server",
"and",
"verify",
"that",
"at",
"least",
"the",
"specified",
"version",
"is",
"present",
".",
"Returns",
"True",
"if",
"version",
"requirement",
"is",
"satisfied",
"False",
"if",
"not",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L359-L373 |
5,829 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.log_in | def log_in(self, username=None, password=None,
code=None, redirect_uri="urn:ietf:wg:oauth:2.0:oob", refresh_token=None,
scopes=__DEFAULT_SCOPES, to_file=None):
"""
Get the access token for a user.
The username is the e-mail used to log in into mastodon.
Can persist access token to file `to_file`, to be used in the constructor.
Handles password and OAuth-based authorization.
Will throw a `MastodonIllegalArgumentError` if the OAuth or the
username / password credentials given are incorrect, and
`MastodonAPIError` if all of the requested scopes were not granted.
For OAuth2, obtain a code via having your user go to the url returned by
`auth_request_url()`_ and pass it as the code parameter. In this case,
make sure to also pass the same redirect_uri parameter as you used when
generating the auth request URL.
Returns the access token as a string.
"""
if username is not None and password is not None:
params = self.__generate_params(locals(), ['scopes', 'to_file', 'code', 'refresh_token'])
params['grant_type'] = 'password'
elif code is not None:
params = self.__generate_params(locals(), ['scopes', 'to_file', 'username', 'password', 'refresh_token'])
params['grant_type'] = 'authorization_code'
elif refresh_token is not None:
params = self.__generate_params(locals(), ['scopes', 'to_file', 'username', 'password', 'code'])
params['grant_type'] = 'refresh_token'
else:
raise MastodonIllegalArgumentError('Invalid arguments given. username and password or code are required.')
params['client_id'] = self.client_id
params['client_secret'] = self.client_secret
params['scope'] = " ".join(scopes)
try:
response = self.__api_request('POST', '/oauth/token', params, do_ratelimiting=False)
self.access_token = response['access_token']
self.__set_refresh_token(response.get('refresh_token'))
self.__set_token_expired(int(response.get('expires_in', 0)))
except Exception as e:
if username is not None or password is not None:
raise MastodonIllegalArgumentError('Invalid user name, password, or redirect_uris: %s' % e)
elif code is not None:
raise MastodonIllegalArgumentError('Invalid access token or redirect_uris: %s' % e)
else:
raise MastodonIllegalArgumentError('Invalid request: %s' % e)
received_scopes = response["scope"].split(" ")
for scope_set in self.__SCOPE_SETS.keys():
if scope_set in received_scopes:
received_scopes += self.__SCOPE_SETS[scope_set]
if not set(scopes) <= set(received_scopes):
raise MastodonAPIError(
'Granted scopes "' + " ".join(received_scopes) + '" do not contain all of the requested scopes "' + " ".join(scopes) + '".')
if to_file is not None:
with open(to_file, 'w') as token_file:
token_file.write(response['access_token'] + '\n')
self.__logged_in_id = None
return response['access_token'] | python | def log_in(self, username=None, password=None,
code=None, redirect_uri="urn:ietf:wg:oauth:2.0:oob", refresh_token=None,
scopes=__DEFAULT_SCOPES, to_file=None):
"""
Get the access token for a user.
The username is the e-mail used to log in into mastodon.
Can persist access token to file `to_file`, to be used in the constructor.
Handles password and OAuth-based authorization.
Will throw a `MastodonIllegalArgumentError` if the OAuth or the
username / password credentials given are incorrect, and
`MastodonAPIError` if all of the requested scopes were not granted.
For OAuth2, obtain a code via having your user go to the url returned by
`auth_request_url()`_ and pass it as the code parameter. In this case,
make sure to also pass the same redirect_uri parameter as you used when
generating the auth request URL.
Returns the access token as a string.
"""
if username is not None and password is not None:
params = self.__generate_params(locals(), ['scopes', 'to_file', 'code', 'refresh_token'])
params['grant_type'] = 'password'
elif code is not None:
params = self.__generate_params(locals(), ['scopes', 'to_file', 'username', 'password', 'refresh_token'])
params['grant_type'] = 'authorization_code'
elif refresh_token is not None:
params = self.__generate_params(locals(), ['scopes', 'to_file', 'username', 'password', 'code'])
params['grant_type'] = 'refresh_token'
else:
raise MastodonIllegalArgumentError('Invalid arguments given. username and password or code are required.')
params['client_id'] = self.client_id
params['client_secret'] = self.client_secret
params['scope'] = " ".join(scopes)
try:
response = self.__api_request('POST', '/oauth/token', params, do_ratelimiting=False)
self.access_token = response['access_token']
self.__set_refresh_token(response.get('refresh_token'))
self.__set_token_expired(int(response.get('expires_in', 0)))
except Exception as e:
if username is not None or password is not None:
raise MastodonIllegalArgumentError('Invalid user name, password, or redirect_uris: %s' % e)
elif code is not None:
raise MastodonIllegalArgumentError('Invalid access token or redirect_uris: %s' % e)
else:
raise MastodonIllegalArgumentError('Invalid request: %s' % e)
received_scopes = response["scope"].split(" ")
for scope_set in self.__SCOPE_SETS.keys():
if scope_set in received_scopes:
received_scopes += self.__SCOPE_SETS[scope_set]
if not set(scopes) <= set(received_scopes):
raise MastodonAPIError(
'Granted scopes "' + " ".join(received_scopes) + '" do not contain all of the requested scopes "' + " ".join(scopes) + '".')
if to_file is not None:
with open(to_file, 'w') as token_file:
token_file.write(response['access_token'] + '\n')
self.__logged_in_id = None
return response['access_token'] | [
"def",
"log_in",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"code",
"=",
"None",
",",
"redirect_uri",
"=",
"\"urn:ietf:wg:oauth:2.0:oob\"",
",",
"refresh_token",
"=",
"None",
",",
"scopes",
"=",
"__DEFAULT_SCOPES",
",",
"to_file",
"=",
"None",
")",
":",
"if",
"username",
"is",
"not",
"None",
"and",
"password",
"is",
"not",
"None",
":",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'scopes'",
",",
"'to_file'",
",",
"'code'",
",",
"'refresh_token'",
"]",
")",
"params",
"[",
"'grant_type'",
"]",
"=",
"'password'",
"elif",
"code",
"is",
"not",
"None",
":",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'scopes'",
",",
"'to_file'",
",",
"'username'",
",",
"'password'",
",",
"'refresh_token'",
"]",
")",
"params",
"[",
"'grant_type'",
"]",
"=",
"'authorization_code'",
"elif",
"refresh_token",
"is",
"not",
"None",
":",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'scopes'",
",",
"'to_file'",
",",
"'username'",
",",
"'password'",
",",
"'code'",
"]",
")",
"params",
"[",
"'grant_type'",
"]",
"=",
"'refresh_token'",
"else",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"'Invalid arguments given. username and password or code are required.'",
")",
"params",
"[",
"'client_id'",
"]",
"=",
"self",
".",
"client_id",
"params",
"[",
"'client_secret'",
"]",
"=",
"self",
".",
"client_secret",
"params",
"[",
"'scope'",
"]",
"=",
"\" \"",
".",
"join",
"(",
"scopes",
")",
"try",
":",
"response",
"=",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"'/oauth/token'",
",",
"params",
",",
"do_ratelimiting",
"=",
"False",
")",
"self",
".",
"access_token",
"=",
"response",
"[",
"'access_token'",
"]",
"self",
".",
"__set_refresh_token",
"(",
"response",
".",
"get",
"(",
"'refresh_token'",
")",
")",
"self",
".",
"__set_token_expired",
"(",
"int",
"(",
"response",
".",
"get",
"(",
"'expires_in'",
",",
"0",
")",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"username",
"is",
"not",
"None",
"or",
"password",
"is",
"not",
"None",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"'Invalid user name, password, or redirect_uris: %s'",
"%",
"e",
")",
"elif",
"code",
"is",
"not",
"None",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"'Invalid access token or redirect_uris: %s'",
"%",
"e",
")",
"else",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"'Invalid request: %s'",
"%",
"e",
")",
"received_scopes",
"=",
"response",
"[",
"\"scope\"",
"]",
".",
"split",
"(",
"\" \"",
")",
"for",
"scope_set",
"in",
"self",
".",
"__SCOPE_SETS",
".",
"keys",
"(",
")",
":",
"if",
"scope_set",
"in",
"received_scopes",
":",
"received_scopes",
"+=",
"self",
".",
"__SCOPE_SETS",
"[",
"scope_set",
"]",
"if",
"not",
"set",
"(",
"scopes",
")",
"<=",
"set",
"(",
"received_scopes",
")",
":",
"raise",
"MastodonAPIError",
"(",
"'Granted scopes \"'",
"+",
"\" \"",
".",
"join",
"(",
"received_scopes",
")",
"+",
"'\" do not contain all of the requested scopes \"'",
"+",
"\" \"",
".",
"join",
"(",
"scopes",
")",
"+",
"'\".'",
")",
"if",
"to_file",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"to_file",
",",
"'w'",
")",
"as",
"token_file",
":",
"token_file",
".",
"write",
"(",
"response",
"[",
"'access_token'",
"]",
"+",
"'\\n'",
")",
"self",
".",
"__logged_in_id",
"=",
"None",
"return",
"response",
"[",
"'access_token'",
"]"
] | Get the access token for a user.
The username is the e-mail used to log in into mastodon.
Can persist access token to file `to_file`, to be used in the constructor.
Handles password and OAuth-based authorization.
Will throw a `MastodonIllegalArgumentError` if the OAuth or the
username / password credentials given are incorrect, and
`MastodonAPIError` if all of the requested scopes were not granted.
For OAuth2, obtain a code via having your user go to the url returned by
`auth_request_url()`_ and pass it as the code parameter. In this case,
make sure to also pass the same redirect_uri parameter as you used when
generating the auth request URL.
Returns the access token as a string. | [
"Get",
"the",
"access",
"token",
"for",
"a",
"user",
".",
"The",
"username",
"is",
"the",
"e",
"-",
"mail",
"used",
"to",
"log",
"in",
"into",
"mastodon",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L414-L481 |
5,830 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.timeline_list | def timeline_list(self, id, max_id=None, min_id=None, since_id=None, limit=None):
"""
Fetches a timeline containing all the toots by users in a given list.
Returns a list of `toot dicts`_.
"""
id = self.__unpack_id(id)
return self.timeline('list/{0}'.format(id), max_id=max_id,
min_id=min_id, since_id=since_id, limit=limit) | python | def timeline_list(self, id, max_id=None, min_id=None, since_id=None, limit=None):
"""
Fetches a timeline containing all the toots by users in a given list.
Returns a list of `toot dicts`_.
"""
id = self.__unpack_id(id)
return self.timeline('list/{0}'.format(id), max_id=max_id,
min_id=min_id, since_id=since_id, limit=limit) | [
"def",
"timeline_list",
"(",
"self",
",",
"id",
",",
"max_id",
"=",
"None",
",",
"min_id",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"return",
"self",
".",
"timeline",
"(",
"'list/{0}'",
".",
"format",
"(",
"id",
")",
",",
"max_id",
"=",
"max_id",
",",
"min_id",
"=",
"min_id",
",",
"since_id",
"=",
"since_id",
",",
"limit",
"=",
"limit",
")"
] | Fetches a timeline containing all the toots by users in a given list.
Returns a list of `toot dicts`_. | [
"Fetches",
"a",
"timeline",
"containing",
"all",
"the",
"toots",
"by",
"users",
"in",
"a",
"given",
"list",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L709-L717 |
5,831 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.conversations | def conversations(self, max_id=None, min_id=None, since_id=None, limit=None):
"""
Fetches a users conversations.
Returns a list of `conversation dicts`_.
"""
if max_id != None:
max_id = self.__unpack_id(max_id)
if min_id != None:
min_id = self.__unpack_id(min_id)
if since_id != None:
since_id = self.__unpack_id(since_id)
params = self.__generate_params(locals())
return self.__api_request('GET', "/api/v1/conversations/", params) | python | def conversations(self, max_id=None, min_id=None, since_id=None, limit=None):
"""
Fetches a users conversations.
Returns a list of `conversation dicts`_.
"""
if max_id != None:
max_id = self.__unpack_id(max_id)
if min_id != None:
min_id = self.__unpack_id(min_id)
if since_id != None:
since_id = self.__unpack_id(since_id)
params = self.__generate_params(locals())
return self.__api_request('GET', "/api/v1/conversations/", params) | [
"def",
"conversations",
"(",
"self",
",",
"max_id",
"=",
"None",
",",
"min_id",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"if",
"max_id",
"!=",
"None",
":",
"max_id",
"=",
"self",
".",
"__unpack_id",
"(",
"max_id",
")",
"if",
"min_id",
"!=",
"None",
":",
"min_id",
"=",
"self",
".",
"__unpack_id",
"(",
"min_id",
")",
"if",
"since_id",
"!=",
"None",
":",
"since_id",
"=",
"self",
".",
"__unpack_id",
"(",
"since_id",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"\"/api/v1/conversations/\"",
",",
"params",
")"
] | Fetches a users conversations.
Returns a list of `conversation dicts`_. | [
"Fetches",
"a",
"users",
"conversations",
".",
"Returns",
"a",
"list",
"of",
"conversation",
"dicts",
"_",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L720-L736 |
5,832 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status | def status(self, id):
"""
Fetch information about a single toot.
Does not require authentication for publicly visible statuses.
Returns a `toot dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}'.format(str(id))
return self.__api_request('GET', url) | python | def status(self, id):
"""
Fetch information about a single toot.
Does not require authentication for publicly visible statuses.
Returns a `toot dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"status",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch information about a single toot.
Does not require authentication for publicly visible statuses.
Returns a `toot dict`_. | [
"Fetch",
"information",
"about",
"a",
"single",
"toot",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L742-L752 |
5,833 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_context | def status_context(self, id):
"""
Fetch information about ancestors and descendants of a toot.
Does not require authentication for publicly visible statuses.
Returns a `context dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/context'.format(str(id))
return self.__api_request('GET', url) | python | def status_context(self, id):
"""
Fetch information about ancestors and descendants of a toot.
Does not require authentication for publicly visible statuses.
Returns a `context dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/context'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"status_context",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/context'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch information about ancestors and descendants of a toot.
Does not require authentication for publicly visible statuses.
Returns a `context dict`_. | [
"Fetch",
"information",
"about",
"ancestors",
"and",
"descendants",
"of",
"a",
"toot",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L769-L779 |
5,834 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_reblogged_by | def status_reblogged_by(self, id):
"""
Fetch a list of users that have reblogged a status.
Does not require authentication for publicly visible statuses.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/reblogged_by'.format(str(id))
return self.__api_request('GET', url) | python | def status_reblogged_by(self, id):
"""
Fetch a list of users that have reblogged a status.
Does not require authentication for publicly visible statuses.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/reblogged_by'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"status_reblogged_by",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/reblogged_by'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch a list of users that have reblogged a status.
Does not require authentication for publicly visible statuses.
Returns a list of `user dicts`_. | [
"Fetch",
"a",
"list",
"of",
"users",
"that",
"have",
"reblogged",
"a",
"status",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L782-L792 |
5,835 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_favourited_by | def status_favourited_by(self, id):
"""
Fetch a list of users that have favourited a status.
Does not require authentication for publicly visible statuses.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/favourited_by'.format(str(id))
return self.__api_request('GET', url) | python | def status_favourited_by(self, id):
"""
Fetch a list of users that have favourited a status.
Does not require authentication for publicly visible statuses.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/favourited_by'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"status_favourited_by",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/favourited_by'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch a list of users that have favourited a status.
Does not require authentication for publicly visible statuses.
Returns a list of `user dicts`_. | [
"Fetch",
"a",
"list",
"of",
"users",
"that",
"have",
"favourited",
"a",
"status",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L795-L805 |
5,836 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.scheduled_status | def scheduled_status(self, id):
"""
Fetch information about the scheduled status with the given id.
Returns a `scheduled toot dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/scheduled_statuses/{0}'.format(str(id))
return self.__api_request('GET', url) | python | def scheduled_status(self, id):
"""
Fetch information about the scheduled status with the given id.
Returns a `scheduled toot dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/scheduled_statuses/{0}'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"scheduled_status",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/scheduled_statuses/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch information about the scheduled status with the given id.
Returns a `scheduled toot dict`_. | [
"Fetch",
"information",
"about",
"the",
"scheduled",
"status",
"with",
"the",
"given",
"id",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L820-L828 |
5,837 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.poll | def poll(self, id):
"""
Fetch information about the poll with the given id
Returns a `poll dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/polls/{0}'.format(str(id))
return self.__api_request('GET', url) | python | def poll(self, id):
"""
Fetch information about the poll with the given id
Returns a `poll dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/polls/{0}'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"poll",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/polls/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch information about the poll with the given id
Returns a `poll dict`_. | [
"Fetch",
"information",
"about",
"the",
"poll",
"with",
"the",
"given",
"id"
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L834-L842 |
5,838 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.account | def account(self, id):
"""
Fetch account information by user `id`.
Does not require authentication.
Returns a `user dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}'.format(str(id))
return self.__api_request('GET', url) | python | def account(self, id):
"""
Fetch account information by user `id`.
Does not require authentication.
Returns a `user dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"account",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/accounts/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch account information by user `id`.
Does not require authentication.
Returns a `user dict`_. | [
"Fetch",
"account",
"information",
"by",
"user",
"id",
".",
"Does",
"not",
"require",
"authentication",
".",
"Returns",
"a",
"user",
"dict",
"_",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L878-L888 |
5,839 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.account_following | def account_following(self, id, max_id=None, min_id=None, since_id=None, limit=None):
"""
Fetch users the given user is following.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
if max_id != None:
max_id = self.__unpack_id(max_id)
if min_id != None:
min_id = self.__unpack_id(min_id)
if since_id != None:
since_id = self.__unpack_id(since_id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/accounts/{0}/following'.format(str(id))
return self.__api_request('GET', url, params) | python | def account_following(self, id, max_id=None, min_id=None, since_id=None, limit=None):
"""
Fetch users the given user is following.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
if max_id != None:
max_id = self.__unpack_id(max_id)
if min_id != None:
min_id = self.__unpack_id(min_id)
if since_id != None:
since_id = self.__unpack_id(since_id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/accounts/{0}/following'.format(str(id))
return self.__api_request('GET', url, params) | [
"def",
"account_following",
"(",
"self",
",",
"id",
",",
"max_id",
"=",
"None",
",",
"min_id",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"if",
"max_id",
"!=",
"None",
":",
"max_id",
"=",
"self",
".",
"__unpack_id",
"(",
"max_id",
")",
"if",
"min_id",
"!=",
"None",
":",
"min_id",
"=",
"self",
".",
"__unpack_id",
"(",
"min_id",
")",
"if",
"since_id",
"!=",
"None",
":",
"since_id",
"=",
"self",
".",
"__unpack_id",
"(",
"since_id",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'id'",
"]",
")",
"url",
"=",
"'/api/v1/accounts/{0}/following'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
",",
"params",
")"
] | Fetch users the given user is following.
Returns a list of `user dicts`_. | [
"Fetch",
"users",
"the",
"given",
"user",
"is",
"following",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L938-L956 |
5,840 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.account_lists | def account_lists(self, id):
"""
Get all of the logged-in users lists which the specified user is
a member of.
Returns a list of `list dicts`_.
"""
id = self.__unpack_id(id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/accounts/{0}/lists'.format(str(id))
return self.__api_request('GET', url, params) | python | def account_lists(self, id):
"""
Get all of the logged-in users lists which the specified user is
a member of.
Returns a list of `list dicts`_.
"""
id = self.__unpack_id(id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/accounts/{0}/lists'.format(str(id))
return self.__api_request('GET', url, params) | [
"def",
"account_lists",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'id'",
"]",
")",
"url",
"=",
"'/api/v1/accounts/{0}/lists'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
",",
"params",
")"
] | Get all of the logged-in users lists which the specified user is
a member of.
Returns a list of `list dicts`_. | [
"Get",
"all",
"of",
"the",
"logged",
"-",
"in",
"users",
"lists",
"which",
"the",
"specified",
"user",
"is",
"a",
"member",
"of",
".",
"Returns",
"a",
"list",
"of",
"list",
"dicts",
"_",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1009-L1019 |
5,841 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.filter | def filter(self, id):
"""
Fetches information about the filter with the specified `id`.
Returns a `filter dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/filters/{0}'.format(str(id))
return self.__api_request('GET', url) | python | def filter(self, id):
"""
Fetches information about the filter with the specified `id`.
Returns a `filter dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/filters/{0}'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"filter",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/filters/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetches information about the filter with the specified `id`.
Returns a `filter dict`_. | [
"Fetches",
"information",
"about",
"the",
"filter",
"with",
"the",
"specified",
"id",
".",
"Returns",
"a",
"filter",
"dict",
"_",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1034-L1042 |
5,842 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.search | def search(self, q, resolve=True, result_type=None, account_id=None, offset=None, min_id=None, max_id=None):
"""
Fetch matching hashtags, accounts and statuses. Will perform webfinger
lookups if resolve is True. Full-text search is only enabled if
the instance supports it, and is restricted to statuses the logged-in
user wrote or was mentioned in.
`result_type` can be one of "accounts", "hashtags" or "statuses", to only
search for that type of object.
Specify `account_id` to only get results from the account with that id.
`offset`, `min_id` and `max_id` can be used to paginate.
Returns a `search result dict`_, with tags as `hashtag dicts`_.
"""
return self.search_v2(q, resolve=resolve, result_type=result_type, account_id=account_id,
offset=offset, min_id=min_id, max_id=max_id) | python | def search(self, q, resolve=True, result_type=None, account_id=None, offset=None, min_id=None, max_id=None):
"""
Fetch matching hashtags, accounts and statuses. Will perform webfinger
lookups if resolve is True. Full-text search is only enabled if
the instance supports it, and is restricted to statuses the logged-in
user wrote or was mentioned in.
`result_type` can be one of "accounts", "hashtags" or "statuses", to only
search for that type of object.
Specify `account_id` to only get results from the account with that id.
`offset`, `min_id` and `max_id` can be used to paginate.
Returns a `search result dict`_, with tags as `hashtag dicts`_.
"""
return self.search_v2(q, resolve=resolve, result_type=result_type, account_id=account_id,
offset=offset, min_id=min_id, max_id=max_id) | [
"def",
"search",
"(",
"self",
",",
"q",
",",
"resolve",
"=",
"True",
",",
"result_type",
"=",
"None",
",",
"account_id",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"min_id",
"=",
"None",
",",
"max_id",
"=",
"None",
")",
":",
"return",
"self",
".",
"search_v2",
"(",
"q",
",",
"resolve",
"=",
"resolve",
",",
"result_type",
"=",
"result_type",
",",
"account_id",
"=",
"account_id",
",",
"offset",
"=",
"offset",
",",
"min_id",
"=",
"min_id",
",",
"max_id",
"=",
"max_id",
")"
] | Fetch matching hashtags, accounts and statuses. Will perform webfinger
lookups if resolve is True. Full-text search is only enabled if
the instance supports it, and is restricted to statuses the logged-in
user wrote or was mentioned in.
`result_type` can be one of "accounts", "hashtags" or "statuses", to only
search for that type of object.
Specify `account_id` to only get results from the account with that id.
`offset`, `min_id` and `max_id` can be used to paginate.
Returns a `search result dict`_, with tags as `hashtag dicts`_. | [
"Fetch",
"matching",
"hashtags",
"accounts",
"and",
"statuses",
".",
"Will",
"perform",
"webfinger",
"lookups",
"if",
"resolve",
"is",
"True",
".",
"Full",
"-",
"text",
"search",
"is",
"only",
"enabled",
"if",
"the",
"instance",
"supports",
"it",
"and",
"is",
"restricted",
"to",
"statuses",
"the",
"logged",
"-",
"in",
"user",
"wrote",
"or",
"was",
"mentioned",
"in",
".",
"result_type",
"can",
"be",
"one",
"of",
"accounts",
"hashtags",
"or",
"statuses",
"to",
"only",
"search",
"for",
"that",
"type",
"of",
"object",
".",
"Specify",
"account_id",
"to",
"only",
"get",
"results",
"from",
"the",
"account",
"with",
"that",
"id",
".",
"offset",
"min_id",
"and",
"max_id",
"can",
"be",
"used",
"to",
"paginate",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1110-L1127 |
5,843 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.list | def list(self, id):
"""
Fetch info about a specific list.
Returns a `list dict`_.
"""
id = self.__unpack_id(id)
return self.__api_request('GET', '/api/v1/lists/{0}'.format(id)) | python | def list(self, id):
"""
Fetch info about a specific list.
Returns a `list dict`_.
"""
id = self.__unpack_id(id)
return self.__api_request('GET', '/api/v1/lists/{0}'.format(id)) | [
"def",
"list",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"'/api/v1/lists/{0}'",
".",
"format",
"(",
"id",
")",
")"
] | Fetch info about a specific list.
Returns a `list dict`_. | [
"Fetch",
"info",
"about",
"a",
"specific",
"list",
".",
"Returns",
"a",
"list",
"dict",
"_",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1174-L1181 |
5,844 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.list_accounts | def list_accounts(self, id, max_id=None, min_id=None, since_id=None, limit=None):
"""
Get the accounts that are on the given list. A `limit` of 0 can
be specified to get all accounts without pagination.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
if max_id != None:
max_id = self.__unpack_id(max_id)
if min_id != None:
min_id = self.__unpack_id(min_id)
if since_id != None:
since_id = self.__unpack_id(since_id)
params = self.__generate_params(locals(), ['id'])
return self.__api_request('GET', '/api/v1/lists/{0}/accounts'.format(id)) | python | def list_accounts(self, id, max_id=None, min_id=None, since_id=None, limit=None):
"""
Get the accounts that are on the given list. A `limit` of 0 can
be specified to get all accounts without pagination.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
if max_id != None:
max_id = self.__unpack_id(max_id)
if min_id != None:
min_id = self.__unpack_id(min_id)
if since_id != None:
since_id = self.__unpack_id(since_id)
params = self.__generate_params(locals(), ['id'])
return self.__api_request('GET', '/api/v1/lists/{0}/accounts'.format(id)) | [
"def",
"list_accounts",
"(",
"self",
",",
"id",
",",
"max_id",
"=",
"None",
",",
"min_id",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"if",
"max_id",
"!=",
"None",
":",
"max_id",
"=",
"self",
".",
"__unpack_id",
"(",
"max_id",
")",
"if",
"min_id",
"!=",
"None",
":",
"min_id",
"=",
"self",
".",
"__unpack_id",
"(",
"min_id",
")",
"if",
"since_id",
"!=",
"None",
":",
"since_id",
"=",
"self",
".",
"__unpack_id",
"(",
"since_id",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'id'",
"]",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"'/api/v1/lists/{0}/accounts'",
".",
"format",
"(",
"id",
")",
")"
] | Get the accounts that are on the given list. A `limit` of 0 can
be specified to get all accounts without pagination.
Returns a list of `user dicts`_. | [
"Get",
"the",
"accounts",
"that",
"are",
"on",
"the",
"given",
"list",
".",
"A",
"limit",
"of",
"0",
"can",
"be",
"specified",
"to",
"get",
"all",
"accounts",
"without",
"pagination",
".",
"Returns",
"a",
"list",
"of",
"user",
"dicts",
"_",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1184-L1203 |
5,845 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_reply | def status_reply(self, to_status, status, media_ids=None, sensitive=False, visibility=None,
spoiler_text=None, language=None, idempotency_key=None, content_type=None,
scheduled_at=None, poll=None, untag=False):
"""
Helper function - acts like status_post, but prepends the name of all
the users that are being replied to to the status text and retains
CW and visibility if not explicitly overridden.
Set `untag` to True if you want the reply to only go to the user you
are replying to, removing every other mentioned user from the
conversation.
"""
user_id = self.__get_logged_in_id()
# Determine users to mention
mentioned_accounts = collections.OrderedDict()
mentioned_accounts[to_status.account.id] = to_status.account.acct
if not untag:
for account in to_status.mentions:
if account.id != user_id and not account.id in mentioned_accounts.keys():
mentioned_accounts[account.id] = account.acct
# Join into one piece of text. The space is added inside because of self-replies.
status = "".join(map(lambda x: "@" + x + " ", mentioned_accounts.values())) + status
# Retain visibility / cw
if visibility == None and 'visibility' in to_status:
visibility = to_status.visibility
if spoiler_text == None and 'spoiler_text' in to_status:
spoiler_text = to_status.spoiler_text
return self.status_post(status, in_reply_to_id = to_status.id, media_ids = media_ids, sensitive = sensitive,
visibility = visibility, spoiler_text = spoiler_text, language = language,
idempotency_key = idempotency_key, content_type = content_type,
scheduled_at = scheduled_at, poll = poll) | python | def status_reply(self, to_status, status, media_ids=None, sensitive=False, visibility=None,
spoiler_text=None, language=None, idempotency_key=None, content_type=None,
scheduled_at=None, poll=None, untag=False):
"""
Helper function - acts like status_post, but prepends the name of all
the users that are being replied to to the status text and retains
CW and visibility if not explicitly overridden.
Set `untag` to True if you want the reply to only go to the user you
are replying to, removing every other mentioned user from the
conversation.
"""
user_id = self.__get_logged_in_id()
# Determine users to mention
mentioned_accounts = collections.OrderedDict()
mentioned_accounts[to_status.account.id] = to_status.account.acct
if not untag:
for account in to_status.mentions:
if account.id != user_id and not account.id in mentioned_accounts.keys():
mentioned_accounts[account.id] = account.acct
# Join into one piece of text. The space is added inside because of self-replies.
status = "".join(map(lambda x: "@" + x + " ", mentioned_accounts.values())) + status
# Retain visibility / cw
if visibility == None and 'visibility' in to_status:
visibility = to_status.visibility
if spoiler_text == None and 'spoiler_text' in to_status:
spoiler_text = to_status.spoiler_text
return self.status_post(status, in_reply_to_id = to_status.id, media_ids = media_ids, sensitive = sensitive,
visibility = visibility, spoiler_text = spoiler_text, language = language,
idempotency_key = idempotency_key, content_type = content_type,
scheduled_at = scheduled_at, poll = poll) | [
"def",
"status_reply",
"(",
"self",
",",
"to_status",
",",
"status",
",",
"media_ids",
"=",
"None",
",",
"sensitive",
"=",
"False",
",",
"visibility",
"=",
"None",
",",
"spoiler_text",
"=",
"None",
",",
"language",
"=",
"None",
",",
"idempotency_key",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"scheduled_at",
"=",
"None",
",",
"poll",
"=",
"None",
",",
"untag",
"=",
"False",
")",
":",
"user_id",
"=",
"self",
".",
"__get_logged_in_id",
"(",
")",
"# Determine users to mention",
"mentioned_accounts",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"mentioned_accounts",
"[",
"to_status",
".",
"account",
".",
"id",
"]",
"=",
"to_status",
".",
"account",
".",
"acct",
"if",
"not",
"untag",
":",
"for",
"account",
"in",
"to_status",
".",
"mentions",
":",
"if",
"account",
".",
"id",
"!=",
"user_id",
"and",
"not",
"account",
".",
"id",
"in",
"mentioned_accounts",
".",
"keys",
"(",
")",
":",
"mentioned_accounts",
"[",
"account",
".",
"id",
"]",
"=",
"account",
".",
"acct",
"# Join into one piece of text. The space is added inside because of self-replies.",
"status",
"=",
"\"\"",
".",
"join",
"(",
"map",
"(",
"lambda",
"x",
":",
"\"@\"",
"+",
"x",
"+",
"\" \"",
",",
"mentioned_accounts",
".",
"values",
"(",
")",
")",
")",
"+",
"status",
"# Retain visibility / cw",
"if",
"visibility",
"==",
"None",
"and",
"'visibility'",
"in",
"to_status",
":",
"visibility",
"=",
"to_status",
".",
"visibility",
"if",
"spoiler_text",
"==",
"None",
"and",
"'spoiler_text'",
"in",
"to_status",
":",
"spoiler_text",
"=",
"to_status",
".",
"spoiler_text",
"return",
"self",
".",
"status_post",
"(",
"status",
",",
"in_reply_to_id",
"=",
"to_status",
".",
"id",
",",
"media_ids",
"=",
"media_ids",
",",
"sensitive",
"=",
"sensitive",
",",
"visibility",
"=",
"visibility",
",",
"spoiler_text",
"=",
"spoiler_text",
",",
"language",
"=",
"language",
",",
"idempotency_key",
"=",
"idempotency_key",
",",
"content_type",
"=",
"content_type",
",",
"scheduled_at",
"=",
"scheduled_at",
",",
"poll",
"=",
"poll",
")"
] | Helper function - acts like status_post, but prepends the name of all
the users that are being replied to to the status text and retains
CW and visibility if not explicitly overridden.
Set `untag` to True if you want the reply to only go to the user you
are replying to, removing every other mentioned user from the
conversation. | [
"Helper",
"function",
"-",
"acts",
"like",
"status_post",
"but",
"prepends",
"the",
"name",
"of",
"all",
"the",
"users",
"that",
"are",
"being",
"replied",
"to",
"to",
"the",
"status",
"text",
"and",
"retains",
"CW",
"and",
"visibility",
"if",
"not",
"explicitly",
"overridden",
".",
"Set",
"untag",
"to",
"True",
"if",
"you",
"want",
"the",
"reply",
"to",
"only",
"go",
"to",
"the",
"user",
"you",
"are",
"replying",
"to",
"removing",
"every",
"other",
"mentioned",
"user",
"from",
"the",
"conversation",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1506-L1541 |
5,846 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_delete | def status_delete(self, id):
"""
Delete a status
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}'.format(str(id))
self.__api_request('DELETE', url) | python | def status_delete(self, id):
"""
Delete a status
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}'.format(str(id))
self.__api_request('DELETE', url) | [
"def",
"status_delete",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"self",
".",
"__api_request",
"(",
"'DELETE'",
",",
"url",
")"
] | Delete a status | [
"Delete",
"a",
"status"
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1558-L1564 |
5,847 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_unreblog | def status_unreblog(self, id):
"""
Un-reblog a status.
Returns a `toot dict`_ with the status that used to be reblogged.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/unreblog'.format(str(id))
return self.__api_request('POST', url) | python | def status_unreblog(self, id):
"""
Un-reblog a status.
Returns a `toot dict`_ with the status that used to be reblogged.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/unreblog'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"status_unreblog",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/unreblog'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] | Un-reblog a status.
Returns a `toot dict`_ with the status that used to be reblogged. | [
"Un",
"-",
"reblog",
"a",
"status",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1589-L1597 |
5,848 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_favourite | def status_favourite(self, id):
"""
Favourite a status.
Returns a `toot dict`_ with the favourited status.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/favourite'.format(str(id))
return self.__api_request('POST', url) | python | def status_favourite(self, id):
"""
Favourite a status.
Returns a `toot dict`_ with the favourited status.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/favourite'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"status_favourite",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/favourite'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] | Favourite a status.
Returns a `toot dict`_ with the favourited status. | [
"Favourite",
"a",
"status",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1600-L1608 |
5,849 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_unfavourite | def status_unfavourite(self, id):
"""
Un-favourite a status.
Returns a `toot dict`_ with the un-favourited status.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/unfavourite'.format(str(id))
return self.__api_request('POST', url) | python | def status_unfavourite(self, id):
"""
Un-favourite a status.
Returns a `toot dict`_ with the un-favourited status.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/unfavourite'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"status_unfavourite",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/unfavourite'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] | Un-favourite a status.
Returns a `toot dict`_ with the un-favourited status. | [
"Un",
"-",
"favourite",
"a",
"status",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1611-L1619 |
5,850 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_mute | def status_mute(self, id):
"""
Mute notifications for a status.
Returns a `toot dict`_ with the now muted status
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/mute'.format(str(id))
return self.__api_request('POST', url) | python | def status_mute(self, id):
"""
Mute notifications for a status.
Returns a `toot dict`_ with the now muted status
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/mute'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"status_mute",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/mute'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] | Mute notifications for a status.
Returns a `toot dict`_ with the now muted status | [
"Mute",
"notifications",
"for",
"a",
"status",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1622-L1630 |
5,851 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_unmute | def status_unmute(self, id):
"""
Unmute notifications for a status.
Returns a `toot dict`_ with the status that used to be muted.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/unmute'.format(str(id))
return self.__api_request('POST', url) | python | def status_unmute(self, id):
"""
Unmute notifications for a status.
Returns a `toot dict`_ with the status that used to be muted.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/unmute'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"status_unmute",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/unmute'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] | Unmute notifications for a status.
Returns a `toot dict`_ with the status that used to be muted. | [
"Unmute",
"notifications",
"for",
"a",
"status",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1633-L1641 |
5,852 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_pin | def status_pin(self, id):
"""
Pin a status for the logged-in user.
Returns a `toot dict`_ with the now pinned status
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/pin'.format(str(id))
return self.__api_request('POST', url) | python | def status_pin(self, id):
"""
Pin a status for the logged-in user.
Returns a `toot dict`_ with the now pinned status
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/pin'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"status_pin",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/pin'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] | Pin a status for the logged-in user.
Returns a `toot dict`_ with the now pinned status | [
"Pin",
"a",
"status",
"for",
"the",
"logged",
"-",
"in",
"user",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1644-L1652 |
5,853 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_unpin | def status_unpin(self, id):
"""
Unpin a pinned status for the logged-in user.
Returns a `toot dict`_ with the status that used to be pinned.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/unpin'.format(str(id))
return self.__api_request('POST', url) | python | def status_unpin(self, id):
"""
Unpin a pinned status for the logged-in user.
Returns a `toot dict`_ with the status that used to be pinned.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/unpin'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"status_unpin",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/unpin'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] | Unpin a pinned status for the logged-in user.
Returns a `toot dict`_ with the status that used to be pinned. | [
"Unpin",
"a",
"pinned",
"status",
"for",
"the",
"logged",
"-",
"in",
"user",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1655-L1663 |
5,854 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.scheduled_status_update | def scheduled_status_update(self, id, scheduled_at):
"""
Update the scheduled time of a scheduled status.
New time must be at least 5 minutes into the future.
Returns a `scheduled toot dict`_
"""
scheduled_at = self.__consistent_isoformat_utc(scheduled_at)
id = self.__unpack_id(id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/scheduled_statuses/{0}'.format(str(id))
return self.__api_request('PUT', url, params) | python | def scheduled_status_update(self, id, scheduled_at):
"""
Update the scheduled time of a scheduled status.
New time must be at least 5 minutes into the future.
Returns a `scheduled toot dict`_
"""
scheduled_at = self.__consistent_isoformat_utc(scheduled_at)
id = self.__unpack_id(id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/scheduled_statuses/{0}'.format(str(id))
return self.__api_request('PUT', url, params) | [
"def",
"scheduled_status_update",
"(",
"self",
",",
"id",
",",
"scheduled_at",
")",
":",
"scheduled_at",
"=",
"self",
".",
"__consistent_isoformat_utc",
"(",
"scheduled_at",
")",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'id'",
"]",
")",
"url",
"=",
"'/api/v1/scheduled_statuses/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'PUT'",
",",
"url",
",",
"params",
")"
] | Update the scheduled time of a scheduled status.
New time must be at least 5 minutes into the future.
Returns a `scheduled toot dict`_ | [
"Update",
"the",
"scheduled",
"time",
"of",
"a",
"scheduled",
"status",
".",
"New",
"time",
"must",
"be",
"at",
"least",
"5",
"minutes",
"into",
"the",
"future",
".",
"Returns",
"a",
"scheduled",
"toot",
"dict",
"_"
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1669-L1681 |
5,855 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.scheduled_status_delete | def scheduled_status_delete(self, id):
"""
Deletes a scheduled status.
"""
id = self.__unpack_id(id)
url = '/api/v1/scheduled_statuses/{0}'.format(str(id))
self.__api_request('DELETE', url) | python | def scheduled_status_delete(self, id):
"""
Deletes a scheduled status.
"""
id = self.__unpack_id(id)
url = '/api/v1/scheduled_statuses/{0}'.format(str(id))
self.__api_request('DELETE', url) | [
"def",
"scheduled_status_delete",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/scheduled_statuses/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"self",
".",
"__api_request",
"(",
"'DELETE'",
",",
"url",
")"
] | Deletes a scheduled status. | [
"Deletes",
"a",
"scheduled",
"status",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1684-L1690 |
5,856 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.poll_vote | def poll_vote(self, id, choices):
"""
Vote in the given poll.
`choices` is the index of the choice you wish to register a vote for
(i.e. its index in the corresponding polls `options` field. In case
of a poll that allows selection of more than one option, a list of
indices can be passed.
You can only submit choices for any given poll once in case of
single-option polls, or only once per option in case of multi-option
polls.
Returns the updated `poll dict`_
"""
id = self.__unpack_id(id)
if not isinstance(choices, list):
choices = [choices]
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/polls/{0}/votes'.format(id)
self.__api_request('POST', url, params) | python | def poll_vote(self, id, choices):
"""
Vote in the given poll.
`choices` is the index of the choice you wish to register a vote for
(i.e. its index in the corresponding polls `options` field. In case
of a poll that allows selection of more than one option, a list of
indices can be passed.
You can only submit choices for any given poll once in case of
single-option polls, or only once per option in case of multi-option
polls.
Returns the updated `poll dict`_
"""
id = self.__unpack_id(id)
if not isinstance(choices, list):
choices = [choices]
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/polls/{0}/votes'.format(id)
self.__api_request('POST', url, params) | [
"def",
"poll_vote",
"(",
"self",
",",
"id",
",",
"choices",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"if",
"not",
"isinstance",
"(",
"choices",
",",
"list",
")",
":",
"choices",
"=",
"[",
"choices",
"]",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'id'",
"]",
")",
"url",
"=",
"'/api/v1/polls/{0}/votes'",
".",
"format",
"(",
"id",
")",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
",",
"params",
")"
] | Vote in the given poll.
`choices` is the index of the choice you wish to register a vote for
(i.e. its index in the corresponding polls `options` field. In case
of a poll that allows selection of more than one option, a list of
indices can be passed.
You can only submit choices for any given poll once in case of
single-option polls, or only once per option in case of multi-option
polls.
Returns the updated `poll dict`_ | [
"Vote",
"in",
"the",
"given",
"poll",
".",
"choices",
"is",
"the",
"index",
"of",
"the",
"choice",
"you",
"wish",
"to",
"register",
"a",
"vote",
"for",
"(",
"i",
".",
"e",
".",
"its",
"index",
"in",
"the",
"corresponding",
"polls",
"options",
"field",
".",
"In",
"case",
"of",
"a",
"poll",
"that",
"allows",
"selection",
"of",
"more",
"than",
"one",
"option",
"a",
"list",
"of",
"indices",
"can",
"be",
"passed",
".",
"You",
"can",
"only",
"submit",
"choices",
"for",
"any",
"given",
"poll",
"once",
"in",
"case",
"of",
"single",
"-",
"option",
"polls",
"or",
"only",
"once",
"per",
"option",
"in",
"case",
"of",
"multi",
"-",
"option",
"polls",
".",
"Returns",
"the",
"updated",
"poll",
"dict",
"_"
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1696-L1717 |
5,857 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.notifications_dismiss | def notifications_dismiss(self, id):
"""
Deletes a single notification
"""
id = self.__unpack_id(id)
params = self.__generate_params(locals())
self.__api_request('POST', '/api/v1/notifications/dismiss', params) | python | def notifications_dismiss(self, id):
"""
Deletes a single notification
"""
id = self.__unpack_id(id)
params = self.__generate_params(locals())
self.__api_request('POST', '/api/v1/notifications/dismiss', params) | [
"def",
"notifications_dismiss",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
")",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"'/api/v1/notifications/dismiss'",
",",
"params",
")"
] | Deletes a single notification | [
"Deletes",
"a",
"single",
"notification"
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1732-L1738 |
5,858 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.account_block | def account_block(self, id):
"""
Block a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/block'.format(str(id))
return self.__api_request('POST', url) | python | def account_block(self, id):
"""
Block a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/block'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"account_block",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/accounts/{0}/block'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] | Block a user.
Returns a `relationship dict`_ containing the updated relationship to the user. | [
"Block",
"a",
"user",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1801-L1809 |
5,859 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.account_unblock | def account_unblock(self, id):
"""
Unblock a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/unblock'.format(str(id))
return self.__api_request('POST', url) | python | def account_unblock(self, id):
"""
Unblock a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/unblock'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"account_unblock",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/accounts/{0}/unblock'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] | Unblock a user.
Returns a `relationship dict`_ containing the updated relationship to the user. | [
"Unblock",
"a",
"user",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1812-L1820 |
5,860 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.account_mute | def account_mute(self, id, notifications=True):
"""
Mute a user.
Set `notifications` to False to receive notifications even though the user is
muted from timelines.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/accounts/{0}/mute'.format(str(id))
return self.__api_request('POST', url, params) | python | def account_mute(self, id, notifications=True):
"""
Mute a user.
Set `notifications` to False to receive notifications even though the user is
muted from timelines.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/accounts/{0}/mute'.format(str(id))
return self.__api_request('POST', url, params) | [
"def",
"account_mute",
"(",
"self",
",",
"id",
",",
"notifications",
"=",
"True",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'id'",
"]",
")",
"url",
"=",
"'/api/v1/accounts/{0}/mute'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
",",
"params",
")"
] | Mute a user.
Set `notifications` to False to receive notifications even though the user is
muted from timelines.
Returns a `relationship dict`_ containing the updated relationship to the user. | [
"Mute",
"a",
"user",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1823-L1835 |
5,861 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.account_unmute | def account_unmute(self, id):
"""
Unmute a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/unmute'.format(str(id))
return self.__api_request('POST', url) | python | def account_unmute(self, id):
"""
Unmute a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/unmute'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"account_unmute",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/accounts/{0}/unmute'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] | Unmute a user.
Returns a `relationship dict`_ containing the updated relationship to the user. | [
"Unmute",
"a",
"user",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1838-L1846 |
5,862 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.account_update_credentials | def account_update_credentials(self, display_name=None, note=None,
avatar=None, avatar_mime_type=None,
header=None, header_mime_type=None,
locked=None, fields=None):
"""
Update the profile for the currently logged-in user.
'note' is the user's bio.
'avatar' and 'header' are images. As with media uploads, it is possible to either
pass image data and a mime type, or a filename of an image file, for either.
'locked' specifies whether the user needs to manually approve follow requests.
'fields' can be a list of up to four name-value pairs (specified as tuples) to
appear as semi-structured information in the users profile.
Returns the updated `user dict` of the logged-in user.
"""
params_initial = collections.OrderedDict(locals())
# Load avatar, if specified
if not avatar is None:
if avatar_mime_type is None and (isinstance(avatar, str) and os.path.isfile(avatar)):
avatar_mime_type = guess_type(avatar)
avatar = open(avatar, 'rb')
if avatar_mime_type is None:
raise MastodonIllegalArgumentError('Could not determine mime type or data passed directly without mime type.')
# Load header, if specified
if not header is None:
if header_mime_type is None and (isinstance(avatar, str) and os.path.isfile(header)):
header_mime_type = guess_type(header)
header = open(header, 'rb')
if header_mime_type is None:
raise MastodonIllegalArgumentError('Could not determine mime type or data passed directly without mime type.')
# Convert fields
if fields != None:
if len(fields) > 4:
raise MastodonIllegalArgumentError('A maximum of four fields are allowed.')
fields_attributes = []
for idx, (field_name, field_value) in enumerate(fields):
params_initial['fields_attributes[' + str(idx) + '][name]'] = field_name
params_initial['fields_attributes[' + str(idx) + '][value]'] = field_value
# Clean up params
for param in ["avatar", "avatar_mime_type", "header", "header_mime_type", "fields"]:
if param in params_initial:
del params_initial[param]
# Create file info
files = {}
if not avatar is None:
avatar_file_name = "mastodonpyupload_" + mimetypes.guess_extension(avatar_mime_type)
files["avatar"] = (avatar_file_name, avatar, avatar_mime_type)
if not header is None:
header_file_name = "mastodonpyupload_" + mimetypes.guess_extension(header_mime_type)
files["header"] = (header_file_name, header, header_mime_type)
params = self.__generate_params(params_initial)
return self.__api_request('PATCH', '/api/v1/accounts/update_credentials', params, files=files) | python | def account_update_credentials(self, display_name=None, note=None,
avatar=None, avatar_mime_type=None,
header=None, header_mime_type=None,
locked=None, fields=None):
"""
Update the profile for the currently logged-in user.
'note' is the user's bio.
'avatar' and 'header' are images. As with media uploads, it is possible to either
pass image data and a mime type, or a filename of an image file, for either.
'locked' specifies whether the user needs to manually approve follow requests.
'fields' can be a list of up to four name-value pairs (specified as tuples) to
appear as semi-structured information in the users profile.
Returns the updated `user dict` of the logged-in user.
"""
params_initial = collections.OrderedDict(locals())
# Load avatar, if specified
if not avatar is None:
if avatar_mime_type is None and (isinstance(avatar, str) and os.path.isfile(avatar)):
avatar_mime_type = guess_type(avatar)
avatar = open(avatar, 'rb')
if avatar_mime_type is None:
raise MastodonIllegalArgumentError('Could not determine mime type or data passed directly without mime type.')
# Load header, if specified
if not header is None:
if header_mime_type is None and (isinstance(avatar, str) and os.path.isfile(header)):
header_mime_type = guess_type(header)
header = open(header, 'rb')
if header_mime_type is None:
raise MastodonIllegalArgumentError('Could not determine mime type or data passed directly without mime type.')
# Convert fields
if fields != None:
if len(fields) > 4:
raise MastodonIllegalArgumentError('A maximum of four fields are allowed.')
fields_attributes = []
for idx, (field_name, field_value) in enumerate(fields):
params_initial['fields_attributes[' + str(idx) + '][name]'] = field_name
params_initial['fields_attributes[' + str(idx) + '][value]'] = field_value
# Clean up params
for param in ["avatar", "avatar_mime_type", "header", "header_mime_type", "fields"]:
if param in params_initial:
del params_initial[param]
# Create file info
files = {}
if not avatar is None:
avatar_file_name = "mastodonpyupload_" + mimetypes.guess_extension(avatar_mime_type)
files["avatar"] = (avatar_file_name, avatar, avatar_mime_type)
if not header is None:
header_file_name = "mastodonpyupload_" + mimetypes.guess_extension(header_mime_type)
files["header"] = (header_file_name, header, header_mime_type)
params = self.__generate_params(params_initial)
return self.__api_request('PATCH', '/api/v1/accounts/update_credentials', params, files=files) | [
"def",
"account_update_credentials",
"(",
"self",
",",
"display_name",
"=",
"None",
",",
"note",
"=",
"None",
",",
"avatar",
"=",
"None",
",",
"avatar_mime_type",
"=",
"None",
",",
"header",
"=",
"None",
",",
"header_mime_type",
"=",
"None",
",",
"locked",
"=",
"None",
",",
"fields",
"=",
"None",
")",
":",
"params_initial",
"=",
"collections",
".",
"OrderedDict",
"(",
"locals",
"(",
")",
")",
"# Load avatar, if specified",
"if",
"not",
"avatar",
"is",
"None",
":",
"if",
"avatar_mime_type",
"is",
"None",
"and",
"(",
"isinstance",
"(",
"avatar",
",",
"str",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"avatar",
")",
")",
":",
"avatar_mime_type",
"=",
"guess_type",
"(",
"avatar",
")",
"avatar",
"=",
"open",
"(",
"avatar",
",",
"'rb'",
")",
"if",
"avatar_mime_type",
"is",
"None",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"'Could not determine mime type or data passed directly without mime type.'",
")",
"# Load header, if specified",
"if",
"not",
"header",
"is",
"None",
":",
"if",
"header_mime_type",
"is",
"None",
"and",
"(",
"isinstance",
"(",
"avatar",
",",
"str",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"header",
")",
")",
":",
"header_mime_type",
"=",
"guess_type",
"(",
"header",
")",
"header",
"=",
"open",
"(",
"header",
",",
"'rb'",
")",
"if",
"header_mime_type",
"is",
"None",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"'Could not determine mime type or data passed directly without mime type.'",
")",
"# Convert fields",
"if",
"fields",
"!=",
"None",
":",
"if",
"len",
"(",
"fields",
")",
">",
"4",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"'A maximum of four fields are allowed.'",
")",
"fields_attributes",
"=",
"[",
"]",
"for",
"idx",
",",
"(",
"field_name",
",",
"field_value",
")",
"in",
"enumerate",
"(",
"fields",
")",
":",
"params_initial",
"[",
"'fields_attributes['",
"+",
"str",
"(",
"idx",
")",
"+",
"'][name]'",
"]",
"=",
"field_name",
"params_initial",
"[",
"'fields_attributes['",
"+",
"str",
"(",
"idx",
")",
"+",
"'][value]'",
"]",
"=",
"field_value",
"# Clean up params",
"for",
"param",
"in",
"[",
"\"avatar\"",
",",
"\"avatar_mime_type\"",
",",
"\"header\"",
",",
"\"header_mime_type\"",
",",
"\"fields\"",
"]",
":",
"if",
"param",
"in",
"params_initial",
":",
"del",
"params_initial",
"[",
"param",
"]",
"# Create file info",
"files",
"=",
"{",
"}",
"if",
"not",
"avatar",
"is",
"None",
":",
"avatar_file_name",
"=",
"\"mastodonpyupload_\"",
"+",
"mimetypes",
".",
"guess_extension",
"(",
"avatar_mime_type",
")",
"files",
"[",
"\"avatar\"",
"]",
"=",
"(",
"avatar_file_name",
",",
"avatar",
",",
"avatar_mime_type",
")",
"if",
"not",
"header",
"is",
"None",
":",
"header_file_name",
"=",
"\"mastodonpyupload_\"",
"+",
"mimetypes",
".",
"guess_extension",
"(",
"header_mime_type",
")",
"files",
"[",
"\"header\"",
"]",
"=",
"(",
"header_file_name",
",",
"header",
",",
"header_mime_type",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"params_initial",
")",
"return",
"self",
".",
"__api_request",
"(",
"'PATCH'",
",",
"'/api/v1/accounts/update_credentials'",
",",
"params",
",",
"files",
"=",
"files",
")"
] | Update the profile for the currently logged-in user.
'note' is the user's bio.
'avatar' and 'header' are images. As with media uploads, it is possible to either
pass image data and a mime type, or a filename of an image file, for either.
'locked' specifies whether the user needs to manually approve follow requests.
'fields' can be a list of up to four name-value pairs (specified as tuples) to
appear as semi-structured information in the users profile.
Returns the updated `user dict` of the logged-in user. | [
"Update",
"the",
"profile",
"for",
"the",
"currently",
"logged",
"-",
"in",
"user",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1849-L1913 |
5,863 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.filter_create | def filter_create(self, phrase, context, irreversible = False, whole_word = True, expires_in = None):
"""
Creates a new keyword filter. `phrase` is the phrase that should be
filtered out, `context` specifies from where to filter the keywords.
Valid contexts are 'home', 'notifications', 'public' and 'thread'.
Set `irreversible` to True if you want the filter to just delete statuses
server side. This works only for the 'home' and 'notifications' contexts.
Set `whole_word` to False if you want to allow filter matches to
start or end within a word, not only at word boundaries.
Set `expires_in` to specify for how many seconds the filter should be
kept around.
Returns the `filter dict`_ of the newly created filter.
"""
params = self.__generate_params(locals())
for context_val in context:
if not context_val in ['home', 'notifications', 'public', 'thread']:
raise MastodonIllegalArgumentError('Invalid filter context.')
return self.__api_request('POST', '/api/v1/filters', params) | python | def filter_create(self, phrase, context, irreversible = False, whole_word = True, expires_in = None):
"""
Creates a new keyword filter. `phrase` is the phrase that should be
filtered out, `context` specifies from where to filter the keywords.
Valid contexts are 'home', 'notifications', 'public' and 'thread'.
Set `irreversible` to True if you want the filter to just delete statuses
server side. This works only for the 'home' and 'notifications' contexts.
Set `whole_word` to False if you want to allow filter matches to
start or end within a word, not only at word boundaries.
Set `expires_in` to specify for how many seconds the filter should be
kept around.
Returns the `filter dict`_ of the newly created filter.
"""
params = self.__generate_params(locals())
for context_val in context:
if not context_val in ['home', 'notifications', 'public', 'thread']:
raise MastodonIllegalArgumentError('Invalid filter context.')
return self.__api_request('POST', '/api/v1/filters', params) | [
"def",
"filter_create",
"(",
"self",
",",
"phrase",
",",
"context",
",",
"irreversible",
"=",
"False",
",",
"whole_word",
"=",
"True",
",",
"expires_in",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
")",
"for",
"context_val",
"in",
"context",
":",
"if",
"not",
"context_val",
"in",
"[",
"'home'",
",",
"'notifications'",
",",
"'public'",
",",
"'thread'",
"]",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"'Invalid filter context.'",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"'/api/v1/filters'",
",",
"params",
")"
] | Creates a new keyword filter. `phrase` is the phrase that should be
filtered out, `context` specifies from where to filter the keywords.
Valid contexts are 'home', 'notifications', 'public' and 'thread'.
Set `irreversible` to True if you want the filter to just delete statuses
server side. This works only for the 'home' and 'notifications' contexts.
Set `whole_word` to False if you want to allow filter matches to
start or end within a word, not only at word boundaries.
Set `expires_in` to specify for how many seconds the filter should be
kept around.
Returns the `filter dict`_ of the newly created filter. | [
"Creates",
"a",
"new",
"keyword",
"filter",
".",
"phrase",
"is",
"the",
"phrase",
"that",
"should",
"be",
"filtered",
"out",
"context",
"specifies",
"from",
"where",
"to",
"filter",
"the",
"keywords",
".",
"Valid",
"contexts",
"are",
"home",
"notifications",
"public",
"and",
"thread",
".",
"Set",
"irreversible",
"to",
"True",
"if",
"you",
"want",
"the",
"filter",
"to",
"just",
"delete",
"statuses",
"server",
"side",
".",
"This",
"works",
"only",
"for",
"the",
"home",
"and",
"notifications",
"contexts",
".",
"Set",
"whole_word",
"to",
"False",
"if",
"you",
"want",
"to",
"allow",
"filter",
"matches",
"to",
"start",
"or",
"end",
"within",
"a",
"word",
"not",
"only",
"at",
"word",
"boundaries",
".",
"Set",
"expires_in",
"to",
"specify",
"for",
"how",
"many",
"seconds",
"the",
"filter",
"should",
"be",
"kept",
"around",
".",
"Returns",
"the",
"filter",
"dict",
"_",
"of",
"the",
"newly",
"created",
"filter",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1942-L1965 |
5,864 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.filter_delete | def filter_delete(self, id):
"""
Deletes the filter with the given `id`.
"""
id = self.__unpack_id(id)
url = '/api/v1/filters/{0}'.format(str(id))
self.__api_request('DELETE', url) | python | def filter_delete(self, id):
"""
Deletes the filter with the given `id`.
"""
id = self.__unpack_id(id)
url = '/api/v1/filters/{0}'.format(str(id))
self.__api_request('DELETE', url) | [
"def",
"filter_delete",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/filters/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"self",
".",
"__api_request",
"(",
"'DELETE'",
",",
"url",
")"
] | Deletes the filter with the given `id`. | [
"Deletes",
"the",
"filter",
"with",
"the",
"given",
"id",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1981-L1987 |
5,865 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.suggestion_delete | def suggestion_delete(self, account_id):
"""
Remove the user with the given `account_id` from the follow suggestions.
"""
account_id = self.__unpack_id(account_id)
url = '/api/v1/suggestions/{0}'.format(str(account_id))
self.__api_request('DELETE', url) | python | def suggestion_delete(self, account_id):
"""
Remove the user with the given `account_id` from the follow suggestions.
"""
account_id = self.__unpack_id(account_id)
url = '/api/v1/suggestions/{0}'.format(str(account_id))
self.__api_request('DELETE', url) | [
"def",
"suggestion_delete",
"(",
"self",
",",
"account_id",
")",
":",
"account_id",
"=",
"self",
".",
"__unpack_id",
"(",
"account_id",
")",
"url",
"=",
"'/api/v1/suggestions/{0}'",
".",
"format",
"(",
"str",
"(",
"account_id",
")",
")",
"self",
".",
"__api_request",
"(",
"'DELETE'",
",",
"url",
")"
] | Remove the user with the given `account_id` from the follow suggestions. | [
"Remove",
"the",
"user",
"with",
"the",
"given",
"account_id",
"from",
"the",
"follow",
"suggestions",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1993-L1999 |
5,866 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.list_create | def list_create(self, title):
"""
Create a new list with the given `title`.
Returns the `list dict`_ of the created list.
"""
params = self.__generate_params(locals())
return self.__api_request('POST', '/api/v1/lists', params) | python | def list_create(self, title):
"""
Create a new list with the given `title`.
Returns the `list dict`_ of the created list.
"""
params = self.__generate_params(locals())
return self.__api_request('POST', '/api/v1/lists', params) | [
"def",
"list_create",
"(",
"self",
",",
"title",
")",
":",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"'/api/v1/lists'",
",",
"params",
")"
] | Create a new list with the given `title`.
Returns the `list dict`_ of the created list. | [
"Create",
"a",
"new",
"list",
"with",
"the",
"given",
"title",
".",
"Returns",
"the",
"list",
"dict",
"_",
"of",
"the",
"created",
"list",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2005-L2012 |
5,867 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.list_update | def list_update(self, id, title):
"""
Update info about a list, where "info" is really the lists `title`.
Returns the `list dict`_ of the modified list.
"""
id = self.__unpack_id(id)
params = self.__generate_params(locals(), ['id'])
return self.__api_request('PUT', '/api/v1/lists/{0}'.format(id), params) | python | def list_update(self, id, title):
"""
Update info about a list, where "info" is really the lists `title`.
Returns the `list dict`_ of the modified list.
"""
id = self.__unpack_id(id)
params = self.__generate_params(locals(), ['id'])
return self.__api_request('PUT', '/api/v1/lists/{0}'.format(id), params) | [
"def",
"list_update",
"(",
"self",
",",
"id",
",",
"title",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'id'",
"]",
")",
"return",
"self",
".",
"__api_request",
"(",
"'PUT'",
",",
"'/api/v1/lists/{0}'",
".",
"format",
"(",
"id",
")",
",",
"params",
")"
] | Update info about a list, where "info" is really the lists `title`.
Returns the `list dict`_ of the modified list. | [
"Update",
"info",
"about",
"a",
"list",
"where",
"info",
"is",
"really",
"the",
"lists",
"title",
".",
"Returns",
"the",
"list",
"dict",
"_",
"of",
"the",
"modified",
"list",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2015-L2023 |
5,868 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.list_delete | def list_delete(self, id):
"""
Delete a list.
"""
id = self.__unpack_id(id)
self.__api_request('DELETE', '/api/v1/lists/{0}'.format(id)) | python | def list_delete(self, id):
"""
Delete a list.
"""
id = self.__unpack_id(id)
self.__api_request('DELETE', '/api/v1/lists/{0}'.format(id)) | [
"def",
"list_delete",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"self",
".",
"__api_request",
"(",
"'DELETE'",
",",
"'/api/v1/lists/{0}'",
".",
"format",
"(",
"id",
")",
")"
] | Delete a list. | [
"Delete",
"a",
"list",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2026-L2031 |
5,869 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.report | def report(self, account_id, status_ids = None, comment = None, forward = False):
"""
Report statuses to the instances administrators.
Accepts a list of toot IDs associated with the report, and a comment.
Set forward to True to forward a report of a remote user to that users
instance as well as sending it to the instance local administrators.
Returns a `report dict`_.
"""
account_id = self.__unpack_id(account_id)
if not status_ids is None:
if not isinstance(status_ids, list):
status_ids = [status_ids]
status_ids = list(map(lambda x: self.__unpack_id(x), status_ids))
params_initial = locals()
if forward == False:
del params_initial['forward']
params = self.__generate_params(params_initial)
return self.__api_request('POST', '/api/v1/reports/', params) | python | def report(self, account_id, status_ids = None, comment = None, forward = False):
"""
Report statuses to the instances administrators.
Accepts a list of toot IDs associated with the report, and a comment.
Set forward to True to forward a report of a remote user to that users
instance as well as sending it to the instance local administrators.
Returns a `report dict`_.
"""
account_id = self.__unpack_id(account_id)
if not status_ids is None:
if not isinstance(status_ids, list):
status_ids = [status_ids]
status_ids = list(map(lambda x: self.__unpack_id(x), status_ids))
params_initial = locals()
if forward == False:
del params_initial['forward']
params = self.__generate_params(params_initial)
return self.__api_request('POST', '/api/v1/reports/', params) | [
"def",
"report",
"(",
"self",
",",
"account_id",
",",
"status_ids",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"forward",
"=",
"False",
")",
":",
"account_id",
"=",
"self",
".",
"__unpack_id",
"(",
"account_id",
")",
"if",
"not",
"status_ids",
"is",
"None",
":",
"if",
"not",
"isinstance",
"(",
"status_ids",
",",
"list",
")",
":",
"status_ids",
"=",
"[",
"status_ids",
"]",
"status_ids",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"self",
".",
"__unpack_id",
"(",
"x",
")",
",",
"status_ids",
")",
")",
"params_initial",
"=",
"locals",
"(",
")",
"if",
"forward",
"==",
"False",
":",
"del",
"params_initial",
"[",
"'forward'",
"]",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"params_initial",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"'/api/v1/reports/'",
",",
"params",
")"
] | Report statuses to the instances administrators.
Accepts a list of toot IDs associated with the report, and a comment.
Set forward to True to forward a report of a remote user to that users
instance as well as sending it to the instance local administrators.
Returns a `report dict`_. | [
"Report",
"statuses",
"to",
"the",
"instances",
"administrators",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2065-L2088 |
5,870 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.follow_request_authorize | def follow_request_authorize(self, id):
"""
Accept an incoming follow request.
"""
id = self.__unpack_id(id)
url = '/api/v1/follow_requests/{0}/authorize'.format(str(id))
self.__api_request('POST', url) | python | def follow_request_authorize(self, id):
"""
Accept an incoming follow request.
"""
id = self.__unpack_id(id)
url = '/api/v1/follow_requests/{0}/authorize'.format(str(id))
self.__api_request('POST', url) | [
"def",
"follow_request_authorize",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/follow_requests/{0}/authorize'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] | Accept an incoming follow request. | [
"Accept",
"an",
"incoming",
"follow",
"request",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2094-L2100 |
5,871 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.follow_request_reject | def follow_request_reject(self, id):
"""
Reject an incoming follow request.
"""
id = self.__unpack_id(id)
url = '/api/v1/follow_requests/{0}/reject'.format(str(id))
self.__api_request('POST', url) | python | def follow_request_reject(self, id):
"""
Reject an incoming follow request.
"""
id = self.__unpack_id(id)
url = '/api/v1/follow_requests/{0}/reject'.format(str(id))
self.__api_request('POST', url) | [
"def",
"follow_request_reject",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/follow_requests/{0}/reject'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] | Reject an incoming follow request. | [
"Reject",
"an",
"incoming",
"follow",
"request",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2103-L2109 |
5,872 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.domain_block | def domain_block(self, domain=None):
"""
Add a block for all statuses originating from the specified domain for the logged-in user.
"""
params = self.__generate_params(locals())
self.__api_request('POST', '/api/v1/domain_blocks', params) | python | def domain_block(self, domain=None):
"""
Add a block for all statuses originating from the specified domain for the logged-in user.
"""
params = self.__generate_params(locals())
self.__api_request('POST', '/api/v1/domain_blocks', params) | [
"def",
"domain_block",
"(",
"self",
",",
"domain",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
")",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"'/api/v1/domain_blocks'",
",",
"params",
")"
] | Add a block for all statuses originating from the specified domain for the logged-in user. | [
"Add",
"a",
"block",
"for",
"all",
"statuses",
"originating",
"from",
"the",
"specified",
"domain",
"for",
"the",
"logged",
"-",
"in",
"user",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2174-L2179 |
5,873 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.domain_unblock | def domain_unblock(self, domain=None):
"""
Remove a domain block for the logged-in user.
"""
params = self.__generate_params(locals())
self.__api_request('DELETE', '/api/v1/domain_blocks', params) | python | def domain_unblock(self, domain=None):
"""
Remove a domain block for the logged-in user.
"""
params = self.__generate_params(locals())
self.__api_request('DELETE', '/api/v1/domain_blocks', params) | [
"def",
"domain_unblock",
"(",
"self",
",",
"domain",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
")",
"self",
".",
"__api_request",
"(",
"'DELETE'",
",",
"'/api/v1/domain_blocks'",
",",
"params",
")"
] | Remove a domain block for the logged-in user. | [
"Remove",
"a",
"domain",
"block",
"for",
"the",
"logged",
"-",
"in",
"user",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2182-L2187 |
5,874 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.push_subscription_update | def push_subscription_update(self, follow_events=None,
favourite_events=None, reblog_events=None,
mention_events=None):
"""
Modifies what kind of events the app wishes to subscribe to.
Returns the updated `push subscription dict`_.
"""
params = {}
if follow_events != None:
params['data[alerts][follow]'] = follow_events
if favourite_events != None:
params['data[alerts][favourite]'] = favourite_events
if reblog_events != None:
params['data[alerts][reblog]'] = reblog_events
if mention_events != None:
params['data[alerts][mention]'] = mention_events
return self.__api_request('PUT', '/api/v1/push/subscription', params) | python | def push_subscription_update(self, follow_events=None,
favourite_events=None, reblog_events=None,
mention_events=None):
"""
Modifies what kind of events the app wishes to subscribe to.
Returns the updated `push subscription dict`_.
"""
params = {}
if follow_events != None:
params['data[alerts][follow]'] = follow_events
if favourite_events != None:
params['data[alerts][favourite]'] = favourite_events
if reblog_events != None:
params['data[alerts][reblog]'] = reblog_events
if mention_events != None:
params['data[alerts][mention]'] = mention_events
return self.__api_request('PUT', '/api/v1/push/subscription', params) | [
"def",
"push_subscription_update",
"(",
"self",
",",
"follow_events",
"=",
"None",
",",
"favourite_events",
"=",
"None",
",",
"reblog_events",
"=",
"None",
",",
"mention_events",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"follow_events",
"!=",
"None",
":",
"params",
"[",
"'data[alerts][follow]'",
"]",
"=",
"follow_events",
"if",
"favourite_events",
"!=",
"None",
":",
"params",
"[",
"'data[alerts][favourite]'",
"]",
"=",
"favourite_events",
"if",
"reblog_events",
"!=",
"None",
":",
"params",
"[",
"'data[alerts][reblog]'",
"]",
"=",
"reblog_events",
"if",
"mention_events",
"!=",
"None",
":",
"params",
"[",
"'data[alerts][mention]'",
"]",
"=",
"mention_events",
"return",
"self",
".",
"__api_request",
"(",
"'PUT'",
",",
"'/api/v1/push/subscription'",
",",
"params",
")"
] | Modifies what kind of events the app wishes to subscribe to.
Returns the updated `push subscription dict`_. | [
"Modifies",
"what",
"kind",
"of",
"events",
"the",
"app",
"wishes",
"to",
"subscribe",
"to",
".",
"Returns",
"the",
"updated",
"push",
"subscription",
"dict",
"_",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2235-L2257 |
5,875 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.stream_user | def stream_user(self, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
"""
Streams events that are relevant to the authorized user, i.e. home
timeline and notifications.
"""
return self.__stream('/api/v1/streaming/user', listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec) | python | def stream_user(self, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
"""
Streams events that are relevant to the authorized user, i.e. home
timeline and notifications.
"""
return self.__stream('/api/v1/streaming/user', listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec) | [
"def",
"stream_user",
"(",
"self",
",",
"listener",
",",
"run_async",
"=",
"False",
",",
"timeout",
"=",
"__DEFAULT_STREAM_TIMEOUT",
",",
"reconnect_async",
"=",
"False",
",",
"reconnect_async_wait_sec",
"=",
"__DEFAULT_STREAM_RECONNECT_WAIT_SEC",
")",
":",
"return",
"self",
".",
"__stream",
"(",
"'/api/v1/streaming/user'",
",",
"listener",
",",
"run_async",
"=",
"run_async",
",",
"timeout",
"=",
"timeout",
",",
"reconnect_async",
"=",
"reconnect_async",
",",
"reconnect_async_wait_sec",
"=",
"reconnect_async_wait_sec",
")"
] | Streams events that are relevant to the authorized user, i.e. home
timeline and notifications. | [
"Streams",
"events",
"that",
"are",
"relevant",
"to",
"the",
"authorized",
"user",
"i",
".",
"e",
".",
"home",
"timeline",
"and",
"notifications",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2393-L2398 |
5,876 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.stream_hashtag | def stream_hashtag(self, tag, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
"""
Stream for all public statuses for the hashtag 'tag' seen by the connected
instance.
"""
if tag.startswith("#"):
raise MastodonIllegalArgumentError("Tag parameter should omit leading #")
return self.__stream("/api/v1/streaming/hashtag?tag={}".format(tag), listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec) | python | def stream_hashtag(self, tag, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
"""
Stream for all public statuses for the hashtag 'tag' seen by the connected
instance.
"""
if tag.startswith("#"):
raise MastodonIllegalArgumentError("Tag parameter should omit leading #")
return self.__stream("/api/v1/streaming/hashtag?tag={}".format(tag), listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec) | [
"def",
"stream_hashtag",
"(",
"self",
",",
"tag",
",",
"listener",
",",
"run_async",
"=",
"False",
",",
"timeout",
"=",
"__DEFAULT_STREAM_TIMEOUT",
",",
"reconnect_async",
"=",
"False",
",",
"reconnect_async_wait_sec",
"=",
"__DEFAULT_STREAM_RECONNECT_WAIT_SEC",
")",
":",
"if",
"tag",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"\"Tag parameter should omit leading #\"",
")",
"return",
"self",
".",
"__stream",
"(",
"\"/api/v1/streaming/hashtag?tag={}\"",
".",
"format",
"(",
"tag",
")",
",",
"listener",
",",
"run_async",
"=",
"run_async",
",",
"timeout",
"=",
"timeout",
",",
"reconnect_async",
"=",
"reconnect_async",
",",
"reconnect_async_wait_sec",
"=",
"reconnect_async_wait_sec",
")"
] | Stream for all public statuses for the hashtag 'tag' seen by the connected
instance. | [
"Stream",
"for",
"all",
"public",
"statuses",
"for",
"the",
"hashtag",
"tag",
"seen",
"by",
"the",
"connected",
"instance",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2415-L2422 |
5,877 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.stream_list | def stream_list(self, id, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
"""
Stream events for the current user, restricted to accounts on the given
list.
"""
id = self.__unpack_id(id)
return self.__stream("/api/v1/streaming/list?list={}".format(id), listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec) | python | def stream_list(self, id, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
"""
Stream events for the current user, restricted to accounts on the given
list.
"""
id = self.__unpack_id(id)
return self.__stream("/api/v1/streaming/list?list={}".format(id), listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec) | [
"def",
"stream_list",
"(",
"self",
",",
"id",
",",
"listener",
",",
"run_async",
"=",
"False",
",",
"timeout",
"=",
"__DEFAULT_STREAM_TIMEOUT",
",",
"reconnect_async",
"=",
"False",
",",
"reconnect_async_wait_sec",
"=",
"__DEFAULT_STREAM_RECONNECT_WAIT_SEC",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"return",
"self",
".",
"__stream",
"(",
"\"/api/v1/streaming/list?list={}\"",
".",
"format",
"(",
"id",
")",
",",
"listener",
",",
"run_async",
"=",
"run_async",
",",
"timeout",
"=",
"timeout",
",",
"reconnect_async",
"=",
"reconnect_async",
",",
"reconnect_async_wait_sec",
"=",
"reconnect_async_wait_sec",
")"
] | Stream events for the current user, restricted to accounts on the given
list. | [
"Stream",
"events",
"for",
"the",
"current",
"user",
"restricted",
"to",
"accounts",
"on",
"the",
"given",
"list",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2425-L2431 |
5,878 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.__datetime_to_epoch | def __datetime_to_epoch(self, date_time):
"""
Converts a python datetime to unix epoch, accounting for
time zones and such.
Assumes UTC if timezone is not given.
"""
date_time_utc = None
if date_time.tzinfo is None:
date_time_utc = date_time.replace(tzinfo=pytz.utc)
else:
date_time_utc = date_time.astimezone(pytz.utc)
epoch_utc = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)
return (date_time_utc - epoch_utc).total_seconds() | python | def __datetime_to_epoch(self, date_time):
"""
Converts a python datetime to unix epoch, accounting for
time zones and such.
Assumes UTC if timezone is not given.
"""
date_time_utc = None
if date_time.tzinfo is None:
date_time_utc = date_time.replace(tzinfo=pytz.utc)
else:
date_time_utc = date_time.astimezone(pytz.utc)
epoch_utc = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)
return (date_time_utc - epoch_utc).total_seconds() | [
"def",
"__datetime_to_epoch",
"(",
"self",
",",
"date_time",
")",
":",
"date_time_utc",
"=",
"None",
"if",
"date_time",
".",
"tzinfo",
"is",
"None",
":",
"date_time_utc",
"=",
"date_time",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"else",
":",
"date_time_utc",
"=",
"date_time",
".",
"astimezone",
"(",
"pytz",
".",
"utc",
")",
"epoch_utc",
"=",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"0",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"return",
"(",
"date_time_utc",
"-",
"epoch_utc",
")",
".",
"total_seconds",
"(",
")"
] | Converts a python datetime to unix epoch, accounting for
time zones and such.
Assumes UTC if timezone is not given. | [
"Converts",
"a",
"python",
"datetime",
"to",
"unix",
"epoch",
"accounting",
"for",
"time",
"zones",
"and",
"such",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2443-L2458 |
5,879 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.__get_logged_in_id | def __get_logged_in_id(self):
"""
Fetch the logged in users ID, with caching. ID is reset on calls to log_in.
"""
if self.__logged_in_id == None:
self.__logged_in_id = self.account_verify_credentials().id
return self.__logged_in_id | python | def __get_logged_in_id(self):
"""
Fetch the logged in users ID, with caching. ID is reset on calls to log_in.
"""
if self.__logged_in_id == None:
self.__logged_in_id = self.account_verify_credentials().id
return self.__logged_in_id | [
"def",
"__get_logged_in_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"__logged_in_id",
"==",
"None",
":",
"self",
".",
"__logged_in_id",
"=",
"self",
".",
"account_verify_credentials",
"(",
")",
".",
"id",
"return",
"self",
".",
"__logged_in_id"
] | Fetch the logged in users ID, with caching. ID is reset on calls to log_in. | [
"Fetch",
"the",
"logged",
"in",
"users",
"ID",
"with",
"caching",
".",
"ID",
"is",
"reset",
"on",
"calls",
"to",
"log_in",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2460-L2466 |
5,880 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.__json_date_parse | def __json_date_parse(json_object):
"""
Parse dates in certain known json fields, if possible.
"""
known_date_fields = ["created_at", "week", "day", "expires_at", "scheduled_at"]
for k, v in json_object.items():
if k in known_date_fields:
if v != None:
try:
if isinstance(v, int):
json_object[k] = datetime.datetime.fromtimestamp(v, pytz.utc)
else:
json_object[k] = dateutil.parser.parse(v)
except:
raise MastodonAPIError('Encountered invalid date.')
return json_object | python | def __json_date_parse(json_object):
"""
Parse dates in certain known json fields, if possible.
"""
known_date_fields = ["created_at", "week", "day", "expires_at", "scheduled_at"]
for k, v in json_object.items():
if k in known_date_fields:
if v != None:
try:
if isinstance(v, int):
json_object[k] = datetime.datetime.fromtimestamp(v, pytz.utc)
else:
json_object[k] = dateutil.parser.parse(v)
except:
raise MastodonAPIError('Encountered invalid date.')
return json_object | [
"def",
"__json_date_parse",
"(",
"json_object",
")",
":",
"known_date_fields",
"=",
"[",
"\"created_at\"",
",",
"\"week\"",
",",
"\"day\"",
",",
"\"expires_at\"",
",",
"\"scheduled_at\"",
"]",
"for",
"k",
",",
"v",
"in",
"json_object",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"known_date_fields",
":",
"if",
"v",
"!=",
"None",
":",
"try",
":",
"if",
"isinstance",
"(",
"v",
",",
"int",
")",
":",
"json_object",
"[",
"k",
"]",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"v",
",",
"pytz",
".",
"utc",
")",
"else",
":",
"json_object",
"[",
"k",
"]",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"v",
")",
"except",
":",
"raise",
"MastodonAPIError",
"(",
"'Encountered invalid date.'",
")",
"return",
"json_object"
] | Parse dates in certain known json fields, if possible. | [
"Parse",
"dates",
"in",
"certain",
"known",
"json",
"fields",
"if",
"possible",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2480-L2495 |
5,881 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.__json_strnum_to_bignum | def __json_strnum_to_bignum(json_object):
"""
Converts json string numerals to native python bignums.
"""
for key in ('id', 'week', 'in_reply_to_id', 'in_reply_to_account_id', 'logins', 'registrations', 'statuses'):
if (key in json_object and isinstance(json_object[key], six.text_type)):
try:
json_object[key] = int(json_object[key])
except ValueError:
pass
return json_object | python | def __json_strnum_to_bignum(json_object):
"""
Converts json string numerals to native python bignums.
"""
for key in ('id', 'week', 'in_reply_to_id', 'in_reply_to_account_id', 'logins', 'registrations', 'statuses'):
if (key in json_object and isinstance(json_object[key], six.text_type)):
try:
json_object[key] = int(json_object[key])
except ValueError:
pass
return json_object | [
"def",
"__json_strnum_to_bignum",
"(",
"json_object",
")",
":",
"for",
"key",
"in",
"(",
"'id'",
",",
"'week'",
",",
"'in_reply_to_id'",
",",
"'in_reply_to_account_id'",
",",
"'logins'",
",",
"'registrations'",
",",
"'statuses'",
")",
":",
"if",
"(",
"key",
"in",
"json_object",
"and",
"isinstance",
"(",
"json_object",
"[",
"key",
"]",
",",
"six",
".",
"text_type",
")",
")",
":",
"try",
":",
"json_object",
"[",
"key",
"]",
"=",
"int",
"(",
"json_object",
"[",
"key",
"]",
")",
"except",
"ValueError",
":",
"pass",
"return",
"json_object"
] | Converts json string numerals to native python bignums. | [
"Converts",
"json",
"string",
"numerals",
"to",
"native",
"python",
"bignums",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2511-L2522 |
5,882 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.__json_hooks | def __json_hooks(json_object):
"""
All the json hooks. Used in request parsing.
"""
json_object = Mastodon.__json_strnum_to_bignum(json_object)
json_object = Mastodon.__json_date_parse(json_object)
json_object = Mastodon.__json_truefalse_parse(json_object)
json_object = Mastodon.__json_allow_dict_attrs(json_object)
return json_object | python | def __json_hooks(json_object):
"""
All the json hooks. Used in request parsing.
"""
json_object = Mastodon.__json_strnum_to_bignum(json_object)
json_object = Mastodon.__json_date_parse(json_object)
json_object = Mastodon.__json_truefalse_parse(json_object)
json_object = Mastodon.__json_allow_dict_attrs(json_object)
return json_object | [
"def",
"__json_hooks",
"(",
"json_object",
")",
":",
"json_object",
"=",
"Mastodon",
".",
"__json_strnum_to_bignum",
"(",
"json_object",
")",
"json_object",
"=",
"Mastodon",
".",
"__json_date_parse",
"(",
"json_object",
")",
"json_object",
"=",
"Mastodon",
".",
"__json_truefalse_parse",
"(",
"json_object",
")",
"json_object",
"=",
"Mastodon",
".",
"__json_allow_dict_attrs",
"(",
"json_object",
")",
"return",
"json_object"
] | All the json hooks. Used in request parsing. | [
"All",
"the",
"json",
"hooks",
".",
"Used",
"in",
"request",
"parsing",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2525-L2533 |
5,883 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.__consistent_isoformat_utc | def __consistent_isoformat_utc(datetime_val):
"""
Function that does what isoformat does but it actually does the same
every time instead of randomly doing different things on some systems
and also it represents that time as the equivalent UTC time.
"""
isotime = datetime_val.astimezone(pytz.utc).strftime("%Y-%m-%dT%H:%M:%S%z")
if isotime[-2] != ":":
isotime = isotime[:-2] + ":" + isotime[-2:]
return isotime | python | def __consistent_isoformat_utc(datetime_val):
"""
Function that does what isoformat does but it actually does the same
every time instead of randomly doing different things on some systems
and also it represents that time as the equivalent UTC time.
"""
isotime = datetime_val.astimezone(pytz.utc).strftime("%Y-%m-%dT%H:%M:%S%z")
if isotime[-2] != ":":
isotime = isotime[:-2] + ":" + isotime[-2:]
return isotime | [
"def",
"__consistent_isoformat_utc",
"(",
"datetime_val",
")",
":",
"isotime",
"=",
"datetime_val",
".",
"astimezone",
"(",
"pytz",
".",
"utc",
")",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H:%M:%S%z\"",
")",
"if",
"isotime",
"[",
"-",
"2",
"]",
"!=",
"\":\"",
":",
"isotime",
"=",
"isotime",
"[",
":",
"-",
"2",
"]",
"+",
"\":\"",
"+",
"isotime",
"[",
"-",
"2",
":",
"]",
"return",
"isotime"
] | Function that does what isoformat does but it actually does the same
every time instead of randomly doing different things on some systems
and also it represents that time as the equivalent UTC time. | [
"Function",
"that",
"does",
"what",
"isoformat",
"does",
"but",
"it",
"actually",
"does",
"the",
"same",
"every",
"time",
"instead",
"of",
"randomly",
"doing",
"different",
"things",
"on",
"some",
"systems",
"and",
"also",
"it",
"represents",
"that",
"time",
"as",
"the",
"equivalent",
"UTC",
"time",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2536-L2545 |
5,884 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.__generate_params | def __generate_params(self, params, exclude=[]):
"""
Internal named-parameters-to-dict helper.
Note for developers: If called with locals() as params,
as is the usual practice in this code, the __generate_params call
(or at least the locals() call) should generally be the first thing
in your function.
"""
params = collections.OrderedDict(params)
del params['self']
param_keys = list(params.keys())
for key in param_keys:
if isinstance(params[key], bool) and params[key] == False:
params[key] = '0'
if isinstance(params[key], bool) and params[key] == True:
params[key] = '1'
for key in param_keys:
if params[key] is None or key in exclude:
del params[key]
param_keys = list(params.keys())
for key in param_keys:
if isinstance(params[key], list):
params[key + "[]"] = params[key]
del params[key]
return params | python | def __generate_params(self, params, exclude=[]):
"""
Internal named-parameters-to-dict helper.
Note for developers: If called with locals() as params,
as is the usual practice in this code, the __generate_params call
(or at least the locals() call) should generally be the first thing
in your function.
"""
params = collections.OrderedDict(params)
del params['self']
param_keys = list(params.keys())
for key in param_keys:
if isinstance(params[key], bool) and params[key] == False:
params[key] = '0'
if isinstance(params[key], bool) and params[key] == True:
params[key] = '1'
for key in param_keys:
if params[key] is None or key in exclude:
del params[key]
param_keys = list(params.keys())
for key in param_keys:
if isinstance(params[key], list):
params[key + "[]"] = params[key]
del params[key]
return params | [
"def",
"__generate_params",
"(",
"self",
",",
"params",
",",
"exclude",
"=",
"[",
"]",
")",
":",
"params",
"=",
"collections",
".",
"OrderedDict",
"(",
"params",
")",
"del",
"params",
"[",
"'self'",
"]",
"param_keys",
"=",
"list",
"(",
"params",
".",
"keys",
"(",
")",
")",
"for",
"key",
"in",
"param_keys",
":",
"if",
"isinstance",
"(",
"params",
"[",
"key",
"]",
",",
"bool",
")",
"and",
"params",
"[",
"key",
"]",
"==",
"False",
":",
"params",
"[",
"key",
"]",
"=",
"'0'",
"if",
"isinstance",
"(",
"params",
"[",
"key",
"]",
",",
"bool",
")",
"and",
"params",
"[",
"key",
"]",
"==",
"True",
":",
"params",
"[",
"key",
"]",
"=",
"'1'",
"for",
"key",
"in",
"param_keys",
":",
"if",
"params",
"[",
"key",
"]",
"is",
"None",
"or",
"key",
"in",
"exclude",
":",
"del",
"params",
"[",
"key",
"]",
"param_keys",
"=",
"list",
"(",
"params",
".",
"keys",
"(",
")",
")",
"for",
"key",
"in",
"param_keys",
":",
"if",
"isinstance",
"(",
"params",
"[",
"key",
"]",
",",
"list",
")",
":",
"params",
"[",
"key",
"+",
"\"[]\"",
"]",
"=",
"params",
"[",
"key",
"]",
"del",
"params",
"[",
"key",
"]",
"return",
"params"
] | Internal named-parameters-to-dict helper.
Note for developers: If called with locals() as params,
as is the usual practice in this code, the __generate_params call
(or at least the locals() call) should generally be the first thing
in your function. | [
"Internal",
"named",
"-",
"parameters",
"-",
"to",
"-",
"dict",
"helper",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2867-L2896 |
5,885 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.__decode_webpush_b64 | def __decode_webpush_b64(self, data):
"""
Re-pads and decodes urlsafe base64.
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += '=' * (4 - missing_padding)
return base64.urlsafe_b64decode(data) | python | def __decode_webpush_b64(self, data):
"""
Re-pads and decodes urlsafe base64.
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += '=' * (4 - missing_padding)
return base64.urlsafe_b64decode(data) | [
"def",
"__decode_webpush_b64",
"(",
"self",
",",
"data",
")",
":",
"missing_padding",
"=",
"len",
"(",
"data",
")",
"%",
"4",
"if",
"missing_padding",
"!=",
"0",
":",
"data",
"+=",
"'='",
"*",
"(",
"4",
"-",
"missing_padding",
")",
"return",
"base64",
".",
"urlsafe_b64decode",
"(",
"data",
")"
] | Re-pads and decodes urlsafe base64. | [
"Re",
"-",
"pads",
"and",
"decodes",
"urlsafe",
"base64",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2911-L2918 |
5,886 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.__set_token_expired | def __set_token_expired(self, value):
"""Internal helper for oauth code"""
self._token_expired = datetime.datetime.now() + datetime.timedelta(seconds=value)
return | python | def __set_token_expired(self, value):
"""Internal helper for oauth code"""
self._token_expired = datetime.datetime.now() + datetime.timedelta(seconds=value)
return | [
"def",
"__set_token_expired",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_token_expired",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"value",
")",
"return"
] | Internal helper for oauth code | [
"Internal",
"helper",
"for",
"oauth",
"code"
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2924-L2927 |
5,887 | halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.__protocolize | def __protocolize(base_url):
"""Internal add-protocol-to-url helper"""
if not base_url.startswith("http://") and not base_url.startswith("https://"):
base_url = "https://" + base_url
# Some API endpoints can't handle extra /'s in path requests
base_url = base_url.rstrip("/")
return base_url | python | def __protocolize(base_url):
"""Internal add-protocol-to-url helper"""
if not base_url.startswith("http://") and not base_url.startswith("https://"):
base_url = "https://" + base_url
# Some API endpoints can't handle extra /'s in path requests
base_url = base_url.rstrip("/")
return base_url | [
"def",
"__protocolize",
"(",
"base_url",
")",
":",
"if",
"not",
"base_url",
".",
"startswith",
"(",
"\"http://\"",
")",
"and",
"not",
"base_url",
".",
"startswith",
"(",
"\"https://\"",
")",
":",
"base_url",
"=",
"\"https://\"",
"+",
"base_url",
"# Some API endpoints can't handle extra /'s in path requests",
"base_url",
"=",
"base_url",
".",
"rstrip",
"(",
"\"/\"",
")",
"return",
"base_url"
] | Internal add-protocol-to-url helper | [
"Internal",
"add",
"-",
"protocol",
"-",
"to",
"-",
"url",
"helper"
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2939-L2946 |
5,888 | faucamp/python-gsmmodem | gsmmodem/modem.py | SentSms.status | def status(self):
""" Status of this SMS. Can be ENROUTE, DELIVERED or FAILED
The actual status report object may be accessed via the 'report' attribute
if status is 'DELIVERED' or 'FAILED'
"""
if self.report == None:
return SentSms.ENROUTE
else:
return SentSms.DELIVERED if self.report.deliveryStatus == StatusReport.DELIVERED else SentSms.FAILED | python | def status(self):
""" Status of this SMS. Can be ENROUTE, DELIVERED or FAILED
The actual status report object may be accessed via the 'report' attribute
if status is 'DELIVERED' or 'FAILED'
"""
if self.report == None:
return SentSms.ENROUTE
else:
return SentSms.DELIVERED if self.report.deliveryStatus == StatusReport.DELIVERED else SentSms.FAILED | [
"def",
"status",
"(",
"self",
")",
":",
"if",
"self",
".",
"report",
"==",
"None",
":",
"return",
"SentSms",
".",
"ENROUTE",
"else",
":",
"return",
"SentSms",
".",
"DELIVERED",
"if",
"self",
".",
"report",
".",
"deliveryStatus",
"==",
"StatusReport",
".",
"DELIVERED",
"else",
"SentSms",
".",
"FAILED"
] | Status of this SMS. Can be ENROUTE, DELIVERED or FAILED
The actual status report object may be accessed via the 'report' attribute
if status is 'DELIVERED' or 'FAILED' | [
"Status",
"of",
"this",
"SMS",
".",
"Can",
"be",
"ENROUTE",
"DELIVERED",
"or",
"FAILED",
"The",
"actual",
"status",
"report",
"object",
"may",
"be",
"accessed",
"via",
"the",
"report",
"attribute",
"if",
"status",
"is",
"DELIVERED",
"or",
"FAILED"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L76-L85 |
5,889 | faucamp/python-gsmmodem | gsmmodem/modem.py | GsmModem.write | def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTerm='\r', expectedResponseTermSeq=None):
""" Write data to the modem.
This method adds the ``\\r\\n`` end-of-line sequence to the data parameter, and
writes it to the modem.
:param data: Command/data to be written to the modem
:type data: str
:param waitForResponse: Whether this method should block and return the response from the modem or not
:type waitForResponse: bool
:param timeout: Maximum amount of time in seconds to wait for a response from the modem
:type timeout: int
:param parseError: If True, a CommandError is raised if the modem responds with an error (otherwise the response is returned as-is)
:type parseError: bool
:param writeTerm: The terminating sequence to append to the written data
:type writeTerm: str
:param expectedResponseTermSeq: The expected terminating sequence that marks the end of the modem's response (defaults to ``\\r\\n``)
:type expectedResponseTermSeq: str
:raise CommandError: if the command returns an error (only if parseError parameter is True)
:raise TimeoutException: if no response to the command was received from the modem
:return: A list containing the response lines from the modem, or None if waitForResponse is False
:rtype: list
"""
self.log.debug('write: %s', data)
responseLines = super(GsmModem, self).write(data + writeTerm, waitForResponse=waitForResponse, timeout=timeout, expectedResponseTermSeq=expectedResponseTermSeq)
if self._writeWait > 0: # Sleep a bit if required (some older modems suffer under load)
time.sleep(self._writeWait)
if waitForResponse:
cmdStatusLine = responseLines[-1]
if parseError:
if 'ERROR' in cmdStatusLine:
cmErrorMatch = self.CM_ERROR_REGEX.match(cmdStatusLine)
if cmErrorMatch:
errorType = cmErrorMatch.group(1)
errorCode = int(cmErrorMatch.group(2))
if errorCode == 515 or errorCode == 14:
# 515 means: "Please wait, init or command processing in progress."
# 14 means "SIM busy"
self._writeWait += 0.2 # Increase waiting period temporarily
# Retry the command after waiting a bit
self.log.debug('Device/SIM busy error detected; self._writeWait adjusted to %fs', self._writeWait)
time.sleep(self._writeWait)
result = self.write(data, waitForResponse, timeout, parseError, writeTerm, expectedResponseTermSeq)
self.log.debug('self_writeWait set to 0.1 because of recovering from device busy (515) error')
if errorCode == 515:
self._writeWait = 0.1 # Set this to something sane for further commands (slow modem)
else:
self._writeWait = 0 # The modem was just waiting for the SIM card
return result
if errorType == 'CME':
raise CmeError(data, int(errorCode))
else: # CMS error
raise CmsError(data, int(errorCode))
else:
raise CommandError(data)
elif cmdStatusLine == 'COMMAND NOT SUPPORT': # Some Huawei modems respond with this for unknown commands
raise CommandError(data + '({0})'.format(cmdStatusLine))
return responseLines | python | def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTerm='\r', expectedResponseTermSeq=None):
""" Write data to the modem.
This method adds the ``\\r\\n`` end-of-line sequence to the data parameter, and
writes it to the modem.
:param data: Command/data to be written to the modem
:type data: str
:param waitForResponse: Whether this method should block and return the response from the modem or not
:type waitForResponse: bool
:param timeout: Maximum amount of time in seconds to wait for a response from the modem
:type timeout: int
:param parseError: If True, a CommandError is raised if the modem responds with an error (otherwise the response is returned as-is)
:type parseError: bool
:param writeTerm: The terminating sequence to append to the written data
:type writeTerm: str
:param expectedResponseTermSeq: The expected terminating sequence that marks the end of the modem's response (defaults to ``\\r\\n``)
:type expectedResponseTermSeq: str
:raise CommandError: if the command returns an error (only if parseError parameter is True)
:raise TimeoutException: if no response to the command was received from the modem
:return: A list containing the response lines from the modem, or None if waitForResponse is False
:rtype: list
"""
self.log.debug('write: %s', data)
responseLines = super(GsmModem, self).write(data + writeTerm, waitForResponse=waitForResponse, timeout=timeout, expectedResponseTermSeq=expectedResponseTermSeq)
if self._writeWait > 0: # Sleep a bit if required (some older modems suffer under load)
time.sleep(self._writeWait)
if waitForResponse:
cmdStatusLine = responseLines[-1]
if parseError:
if 'ERROR' in cmdStatusLine:
cmErrorMatch = self.CM_ERROR_REGEX.match(cmdStatusLine)
if cmErrorMatch:
errorType = cmErrorMatch.group(1)
errorCode = int(cmErrorMatch.group(2))
if errorCode == 515 or errorCode == 14:
# 515 means: "Please wait, init or command processing in progress."
# 14 means "SIM busy"
self._writeWait += 0.2 # Increase waiting period temporarily
# Retry the command after waiting a bit
self.log.debug('Device/SIM busy error detected; self._writeWait adjusted to %fs', self._writeWait)
time.sleep(self._writeWait)
result = self.write(data, waitForResponse, timeout, parseError, writeTerm, expectedResponseTermSeq)
self.log.debug('self_writeWait set to 0.1 because of recovering from device busy (515) error')
if errorCode == 515:
self._writeWait = 0.1 # Set this to something sane for further commands (slow modem)
else:
self._writeWait = 0 # The modem was just waiting for the SIM card
return result
if errorType == 'CME':
raise CmeError(data, int(errorCode))
else: # CMS error
raise CmsError(data, int(errorCode))
else:
raise CommandError(data)
elif cmdStatusLine == 'COMMAND NOT SUPPORT': # Some Huawei modems respond with this for unknown commands
raise CommandError(data + '({0})'.format(cmdStatusLine))
return responseLines | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"waitForResponse",
"=",
"True",
",",
"timeout",
"=",
"5",
",",
"parseError",
"=",
"True",
",",
"writeTerm",
"=",
"'\\r'",
",",
"expectedResponseTermSeq",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'write: %s'",
",",
"data",
")",
"responseLines",
"=",
"super",
"(",
"GsmModem",
",",
"self",
")",
".",
"write",
"(",
"data",
"+",
"writeTerm",
",",
"waitForResponse",
"=",
"waitForResponse",
",",
"timeout",
"=",
"timeout",
",",
"expectedResponseTermSeq",
"=",
"expectedResponseTermSeq",
")",
"if",
"self",
".",
"_writeWait",
">",
"0",
":",
"# Sleep a bit if required (some older modems suffer under load) ",
"time",
".",
"sleep",
"(",
"self",
".",
"_writeWait",
")",
"if",
"waitForResponse",
":",
"cmdStatusLine",
"=",
"responseLines",
"[",
"-",
"1",
"]",
"if",
"parseError",
":",
"if",
"'ERROR'",
"in",
"cmdStatusLine",
":",
"cmErrorMatch",
"=",
"self",
".",
"CM_ERROR_REGEX",
".",
"match",
"(",
"cmdStatusLine",
")",
"if",
"cmErrorMatch",
":",
"errorType",
"=",
"cmErrorMatch",
".",
"group",
"(",
"1",
")",
"errorCode",
"=",
"int",
"(",
"cmErrorMatch",
".",
"group",
"(",
"2",
")",
")",
"if",
"errorCode",
"==",
"515",
"or",
"errorCode",
"==",
"14",
":",
"# 515 means: \"Please wait, init or command processing in progress.\"",
"# 14 means \"SIM busy\"",
"self",
".",
"_writeWait",
"+=",
"0.2",
"# Increase waiting period temporarily",
"# Retry the command after waiting a bit",
"self",
".",
"log",
".",
"debug",
"(",
"'Device/SIM busy error detected; self._writeWait adjusted to %fs'",
",",
"self",
".",
"_writeWait",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"_writeWait",
")",
"result",
"=",
"self",
".",
"write",
"(",
"data",
",",
"waitForResponse",
",",
"timeout",
",",
"parseError",
",",
"writeTerm",
",",
"expectedResponseTermSeq",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'self_writeWait set to 0.1 because of recovering from device busy (515) error'",
")",
"if",
"errorCode",
"==",
"515",
":",
"self",
".",
"_writeWait",
"=",
"0.1",
"# Set this to something sane for further commands (slow modem)",
"else",
":",
"self",
".",
"_writeWait",
"=",
"0",
"# The modem was just waiting for the SIM card",
"return",
"result",
"if",
"errorType",
"==",
"'CME'",
":",
"raise",
"CmeError",
"(",
"data",
",",
"int",
"(",
"errorCode",
")",
")",
"else",
":",
"# CMS error",
"raise",
"CmsError",
"(",
"data",
",",
"int",
"(",
"errorCode",
")",
")",
"else",
":",
"raise",
"CommandError",
"(",
"data",
")",
"elif",
"cmdStatusLine",
"==",
"'COMMAND NOT SUPPORT'",
":",
"# Some Huawei modems respond with this for unknown commands",
"raise",
"CommandError",
"(",
"data",
"+",
"'({0})'",
".",
"format",
"(",
"cmdStatusLine",
")",
")",
"return",
"responseLines"
] | Write data to the modem.
This method adds the ``\\r\\n`` end-of-line sequence to the data parameter, and
writes it to the modem.
:param data: Command/data to be written to the modem
:type data: str
:param waitForResponse: Whether this method should block and return the response from the modem or not
:type waitForResponse: bool
:param timeout: Maximum amount of time in seconds to wait for a response from the modem
:type timeout: int
:param parseError: If True, a CommandError is raised if the modem responds with an error (otherwise the response is returned as-is)
:type parseError: bool
:param writeTerm: The terminating sequence to append to the written data
:type writeTerm: str
:param expectedResponseTermSeq: The expected terminating sequence that marks the end of the modem's response (defaults to ``\\r\\n``)
:type expectedResponseTermSeq: str
:raise CommandError: if the command returns an error (only if parseError parameter is True)
:raise TimeoutException: if no response to the command was received from the modem
:return: A list containing the response lines from the modem, or None if waitForResponse is False
:rtype: list | [
"Write",
"data",
"to",
"the",
"modem",
"."
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L387-L446 |
5,890 | faucamp/python-gsmmodem | gsmmodem/modem.py | GsmModem.smsTextMode | def smsTextMode(self, textMode):
""" Set to True for the modem to use text mode for SMS, or False for it to use PDU mode """
if textMode != self._smsTextMode:
if self.alive:
self.write('AT+CMGF={0}'.format(1 if textMode else 0))
self._smsTextMode = textMode
self._compileSmsRegexes() | python | def smsTextMode(self, textMode):
""" Set to True for the modem to use text mode for SMS, or False for it to use PDU mode """
if textMode != self._smsTextMode:
if self.alive:
self.write('AT+CMGF={0}'.format(1 if textMode else 0))
self._smsTextMode = textMode
self._compileSmsRegexes() | [
"def",
"smsTextMode",
"(",
"self",
",",
"textMode",
")",
":",
"if",
"textMode",
"!=",
"self",
".",
"_smsTextMode",
":",
"if",
"self",
".",
"alive",
":",
"self",
".",
"write",
"(",
"'AT+CMGF={0}'",
".",
"format",
"(",
"1",
"if",
"textMode",
"else",
"0",
")",
")",
"self",
".",
"_smsTextMode",
"=",
"textMode",
"self",
".",
"_compileSmsRegexes",
"(",
")"
] | Set to True for the modem to use text mode for SMS, or False for it to use PDU mode | [
"Set",
"to",
"True",
"for",
"the",
"modem",
"to",
"use",
"text",
"mode",
"for",
"SMS",
"or",
"False",
"for",
"it",
"to",
"use",
"PDU",
"mode"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L524-L530 |
5,891 | faucamp/python-gsmmodem | gsmmodem/modem.py | GsmModem._compileSmsRegexes | def _compileSmsRegexes(self):
""" Compiles regular expression used for parsing SMS messages based on current mode """
if self._smsTextMode:
if self.CMGR_SM_DELIVER_REGEX_TEXT == None:
self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$')
self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(r'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$')
elif self.CMGR_REGEX_PDU == None:
self.CMGR_REGEX_PDU = re.compile(r'^\+CMGR: (\d*),"{0,1}([^"]*)"{0,1},(\d+)$') | python | def _compileSmsRegexes(self):
""" Compiles regular expression used for parsing SMS messages based on current mode """
if self._smsTextMode:
if self.CMGR_SM_DELIVER_REGEX_TEXT == None:
self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$')
self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(r'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$')
elif self.CMGR_REGEX_PDU == None:
self.CMGR_REGEX_PDU = re.compile(r'^\+CMGR: (\d*),"{0,1}([^"]*)"{0,1},(\d+)$') | [
"def",
"_compileSmsRegexes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_smsTextMode",
":",
"if",
"self",
".",
"CMGR_SM_DELIVER_REGEX_TEXT",
"==",
"None",
":",
"self",
".",
"CMGR_SM_DELIVER_REGEX_TEXT",
"=",
"re",
".",
"compile",
"(",
"r'^\\+CMGR: \"([^\"]+)\",\"([^\"]+)\",[^,]*,\"([^\"]+)\"$'",
")",
"self",
".",
"CMGR_SM_REPORT_REGEXT_TEXT",
"=",
"re",
".",
"compile",
"(",
"r'^\\+CMGR: ([^,]*),\\d+,(\\d+),\"{0,1}([^\"]*)\"{0,1},\\d*,\"([^\"]+)\",\"([^\"]+)\",(\\d+)$'",
")",
"elif",
"self",
".",
"CMGR_REGEX_PDU",
"==",
"None",
":",
"self",
".",
"CMGR_REGEX_PDU",
"=",
"re",
".",
"compile",
"(",
"r'^\\+CMGR: (\\d*),\"{0,1}([^\"]*)\"{0,1},(\\d+)$'",
")"
] | Compiles regular expression used for parsing SMS messages based on current mode | [
"Compiles",
"regular",
"expression",
"used",
"for",
"parsing",
"SMS",
"messages",
"based",
"on",
"current",
"mode"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L545-L552 |
5,892 | faucamp/python-gsmmodem | gsmmodem/modem.py | GsmModem.smsc | def smsc(self, smscNumber):
""" Set the default SMSC number to use when sending SMS messages """
if smscNumber != self._smscNumber:
if self.alive:
self.write('AT+CSCA="{0}"'.format(smscNumber))
self._smscNumber = smscNumber | python | def smsc(self, smscNumber):
""" Set the default SMSC number to use when sending SMS messages """
if smscNumber != self._smscNumber:
if self.alive:
self.write('AT+CSCA="{0}"'.format(smscNumber))
self._smscNumber = smscNumber | [
"def",
"smsc",
"(",
"self",
",",
"smscNumber",
")",
":",
"if",
"smscNumber",
"!=",
"self",
".",
"_smscNumber",
":",
"if",
"self",
".",
"alive",
":",
"self",
".",
"write",
"(",
"'AT+CSCA=\"{0}\"'",
".",
"format",
"(",
"smscNumber",
")",
")",
"self",
".",
"_smscNumber",
"=",
"smscNumber"
] | Set the default SMSC number to use when sending SMS messages | [
"Set",
"the",
"default",
"SMSC",
"number",
"to",
"use",
"when",
"sending",
"SMS",
"messages"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L568-L573 |
5,893 | faucamp/python-gsmmodem | gsmmodem/modem.py | GsmModem.dial | def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None):
""" Calls the specified phone number using a voice phone call
:param number: The phone number to dial
:param timeout: Maximum time to wait for the call to be established
:param callStatusUpdateCallbackFunc: Callback function that is executed if the call's status changes due to
remote events (i.e. when it is answered, the call is ended by the remote party)
:return: The outgoing call
:rtype: gsmmodem.modem.Call
"""
if self._waitForCallInitUpdate:
# Wait for the "call originated" notification message
self._dialEvent = threading.Event()
try:
self.write('ATD{0};'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse)
except Exception:
self._dialEvent = None # Cancel the thread sync lock
raise
else:
# Don't wait for a call init update - base the call ID on the number of active calls
self.write('ATD{0};'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse)
self.log.debug("Not waiting for outgoing call init update message")
callId = len(self.activeCalls) + 1
callType = 0 # Assume voice
call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc)
self.activeCalls[callId] = call
return call
if self._mustPollCallStatus:
# Fake a call notification by polling call status until the status indicates that the call is being dialed
threading.Thread(target=self._pollCallStatus, kwargs={'expectedState': 0, 'timeout': timeout}).start()
if self._dialEvent.wait(timeout):
self._dialEvent = None
callId, callType = self._dialResponse
call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc)
self.activeCalls[callId] = call
return call
else: # Call establishing timed out
self._dialEvent = None
raise TimeoutException() | python | def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None):
""" Calls the specified phone number using a voice phone call
:param number: The phone number to dial
:param timeout: Maximum time to wait for the call to be established
:param callStatusUpdateCallbackFunc: Callback function that is executed if the call's status changes due to
remote events (i.e. when it is answered, the call is ended by the remote party)
:return: The outgoing call
:rtype: gsmmodem.modem.Call
"""
if self._waitForCallInitUpdate:
# Wait for the "call originated" notification message
self._dialEvent = threading.Event()
try:
self.write('ATD{0};'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse)
except Exception:
self._dialEvent = None # Cancel the thread sync lock
raise
else:
# Don't wait for a call init update - base the call ID on the number of active calls
self.write('ATD{0};'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse)
self.log.debug("Not waiting for outgoing call init update message")
callId = len(self.activeCalls) + 1
callType = 0 # Assume voice
call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc)
self.activeCalls[callId] = call
return call
if self._mustPollCallStatus:
# Fake a call notification by polling call status until the status indicates that the call is being dialed
threading.Thread(target=self._pollCallStatus, kwargs={'expectedState': 0, 'timeout': timeout}).start()
if self._dialEvent.wait(timeout):
self._dialEvent = None
callId, callType = self._dialResponse
call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc)
self.activeCalls[callId] = call
return call
else: # Call establishing timed out
self._dialEvent = None
raise TimeoutException() | [
"def",
"dial",
"(",
"self",
",",
"number",
",",
"timeout",
"=",
"5",
",",
"callStatusUpdateCallbackFunc",
"=",
"None",
")",
":",
"if",
"self",
".",
"_waitForCallInitUpdate",
":",
"# Wait for the \"call originated\" notification message",
"self",
".",
"_dialEvent",
"=",
"threading",
".",
"Event",
"(",
")",
"try",
":",
"self",
".",
"write",
"(",
"'ATD{0};'",
".",
"format",
"(",
"number",
")",
",",
"timeout",
"=",
"timeout",
",",
"waitForResponse",
"=",
"self",
".",
"_waitForAtdResponse",
")",
"except",
"Exception",
":",
"self",
".",
"_dialEvent",
"=",
"None",
"# Cancel the thread sync lock",
"raise",
"else",
":",
"# Don't wait for a call init update - base the call ID on the number of active calls",
"self",
".",
"write",
"(",
"'ATD{0};'",
".",
"format",
"(",
"number",
")",
",",
"timeout",
"=",
"timeout",
",",
"waitForResponse",
"=",
"self",
".",
"_waitForAtdResponse",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"Not waiting for outgoing call init update message\"",
")",
"callId",
"=",
"len",
"(",
"self",
".",
"activeCalls",
")",
"+",
"1",
"callType",
"=",
"0",
"# Assume voice",
"call",
"=",
"Call",
"(",
"self",
",",
"callId",
",",
"callType",
",",
"number",
",",
"callStatusUpdateCallbackFunc",
")",
"self",
".",
"activeCalls",
"[",
"callId",
"]",
"=",
"call",
"return",
"call",
"if",
"self",
".",
"_mustPollCallStatus",
":",
"# Fake a call notification by polling call status until the status indicates that the call is being dialed",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_pollCallStatus",
",",
"kwargs",
"=",
"{",
"'expectedState'",
":",
"0",
",",
"'timeout'",
":",
"timeout",
"}",
")",
".",
"start",
"(",
")",
"if",
"self",
".",
"_dialEvent",
".",
"wait",
"(",
"timeout",
")",
":",
"self",
".",
"_dialEvent",
"=",
"None",
"callId",
",",
"callType",
"=",
"self",
".",
"_dialResponse",
"call",
"=",
"Call",
"(",
"self",
",",
"callId",
",",
"callType",
",",
"number",
",",
"callStatusUpdateCallbackFunc",
")",
"self",
".",
"activeCalls",
"[",
"callId",
"]",
"=",
"call",
"return",
"call",
"else",
":",
"# Call establishing timed out",
"self",
".",
"_dialEvent",
"=",
"None",
"raise",
"TimeoutException",
"(",
")"
] | Calls the specified phone number using a voice phone call
:param number: The phone number to dial
:param timeout: Maximum time to wait for the call to be established
:param callStatusUpdateCallbackFunc: Callback function that is executed if the call's status changes due to
remote events (i.e. when it is answered, the call is ended by the remote party)
:return: The outgoing call
:rtype: gsmmodem.modem.Call | [
"Calls",
"the",
"specified",
"phone",
"number",
"using",
"a",
"voice",
"phone",
"call"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L701-L742 |
5,894 | faucamp/python-gsmmodem | gsmmodem/modem.py | GsmModem._handleCallInitiated | def _handleCallInitiated(self, regexMatch, callId=None, callType=1):
""" Handler for "outgoing call initiated" event notification line """
if self._dialEvent:
if regexMatch:
groups = regexMatch.groups()
# Set self._dialReponse to (callId, callType)
if len(groups) >= 2:
self._dialResponse = (int(groups[0]) , int(groups[1]))
else:
self._dialResponse = (int(groups[0]), 1) # assume call type: VOICE
else:
self._dialResponse = callId, callType
self._dialEvent.set() | python | def _handleCallInitiated(self, regexMatch, callId=None, callType=1):
""" Handler for "outgoing call initiated" event notification line """
if self._dialEvent:
if regexMatch:
groups = regexMatch.groups()
# Set self._dialReponse to (callId, callType)
if len(groups) >= 2:
self._dialResponse = (int(groups[0]) , int(groups[1]))
else:
self._dialResponse = (int(groups[0]), 1) # assume call type: VOICE
else:
self._dialResponse = callId, callType
self._dialEvent.set() | [
"def",
"_handleCallInitiated",
"(",
"self",
",",
"regexMatch",
",",
"callId",
"=",
"None",
",",
"callType",
"=",
"1",
")",
":",
"if",
"self",
".",
"_dialEvent",
":",
"if",
"regexMatch",
":",
"groups",
"=",
"regexMatch",
".",
"groups",
"(",
")",
"# Set self._dialReponse to (callId, callType)",
"if",
"len",
"(",
"groups",
")",
">=",
"2",
":",
"self",
".",
"_dialResponse",
"=",
"(",
"int",
"(",
"groups",
"[",
"0",
"]",
")",
",",
"int",
"(",
"groups",
"[",
"1",
"]",
")",
")",
"else",
":",
"self",
".",
"_dialResponse",
"=",
"(",
"int",
"(",
"groups",
"[",
"0",
"]",
")",
",",
"1",
")",
"# assume call type: VOICE",
"else",
":",
"self",
".",
"_dialResponse",
"=",
"callId",
",",
"callType",
"self",
".",
"_dialEvent",
".",
"set",
"(",
")"
] | Handler for "outgoing call initiated" event notification line | [
"Handler",
"for",
"outgoing",
"call",
"initiated",
"event",
"notification",
"line"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L935-L947 |
5,895 | faucamp/python-gsmmodem | gsmmodem/modem.py | GsmModem._handleCallAnswered | def _handleCallAnswered(self, regexMatch, callId=None):
""" Handler for "outgoing call answered" event notification line """
if regexMatch:
groups = regexMatch.groups()
if len(groups) > 1:
callId = int(groups[0])
self.activeCalls[callId].answered = True
else:
# Call ID not available for this notificition - check for the first outgoing call that has not been answered
for call in dictValuesIter(self.activeCalls):
if call.answered == False and type(call) == Call:
call.answered = True
return
else:
# Use supplied values
self.activeCalls[callId].answered = True | python | def _handleCallAnswered(self, regexMatch, callId=None):
""" Handler for "outgoing call answered" event notification line """
if regexMatch:
groups = regexMatch.groups()
if len(groups) > 1:
callId = int(groups[0])
self.activeCalls[callId].answered = True
else:
# Call ID not available for this notificition - check for the first outgoing call that has not been answered
for call in dictValuesIter(self.activeCalls):
if call.answered == False and type(call) == Call:
call.answered = True
return
else:
# Use supplied values
self.activeCalls[callId].answered = True | [
"def",
"_handleCallAnswered",
"(",
"self",
",",
"regexMatch",
",",
"callId",
"=",
"None",
")",
":",
"if",
"regexMatch",
":",
"groups",
"=",
"regexMatch",
".",
"groups",
"(",
")",
"if",
"len",
"(",
"groups",
")",
">",
"1",
":",
"callId",
"=",
"int",
"(",
"groups",
"[",
"0",
"]",
")",
"self",
".",
"activeCalls",
"[",
"callId",
"]",
".",
"answered",
"=",
"True",
"else",
":",
"# Call ID not available for this notificition - check for the first outgoing call that has not been answered",
"for",
"call",
"in",
"dictValuesIter",
"(",
"self",
".",
"activeCalls",
")",
":",
"if",
"call",
".",
"answered",
"==",
"False",
"and",
"type",
"(",
"call",
")",
"==",
"Call",
":",
"call",
".",
"answered",
"=",
"True",
"return",
"else",
":",
"# Use supplied values",
"self",
".",
"activeCalls",
"[",
"callId",
"]",
".",
"answered",
"=",
"True"
] | Handler for "outgoing call answered" event notification line | [
"Handler",
"for",
"outgoing",
"call",
"answered",
"event",
"notification",
"line"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L949-L964 |
5,896 | faucamp/python-gsmmodem | gsmmodem/modem.py | GsmModem._handleSmsReceived | def _handleSmsReceived(self, notificationLine):
""" Handler for "new SMS" unsolicited notification line """
self.log.debug('SMS message received')
cmtiMatch = self.CMTI_REGEX.match(notificationLine)
if cmtiMatch:
msgMemory = cmtiMatch.group(1)
msgIndex = cmtiMatch.group(2)
sms = self.readStoredSms(msgIndex, msgMemory)
self.deleteStoredSms(msgIndex)
self.smsReceivedCallback(sms) | python | def _handleSmsReceived(self, notificationLine):
""" Handler for "new SMS" unsolicited notification line """
self.log.debug('SMS message received')
cmtiMatch = self.CMTI_REGEX.match(notificationLine)
if cmtiMatch:
msgMemory = cmtiMatch.group(1)
msgIndex = cmtiMatch.group(2)
sms = self.readStoredSms(msgIndex, msgMemory)
self.deleteStoredSms(msgIndex)
self.smsReceivedCallback(sms) | [
"def",
"_handleSmsReceived",
"(",
"self",
",",
"notificationLine",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'SMS message received'",
")",
"cmtiMatch",
"=",
"self",
".",
"CMTI_REGEX",
".",
"match",
"(",
"notificationLine",
")",
"if",
"cmtiMatch",
":",
"msgMemory",
"=",
"cmtiMatch",
".",
"group",
"(",
"1",
")",
"msgIndex",
"=",
"cmtiMatch",
".",
"group",
"(",
"2",
")",
"sms",
"=",
"self",
".",
"readStoredSms",
"(",
"msgIndex",
",",
"msgMemory",
")",
"self",
".",
"deleteStoredSms",
"(",
"msgIndex",
")",
"self",
".",
"smsReceivedCallback",
"(",
"sms",
")"
] | Handler for "new SMS" unsolicited notification line | [
"Handler",
"for",
"new",
"SMS",
"unsolicited",
"notification",
"line"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L991-L1000 |
5,897 | faucamp/python-gsmmodem | gsmmodem/modem.py | GsmModem._handleSmsStatusReport | def _handleSmsStatusReport(self, notificationLine):
""" Handler for SMS status reports """
self.log.debug('SMS status report received')
cdsiMatch = self.CDSI_REGEX.match(notificationLine)
if cdsiMatch:
msgMemory = cdsiMatch.group(1)
msgIndex = cdsiMatch.group(2)
report = self.readStoredSms(msgIndex, msgMemory)
self.deleteStoredSms(msgIndex)
# Update sent SMS status if possible
if report.reference in self.sentSms:
self.sentSms[report.reference].report = report
if self._smsStatusReportEvent:
# A sendSms() call is waiting for this response - notify waiting thread
self._smsStatusReportEvent.set()
else:
# Nothing is waiting for this report directly - use callback
self.smsStatusReportCallback(report) | python | def _handleSmsStatusReport(self, notificationLine):
""" Handler for SMS status reports """
self.log.debug('SMS status report received')
cdsiMatch = self.CDSI_REGEX.match(notificationLine)
if cdsiMatch:
msgMemory = cdsiMatch.group(1)
msgIndex = cdsiMatch.group(2)
report = self.readStoredSms(msgIndex, msgMemory)
self.deleteStoredSms(msgIndex)
# Update sent SMS status if possible
if report.reference in self.sentSms:
self.sentSms[report.reference].report = report
if self._smsStatusReportEvent:
# A sendSms() call is waiting for this response - notify waiting thread
self._smsStatusReportEvent.set()
else:
# Nothing is waiting for this report directly - use callback
self.smsStatusReportCallback(report) | [
"def",
"_handleSmsStatusReport",
"(",
"self",
",",
"notificationLine",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'SMS status report received'",
")",
"cdsiMatch",
"=",
"self",
".",
"CDSI_REGEX",
".",
"match",
"(",
"notificationLine",
")",
"if",
"cdsiMatch",
":",
"msgMemory",
"=",
"cdsiMatch",
".",
"group",
"(",
"1",
")",
"msgIndex",
"=",
"cdsiMatch",
".",
"group",
"(",
"2",
")",
"report",
"=",
"self",
".",
"readStoredSms",
"(",
"msgIndex",
",",
"msgMemory",
")",
"self",
".",
"deleteStoredSms",
"(",
"msgIndex",
")",
"# Update sent SMS status if possible ",
"if",
"report",
".",
"reference",
"in",
"self",
".",
"sentSms",
":",
"self",
".",
"sentSms",
"[",
"report",
".",
"reference",
"]",
".",
"report",
"=",
"report",
"if",
"self",
".",
"_smsStatusReportEvent",
":",
"# A sendSms() call is waiting for this response - notify waiting thread",
"self",
".",
"_smsStatusReportEvent",
".",
"set",
"(",
")",
"else",
":",
"# Nothing is waiting for this report directly - use callback",
"self",
".",
"smsStatusReportCallback",
"(",
"report",
")"
] | Handler for SMS status reports | [
"Handler",
"for",
"SMS",
"status",
"reports"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L1002-L1019 |
5,898 | faucamp/python-gsmmodem | gsmmodem/modem.py | Call.hangup | def hangup(self):
""" End the phone call.
Does nothing if the call is already inactive.
"""
if self.active:
self._gsmModem.write('ATH')
self.answered = False
self.active = False
if self.id in self._gsmModem.activeCalls:
del self._gsmModem.activeCalls[self.id] | python | def hangup(self):
""" End the phone call.
Does nothing if the call is already inactive.
"""
if self.active:
self._gsmModem.write('ATH')
self.answered = False
self.active = False
if self.id in self._gsmModem.activeCalls:
del self._gsmModem.activeCalls[self.id] | [
"def",
"hangup",
"(",
"self",
")",
":",
"if",
"self",
".",
"active",
":",
"self",
".",
"_gsmModem",
".",
"write",
"(",
"'ATH'",
")",
"self",
".",
"answered",
"=",
"False",
"self",
".",
"active",
"=",
"False",
"if",
"self",
".",
"id",
"in",
"self",
".",
"_gsmModem",
".",
"activeCalls",
":",
"del",
"self",
".",
"_gsmModem",
".",
"activeCalls",
"[",
"self",
".",
"id",
"]"
] | End the phone call.
Does nothing if the call is already inactive. | [
"End",
"the",
"phone",
"call",
".",
"Does",
"nothing",
"if",
"the",
"call",
"is",
"already",
"inactive",
"."
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L1272-L1282 |
5,899 | faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | GsmTerm._color | def _color(self, color, msg):
""" Converts a message to be printed to the user's terminal in red """
if self.useColor:
return '{0}{1}{2}'.format(color, msg, self.RESET_SEQ)
else:
return msg | python | def _color(self, color, msg):
""" Converts a message to be printed to the user's terminal in red """
if self.useColor:
return '{0}{1}{2}'.format(color, msg, self.RESET_SEQ)
else:
return msg | [
"def",
"_color",
"(",
"self",
",",
"color",
",",
"msg",
")",
":",
"if",
"self",
".",
"useColor",
":",
"return",
"'{0}{1}{2}'",
".",
"format",
"(",
"color",
",",
"msg",
",",
"self",
".",
"RESET_SEQ",
")",
"else",
":",
"return",
"msg"
] | Converts a message to be printed to the user's terminal in red | [
"Converts",
"a",
"message",
"to",
"be",
"printed",
"to",
"the",
"user",
"s",
"terminal",
"in",
"red"
] | 834c68b1387ca2c91e2210faa8f75526b39723b5 | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L216-L221 |
Subsets and Splits