nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jankrepl/deepdow | eb6c85845c45f89e0743b8e8c29ddb69cb78da4f | deepdow/losses.py | python | Loss.__pow__ | (self, power) | Put a loss to a power.
Parameters
----------
power : int or float
Number representing the exponent
Returns
-------
new : Loss
Instance of a ``Loss`` representing the `self ** power`. | Put a loss to a power. | [
"Put",
"a",
"loss",
"to",
"a",
"power",
"."
] | def __pow__(self, power):
"""Put a loss to a power.
Parameters
----------
power : int or float
Number representing the exponent
Returns
-------
new : Loss
Instance of a ``Loss`` representing the `self ** power`.
"""
if isinstance(power, (int, float)):
new_instance = Loss()
new_instance._call = MethodType(lambda inst, weights, y: self(weights, y) ** power, new_instance)
new_instance._repr = MethodType(lambda inst: '({}) ** {}'.format(self.__repr__(), power),
new_instance)
return new_instance
else:
raise TypeError('Unsupported type: {}'.format(type(power))) | [
"def",
"__pow__",
"(",
"self",
",",
"power",
")",
":",
"if",
"isinstance",
"(",
"power",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"new_instance",
"=",
"Loss",
"(",
")",
"new_instance",
".",
"_call",
"=",
"MethodType",
"(",
"lambda",
"inst",
",",... | https://github.com/jankrepl/deepdow/blob/eb6c85845c45f89e0743b8e8c29ddb69cb78da4f/deepdow/losses.py#L344-L365 | ||
ninthDevilHAUNSTER/ArknightsAutoHelper | a27a930502d6e432368d9f62595a1d69a992f4e6 | vendor/penguin_client/penguin_client/models/item_quantity.py | python | ItemQuantity.item_id | (self, item_id) | Sets the item_id of this ItemQuantity.
:param item_id: The item_id of this ItemQuantity. # noqa: E501
:type: str | Sets the item_id of this ItemQuantity. | [
"Sets",
"the",
"item_id",
"of",
"this",
"ItemQuantity",
"."
] | def item_id(self, item_id):
"""Sets the item_id of this ItemQuantity.
:param item_id: The item_id of this ItemQuantity. # noqa: E501
:type: str
"""
self._item_id = item_id | [
"def",
"item_id",
"(",
"self",
",",
"item_id",
")",
":",
"self",
".",
"_item_id",
"=",
"item_id"
] | https://github.com/ninthDevilHAUNSTER/ArknightsAutoHelper/blob/a27a930502d6e432368d9f62595a1d69a992f4e6/vendor/penguin_client/penguin_client/models/item_quantity.py#L66-L74 | ||
abhishekkr/gmail-helper | f3f4e586cd19a920a70d689d301e0519ed91fdb0 | _logging_/__init__.py | python | get_logger | (logger_name) | return logger | Returns logger object with console and file handler attached.
Args:
logger_name: an id for logging object generated | Returns logger object with console and file handler attached. | [
"Returns",
"logger",
"object",
"with",
"console",
"and",
"file",
"handler",
"attached",
"."
] | def get_logger(logger_name):
"""Returns logger object with console and file handler attached.
Args:
logger_name: an id for logging object generated
"""
logger = logging.getLogger(logger_name)
logger.setLevel(logging.INFO) # default INFO mode for logging
try:
if _cfg.log_debug() == 'on':
logger.setLevel(logging.DEBUG)
except:
print('default logging mode enabled, can turn on debug by env "GMAIL_HELPER_DEBUG=on"')
logger.addHandler(get_console_handler())
if len(LOG_FILE) > 0:
logger.addHandler(get_file_handler())
logger.propagate = False
return logger | [
"def",
"get_logger",
"(",
"logger_name",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"logger_name",
")",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"# default INFO mode for logging",
"try",
":",
"if",
"_cfg",
".",
"log_debug",
... | https://github.com/abhishekkr/gmail-helper/blob/f3f4e586cd19a920a70d689d301e0519ed91fdb0/_logging_/__init__.py#L42-L59 | |
pandas-dev/pandas | 5ba7d714014ae8feaccc0dd4a98890828cf2832d | pandas/core/strings/accessor.py | python | StringMethods.repeat | (self, repeats) | return self._wrap_result(result) | Duplicate each string in the Series or Index.
Parameters
----------
repeats : int or sequence of int
Same value for all (int) or different value per (sequence).
Returns
-------
Series or Index of object
Series or Index of repeated string objects specified by
input parameter repeats.
Examples
--------
>>> s = pd.Series(['a', 'b', 'c'])
>>> s
0 a
1 b
2 c
dtype: object
Single int repeats string in Series
>>> s.str.repeat(repeats=2)
0 aa
1 bb
2 cc
dtype: object
Sequence of int repeats corresponding string in Series
>>> s.str.repeat(repeats=[1, 2, 3])
0 a
1 bb
2 ccc
dtype: object | Duplicate each string in the Series or Index. | [
"Duplicate",
"each",
"string",
"in",
"the",
"Series",
"or",
"Index",
"."
] | def repeat(self, repeats):
"""
Duplicate each string in the Series or Index.
Parameters
----------
repeats : int or sequence of int
Same value for all (int) or different value per (sequence).
Returns
-------
Series or Index of object
Series or Index of repeated string objects specified by
input parameter repeats.
Examples
--------
>>> s = pd.Series(['a', 'b', 'c'])
>>> s
0 a
1 b
2 c
dtype: object
Single int repeats string in Series
>>> s.str.repeat(repeats=2)
0 aa
1 bb
2 cc
dtype: object
Sequence of int repeats corresponding string in Series
>>> s.str.repeat(repeats=[1, 2, 3])
0 a
1 bb
2 ccc
dtype: object
"""
result = self._data.array._str_repeat(repeats)
return self._wrap_result(result) | [
"def",
"repeat",
"(",
"self",
",",
"repeats",
")",
":",
"result",
"=",
"self",
".",
"_data",
".",
"array",
".",
"_str_repeat",
"(",
"repeats",
")",
"return",
"self",
".",
"_wrap_result",
"(",
"result",
")"
] | https://github.com/pandas-dev/pandas/blob/5ba7d714014ae8feaccc0dd4a98890828cf2832d/pandas/core/strings/accessor.py#L1468-L1509 | |
demisto/content | 5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07 | Packs/CofenseIntelligenceV2/Integrations/CofenseIntelligenceV2/CofenseIntelligenceV2.py | python | search_url_command | (client: Client, args: Dict[str, Any], params) | return results_list | Performs the api call to cofense threts-search endpoint to get all threats associated with the given url,
analyze the response and generates the command result object for the url command
Args:
- client (Client): client instance that is responsible for connecting with cofense API
- args (Dict): the command args- url
- params (Dict): The integartion params such as threshold, reliability
return:
CommandResults: results of the url command including outputs, raw response, readable output | Performs the api call to cofense threts-search endpoint to get all threats associated with the given url,
analyze the response and generates the command result object for the url command
Args:
- client (Client): client instance that is responsible for connecting with cofense API
- args (Dict): the command args- url
- params (Dict): The integartion params such as threshold, reliability
return:
CommandResults: results of the url command including outputs, raw response, readable output | [
"Performs",
"the",
"api",
"call",
"to",
"cofense",
"threts",
"-",
"search",
"endpoint",
"to",
"get",
"all",
"threats",
"associated",
"with",
"the",
"given",
"url",
"analyze",
"the",
"response",
"and",
"generates",
"the",
"command",
"result",
"object",
"for",
... | def search_url_command(client: Client, args: Dict[str, Any], params) -> List[CommandResults]:
""" Performs the api call to cofense threts-search endpoint to get all threats associated with the given url,
analyze the response and generates the command result object for the url command
Args:
- client (Client): client instance that is responsible for connecting with cofense API
- args (Dict): the command args- url
- params (Dict): The integartion params such as threshold, reliability
return:
CommandResults: results of the url command including outputs, raw response, readable output
"""
urls = argToList(args.get('url'))
days_back = args.get('days_back') if args.get('days_back') else params.get('days_back')
if not urls:
raise ValueError('URL not specified')
results_list = []
for url in urls:
result = client.threat_search_call(url=url, days_back=days_back)
threats = result.get('data', {}).get('threats', [])
remove_false_vendors_detections_from_threat(threats)
outputs = {'Data': url, 'Threats': threats}
md_data, dbot_score = threats_analysis(client.severity_score, threats, indicator=url,
threshold=params.get('url_threshold'))
dbot_score_obj = Common.DBotScore(indicator=url, indicator_type=DBotScoreType.URL,
integration_name=INTEGRATION_NAME, score=dbot_score,
reliability=params.get(RELIABILITY))
relationships = create_relationship(client, url, threats, FeedIndicatorType.URL)
url_indicator = Common.URL(url=url, dbot_score=dbot_score_obj, relationships=relationships)
command_results = CommandResults(
outputs_prefix=f'{OUTPUT_PREFIX}.URL',
outputs_key_field='Data',
outputs=outputs,
raw_response=result,
readable_output=tableToMarkdown(name=f'Cofense URL Reputation for url {url}', t=md_data,
headers=['Threat ID', 'Threat Type', 'Verdict', 'Executive Summary',
'Campaign', 'Malware Family Description', 'Last Published',
'Threat Report']),
indicator=url_indicator,
relationships=relationships)
results_list.append(command_results)
return results_list | [
"def",
"search_url_command",
"(",
"client",
":",
"Client",
",",
"args",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"params",
")",
"->",
"List",
"[",
"CommandResults",
"]",
":",
"urls",
"=",
"argToList",
"(",
"args",
".",
"get",
"(",
"'url'",
")",... | https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/CofenseIntelligenceV2/Integrations/CofenseIntelligenceV2/CofenseIntelligenceV2.py#L401-L443 | |
openstack/python-novaclient | 63d368168c87bc0b9a9b7928b42553c609e46089 | novaclient/v2/servers.py | python | Server.delete_tag | (self, tag) | return self.manager.delete_tag(self, tag) | Remove single tag from an instance. | Remove single tag from an instance. | [
"Remove",
"single",
"tag",
"from",
"an",
"instance",
"."
] | def delete_tag(self, tag):
"""
Remove single tag from an instance.
"""
return self.manager.delete_tag(self, tag) | [
"def",
"delete_tag",
"(",
"self",
",",
"tag",
")",
":",
"return",
"self",
".",
"manager",
".",
"delete_tag",
"(",
"self",
",",
"tag",
")"
] | https://github.com/openstack/python-novaclient/blob/63d368168c87bc0b9a9b7928b42553c609e46089/novaclient/v2/servers.py#L655-L659 | |
aparo/django-elasticsearch | 8fd25bd86b58cfc0d6490cfac08e4846ab4ddf97 | django_elasticsearch/manager.py | python | QuerySet.filter | (self, *q_objs, **query) | return self.__call__(*q_objs, **query) | An alias of :meth:`~mongoengine.queryset.QuerySet.__call__` | An alias of :meth:`~mongoengine.queryset.QuerySet.__call__` | [
"An",
"alias",
"of",
":",
"meth",
":",
"~mongoengine",
".",
"queryset",
".",
"QuerySet",
".",
"__call__"
] | def filter(self, *q_objs, **query):
"""An alias of :meth:`~mongoengine.queryset.QuerySet.__call__`
"""
return self.__call__(*q_objs, **query) | [
"def",
"filter",
"(",
"self",
",",
"*",
"q_objs",
",",
"*",
"*",
"query",
")",
":",
"return",
"self",
".",
"__call__",
"(",
"*",
"q_objs",
",",
"*",
"*",
"query",
")"
] | https://github.com/aparo/django-elasticsearch/blob/8fd25bd86b58cfc0d6490cfac08e4846ab4ddf97/django_elasticsearch/manager.py#L189-L192 | |
pygeos/pygeos | 0835379a5bc534be63037696b1b70cf4337e3841 | pygeos/constructive.py | python | polygonize_full | (geometries, **kwargs) | return lib.polygonize_full(geometries, **kwargs) | Creates polygons formed from the linework of a set of Geometries and
return all extra outputs as well.
Polygonizes an array of Geometries that contain linework which
represents the edges of a planar graph. Any type of Geometry may be
provided as input; only the constituent lines and rings will be used to
create the output polygons.
This function performs the same polygonization as ``polygonize`` but does
not only return the polygonal result but all extra outputs as well. The
return value consists of 4 elements:
* The polygonal valid output
* **Cut edges**: edges connected on both ends but not part of polygonal output
* **dangles**: edges connected on one end but not part of polygonal output
* **invalid rings**: polygons formed but which are not valid
This function returns the geometries within GeometryCollections.
Individual geometries can be obtained using ``get_geometry`` to get
a single geometry or ``get_parts`` to get an array of geometries.
Parameters
----------
geometries : array_like
An array of geometries.
axis : int
Axis along which the geometries are polygonized.
The default is to perform a reduction over the last dimension
of the input array. A 1D array results in a scalar geometry.
**kwargs
For other keyword-only arguments, see the
`NumPy ufunc docs <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_.
Returns
-------
(polgyons, cuts, dangles, invalid)
tuple of 4 GeometryCollections or arrays of GeometryCollections
See Also
--------
polygonize
Examples
--------
>>> lines = [
... Geometry("LINESTRING (0 0, 1 1)"),
... Geometry("LINESTRING (0 0, 0 1, 1 1)"),
... Geometry("LINESTRING (0 1, 1 1)"),
... ]
>>> polygonize_full(lines) # doctest: +NORMALIZE_WHITESPACE
(<pygeos.Geometry GEOMETRYCOLLECTION (POLYGON ((1 1, 0 0, 0 1, 1 1)))>,
<pygeos.Geometry GEOMETRYCOLLECTION EMPTY>,
<pygeos.Geometry GEOMETRYCOLLECTION (LINESTRING (0 1, 1 1))>,
<pygeos.Geometry GEOMETRYCOLLECTION EMPTY>) | Creates polygons formed from the linework of a set of Geometries and
return all extra outputs as well. | [
"Creates",
"polygons",
"formed",
"from",
"the",
"linework",
"of",
"a",
"set",
"of",
"Geometries",
"and",
"return",
"all",
"extra",
"outputs",
"as",
"well",
"."
] | def polygonize_full(geometries, **kwargs):
"""Creates polygons formed from the linework of a set of Geometries and
return all extra outputs as well.
Polygonizes an array of Geometries that contain linework which
represents the edges of a planar graph. Any type of Geometry may be
provided as input; only the constituent lines and rings will be used to
create the output polygons.
This function performs the same polygonization as ``polygonize`` but does
not only return the polygonal result but all extra outputs as well. The
return value consists of 4 elements:
* The polygonal valid output
* **Cut edges**: edges connected on both ends but not part of polygonal output
* **dangles**: edges connected on one end but not part of polygonal output
* **invalid rings**: polygons formed but which are not valid
This function returns the geometries within GeometryCollections.
Individual geometries can be obtained using ``get_geometry`` to get
a single geometry or ``get_parts`` to get an array of geometries.
Parameters
----------
geometries : array_like
An array of geometries.
axis : int
Axis along which the geometries are polygonized.
The default is to perform a reduction over the last dimension
of the input array. A 1D array results in a scalar geometry.
**kwargs
For other keyword-only arguments, see the
`NumPy ufunc docs <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_.
Returns
-------
(polgyons, cuts, dangles, invalid)
tuple of 4 GeometryCollections or arrays of GeometryCollections
See Also
--------
polygonize
Examples
--------
>>> lines = [
... Geometry("LINESTRING (0 0, 1 1)"),
... Geometry("LINESTRING (0 0, 0 1, 1 1)"),
... Geometry("LINESTRING (0 1, 1 1)"),
... ]
>>> polygonize_full(lines) # doctest: +NORMALIZE_WHITESPACE
(<pygeos.Geometry GEOMETRYCOLLECTION (POLYGON ((1 1, 0 0, 0 1, 1 1)))>,
<pygeos.Geometry GEOMETRYCOLLECTION EMPTY>,
<pygeos.Geometry GEOMETRYCOLLECTION (LINESTRING (0 1, 1 1))>,
<pygeos.Geometry GEOMETRYCOLLECTION EMPTY>)
"""
return lib.polygonize_full(geometries, **kwargs) | [
"def",
"polygonize_full",
"(",
"geometries",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"lib",
".",
"polygonize_full",
"(",
"geometries",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/pygeos/pygeos/blob/0835379a5bc534be63037696b1b70cf4337e3841/pygeos/constructive.py#L582-L638 | |
twitterdev/twitter-for-bigquery | 8dcbcd28f813587e8f53e4436ad3e7e61f1c0a37 | libs/requests/cookies.py | python | RequestsCookieJar.values | (self) | return values | Dict-like values() that returns a list of values of cookies from the jar.
See keys() and items(). | Dict-like values() that returns a list of values of cookies from the jar.
See keys() and items(). | [
"Dict",
"-",
"like",
"values",
"()",
"that",
"returns",
"a",
"list",
"of",
"values",
"of",
"cookies",
"from",
"the",
"jar",
".",
"See",
"keys",
"()",
"and",
"items",
"()",
"."
] | def values(self):
"""Dict-like values() that returns a list of values of cookies from the jar.
See keys() and items()."""
values = []
for cookie in iter(self):
values.append(cookie.value)
return values | [
"def",
"values",
"(",
"self",
")",
":",
"values",
"=",
"[",
"]",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"values",
".",
"append",
"(",
"cookie",
".",
"value",
")",
"return",
"values"
] | https://github.com/twitterdev/twitter-for-bigquery/blob/8dcbcd28f813587e8f53e4436ad3e7e61f1c0a37/libs/requests/cookies.py#L198-L204 | |
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/fileserver/gitfs.py | python | clear_cache | () | return _gitfs(init_remotes=False).clear_cache() | Completely clear gitfs cache | Completely clear gitfs cache | [
"Completely",
"clear",
"gitfs",
"cache"
] | def clear_cache():
"""
Completely clear gitfs cache
"""
return _gitfs(init_remotes=False).clear_cache() | [
"def",
"clear_cache",
"(",
")",
":",
"return",
"_gitfs",
"(",
"init_remotes",
"=",
"False",
")",
".",
"clear_cache",
"(",
")"
] | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/fileserver/gitfs.py#L110-L114 | |
timkpaine/pyEX | 254acd2b0cf7cb7183100106f4ecc11d1860c46a | pyEX/refdata/refdata.py | python | directory | (date=None, token="", version="stable", filter="", format="json") | return _get(
"ref-data/daily-list/symbol-directory",
token=token,
version=version,
filter=filter,
format=format,
) | Args:
date (datetime): Effective date
token (str): Access token
version (str): API version
filter (str): filters: https://iexcloud.io/docs/api/#filter-results
format (str): return format, defaults to json
Returns:
dict or DataFrame: result | [] | def directory(date=None, token="", version="stable", filter="", format="json"):
"""
Args:
date (datetime): Effective date
token (str): Access token
version (str): API version
filter (str): filters: https://iexcloud.io/docs/api/#filter-results
format (str): return format, defaults to json
Returns:
dict or DataFrame: result
"""
if date:
date = _strOrDate(date)
return _get(
"ref-data/daily-list/symbol-directory/" + date,
token=token,
version=version,
filter=filter,
format=format,
)
return _get(
"ref-data/daily-list/symbol-directory",
token=token,
version=version,
filter=filter,
format=format,
) | [
"def",
"directory",
"(",
"date",
"=",
"None",
",",
"token",
"=",
"\"\"",
",",
"version",
"=",
"\"stable\"",
",",
"filter",
"=",
"\"\"",
",",
"format",
"=",
"\"json\"",
")",
":",
"if",
"date",
":",
"date",
"=",
"_strOrDate",
"(",
"date",
")",
"return"... | https://github.com/timkpaine/pyEX/blob/254acd2b0cf7cb7183100106f4ecc11d1860c46a/pyEX/refdata/refdata.py#L131-L159 | ||
fabioz/PyDev.Debugger | 0f8c02a010fe5690405da1dd30ed72326191ce63 | pydevd_attach_to_process/winappdbg/breakpoint.py | python | _BreakpointContainer.__cleanup_process | (self, event) | Auxiliary method for L{_notify_exit_process}. | Auxiliary method for L{_notify_exit_process}. | [
"Auxiliary",
"method",
"for",
"L",
"{",
"_notify_exit_process",
"}",
"."
] | def __cleanup_process(self, event):
"""
Auxiliary method for L{_notify_exit_process}.
"""
pid = event.get_pid()
process = event.get_process()
# Cleanup code breakpoints
for (bp_pid, bp_address) in compat.keys(self.__codeBP):
if bp_pid == pid:
bp = self.__codeBP[ (bp_pid, bp_address) ]
self.__cleanup_breakpoint(event, bp)
del self.__codeBP[ (bp_pid, bp_address) ]
# Cleanup page breakpoints
for (bp_pid, bp_address) in compat.keys(self.__pageBP):
if bp_pid == pid:
bp = self.__pageBP[ (bp_pid, bp_address) ]
self.__cleanup_breakpoint(event, bp)
del self.__pageBP[ (bp_pid, bp_address) ]
# Cleanup deferred code breakpoints
try:
del self.__deferredBP[pid]
except KeyError:
pass | [
"def",
"__cleanup_process",
"(",
"self",
",",
"event",
")",
":",
"pid",
"=",
"event",
".",
"get_pid",
"(",
")",
"process",
"=",
"event",
".",
"get_process",
"(",
")",
"# Cleanup code breakpoints",
"for",
"(",
"bp_pid",
",",
"bp_address",
")",
"in",
"compat... | https://github.com/fabioz/PyDev.Debugger/blob/0f8c02a010fe5690405da1dd30ed72326191ce63/pydevd_attach_to_process/winappdbg/breakpoint.py#L2139-L2164 | ||
robotlearn/pyrobolearn | 9cd7c060723fda7d2779fa255ac998c2c82b8436 | pyrobolearn/models/gaussian.py | python | Gaussian.__init__ | (self, mean=None, covariance=None, seed=None, manifold=None, N=None) | Initialize the multivariate normal distribution on the given manifold.
Args:
mean (np.array[float[D]]): mean vector.
covariance (np.array[float[D,D]]): covariance matrix.
seed (int): random seed. Useful when sampling.
manifold (None): By default, it is the Euclidean space.
N (int, N): the number of data points | Initialize the multivariate normal distribution on the given manifold. | [
"Initialize",
"the",
"multivariate",
"normal",
"distribution",
"on",
"the",
"given",
"manifold",
"."
] | def __init__(self, mean=None, covariance=None, seed=None, manifold=None, N=None): # coefficient=1.
"""
Initialize the multivariate normal distribution on the given manifold.
Args:
mean (np.array[float[D]]): mean vector.
covariance (np.array[float[D,D]]): covariance matrix.
seed (int): random seed. Useful when sampling.
manifold (None): By default, it is the Euclidean space.
N (int, N): the number of data points
"""
# Args: coefficient (float): coefficient in front of the Gaussian PDF. This is useful when multiplying two
# Gaussian PDFs which results in a Gaussian PDF multiplied by a coefficient (and thus, is no more
# a valid probability distribution).
# set mean
self.mean = mean
# check that the covariance is symmetric and is PSD
self.cov = covariance
# set the coefficient
# self.coefficient = coefficient
# set the seed
self.seed = seed
# TODO: formulas are different depending on the space we are in
# TODO: the manifold should be an object (see the `geomstats` module)
# For now, it will just be a string and we will focus on the Euclidean space
self.manifold = 'euclidean' # manifold
# number of data points
self.N = N | [
"def",
"__init__",
"(",
"self",
",",
"mean",
"=",
"None",
",",
"covariance",
"=",
"None",
",",
"seed",
"=",
"None",
",",
"manifold",
"=",
"None",
",",
"N",
"=",
"None",
")",
":",
"# coefficient=1.",
"# Args: coefficient (float): coefficient in front of the Gauss... | https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/models/gaussian.py#L106-L139 | ||
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit - MAC OSX/tools/sqli/thirdparty/gprof2dot/gprof2dot.py | python | Theme.graph_fontname | (self) | return self.fontname | [] | def graph_fontname(self):
return self.fontname | [
"def",
"graph_fontname",
"(",
"self",
")",
":",
"return",
"self",
".",
"fontname"
] | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/sqli/thirdparty/gprof2dot/gprof2dot.py#L2158-L2159 | |||
gmr/rabbitpy | d97fd2b1e983df0d95c2b0e2c6b29f61c79d82b9 | rabbitpy/base.py | python | AMQPClass.__init__ | (self, channel, name) | Create a new ClassObject.
:param channel: The channel to execute commands on
:type channel: rabbitpy.Channel
:param str name: Set the name
:raises: ValueError | Create a new ClassObject. | [
"Create",
"a",
"new",
"ClassObject",
"."
] | def __init__(self, channel, name):
"""Create a new ClassObject.
:param channel: The channel to execute commands on
:type channel: rabbitpy.Channel
:param str name: Set the name
:raises: ValueError
"""
super(AMQPClass, self).__init__(channel)
# Use type so there's not a circular dependency
if channel.__class__.__name__ != 'Channel':
raise ValueError('channel must be a valid rabbitpy Channel object')
elif not utils.is_string(name):
raise ValueError('name must be str, bytes or unicode')
self.name = name | [
"def",
"__init__",
"(",
"self",
",",
"channel",
",",
"name",
")",
":",
"super",
"(",
"AMQPClass",
",",
"self",
")",
".",
"__init__",
"(",
"channel",
")",
"# Use type so there's not a circular dependency",
"if",
"channel",
".",
"__class__",
".",
"__name__",
"!=... | https://github.com/gmr/rabbitpy/blob/d97fd2b1e983df0d95c2b0e2c6b29f61c79d82b9/rabbitpy/base.py#L53-L68 | ||
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework | cb692f527e4e819b6c228187c5702d990a180043 | bin/x86/Debug/scripting_engine/Lib/timeit.py | python | _template_func | (setup, func) | return inner | Create a timer function. Used if the "statement" is a callable. | Create a timer function. Used if the "statement" is a callable. | [
"Create",
"a",
"timer",
"function",
".",
"Used",
"if",
"the",
"statement",
"is",
"a",
"callable",
"."
] | def _template_func(setup, func):
"""Create a timer function. Used if the "statement" is a callable."""
def inner(_it, _timer, _func=func):
setup()
_t0 = _timer()
for _i in _it:
_func()
_t1 = _timer()
return _t1 - _t0
return inner | [
"def",
"_template_func",
"(",
"setup",
",",
"func",
")",
":",
"def",
"inner",
"(",
"_it",
",",
"_timer",
",",
"_func",
"=",
"func",
")",
":",
"setup",
"(",
")",
"_t0",
"=",
"_timer",
"(",
")",
"for",
"_i",
"in",
"_it",
":",
"_func",
"(",
")",
"... | https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/bin/x86/Debug/scripting_engine/Lib/timeit.py#L94-L103 | |
Kraymer/flinck | b3d0076e2b3ab74c0a8f4a3c8abf5631ee362438 | flinck/confit.py | python | String.__init__ | (self, default=REQUIRED, pattern=None) | Create a template with the added optional `pattern` argument,
a regular expression string that the value should match. | Create a template with the added optional `pattern` argument,
a regular expression string that the value should match. | [
"Create",
"a",
"template",
"with",
"the",
"added",
"optional",
"pattern",
"argument",
"a",
"regular",
"expression",
"string",
"that",
"the",
"value",
"should",
"match",
"."
] | def __init__(self, default=REQUIRED, pattern=None):
"""Create a template with the added optional `pattern` argument,
a regular expression string that the value should match.
"""
super(String, self).__init__(default)
self.pattern = pattern
if pattern:
self.regex = re.compile(pattern) | [
"def",
"__init__",
"(",
"self",
",",
"default",
"=",
"REQUIRED",
",",
"pattern",
"=",
"None",
")",
":",
"super",
"(",
"String",
",",
"self",
")",
".",
"__init__",
"(",
"default",
")",
"self",
".",
"pattern",
"=",
"pattern",
"if",
"pattern",
":",
"sel... | https://github.com/Kraymer/flinck/blob/b3d0076e2b3ab74c0a8f4a3c8abf5631ee362438/flinck/confit.py#L1087-L1094 | ||
TheAlgorithms/Python | 9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c | maths/area.py | python | surface_area_cone | (radius: float, height: float) | return pi * radius * (radius + (height ** 2 + radius ** 2) ** 0.5) | Calculate the Surface Area of a Cone.
Wikipedia reference: https://en.wikipedia.org/wiki/Cone
Formula: pi * r * (r + (h ** 2 + r ** 2) ** 0.5)
>>> surface_area_cone(10, 24)
1130.9733552923256
>>> surface_area_cone(6, 8)
301.59289474462014
>>> surface_area_cone(-1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
>>> surface_area_cone(1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
>>> surface_area_cone(-1, 2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values | Calculate the Surface Area of a Cone.
Wikipedia reference: https://en.wikipedia.org/wiki/Cone
Formula: pi * r * (r + (h ** 2 + r ** 2) ** 0.5) | [
"Calculate",
"the",
"Surface",
"Area",
"of",
"a",
"Cone",
".",
"Wikipedia",
"reference",
":",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Cone",
"Formula",
":",
"pi",
"*",
"r",
"*",
"(",
"r",
"+",
"(",
"h",
"**",
"2... | def surface_area_cone(radius: float, height: float) -> float:
"""
Calculate the Surface Area of a Cone.
Wikipedia reference: https://en.wikipedia.org/wiki/Cone
Formula: pi * r * (r + (h ** 2 + r ** 2) ** 0.5)
>>> surface_area_cone(10, 24)
1130.9733552923256
>>> surface_area_cone(6, 8)
301.59289474462014
>>> surface_area_cone(-1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
>>> surface_area_cone(1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
>>> surface_area_cone(-1, 2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
"""
if radius < 0 or height < 0:
raise ValueError("surface_area_cone() only accepts non-negative values")
return pi * radius * (radius + (height ** 2 + radius ** 2) ** 0.5) | [
"def",
"surface_area_cone",
"(",
"radius",
":",
"float",
",",
"height",
":",
"float",
")",
"->",
"float",
":",
"if",
"radius",
"<",
"0",
"or",
"height",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"surface_area_cone() only accepts non-negative values\"",
")",
... | https://github.com/TheAlgorithms/Python/blob/9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c/maths/area.py#L68-L93 | |
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/axes/_axes.py | python | Axes.angle_spectrum | (self, x, Fs=None, Fc=None, window=None,
pad_to=None, sides=None, **kwargs) | return spec, freqs, lines[0] | Plot the angle spectrum.
Call signature::
angle_spectrum(x, Fs=2, Fc=0, window=mlab.window_hanning,
pad_to=None, sides='default', **kwargs)
Compute the angle spectrum (wrapped phase spectrum) of *x*.
Data is padded to a length of *pad_to* and the windowing function
*window* is applied to the signal.
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data.
%(Spectral)s
%(Single_Spectrum)s
Fc : int
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
Returns
-------
spectrum : 1-D array
The values for the angle spectrum in radians (real valued).
freqs : 1-D array
The frequencies corresponding to the elements in *spectrum*.
line : a :class:`~matplotlib.lines.Line2D` instance
The line created by this function.
Other Parameters
----------------
**kwargs :
Keyword arguments control the :class:`~matplotlib.lines.Line2D`
properties:
%(Line2D)s
See Also
--------
:func:`magnitude_spectrum`
:func:`angle_spectrum` plots the magnitudes of the corresponding
frequencies.
:func:`phase_spectrum`
:func:`phase_spectrum` plots the unwrapped version of this
function.
:func:`specgram`
:func:`specgram` can plot the angle spectrum of segments within the
signal in a colormap.
Notes
-----
.. [Notes section required for data comment. See #10189.] | Plot the angle spectrum. | [
"Plot",
"the",
"angle",
"spectrum",
"."
] | def angle_spectrum(self, x, Fs=None, Fc=None, window=None,
pad_to=None, sides=None, **kwargs):
"""
Plot the angle spectrum.
Call signature::
angle_spectrum(x, Fs=2, Fc=0, window=mlab.window_hanning,
pad_to=None, sides='default', **kwargs)
Compute the angle spectrum (wrapped phase spectrum) of *x*.
Data is padded to a length of *pad_to* and the windowing function
*window* is applied to the signal.
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data.
%(Spectral)s
%(Single_Spectrum)s
Fc : int
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
Returns
-------
spectrum : 1-D array
The values for the angle spectrum in radians (real valued).
freqs : 1-D array
The frequencies corresponding to the elements in *spectrum*.
line : a :class:`~matplotlib.lines.Line2D` instance
The line created by this function.
Other Parameters
----------------
**kwargs :
Keyword arguments control the :class:`~matplotlib.lines.Line2D`
properties:
%(Line2D)s
See Also
--------
:func:`magnitude_spectrum`
:func:`angle_spectrum` plots the magnitudes of the corresponding
frequencies.
:func:`phase_spectrum`
:func:`phase_spectrum` plots the unwrapped version of this
function.
:func:`specgram`
:func:`specgram` can plot the angle spectrum of segments within the
signal in a colormap.
Notes
-----
.. [Notes section required for data comment. See #10189.]
"""
if Fc is None:
Fc = 0
spec, freqs = mlab.angle_spectrum(x=x, Fs=Fs, window=window,
pad_to=pad_to, sides=sides)
freqs += Fc
lines = self.plot(freqs, spec, **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Angle (radians)')
return spec, freqs, lines[0] | [
"def",
"angle_spectrum",
"(",
"self",
",",
"x",
",",
"Fs",
"=",
"None",
",",
"Fc",
"=",
"None",
",",
"window",
"=",
"None",
",",
"pad_to",
"=",
"None",
",",
"sides",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"Fc",
"is",
"None",
":",... | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/axes/_axes.py#L7242-L7320 | |
lunixbochs/ActualVim | 1f555ce719e49d6584f0e35e9f0db2f216b98fa5 | lib/asyncio/transports.py | python | BaseTransport.get_extra_info | (self, name, default=None) | return self._extra.get(name, default) | Get optional transport information. | Get optional transport information. | [
"Get",
"optional",
"transport",
"information",
"."
] | def get_extra_info(self, name, default=None):
"""Get optional transport information."""
return self._extra.get(name, default) | [
"def",
"get_extra_info",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"_extra",
".",
"get",
"(",
"name",
",",
"default",
")"
] | https://github.com/lunixbochs/ActualVim/blob/1f555ce719e49d6584f0e35e9f0db2f216b98fa5/lib/asyncio/transports.py#L18-L20 | |
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Tools/scripts/logmerge.py | python | read_chunk | (fp) | return chunk | Read a chunk -- data for one file, ending with sep1.
Split the chunk in parts separated by sep2. | Read a chunk -- data for one file, ending with sep1. | [
"Read",
"a",
"chunk",
"--",
"data",
"for",
"one",
"file",
"ending",
"with",
"sep1",
"."
] | def read_chunk(fp):
"""Read a chunk -- data for one file, ending with sep1.
Split the chunk in parts separated by sep2.
"""
chunk = []
lines = []
while 1:
line = fp.readline()
if not line:
break
if line == sep1:
if lines:
chunk.append(lines)
break
if line == sep2:
if lines:
chunk.append(lines)
lines = []
else:
lines.append(line)
return chunk | [
"def",
"read_chunk",
"(",
"fp",
")",
":",
"chunk",
"=",
"[",
"]",
"lines",
"=",
"[",
"]",
"while",
"1",
":",
"line",
"=",
"fp",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"if",
"line",
"==",
"sep1",
":",
"if",
"lines",
":",
... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Tools/scripts/logmerge.py#L72-L94 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/soma/config_flow.py | python | SomaFlowHandler.async_step_user | (self, user_input=None) | return await self.async_step_creation(user_input) | Handle a flow start. | Handle a flow start. | [
"Handle",
"a",
"flow",
"start",
"."
] | async def async_step_user(self, user_input=None):
"""Handle a flow start."""
if user_input is None:
data = {
vol.Required(CONF_HOST): str,
vol.Required(CONF_PORT, default=DEFAULT_PORT): int,
}
return self.async_show_form(step_id="user", data_schema=vol.Schema(data))
return await self.async_step_creation(user_input) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"if",
"user_input",
"is",
"None",
":",
"data",
"=",
"{",
"vol",
".",
"Required",
"(",
"CONF_HOST",
")",
":",
"str",
",",
"vol",
".",
"Required",
"(",
"CONF_PORT",... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/soma/config_flow.py#L26-L36 | |
golismero/golismero | 7d605b937e241f51c1ca4f47b20f755eeefb9d76 | tools/sqlmap/thirdparty/beautifulsoup/beautifulsoup.py | python | BeautifulStoneSoup.handle_decl | (self, data) | Handle DOCTYPEs and the like as Declaration objects. | Handle DOCTYPEs and the like as Declaration objects. | [
"Handle",
"DOCTYPEs",
"and",
"the",
"like",
"as",
"Declaration",
"objects",
"."
] | def handle_decl(self, data):
"Handle DOCTYPEs and the like as Declaration objects."
self._toStringSubclass(data, Declaration) | [
"def",
"handle_decl",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_toStringSubclass",
"(",
"data",
",",
"Declaration",
")"
] | https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/tools/sqlmap/thirdparty/beautifulsoup/beautifulsoup.py#L1443-L1445 | ||
zim-desktop-wiki/zim-desktop-wiki | fe717d7ee64e5c06d90df90eb87758e5e72d25c5 | zim/fs.py | python | UnixPath.exists | (self) | return os.path.exists(self.path) | Check if a file or folder exists.
@returns: C{True} if the file or folder exists
@implementation: must be implemented by sub classes in order
that they enforce the type of the resource as well | Check if a file or folder exists. | [
"Check",
"if",
"a",
"file",
"or",
"folder",
"exists",
"."
] | def exists(self):
'''Check if a file or folder exists.
@returns: C{True} if the file or folder exists
@implementation: must be implemented by sub classes in order
that they enforce the type of the resource as well
'''
return os.path.exists(self.path) | [
"def",
"exists",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")"
] | https://github.com/zim-desktop-wiki/zim-desktop-wiki/blob/fe717d7ee64e5c06d90df90eb87758e5e72d25c5/zim/fs.py#L469-L475 | |
influxdata/influxdb-python | 7cb565698c88bfbf9f4804650231bd28d09e2e6d | examples/tutorial.py | python | parse_args | () | return parser.parse_args() | Parse the args. | Parse the args. | [
"Parse",
"the",
"args",
"."
] | def parse_args():
"""Parse the args."""
parser = argparse.ArgumentParser(
description='example code to play with InfluxDB')
parser.add_argument('--host', type=str, required=False,
default='localhost',
help='hostname of InfluxDB http API')
parser.add_argument('--port', type=int, required=False, default=8086,
help='port of InfluxDB http API')
return parser.parse_args() | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'example code to play with InfluxDB'",
")",
"parser",
".",
"add_argument",
"(",
"'--host'",
",",
"type",
"=",
"str",
",",
"required",
"=",
"False",
... | https://github.com/influxdata/influxdb-python/blob/7cb565698c88bfbf9f4804650231bd28d09e2e6d/examples/tutorial.py#L67-L76 | |
zzzeek/sqlalchemy | fc5c54fcd4d868c2a4c7ac19668d72f506fe821e | lib/sqlalchemy/orm/session.py | python | ORMExecuteState.invoke_statement | (
self,
statement=None,
params=None,
execution_options=None,
bind_arguments=None,
) | return self.session.execute(
statement,
_params,
_execution_options,
_bind_arguments,
_parent_execute_state=self,
) | Execute the statement represented by this
:class:`.ORMExecuteState`, without re-invoking events that have
already proceeded.
This method essentially performs a re-entrant execution of the current
statement for which the :meth:`.SessionEvents.do_orm_execute` event is
being currently invoked. The use case for this is for event handlers
that want to override how the ultimate
:class:`_engine.Result` object is returned, such as for schemes that
retrieve results from an offline cache or which concatenate results
from multiple executions.
When the :class:`_engine.Result` object is returned by the actual
handler function within :meth:`_orm.SessionEvents.do_orm_execute` and
is propagated to the calling
:meth:`_orm.Session.execute` method, the remainder of the
:meth:`_orm.Session.execute` method is preempted and the
:class:`_engine.Result` object is returned to the caller of
:meth:`_orm.Session.execute` immediately.
:param statement: optional statement to be invoked, in place of the
statement currently represented by :attr:`.ORMExecuteState.statement`.
:param params: optional dictionary of parameters which will be merged
into the existing :attr:`.ORMExecuteState.parameters` of this
:class:`.ORMExecuteState`.
:param execution_options: optional dictionary of execution options
will be merged into the existing
:attr:`.ORMExecuteState.execution_options` of this
:class:`.ORMExecuteState`.
:param bind_arguments: optional dictionary of bind_arguments
which will be merged amongst the current
:attr:`.ORMExecuteState.bind_arguments`
of this :class:`.ORMExecuteState`.
:return: a :class:`_engine.Result` object with ORM-level results.
.. seealso::
:ref:`do_orm_execute_re_executing` - background and examples on the
appropriate usage of :meth:`_orm.ORMExecuteState.invoke_statement`. | Execute the statement represented by this
:class:`.ORMExecuteState`, without re-invoking events that have
already proceeded. | [
"Execute",
"the",
"statement",
"represented",
"by",
"this",
":",
"class",
":",
".",
"ORMExecuteState",
"without",
"re",
"-",
"invoking",
"events",
"that",
"have",
"already",
"proceeded",
"."
] | def invoke_statement(
self,
statement=None,
params=None,
execution_options=None,
bind_arguments=None,
):
"""Execute the statement represented by this
:class:`.ORMExecuteState`, without re-invoking events that have
already proceeded.
This method essentially performs a re-entrant execution of the current
statement for which the :meth:`.SessionEvents.do_orm_execute` event is
being currently invoked. The use case for this is for event handlers
that want to override how the ultimate
:class:`_engine.Result` object is returned, such as for schemes that
retrieve results from an offline cache or which concatenate results
from multiple executions.
When the :class:`_engine.Result` object is returned by the actual
handler function within :meth:`_orm.SessionEvents.do_orm_execute` and
is propagated to the calling
:meth:`_orm.Session.execute` method, the remainder of the
:meth:`_orm.Session.execute` method is preempted and the
:class:`_engine.Result` object is returned to the caller of
:meth:`_orm.Session.execute` immediately.
:param statement: optional statement to be invoked, in place of the
statement currently represented by :attr:`.ORMExecuteState.statement`.
:param params: optional dictionary of parameters which will be merged
into the existing :attr:`.ORMExecuteState.parameters` of this
:class:`.ORMExecuteState`.
:param execution_options: optional dictionary of execution options
will be merged into the existing
:attr:`.ORMExecuteState.execution_options` of this
:class:`.ORMExecuteState`.
:param bind_arguments: optional dictionary of bind_arguments
which will be merged amongst the current
:attr:`.ORMExecuteState.bind_arguments`
of this :class:`.ORMExecuteState`.
:return: a :class:`_engine.Result` object with ORM-level results.
.. seealso::
:ref:`do_orm_execute_re_executing` - background and examples on the
appropriate usage of :meth:`_orm.ORMExecuteState.invoke_statement`.
"""
if statement is None:
statement = self.statement
_bind_arguments = dict(self.bind_arguments)
if bind_arguments:
_bind_arguments.update(bind_arguments)
_bind_arguments["_sa_skip_events"] = True
if params:
_params = dict(self.parameters)
_params.update(params)
else:
_params = self.parameters
_execution_options = self.local_execution_options
if execution_options:
_execution_options = _execution_options.union(execution_options)
return self.session.execute(
statement,
_params,
_execution_options,
_bind_arguments,
_parent_execute_state=self,
) | [
"def",
"invoke_statement",
"(",
"self",
",",
"statement",
"=",
"None",
",",
"params",
"=",
"None",
",",
"execution_options",
"=",
"None",
",",
"bind_arguments",
"=",
"None",
",",
")",
":",
"if",
"statement",
"is",
"None",
":",
"statement",
"=",
"self",
"... | https://github.com/zzzeek/sqlalchemy/blob/fc5c54fcd4d868c2a4c7ac19668d72f506fe821e/lib/sqlalchemy/orm/session.py#L161-L239 | |
fitnr/SublimeDataConverter | d659d3b3615aade9e27b0fb6c5797947f7406518 | DataConverter.py | python | DataConverterCommand.actionscript | (self, data) | return '[' + n + '{' + output + '}' + self.settings['newline'] + '];' | Actionscript converter | Actionscript converter | [
"Actionscript",
"converter"
] | def actionscript(self, data):
"""Actionscript converter"""
self.set_syntax('ActionScript')
n = self.settings['newline'] + self.settings['indent']
linebreak = '},' + n + '{'
output = linebreak.join(self.type_loop(row, '{field}: {value}', field_break=', ') for row in data)
return '[' + n + '{' + output + '}' + self.settings['newline'] + '];' | [
"def",
"actionscript",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"set_syntax",
"(",
"'ActionScript'",
")",
"n",
"=",
"self",
".",
"settings",
"[",
"'newline'",
"]",
"+",
"self",
".",
"settings",
"[",
"'indent'",
"]",
"linebreak",
"=",
"'},'",
"+... | https://github.com/fitnr/SublimeDataConverter/blob/d659d3b3615aade9e27b0fb6c5797947f7406518/DataConverter.py#L464-L470 | |
l11x0m7/Question_Answering_Models | b53c33db08a51f8e5f8c774eb65ec29c75942c66 | cQA/decomposable_att_model/models.py | python | DecompAtt.add_placeholders | (self) | 输入的容器 | 输入的容器 | [
"输入的容器"
] | def add_placeholders(self):
"""
输入的容器
"""
# 问题
self.q = tf.placeholder(tf.int32,
shape=[None, self.config.max_q_length],
name='Question')
# 回答
self.a = tf.placeholder(tf.int32,
shape=[None, self.config.max_a_length],
name='Ans')
self.y = tf.placeholder(tf.int32, shape=[None, ], name='label')
# drop_out
self.keep_prob = tf.placeholder(tf.float32, name='keep_prob')
self.batch_size = tf.shape(self.q)[0] | [
"def",
"add_placeholders",
"(",
"self",
")",
":",
"# 问题",
"self",
".",
"q",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"int32",
",",
"shape",
"=",
"[",
"None",
",",
"self",
".",
"config",
".",
"max_q_length",
"]",
",",
"name",
"=",
"'Question'",
... | https://github.com/l11x0m7/Question_Answering_Models/blob/b53c33db08a51f8e5f8c774eb65ec29c75942c66/cQA/decomposable_att_model/models.py#L26-L41 | ||
QUANTAXIS/QUANTAXIS | d6eccb97c8385854aa596d6ba8d70ec0655519ff | QUANTAXIS/QASU/save_tdx.py | python | QA_SU_save_stock_day | (client=DATABASE, ui_log=None, ui_progress=None) | save stock_day
保存日线数据
:param client:
:param ui_log: 给GUI qt 界面使用
:param ui_progress: 给GUI qt 界面使用
:param ui_progress_int_value: 给GUI qt 界面使用 | save stock_day
保存日线数据
:param client:
:param ui_log: 给GUI qt 界面使用
:param ui_progress: 给GUI qt 界面使用
:param ui_progress_int_value: 给GUI qt 界面使用 | [
"save",
"stock_day",
"保存日线数据",
":",
"param",
"client",
":",
":",
"param",
"ui_log",
":",
"给GUI",
"qt",
"界面使用",
":",
"param",
"ui_progress",
":",
"给GUI",
"qt",
"界面使用",
":",
"param",
"ui_progress_int_value",
":",
"给GUI",
"qt",
"界面使用"
] | def QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None):
'''
save stock_day
保存日线数据
:param client:
:param ui_log: 给GUI qt 界面使用
:param ui_progress: 给GUI qt 界面使用
:param ui_progress_int_value: 给GUI qt 界面使用
'''
stock_list = QA_fetch_get_stock_list().code.unique().tolist()
coll_stock_day = client.stock_day
coll_stock_day.create_index(
[("code",
pymongo.ASCENDING),
("date_stamp",
pymongo.ASCENDING)]
)
err = []
def __saving_work(code, coll_stock_day):
try:
QA_util_log_info(
'##JOB01 Now Saving STOCK_DAY==== {}'.format(str(code)),
ui_log
)
# 首选查找数据库 是否 有 这个代码的数据
ref = coll_stock_day.find({'code': str(code)[0:6]})
end_date = str(now_time())[0:10]
# 当前数据库已经包含了这个代码的数据, 继续增量更新
# 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现
if ref.count() > 0:
# 接着上次获取的日期继续更新
start_date = ref[ref.count() - 1]['date']
QA_util_log_info(
'UPDATE_STOCK_DAY \n Trying updating {} from {} to {}'
.format(code,
start_date,
end_date),
ui_log
)
if start_date != end_date:
coll_stock_day.insert_many(
QA_util_to_json_from_pandas(
QA_fetch_get_stock_day(
str(code),
QA_util_get_next_day(start_date),
end_date,
'00'
)
)
)
# 当前数据库中没有这个代码的股票数据, 从1990-01-01 开始下载所有的数据
else:
start_date = '1990-01-01'
QA_util_log_info(
'UPDATE_STOCK_DAY \n Trying updating {} from {} to {}'
.format(code,
start_date,
end_date),
ui_log
)
if start_date != end_date:
coll_stock_day.insert_many(
QA_util_to_json_from_pandas(
QA_fetch_get_stock_day(
str(code),
start_date,
end_date,
'00'
)
)
)
except Exception as error0:
print(error0)
err.append(str(code))
for item in range(len(stock_list)):
QA_util_log_info('The {} of Total {}'.format(item, len(stock_list)))
strProgressToLog = 'DOWNLOAD PROGRESS {} {}'.format(
str(float(item / len(stock_list) * 100))[0:4] + '%',
ui_log
)
intProgressToLog = int(float(item / len(stock_list) * 100))
QA_util_log_info(
strProgressToLog,
ui_log=ui_log,
ui_progress=ui_progress,
ui_progress_int_value=intProgressToLog
)
__saving_work(stock_list[item], coll_stock_day)
if len(err) < 1:
QA_util_log_info('SUCCESS save stock day ^_^', ui_log)
else:
QA_util_log_info('ERROR CODE \n ', ui_log)
QA_util_log_info(err, ui_log) | [
"def",
"QA_SU_save_stock_day",
"(",
"client",
"=",
"DATABASE",
",",
"ui_log",
"=",
"None",
",",
"ui_progress",
"=",
"None",
")",
":",
"stock_list",
"=",
"QA_fetch_get_stock_list",
"(",
")",
".",
"code",
".",
"unique",
"(",
")",
".",
"tolist",
"(",
")",
"... | https://github.com/QUANTAXIS/QUANTAXIS/blob/d6eccb97c8385854aa596d6ba8d70ec0655519ff/QUANTAXIS/QASU/save_tdx.py#L190-L292 | ||
Pymol-Scripts/Pymol-script-repo | bcd7bb7812dc6db1595953dfa4471fa15fb68c77 | plugins/bnitools.py | python | set_views.mainchain | (self, sele="all", obj_name="MC") | Create mainchain track in a Mainchain Object.
mainchain(sele="all") | Create mainchain track in a Mainchain Object.
mainchain(sele="all") | [
"Create",
"mainchain",
"track",
"in",
"a",
"Mainchain",
"Object",
".",
"mainchain",
"(",
"sele",
"=",
"all",
")"
] | def mainchain(self, sele="all", obj_name="MC"):
'''Create mainchain track in a Mainchain Object.
mainchain(sele="all")
'''
group_name = obj_name + "_track_g"
group_name = check_names(group_name)
obj_name = obj_name + "_track"
obj_name = check_names(obj_name)
dist1 = check_names(obj_name + "_mcp_cont")
dist2 = check_names(obj_name + "_scp_cont")
self.selection = _remove_brakets(sele)
try:
cmd.create(obj_name, "(%s) and (n. C,N,O,CA)" % (self.selection))
# create polar contacts of mainchain with preset and rename the
# contacts
cmd.dist(dist1, "(%s) and not (solvent or (polymer and not name n,o,h))" % self.selection,
"(%s) and not (solvent or (polymer and not name n,o,h))" % self.selection, quiet=1, mode=2, label=0, reset=1)
cmd.enable(dist1)
try:
cmd.color(8, dist1)#color magenta
except:
pass
cmd.show_as("sticks", obj_name)
cmd.set("stick_radius", 0.35, obj_name)
cmd.set("stick_transparency", 0.5, obj_name)
cmd.dist(dist2, "(%s)" % self.selection, "(%s) and not (polymer and name n,o,h)" %
self.selection, quiet=1, mode=2, label=0, reset=1)
cmd.enable(dist2)
try:
cmd.group(group_name, "%s %s %s" % (obj_name, dist1, dist2))
except:
pass
except:
print("# Can not create track. (no selection ?)")
cmd.color("white", obj_name) | [
"def",
"mainchain",
"(",
"self",
",",
"sele",
"=",
"\"all\"",
",",
"obj_name",
"=",
"\"MC\"",
")",
":",
"group_name",
"=",
"obj_name",
"+",
"\"_track_g\"",
"group_name",
"=",
"check_names",
"(",
"group_name",
")",
"obj_name",
"=",
"obj_name",
"+",
"\"_track\... | https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/plugins/bnitools.py#L2684-L2718 | ||
JasperSnoek/spearmint | b37a541be1ea035f82c7c82bbd93f5b4320e7d91 | spearmint/spearmint/chooser/cma.py | python | FitnessFunctions.sphere | (self, x) | return sum((x+0)**2) | Sphere (squared norm) test objective function | Sphere (squared norm) test objective function | [
"Sphere",
"(",
"squared",
"norm",
")",
"test",
"objective",
"function"
] | def sphere(self, x):
"""Sphere (squared norm) test objective function"""
# return np.random.rand(1)[0]**0 * sum(x**2) + 1 * np.random.rand(1)[0]
return sum((x+0)**2) | [
"def",
"sphere",
"(",
"self",
",",
"x",
")",
":",
"# return np.random.rand(1)[0]**0 * sum(x**2) + 1 * np.random.rand(1)[0]",
"return",
"sum",
"(",
"(",
"x",
"+",
"0",
")",
"**",
"2",
")"
] | https://github.com/JasperSnoek/spearmint/blob/b37a541be1ea035f82c7c82bbd93f5b4320e7d91/spearmint/spearmint/chooser/cma.py#L6480-L6483 | |
ChenglongChen/tensorflow-DSMM | 52a499a162f3837aa11bb1bb4c1029accfe5743d | src/tf_common/nn_module.py | python | dense_block | (x, hidden_units, dropouts, densenet=False, scope_name="dense_block", reuse=False, training=False, seed=0, bn=False) | return _dense_block_mode1(x, hidden_units, dropouts, densenet, scope_name, reuse, training, seed, bn) | [] | def dense_block(x, hidden_units, dropouts, densenet=False, scope_name="dense_block", reuse=False, training=False, seed=0, bn=False):
return _dense_block_mode1(x, hidden_units, dropouts, densenet, scope_name, reuse, training, seed, bn) | [
"def",
"dense_block",
"(",
"x",
",",
"hidden_units",
",",
"dropouts",
",",
"densenet",
"=",
"False",
",",
"scope_name",
"=",
"\"dense_block\"",
",",
"reuse",
"=",
"False",
",",
"training",
"=",
"False",
",",
"seed",
"=",
"0",
",",
"bn",
"=",
"False",
"... | https://github.com/ChenglongChen/tensorflow-DSMM/blob/52a499a162f3837aa11bb1bb4c1029accfe5743d/src/tf_common/nn_module.py#L522-L523 | |||
NVIDIA/NeMo | 5b0c0b4dec12d87d3cd960846de4105309ce938e | nemo/utils/app_state.py | python | AppState.data_parallel_size | (self, size) | Property sets the number of GPUs in each data parallel group.
Args:
size (int): Number of GPUs in each data parallel group. | Property sets the number of GPUs in each data parallel group.
Args:
size (int): Number of GPUs in each data parallel group. | [
"Property",
"sets",
"the",
"number",
"of",
"GPUs",
"in",
"each",
"data",
"parallel",
"group",
".",
"Args",
":",
"size",
"(",
"int",
")",
":",
"Number",
"of",
"GPUs",
"in",
"each",
"data",
"parallel",
"group",
"."
] | def data_parallel_size(self, size):
""" Property sets the number of GPUs in each data parallel group.
Args:
size (int): Number of GPUs in each data parallel group.
"""
self._data_parallel_size = size | [
"def",
"data_parallel_size",
"(",
"self",
",",
"size",
")",
":",
"self",
".",
"_data_parallel_size",
"=",
"size"
] | https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/utils/app_state.py#L128-L133 | ||
huawei-noah/vega | d9f13deede7f2b584e4b1d32ffdb833856129989 | vega/modules/operators/functions/pytorch_fn.py | python | minimum | (arg1, arg2) | return torch.min(arg1, arg2) | Get min item. | Get min item. | [
"Get",
"min",
"item",
"."
] | def minimum(arg1, arg2):
"""Get min item."""
return torch.min(arg1, arg2) | [
"def",
"minimum",
"(",
"arg1",
",",
"arg2",
")",
":",
"return",
"torch",
".",
"min",
"(",
"arg1",
",",
"arg2",
")"
] | https://github.com/huawei-noah/vega/blob/d9f13deede7f2b584e4b1d32ffdb833856129989/vega/modules/operators/functions/pytorch_fn.py#L823-L825 | |
scikit-learn/scikit-learn | 1d1aadd0711b87d2a11c80aad15df6f8cf156712 | sklearn/datasets/_base.py | python | load_diabetes | (*, return_X_y=False, as_frame=False, scaled=True) | return Bunch(
data=data,
target=target,
frame=frame,
DESCR=fdescr,
feature_names=feature_names,
data_filename=data_filename,
target_filename=target_filename,
data_module=DATA_MODULE,
) | Load and return the diabetes dataset (regression).
============== ==================
Samples total 442
Dimensionality 10
Features real, -.2 < x < .2
Targets integer 25 - 346
============== ==================
.. note::
The meaning of each feature (i.e. `feature_names`) might be unclear
(especially for `ltg`) as the documentation of the original dataset is
not explicit. We provide information that seems correct in regard with
the scientific literature in this field of research.
Read more in the :ref:`User Guide <diabetes_dataset>`.
Parameters
----------
return_X_y : bool, default=False
If True, returns ``(data, target)`` instead of a Bunch object.
See below for more information about the `data` and `target` object.
.. versionadded:: 0.18
as_frame : bool, default=False
If True, the data is a pandas DataFrame including columns with
appropriate dtypes (numeric). The target is
a pandas DataFrame or Series depending on the number of target columns.
If `return_X_y` is True, then (`data`, `target`) will be pandas
DataFrames or Series as described below.
.. versionadded:: 0.23
scaled : bool, default=True
If True, the feature variables are mean centered and scaled by the
standard deviation times the square root of `n_samples`.
If False, raw data is returned for the feature variables.
.. versionadded:: 1.1
Returns
-------
data : :class:`~sklearn.utils.Bunch`
Dictionary-like object, with the following attributes.
data : {ndarray, dataframe} of shape (442, 10)
The data matrix. If `as_frame=True`, `data` will be a pandas
DataFrame.
target: {ndarray, Series} of shape (442,)
The regression target. If `as_frame=True`, `target` will be
a pandas Series.
feature_names: list
The names of the dataset columns.
frame: DataFrame of shape (442, 11)
Only present when `as_frame=True`. DataFrame with `data` and
`target`.
.. versionadded:: 0.23
DESCR: str
The full description of the dataset.
data_filename: str
The path to the location of the data.
target_filename: str
The path to the location of the target.
(data, target) : tuple if ``return_X_y`` is True
Returns a tuple of two ndarray of shape (n_samples, n_features)
A 2D array with each row representing one sample and each column
representing the features and/or target of a given sample.
.. versionadded:: 0.18 | Load and return the diabetes dataset (regression). | [
"Load",
"and",
"return",
"the",
"diabetes",
"dataset",
"(",
"regression",
")",
"."
] | def load_diabetes(*, return_X_y=False, as_frame=False, scaled=True):
"""Load and return the diabetes dataset (regression).
============== ==================
Samples total 442
Dimensionality 10
Features real, -.2 < x < .2
Targets integer 25 - 346
============== ==================
.. note::
The meaning of each feature (i.e. `feature_names`) might be unclear
(especially for `ltg`) as the documentation of the original dataset is
not explicit. We provide information that seems correct in regard with
the scientific literature in this field of research.
Read more in the :ref:`User Guide <diabetes_dataset>`.
Parameters
----------
return_X_y : bool, default=False
If True, returns ``(data, target)`` instead of a Bunch object.
See below for more information about the `data` and `target` object.
.. versionadded:: 0.18
as_frame : bool, default=False
If True, the data is a pandas DataFrame including columns with
appropriate dtypes (numeric). The target is
a pandas DataFrame or Series depending on the number of target columns.
If `return_X_y` is True, then (`data`, `target`) will be pandas
DataFrames or Series as described below.
.. versionadded:: 0.23
scaled : bool, default=True
If True, the feature variables are mean centered and scaled by the
standard deviation times the square root of `n_samples`.
If False, raw data is returned for the feature variables.
.. versionadded:: 1.1
Returns
-------
data : :class:`~sklearn.utils.Bunch`
Dictionary-like object, with the following attributes.
data : {ndarray, dataframe} of shape (442, 10)
The data matrix. If `as_frame=True`, `data` will be a pandas
DataFrame.
target: {ndarray, Series} of shape (442,)
The regression target. If `as_frame=True`, `target` will be
a pandas Series.
feature_names: list
The names of the dataset columns.
frame: DataFrame of shape (442, 11)
Only present when `as_frame=True`. DataFrame with `data` and
`target`.
.. versionadded:: 0.23
DESCR: str
The full description of the dataset.
data_filename: str
The path to the location of the data.
target_filename: str
The path to the location of the target.
(data, target) : tuple if ``return_X_y`` is True
Returns a tuple of two ndarray of shape (n_samples, n_features)
A 2D array with each row representing one sample and each column
representing the features and/or target of a given sample.
.. versionadded:: 0.18
"""
data_filename = "diabetes_data_raw.csv.gz"
target_filename = "diabetes_target.csv.gz"
data = load_gzip_compressed_csv_data(data_filename)
target = load_gzip_compressed_csv_data(target_filename)
if scaled:
data = scale(data, copy=False)
data /= data.shape[0] ** 0.5
fdescr = load_descr("diabetes.rst")
feature_names = ["age", "sex", "bmi", "bp", "s1", "s2", "s3", "s4", "s5", "s6"]
frame = None
target_columns = [
"target",
]
if as_frame:
frame, data, target = _convert_data_dataframe(
"load_diabetes", data, target, feature_names, target_columns
)
if return_X_y:
return data, target
return Bunch(
data=data,
target=target,
frame=frame,
DESCR=fdescr,
feature_names=feature_names,
data_filename=data_filename,
target_filename=target_filename,
data_module=DATA_MODULE,
) | [
"def",
"load_diabetes",
"(",
"*",
",",
"return_X_y",
"=",
"False",
",",
"as_frame",
"=",
"False",
",",
"scaled",
"=",
"True",
")",
":",
"data_filename",
"=",
"\"diabetes_data_raw.csv.gz\"",
"target_filename",
"=",
"\"diabetes_target.csv.gz\"",
"data",
"=",
"load_g... | https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/sklearn/datasets/_base.py#L916-L1023 | |
garywiz/chaperone | 9ff2c3a5b9c6820f8750320a564ea214042df06f | chaperone/exec/envcp.py | python | main_entry | () | [] | def main_entry():
options = docopt(__doc__, version=VERSION_MESSAGE)
files = options['FILE']
start = options['--xprefix']
braces = options['--xgrouping']
if braces:
if any([b not in '{([' for b in braces]):
print("error: --xgrouping can accept one or more of '{{', '[', or '(' only. Not this: '{0}'.".format(braces))
exit(1)
# Enable or disable, but don't cache them if enabled
Environment.set_backtick_expansion(bool(options['--shell-enable']), False)
Environment.set_parse_parameters(start, braces)
env = Environment()
# Support stdin/stdout behavior if '-' is the only file specified on the command line
if '-' in files:
if len(files) > 1:
print("error: '-' for stdin/stdout cannot be combined with other filename arguments")
exit(1)
sys.stdout.write(env.expand(sys.stdin.read()))
sys.stdout.flush()
exit(0)
if len(files) < 2:
print("error: must include two or more filename arguments")
exit(1)
destdir = os.path.abspath(files[-1]);
destfile = None
if os.path.isdir(destdir):
if not os.access(destdir, os.W_OK|os.X_OK):
print("error: directory {0} exists but is not writable".format(destdir))
st = options['--strip']
if st:
files = [(f, os.path.basename(f).rstrip(st)) for f in files[:-1]]
else:
files = [(f, os.path.basename(f)) for f in files[:-1]]
check_canwrite([os.path.join(destdir, p[1]) for p in files], options['--overwrite'])
elif len(files) != 2:
print("error: destination is not a directory and more than 2 files specified")
exit(1)
else:
destfile = files[1]
files = [(files[0], files[0])]
check_canwrite([destfile], options['--overwrite'])
# files is now a list of pairs [(source, dest-basename), ...]
for curpair in files:
if not os.path.exists(curpair[0]):
print("error: file does not exist, {0}".format(curpair[0]))
exit(1)
if not os.access(curpair[0], os.R_OK):
print("error: file is not readable, {0}".format(curpair[0]))
exit(1)
for curpair in files:
if not destfile:
destfile = os.path.join(destdir, curpair[1])
try:
oldstat = os.stat(curpair[0])
oldf = open(curpair[0], 'r')
except Exception as ex:
print("error: cannot open input file {0}: {1}".format(curpair[0], ex))
exit(1)
try:
newf = open(destfile, 'w')
except Exception as ex:
print("error: cannot open output file {0}: {1}".format(destfile, ex))
exit(1)
newf.write(env.expand(oldf.read()))
oldf.close()
newf.close()
if options['--archive']:
# ATTEMPT to retain permissions
try:
os.chown(destfile, oldstat.st_uid, oldstat.st_gid);
except PermissionError:
# Try them separately. User first, then group.
try:
os.chown(destfile, oldstat.st_uid, -1);
except PermissionError:
pass
try:
os.chown(destfile, -1, oldstat.st_gid);
except PermissionError:
pass
try:
os.chmod(destfile, oldstat.st_mode);
except PermissionError:
pass
try:
os.utime(destfile, times=(oldstat.st_atime, oldstat.st_mtime))
except PermissionError:
pass
if options['--verbose']:
print("envcp {0} {1}".format(curpair[0], destfile))
destfile = None | [
"def",
"main_entry",
"(",
")",
":",
"options",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"VERSION_MESSAGE",
")",
"files",
"=",
"options",
"[",
"'FILE'",
"]",
"start",
"=",
"options",
"[",
"'--xprefix'",
"]",
"braces",
"=",
"options",
"[",
"'--x... | https://github.com/garywiz/chaperone/blob/9ff2c3a5b9c6820f8750320a564ea214042df06f/chaperone/exec/envcp.py#L44-L153 | ||||
danielfrg/PythonFinance | 98f5b090d9180c4cbb9a7e7f14132f3424d68e35 | utils/FileManager.py | python | FileManager.alphavantage_download | (self, symbol, start_date, end_date) | Downloads and saves the equitiy information from Yahoo! Finance between
the specified dates.
Saves the csv file with the name: SYMBOL_start_date_end_date.csv
e.g: AAPL_2009-1-1_2010-1-1.csv
Parameters
----------
symbol: str
start_date: datetime
end_date: datetime
Returns
-------
boolean: True if was able to download the symbol, False otherwise | Downloads and saves the equitiy information from Yahoo! Finance between
the specified dates.
Saves the csv file with the name: SYMBOL_start_date_end_date.csv
e.g: AAPL_2009-1-1_2010-1-1.csv | [
"Downloads",
"and",
"saves",
"the",
"equitiy",
"information",
"from",
"Yahoo!",
"Finance",
"between",
"the",
"specified",
"dates",
".",
"Saves",
"the",
"csv",
"file",
"with",
"the",
"name",
":",
"SYMBOL_start_date_end_date",
".",
"csv",
"e",
".",
"g",
":",
"... | def alphavantage_download(self, symbol, start_date, end_date):
"""
Downloads and saves the equitiy information from Yahoo! Finance between
the specified dates.
Saves the csv file with the name: SYMBOL_start_date_end_date.csv
e.g: AAPL_2009-1-1_2010-1-1.csv
Parameters
----------
symbol: str
start_date: datetime
end_date: datetime
Returns
-------
boolean: True if was able to download the symbol, False otherwise
"""
try:
params = urllib.parse.urlencode(
{
'function': 'TIME_SERIES_DAILY_ADJUSTED',
'symbol': symbol,
'outputsize': 'full',
'datatype': 'csv',
'apikey': self.alpha_vantage_key
})
sourceURL = "https://www.alphavantage.co/query?{0}".format(params)
webFile = urllib.request.urlopen(sourceURL)
# print(webFile.read().decode('utf-8'))
#print("start_date: {0}".format(start_date))
#print("end_date: {0}".format(end_date))
# extract start date and end date from webfile
csvData = pd.read_csv(webFile, parse_dates=True, index_col='timestamp')
# Sort so earliest comes first
csvData = csvData.sort_index()
csvData = csvData.truncate(before=start_date)
csvData = csvData.truncate(after=end_date)
#print(csvData.head())
#print(csvData.tail())
data_start_date = csvData.index.tolist()[0]
#print("data start_date: {0}".format(data_start_date))
data_end_date = csvData.index.tolist()[-1]
#print("data end_date: {0}".format(data_end_date))
filename = "%s_%d-%d-%d_%d-%d-%d.csv" % (symbol, start_date.year, start_date.month,
start_date.day, end_date.year, end_date.month, end_date.day)
localFile = open(os.path.join(self.dir, filename), 'w')
csvData.to_csv(localFile)
webFile.close()
localFile.close()
return True
except:
print("FileManager::alphaVantageDownload: {0}, {1}".format(symbol, sys.exc_info()[1]))
return False | [
"def",
"alphavantage_download",
"(",
"self",
",",
"symbol",
",",
"start_date",
",",
"end_date",
")",
":",
"try",
":",
"params",
"=",
"urllib",
".",
"parse",
".",
"urlencode",
"(",
"{",
"'function'",
":",
"'TIME_SERIES_DAILY_ADJUSTED'",
",",
"'symbol'",
":",
... | https://github.com/danielfrg/PythonFinance/blob/98f5b090d9180c4cbb9a7e7f14132f3424d68e35/utils/FileManager.py#L158-L213 | ||
UCL-INGI/INGInious | 60f10cb4c375ce207471043e76bd813220b95399 | inginious/frontend/submission_manager.py | python | WebAppSubmissionManager.is_done | (self, submissionid_or_submission, user_check=True) | return submission["status"] == "done" or submission["status"] == "error" | Tells if a submission is done and its result is available | Tells if a submission is done and its result is available | [
"Tells",
"if",
"a",
"submission",
"is",
"done",
"and",
"its",
"result",
"is",
"available"
] | def is_done(self, submissionid_or_submission, user_check=True):
""" Tells if a submission is done and its result is available """
# TODO: not a very nice way to avoid too many database call. Should be refactored.
if isinstance(submissionid_or_submission, dict):
submission = submissionid_or_submission
else:
submission = self.get_submission(submissionid_or_submission, False)
if user_check and not self.user_is_submission_owner(submission):
return None
return submission["status"] == "done" or submission["status"] == "error" | [
"def",
"is_done",
"(",
"self",
",",
"submissionid_or_submission",
",",
"user_check",
"=",
"True",
")",
":",
"# TODO: not a very nice way to avoid too many database call. Should be refactored.",
"if",
"isinstance",
"(",
"submissionid_or_submission",
",",
"dict",
")",
":",
"s... | https://github.com/UCL-INGI/INGInious/blob/60f10cb4c375ce207471043e76bd813220b95399/inginious/frontend/submission_manager.py#L427-L436 | |
lixinsu/RCZoo | 37fcb7962fbd4c751c561d4a0c84173881ea8339 | reader/slqa/data.py | python | ReaderDataset.lengths | (self) | return [(len(ex['document']), len(ex['question']))
for ex in self.examples] | [] | def lengths(self):
return [(len(ex['document']), len(ex['question']))
for ex in self.examples] | [
"def",
"lengths",
"(",
"self",
")",
":",
"return",
"[",
"(",
"len",
"(",
"ex",
"[",
"'document'",
"]",
")",
",",
"len",
"(",
"ex",
"[",
"'question'",
"]",
")",
")",
"for",
"ex",
"in",
"self",
".",
"examples",
"]"
] | https://github.com/lixinsu/RCZoo/blob/37fcb7962fbd4c751c561d4a0c84173881ea8339/reader/slqa/data.py#L101-L103 | |||
asyml/texar | a23f021dae289a3d768dc099b220952111da04fd | texar/tf/utils/utils.py | python | get_instance | (class_or_name, kwargs, module_paths=None) | return class_(**kwargs) | Creates a class instance.
Args:
class_or_name: A class, or its name or full path to a class to
instantiate.
kwargs (dict): Keyword arguments for the class constructor.
module_paths (list, optional): Paths to candidate modules to
search for the class. This is used if the class cannot be
located solely based on :attr:`class_name`. The first module
in the list that contains the class is used.
Returns:
A class instance.
Raises:
ValueError: If class is not found based on :attr:`class_or_name` and
:attr:`module_paths`.
ValueError: If :attr:`kwargs` contains arguments that are invalid
for the class construction. | Creates a class instance. | [
"Creates",
"a",
"class",
"instance",
"."
] | def get_instance(class_or_name, kwargs, module_paths=None):
"""Creates a class instance.
Args:
class_or_name: A class, or its name or full path to a class to
instantiate.
kwargs (dict): Keyword arguments for the class constructor.
module_paths (list, optional): Paths to candidate modules to
search for the class. This is used if the class cannot be
located solely based on :attr:`class_name`. The first module
in the list that contains the class is used.
Returns:
A class instance.
Raises:
ValueError: If class is not found based on :attr:`class_or_name` and
:attr:`module_paths`.
ValueError: If :attr:`kwargs` contains arguments that are invalid
for the class construction.
"""
# Locate the class
class_ = class_or_name
if is_str(class_):
class_ = get_class(class_, module_paths)
# Check validity of arguments
class_args = set(get_args(class_.__init__))
if kwargs is None:
kwargs = {}
for key in kwargs.keys():
if key not in class_args:
raise ValueError(
"Invalid argument for class %s.%s: %s, valid args: %s" %
(class_.__module__, class_.__name__, key, list(class_args)))
return class_(**kwargs) | [
"def",
"get_instance",
"(",
"class_or_name",
",",
"kwargs",
",",
"module_paths",
"=",
"None",
")",
":",
"# Locate the class",
"class_",
"=",
"class_or_name",
"if",
"is_str",
"(",
"class_",
")",
":",
"class_",
"=",
"get_class",
"(",
"class_",
",",
"module_paths... | https://github.com/asyml/texar/blob/a23f021dae289a3d768dc099b220952111da04fd/texar/tf/utils/utils.py#L252-L289 | |
misterch0c/shadowbroker | e3a069bea47a2c1009697941ac214adc6f90aa8d | windows/Resources/Python/Core/Lib/numbers.py | python | Real.imag | (self) | return 0 | Real numbers have no imaginary component. | Real numbers have no imaginary component. | [
"Real",
"numbers",
"have",
"no",
"imaginary",
"component",
"."
] | def imag(self):
"""Real numbers have no imaginary component."""
return 0 | [
"def",
"imag",
"(",
"self",
")",
":",
"return",
"0"
] | https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/numbers.py#L248-L250 | |
inkandswitch/livebook | 93c8d467734787366ad084fc3566bf5cbe249c51 | public/pypyjs/modules/_pyio.py | python | IOBase.closed | (self) | return self.__closed | closed: bool. True iff the file has been closed.
For backwards compatibility, this is a property, not a predicate. | closed: bool. True iff the file has been closed. | [
"closed",
":",
"bool",
".",
"True",
"iff",
"the",
"file",
"has",
"been",
"closed",
"."
] | def closed(self):
"""closed: bool. True iff the file has been closed.
For backwards compatibility, this is a property, not a predicate.
"""
return self.__closed | [
"def",
"closed",
"(",
"self",
")",
":",
"return",
"self",
".",
"__closed"
] | https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/_pyio.py#L414-L419 | |
JoelBender/bacpypes | 41104c2b565b2ae9a637c941dfb0fe04195c5e96 | py27/bacpypes/service/file.py | python | FileServicesClient.read_record | (self, address, fileIdentifier, start_record, record_count) | Read a number of records starting at a specific record. | Read a number of records starting at a specific record. | [
"Read",
"a",
"number",
"of",
"records",
"starting",
"at",
"a",
"specific",
"record",
"."
] | def read_record(self, address, fileIdentifier, start_record, record_count):
""" Read a number of records starting at a specific record. """
raise NotImplementedError("read_record") | [
"def",
"read_record",
"(",
"self",
",",
"address",
",",
"fileIdentifier",
",",
"start_record",
",",
"record_count",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"read_record\"",
")"
] | https://github.com/JoelBender/bacpypes/blob/41104c2b565b2ae9a637c941dfb0fe04195c5e96/py27/bacpypes/service/file.py#L283-L285 | ||
facebookresearch/mmf | fb6fe390287e1da12c3bd28d4ab43c5f7dcdfc9f | mmf/datasets/databases/scene_graph_database.py | python | SceneGraphDatabase.__getitem__ | (self, idx) | return self.data_dict[idx] | [] | def __getitem__(self, idx):
return self.data_dict[idx] | [
"def",
"__getitem__",
"(",
"self",
",",
"idx",
")",
":",
"return",
"self",
".",
"data_dict",
"[",
"idx",
"]"
] | https://github.com/facebookresearch/mmf/blob/fb6fe390287e1da12c3bd28d4ab43c5f7dcdfc9f/mmf/datasets/databases/scene_graph_database.py#L12-L13 | |||
microsoft/debugpy | be8dd607f6837244e0b565345e497aff7a0c08bf | src/debugpy/common/messaging.py | python | Message.__init__ | (self, channel, seq, json=None) | Sequence number of the message in its channel.
This can be None for synthesized Responses. | Sequence number of the message in its channel. | [
"Sequence",
"number",
"of",
"the",
"message",
"in",
"its",
"channel",
"."
] | def __init__(self, channel, seq, json=None):
self.channel = channel
self.seq = seq
"""Sequence number of the message in its channel.
This can be None for synthesized Responses.
"""
self.json = json
"""For incoming messages, the MessageDict containing raw JSON from which
this message was originally parsed.
""" | [
"def",
"__init__",
"(",
"self",
",",
"channel",
",",
"seq",
",",
"json",
"=",
"None",
")",
":",
"self",
".",
"channel",
"=",
"channel",
"self",
".",
"seq",
"=",
"seq",
"self",
".",
"json",
"=",
"json",
"\"\"\"For incoming messages, the MessageDict containing... | https://github.com/microsoft/debugpy/blob/be8dd607f6837244e0b565345e497aff7a0c08bf/src/debugpy/common/messaging.py#L470-L482 | ||
ricequant/rqalpha-mod-ctp | bfd40801f9a182226a911cac74660f62993eb6db | rqalpha_mod_ctp/ctp/pyctp/linux64_34/__init__.py | python | TraderApi.ReqQryOptionInstrTradeCost | (self, pQryOptionInstrTradeCost, nRequestID) | return 0 | 请求查询期权交易成本 | 请求查询期权交易成本 | [
"请求查询期权交易成本"
] | def ReqQryOptionInstrTradeCost(self, pQryOptionInstrTradeCost, nRequestID):
"""请求查询期权交易成本"""
return 0 | [
"def",
"ReqQryOptionInstrTradeCost",
"(",
"self",
",",
"pQryOptionInstrTradeCost",
",",
"nRequestID",
")",
":",
"return",
"0"
] | https://github.com/ricequant/rqalpha-mod-ctp/blob/bfd40801f9a182226a911cac74660f62993eb6db/rqalpha_mod_ctp/ctp/pyctp/linux64_34/__init__.py#L413-L415 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/pysaml2-4.9.0/src/saml2/sigver.py | python | verify_redirect_signature | (saml_msg, crypto, cert=None, sigkey=None) | :param saml_msg: A dictionary with strings as values, *NOT* lists as
produced by parse_qs.
:param cert: A certificate to use when verifying the signature
:return: True, if signature verified | [] | def verify_redirect_signature(saml_msg, crypto, cert=None, sigkey=None):
"""
:param saml_msg: A dictionary with strings as values, *NOT* lists as
produced by parse_qs.
:param cert: A certificate to use when verifying the signature
:return: True, if signature verified
"""
try:
signer = crypto.get_signer(saml_msg['SigAlg'], sigkey)
except KeyError:
raise Unsupported('Signature algorithm: {alg}'.format(
alg=saml_msg['SigAlg']))
else:
if saml_msg['SigAlg'] in SIGNER_ALGS:
if 'SAMLRequest' in saml_msg:
_order = REQ_ORDER
elif 'SAMLResponse' in saml_msg:
_order = RESP_ORDER
else:
raise Unsupported(
'Verifying signature on something that should not be '
'signed')
_args = saml_msg.copy()
del _args['Signature'] # everything but the signature
string = '&'.join(
[parse.urlencode({k: _args[k]}) for k in _order if k in
_args]).encode('ascii')
if cert:
_key = extract_rsa_key_from_x509_cert(pem_format(cert))
else:
_key = sigkey
_sign = base64.b64decode(saml_msg['Signature'])
return bool(signer.verify(string, _sign, _key)) | [
"def",
"verify_redirect_signature",
"(",
"saml_msg",
",",
"crypto",
",",
"cert",
"=",
"None",
",",
"sigkey",
"=",
"None",
")",
":",
"try",
":",
"signer",
"=",
"crypto",
".",
"get_signer",
"(",
"saml_msg",
"[",
"'SigAlg'",
"]",
",",
"sigkey",
")",
"except... | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/pysaml2-4.9.0/src/saml2/sigver.py#L569-L606 | |||
mudpi/mudpi-core | fb206b1136f529c7197f1e6b29629ed05630d377 | mudpi/registry.py | python | ComponentRegistry.for_namespace | (self, namespace=None) | return self._registry.setdefault(namespace, {}) | Get all the components for a given namespace | Get all the components for a given namespace | [
"Get",
"all",
"the",
"components",
"for",
"a",
"given",
"namespace"
] | def for_namespace(self, namespace=None):
""" Get all the components for a given namespace """
return self._registry.setdefault(namespace, {}) | [
"def",
"for_namespace",
"(",
"self",
",",
"namespace",
"=",
"None",
")",
":",
"return",
"self",
".",
"_registry",
".",
"setdefault",
"(",
"namespace",
",",
"{",
"}",
")"
] | https://github.com/mudpi/mudpi-core/blob/fb206b1136f529c7197f1e6b29629ed05630d377/mudpi/registry.py#L60-L62 | |
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/sympy/sympy/mpmath/functions/qfunctions.py | python | qgamma | (ctx, z, q, **kwargs) | return ctx.qp(q, q, None, **kwargs) / \
ctx.qp(q**z, q, None, **kwargs) * (1-q)**(1-z) | r"""
Evaluates the q-gamma function
.. math ::
\Gamma_q(z) = \frac{(q; q)_{\infty}}{(q^z; q)_{\infty}} (1-q)^{1-z}.
**Examples**
Evaluation for real and complex arguments::
>>> from sympy.mpmath import *
>>> mp.dps = 25; mp.pretty = True
>>> qgamma(4,0.75)
4.046875
>>> qgamma(6,6)
121226245.0
>>> qgamma(3+4j, 0.5j)
(0.1663082382255199834630088 + 0.01952474576025952984418217j)
The q-gamma function satisfies a functional equation similar
to that of the ordinary gamma function::
>>> q = mpf(0.25)
>>> z = mpf(2.5)
>>> qgamma(z+1,q)
1.428277424823760954685912
>>> (1-q**z)/(1-q)*qgamma(z,q)
1.428277424823760954685912 | r"""
Evaluates the q-gamma function | [
"r",
"Evaluates",
"the",
"q",
"-",
"gamma",
"function"
] | def qgamma(ctx, z, q, **kwargs):
r"""
Evaluates the q-gamma function
.. math ::
\Gamma_q(z) = \frac{(q; q)_{\infty}}{(q^z; q)_{\infty}} (1-q)^{1-z}.
**Examples**
Evaluation for real and complex arguments::
>>> from sympy.mpmath import *
>>> mp.dps = 25; mp.pretty = True
>>> qgamma(4,0.75)
4.046875
>>> qgamma(6,6)
121226245.0
>>> qgamma(3+4j, 0.5j)
(0.1663082382255199834630088 + 0.01952474576025952984418217j)
The q-gamma function satisfies a functional equation similar
to that of the ordinary gamma function::
>>> q = mpf(0.25)
>>> z = mpf(2.5)
>>> qgamma(z+1,q)
1.428277424823760954685912
>>> (1-q**z)/(1-q)*qgamma(z,q)
1.428277424823760954685912
"""
if abs(q) > 1:
return ctx.qgamma(z,1/q)*q**((z-2)*(z-1)*0.5)
return ctx.qp(q, q, None, **kwargs) / \
ctx.qp(q**z, q, None, **kwargs) * (1-q)**(1-z) | [
"def",
"qgamma",
"(",
"ctx",
",",
"z",
",",
"q",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"abs",
"(",
"q",
")",
">",
"1",
":",
"return",
"ctx",
".",
"qgamma",
"(",
"z",
",",
"1",
"/",
"q",
")",
"*",
"q",
"**",
"(",
"(",
"z",
"-",
"2",
... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/mpmath/functions/qfunctions.py#L132-L168 | |
PaddlePaddle/PaddleX | 2bab73f81ab54e328204e7871e6ae4a82e719f5d | static/paddlex/cv/models/yolo_v3.py | python | YOLOv3._get_backbone | (self, backbone_name) | return backbone | [] | def _get_backbone(self, backbone_name):
if backbone_name == 'DarkNet53':
backbone = paddlex.cv.nets.DarkNet(norm_type='sync_bn')
elif backbone_name == 'ResNet34':
backbone = paddlex.cv.nets.ResNet(
norm_type='sync_bn',
layers=34,
freeze_norm=False,
norm_decay=0.,
feature_maps=[3, 4, 5],
freeze_at=0)
elif backbone_name == 'MobileNetV1':
backbone = paddlex.cv.nets.MobileNetV1(norm_type='sync_bn')
elif backbone_name.startswith('MobileNetV3'):
model_name = backbone_name.split('_')[1]
backbone = paddlex.cv.nets.MobileNetV3(
norm_type='sync_bn', model_name=model_name)
return backbone | [
"def",
"_get_backbone",
"(",
"self",
",",
"backbone_name",
")",
":",
"if",
"backbone_name",
"==",
"'DarkNet53'",
":",
"backbone",
"=",
"paddlex",
".",
"cv",
".",
"nets",
".",
"DarkNet",
"(",
"norm_type",
"=",
"'sync_bn'",
")",
"elif",
"backbone_name",
"==",
... | https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/static/paddlex/cv/models/yolo_v3.py#L91-L108 | |||
django-nonrel/django-nonrel | 4fbfe7344481a5eab8698f79207f09124310131b | django/contrib/gis/gdal/srs.py | python | SpatialReference.attr_value | (self, target, index=0) | return capi.get_attr_value(self.ptr, target, index) | The attribute value for the given target node (e.g. 'PROJCS'). The index
keyword specifies an index of the child node to return. | The attribute value for the given target node (e.g. 'PROJCS'). The index
keyword specifies an index of the child node to return. | [
"The",
"attribute",
"value",
"for",
"the",
"given",
"target",
"node",
"(",
"e",
".",
"g",
".",
"PROJCS",
")",
".",
"The",
"index",
"keyword",
"specifies",
"an",
"index",
"of",
"the",
"child",
"node",
"to",
"return",
"."
] | def attr_value(self, target, index=0):
"""
The attribute value for the given target node (e.g. 'PROJCS'). The index
keyword specifies an index of the child node to return.
"""
if not isinstance(target, basestring) or not isinstance(index, int):
raise TypeError
return capi.get_attr_value(self.ptr, target, index) | [
"def",
"attr_value",
"(",
"self",
",",
"target",
",",
"index",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"target",
",",
"basestring",
")",
"or",
"not",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"raise",
"TypeError",
"return",
"capi",
... | https://github.com/django-nonrel/django-nonrel/blob/4fbfe7344481a5eab8698f79207f09124310131b/django/contrib/gis/gdal/srs.py#L132-L139 | |
vpelletier/python-libusb1 | 86ad8ab73f7442874de71c1f9f824724d21da92b | versioneer.py | python | plus_or_dot | (pieces) | return "+" | Return a + if we don't already have one, else return a . | Return a + if we don't already have one, else return a . | [
"Return",
"a",
"+",
"if",
"we",
"don",
"t",
"already",
"have",
"one",
"else",
"return",
"a",
"."
] | def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
return "+" | [
"def",
"plus_or_dot",
"(",
"pieces",
")",
":",
"if",
"\"+\"",
"in",
"pieces",
".",
"get",
"(",
"\"closest-tag\"",
",",
"\"\"",
")",
":",
"return",
"\".\"",
"return",
"\"+\""
] | https://github.com/vpelletier/python-libusb1/blob/86ad8ab73f7442874de71c1f9f824724d21da92b/versioneer.py#L1392-L1396 | |
chenguanyou/weixin_YiQi | ad86ed8061f4f5fa88b6600a9b0809e5bb3bfd08 | backend/Yiqi/Yiqi/partyApp/DjangoUeditor/commands.py | python | UEditorCommand.onExecuteCommand | (self) | return "" | 返回执行Command时的js代码 | 返回执行Command时的js代码 | [
"返回执行Command时的js代码"
] | def onExecuteCommand(self):
""" 返回执行Command时的js代码 """
return "" | [
"def",
"onExecuteCommand",
"(",
"self",
")",
":",
"return",
"\"\""
] | https://github.com/chenguanyou/weixin_YiQi/blob/ad86ed8061f4f5fa88b6600a9b0809e5bb3bfd08/backend/Yiqi/Yiqi/partyApp/DjangoUeditor/commands.py#L113-L115 | |
Cog-Creators/Red-DiscordBot | b05933274a11fb097873ab0d1b246d37b06aa306 | redbot/core/commands/requires.py | python | has_permissions | (**perms: bool) | return Requires.get_decorator(None, perms) | Restrict the command to users with these permissions.
This check can be overridden by rules. | Restrict the command to users with these permissions. | [
"Restrict",
"the",
"command",
"to",
"users",
"with",
"these",
"permissions",
"."
] | def has_permissions(**perms: bool):
"""Restrict the command to users with these permissions.
This check can be overridden by rules.
"""
if perms is None:
raise TypeError("Must provide at least one keyword argument to has_permissions")
return Requires.get_decorator(None, perms) | [
"def",
"has_permissions",
"(",
"*",
"*",
"perms",
":",
"bool",
")",
":",
"if",
"perms",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Must provide at least one keyword argument to has_permissions\"",
")",
"return",
"Requires",
".",
"get_decorator",
"(",
"None",
... | https://github.com/Cog-Creators/Red-DiscordBot/blob/b05933274a11fb097873ab0d1b246d37b06aa306/redbot/core/commands/requires.py#L726-L733 | |
OpenEndedGroup/Field | 4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c | Contents/lib/python/urllib.py | python | FancyURLopener.http_error_default | (self, url, fp, errcode, errmsg, headers) | return addinfourl(fp, headers, "http:" + url) | Default error handling -- don't raise an exception. | Default error handling -- don't raise an exception. | [
"Default",
"error",
"handling",
"--",
"don",
"t",
"raise",
"an",
"exception",
"."
] | def http_error_default(self, url, fp, errcode, errmsg, headers):
"""Default error handling -- don't raise an exception."""
return addinfourl(fp, headers, "http:" + url) | [
"def",
"http_error_default",
"(",
"self",
",",
"url",
",",
"fp",
",",
"errcode",
",",
"errmsg",
",",
"headers",
")",
":",
"return",
"addinfourl",
"(",
"fp",
",",
"headers",
",",
"\"http:\"",
"+",
"url",
")"
] | https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/urllib.py#L614-L616 | |
llSourcell/AI_Artist | 3038c06c2e389b9c919c881c9a169efe2fd7810e | lib/python2.7/site-packages/pip/_vendor/ipaddress.py | python | ip_interface | (address) | Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP address. Either IPv4 or
IPv6 addresses may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
Returns:
An IPv4Interface or IPv6Interface object.
Raises:
ValueError: if the string passed isn't either a v4 or a v6
address.
Notes:
The IPv?Interface classes describe an Address on a particular
Network, so they're basically a combination of both the Address
and Network classes. | Take an IP string/int and return an object of the correct type. | [
"Take",
"an",
"IP",
"string",
"/",
"int",
"and",
"return",
"an",
"object",
"of",
"the",
"correct",
"type",
"."
] | def ip_interface(address):
"""Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP address. Either IPv4 or
IPv6 addresses may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
Returns:
An IPv4Interface or IPv6Interface object.
Raises:
ValueError: if the string passed isn't either a v4 or a v6
address.
Notes:
The IPv?Interface classes describe an Address on a particular
Network, so they're basically a combination of both the Address
and Network classes.
"""
try:
return IPv4Interface(address)
except (AddressValueError, NetmaskValueError):
pass
try:
return IPv6Interface(address)
except (AddressValueError, NetmaskValueError):
pass
raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' %
address) | [
"def",
"ip_interface",
"(",
"address",
")",
":",
"try",
":",
"return",
"IPv4Interface",
"(",
"address",
")",
"except",
"(",
"AddressValueError",
",",
"NetmaskValueError",
")",
":",
"pass",
"try",
":",
"return",
"IPv6Interface",
"(",
"address",
")",
"except",
... | https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/_vendor/ipaddress.py#L205-L237 | ||
Robpol86/Flask-Celery-Helper | 92bd3b02954422665260116adda8eb899546c365 | flask_celery.py | python | _LockManagerRedis.reset_lock | (self) | Removed the lock regardless of timeout. | Removed the lock regardless of timeout. | [
"Removed",
"the",
"lock",
"regardless",
"of",
"timeout",
"."
] | def reset_lock(self):
"""Removed the lock regardless of timeout."""
redis_key = self.CELERY_LOCK.format(task_id=self.task_identifier)
self.celery_self.backend.client.delete(redis_key) | [
"def",
"reset_lock",
"(",
"self",
")",
":",
"redis_key",
"=",
"self",
".",
"CELERY_LOCK",
".",
"format",
"(",
"task_id",
"=",
"self",
".",
"task_identifier",
")",
"self",
".",
"celery_self",
".",
"backend",
".",
"client",
".",
"delete",
"(",
"redis_key",
... | https://github.com/Robpol86/Flask-Celery-Helper/blob/92bd3b02954422665260116adda8eb899546c365/flask_celery.py#L87-L90 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | ansible/roles/lib_openshift_3.2/library/oc_pvc.py | python | Yedit.load | (self, content_type='yaml') | return self.yaml_dict | return yaml file | return yaml file | [
"return",
"yaml",
"file"
] | def load(self, content_type='yaml'):
''' return yaml file '''
contents = self.read()
if not contents and not self.content:
return None
if self.content:
if isinstance(self.content, dict):
self.yaml_dict = self.content
return self.yaml_dict
elif isinstance(self.content, str):
contents = self.content
# check if it is yaml
try:
if content_type == 'yaml' and contents:
self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
# pylint: disable=no-member,maybe-no-member
if hasattr(self.yaml_dict, 'fa'):
self.yaml_dict.fa.set_block_style()
elif content_type == 'json' and contents:
self.yaml_dict = json.loads(contents)
except yaml.YAMLError as err:
# Error loading yaml or json
raise YeditException('Problem with loading yaml file. %s' % err)
return self.yaml_dict | [
"def",
"load",
"(",
"self",
",",
"content_type",
"=",
"'yaml'",
")",
":",
"contents",
"=",
"self",
".",
"read",
"(",
")",
"if",
"not",
"contents",
"and",
"not",
"self",
".",
"content",
":",
"return",
"None",
"if",
"self",
".",
"content",
":",
"if",
... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_openshift_3.2/library/oc_pvc.py#L690-L717 | |
schemathesis/schemathesis | 2eaea40be33067af5f5f6b6b7a79000224e1bbd2 | src/schemathesis/specs/openapi/stateful/links.py | python | default_status_code | (status_codes: List[str]) | return match_default_response | Create a filter that matches all "default" responses.
In Open API, the "default" response is the one that is used if no other options were matched.
Therefore we need to match only responses that were not matched by other listed status codes. | Create a filter that matches all "default" responses. | [
"Create",
"a",
"filter",
"that",
"matches",
"all",
"default",
"responses",
"."
] | def default_status_code(status_codes: List[str]) -> FilterFunction:
"""Create a filter that matches all "default" responses.
In Open API, the "default" response is the one that is used if no other options were matched.
Therefore we need to match only responses that were not matched by other listed status codes.
"""
expanded_status_codes = {
status_code for value in status_codes if value != "default" for status_code in expand_status_code(value)
}
def match_default_response(result: StepResult) -> bool:
return result.response.status_code not in expanded_status_codes
return match_default_response | [
"def",
"default_status_code",
"(",
"status_codes",
":",
"List",
"[",
"str",
"]",
")",
"->",
"FilterFunction",
":",
"expanded_status_codes",
"=",
"{",
"status_code",
"for",
"value",
"in",
"status_codes",
"if",
"value",
"!=",
"\"default\"",
"for",
"status_code",
"... | https://github.com/schemathesis/schemathesis/blob/2eaea40be33067af5f5f6b6b7a79000224e1bbd2/src/schemathesis/specs/openapi/stateful/links.py#L67-L80 | |
miLibris/flask-rest-jsonapi | a4ff3f4d5be78071f015efe003e976d31d4eba10 | flask_rest_jsonapi/data_layers/base.py | python | BaseDataLayer.after_get_object | (self, obj, view_kwargs) | Make work after to retrieve an object
:param obj: an object from data layer
:param dict view_kwargs: kwargs from the resource view | Make work after to retrieve an object | [
"Make",
"work",
"after",
"to",
"retrieve",
"an",
"object"
] | def after_get_object(self, obj, view_kwargs):
"""Make work after to retrieve an object
:param obj: an object from data layer
:param dict view_kwargs: kwargs from the resource view
"""
raise NotImplementedError | [
"def",
"after_get_object",
"(",
"self",
",",
"obj",
",",
"view_kwargs",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/miLibris/flask-rest-jsonapi/blob/a4ff3f4d5be78071f015efe003e976d31d4eba10/flask_rest_jsonapi/data_layers/base.py#L165-L171 | ||
HKUST-KnowComp/ASER | 3290e7cad0ec271c3720f4d578cae2c8d17915a4 | aser/database/db_connection.py | python | BaseDBConnection.update_rows | (self, table_name, rows, update_ops, update_columns) | Update rows that exist in a table
:param table_name: the table name to update
:type table_name: str
:param rows: new rows
:type rows: List[Dict[str, object]]
:param update_ops: operator(s) that returned by `get_update_op`
:type update_ops: Union[List[object], object]
:param update_columns: the columns to update
:type update_columns: List[str] | Update rows that exist in a table | [
"Update",
"rows",
"that",
"exist",
"in",
"a",
"table"
] | def update_rows(self, table_name, rows, update_ops, update_columns):
""" Update rows that exist in a table
:param table_name: the table name to update
:type table_name: str
:param rows: new rows
:type rows: List[Dict[str, object]]
:param update_ops: operator(s) that returned by `get_update_op`
:type update_ops: Union[List[object], object]
:param update_columns: the columns to update
:type update_columns: List[str]
"""
raise NotImplementedError | [
"def",
"update_rows",
"(",
"self",
",",
"table_name",
",",
"rows",
",",
"update_ops",
",",
"update_columns",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/HKUST-KnowComp/ASER/blob/3290e7cad0ec271c3720f4d578cae2c8d17915a4/aser/database/db_connection.py#L135-L148 | ||
VirtueSecurity/aws-extender | d123b7e1a845847709ba3a481f11996bddc68a1c | BappModules/botocore/vendored/requests/packages/urllib3/packages/six.py | python | itervalues | (d) | return iter(getattr(d, _itervalues)()) | Return an iterator over the values of a dictionary. | Return an iterator over the values of a dictionary. | [
"Return",
"an",
"iterator",
"over",
"the",
"values",
"of",
"a",
"dictionary",
"."
] | def itervalues(d):
"""Return an iterator over the values of a dictionary."""
return iter(getattr(d, _itervalues)()) | [
"def",
"itervalues",
"(",
"d",
")",
":",
"return",
"iter",
"(",
"getattr",
"(",
"d",
",",
"_itervalues",
")",
"(",
")",
")"
] | https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/botocore/vendored/requests/packages/urllib3/packages/six.py#L267-L269 | |
MeanEYE/Sunflower | 1024bbdde3b8e202ddad3553b321a7b6230bffc9 | sunflower/widgets/breadcrumbs.py | python | Breadcrumbs.__fragment_click | (self, widget, data=None) | Handle clicking on path fragment. | Handle clicking on path fragment. | [
"Handle",
"clicking",
"on",
"path",
"fragment",
"."
] | def __fragment_click(self, widget, data=None):
"""Handle clicking on path fragment."""
if self._updating:
return
# ignore non active buttons
if not widget.props.active:
return
# change path
file_list = self._parent._parent
if hasattr(file_list, 'change_path'):
file_list.change_path(widget.path) | [
"def",
"__fragment_click",
"(",
"self",
",",
"widget",
",",
"data",
"=",
"None",
")",
":",
"if",
"self",
".",
"_updating",
":",
"return",
"# ignore non active buttons",
"if",
"not",
"widget",
".",
"props",
".",
"active",
":",
"return",
"# change path",
"file... | https://github.com/MeanEYE/Sunflower/blob/1024bbdde3b8e202ddad3553b321a7b6230bffc9/sunflower/widgets/breadcrumbs.py#L32-L44 | ||
XX-net/XX-Net | a9898cfcf0084195fb7e69b6bc834e59aecdf14f | python3.8.2/Lib/dataclasses.py | python | replace | (*args, **changes) | return obj.__class__(**changes) | Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@dataclass(frozen=True)
class C:
x: int
y: int
c = C(1, 2)
c1 = replace(c, x=3)
assert c1.x == 3 and c1.y == 2 | Return a new object replacing specified fields with new values. | [
"Return",
"a",
"new",
"object",
"replacing",
"specified",
"fields",
"with",
"new",
"values",
"."
] | def replace(*args, **changes):
"""Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@dataclass(frozen=True)
class C:
x: int
y: int
c = C(1, 2)
c1 = replace(c, x=3)
assert c1.x == 3 and c1.y == 2
"""
if len(args) > 1:
raise TypeError(f'replace() takes 1 positional argument but {len(args)} were given')
if args:
obj, = args
elif 'obj' in changes:
obj = changes.pop('obj')
import warnings
warnings.warn("Passing 'obj' as keyword argument is deprecated",
DeprecationWarning, stacklevel=2)
else:
raise TypeError("replace() missing 1 required positional argument: 'obj'")
# We're going to mutate 'changes', but that's okay because it's a
# new dict, even if called with 'replace(obj, **my_changes)'.
if not _is_dataclass_instance(obj):
raise TypeError("replace() should be called on dataclass instances")
# It's an error to have init=False fields in 'changes'.
# If a field is not in 'changes', read its value from the provided obj.
for f in getattr(obj, _FIELDS).values():
# Only consider normal fields or InitVars.
if f._field_type is _FIELD_CLASSVAR:
continue
if not f.init:
# Error if this field is specified in changes.
if f.name in changes:
raise ValueError(f'field {f.name} is declared with '
'init=False, it cannot be specified with '
'replace()')
continue
if f.name not in changes:
if f._field_type is _FIELD_INITVAR:
raise ValueError(f"InitVar {f.name!r} "
'must be specified with replace()')
changes[f.name] = getattr(obj, f.name)
# Create the new object, which calls __init__() and
# __post_init__() (if defined), using all of the init fields we've
# added and/or left in 'changes'. If there are values supplied in
# changes that aren't fields, this will correctly raise a
# TypeError.
return obj.__class__(**changes) | [
"def",
"replace",
"(",
"*",
"args",
",",
"*",
"*",
"changes",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"f'replace() takes 1 positional argument but {len(args)} were given'",
")",
"if",
"args",
":",
"obj",
",",
"=",
... | https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/dataclasses.py#L1234-L1293 | |
Netflix/dispatch | f734b7cb91cba0e3a95b4d0adaa7198bfc94552b | src/dispatch/search/fulltext/__init__.py | python | search | (query, search_query, vector=None, regconfig=None, sort=False) | return query.params(term=search_query) | Search given query with full text search.
:param search_query: the search query
:param vector: search vector to use
:param regconfig: postgresql regconfig to be used
:param sort: order results by relevance (quality of hit) | Search given query with full text search. | [
"Search",
"given",
"query",
"with",
"full",
"text",
"search",
"."
] | def search(query, search_query, vector=None, regconfig=None, sort=False):
"""
Search given query with full text search.
:param search_query: the search query
:param vector: search vector to use
:param regconfig: postgresql regconfig to be used
:param sort: order results by relevance (quality of hit)
"""
if not search_query.strip():
return query
if vector is None:
entity = query._entities[0].entity_zero.class_
search_vectors = inspect_search_vectors(entity)
vector = search_vectors[0]
if regconfig is None:
regconfig = search_manager.options["regconfig"]
query = query.filter(vector.op("@@")(func.tsq_parse(regconfig, search_query)))
if sort:
query = query.order_by(desc(func.ts_rank_cd(vector, func.tsq_parse(search_query))))
return query.params(term=search_query) | [
"def",
"search",
"(",
"query",
",",
"search_query",
",",
"vector",
"=",
"None",
",",
"regconfig",
"=",
"None",
",",
"sort",
"=",
"False",
")",
":",
"if",
"not",
"search_query",
".",
"strip",
"(",
")",
":",
"return",
"query",
"if",
"vector",
"is",
"No... | https://github.com/Netflix/dispatch/blob/f734b7cb91cba0e3a95b4d0adaa7198bfc94552b/src/dispatch/search/fulltext/__init__.py#L40-L64 | |
seperman/deepdiff | 7e5e9954d635423d691f37194f3d1d93d363a128 | deepdiff/model.py | python | TreeResult.mutual_add_removes_to_become_value_changes | (self) | There might be the same paths reported in the results as removed and added.
In such cases they should be reported as value_changes.
Note that this function mutates the tree in ways that causes issues when report_repetition=True
and should be avoided in that case.
This function should only be run on the Tree Result. | There might be the same paths reported in the results as removed and added.
In such cases they should be reported as value_changes. | [
"There",
"might",
"be",
"the",
"same",
"paths",
"reported",
"in",
"the",
"results",
"as",
"removed",
"and",
"added",
".",
"In",
"such",
"cases",
"they",
"should",
"be",
"reported",
"as",
"value_changes",
"."
] | def mutual_add_removes_to_become_value_changes(self):
"""
There might be the same paths reported in the results as removed and added.
In such cases they should be reported as value_changes.
Note that this function mutates the tree in ways that causes issues when report_repetition=True
and should be avoided in that case.
This function should only be run on the Tree Result.
"""
if self.get('iterable_item_added') and self.get('iterable_item_removed'):
added_paths = {i.path(): i for i in self['iterable_item_added']}
removed_paths = {i.path(): i for i in self['iterable_item_removed']}
mutual_paths = set(added_paths) & set(removed_paths)
if mutual_paths and 'values_changed' not in self:
self['values_changed'] = PrettyOrderedSet()
for path in mutual_paths:
level_before = removed_paths[path]
self['iterable_item_removed'].remove(level_before)
level_after = added_paths[path]
self['iterable_item_added'].remove(level_after)
level_before.t2 = level_after.t2
self['values_changed'].add(level_before)
if 'iterable_item_removed' in self and not self['iterable_item_removed']:
del self['iterable_item_removed']
if 'iterable_item_added' in self and not self['iterable_item_added']:
del self['iterable_item_added'] | [
"def",
"mutual_add_removes_to_become_value_changes",
"(",
"self",
")",
":",
"if",
"self",
".",
"get",
"(",
"'iterable_item_added'",
")",
"and",
"self",
".",
"get",
"(",
"'iterable_item_removed'",
")",
":",
"added_paths",
"=",
"{",
"i",
".",
"path",
"(",
")",
... | https://github.com/seperman/deepdiff/blob/7e5e9954d635423d691f37194f3d1d93d363a128/deepdiff/model.py#L65-L92 | ||
cython/cython | 9db1fc39b31b7b3b2ed574a79f5f9fd980ee3be7 | Cython/Compiler/Interpreter.py | python | interpret_compiletime_options | (optlist, optdict, type_env=None, type_args=()) | return (optlist, new_optdict) | Tries to interpret a list of compile time option nodes.
The result will be a tuple (optlist, optdict) but where
all expression nodes have been interpreted. The result is
in the form of tuples (value, pos).
optlist is a list of nodes, while optdict is a DictNode (the
result optdict is a dict)
If type_env is set, all type nodes will be analysed and the resulting
type set. Otherwise only interpretateable ExprNodes
are allowed, other nodes raises errors.
A CompileError will be raised if there are problems. | Tries to interpret a list of compile time option nodes.
The result will be a tuple (optlist, optdict) but where
all expression nodes have been interpreted. The result is
in the form of tuples (value, pos). | [
"Tries",
"to",
"interpret",
"a",
"list",
"of",
"compile",
"time",
"option",
"nodes",
".",
"The",
"result",
"will",
"be",
"a",
"tuple",
"(",
"optlist",
"optdict",
")",
"but",
"where",
"all",
"expression",
"nodes",
"have",
"been",
"interpreted",
".",
"The",
... | def interpret_compiletime_options(optlist, optdict, type_env=None, type_args=()):
"""
Tries to interpret a list of compile time option nodes.
The result will be a tuple (optlist, optdict) but where
all expression nodes have been interpreted. The result is
in the form of tuples (value, pos).
optlist is a list of nodes, while optdict is a DictNode (the
result optdict is a dict)
If type_env is set, all type nodes will be analysed and the resulting
type set. Otherwise only interpretateable ExprNodes
are allowed, other nodes raises errors.
A CompileError will be raised if there are problems.
"""
def interpret(node, ix):
if ix in type_args:
if type_env:
type = node.analyse_as_type(type_env)
if not type:
raise CompileError(node.pos, "Invalid type.")
return (type, node.pos)
else:
raise CompileError(node.pos, "Type not allowed here.")
else:
if (sys.version_info[0] >=3 and
isinstance(node, StringNode) and
node.unicode_value is not None):
return (node.unicode_value, node.pos)
return (node.compile_time_value(empty_scope), node.pos)
if optlist:
optlist = [interpret(x, ix) for ix, x in enumerate(optlist)]
if optdict:
assert isinstance(optdict, DictNode)
new_optdict = {}
for item in optdict.key_value_pairs:
new_key, dummy = interpret(item.key, None)
new_optdict[new_key] = interpret(item.value, item.key.value)
optdict = new_optdict
return (optlist, new_optdict) | [
"def",
"interpret_compiletime_options",
"(",
"optlist",
",",
"optdict",
",",
"type_env",
"=",
"None",
",",
"type_args",
"=",
"(",
")",
")",
":",
"def",
"interpret",
"(",
"node",
",",
"ix",
")",
":",
"if",
"ix",
"in",
"type_args",
":",
"if",
"type_env",
... | https://github.com/cython/cython/blob/9db1fc39b31b7b3b2ed574a79f5f9fd980ee3be7/Cython/Compiler/Interpreter.py#L22-L64 | |
F8LEFT/DecLLVM | d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c | python/idaapi.py | python | IDB_Hooks.ti_changed | (self, *args) | return _idaapi.IDB_Hooks_ti_changed(self, *args) | ti_changed(self, arg0, arg1, arg2) -> int | ti_changed(self, arg0, arg1, arg2) -> int | [
"ti_changed",
"(",
"self",
"arg0",
"arg1",
"arg2",
")",
"-",
">",
"int"
] | def ti_changed(self, *args):
"""
ti_changed(self, arg0, arg1, arg2) -> int
"""
return _idaapi.IDB_Hooks_ti_changed(self, *args) | [
"def",
"ti_changed",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"IDB_Hooks_ti_changed",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L5004-L5008 | |
gmate/gmate | 83312e64e0c115a9842500e4eb8617d3f5f4025b | plugins/gedit2/clickconfig/clickconfig/ui.py | python | ConfigUI.on_Browse_button_clicked | (self, button) | Browse to the configuration file. | Browse to the configuration file. | [
"Browse",
"to",
"the",
"configuration",
"file",
"."
] | def on_Browse_button_clicked(self, button):
"""Browse to the configuration file."""
LOGGER.log()
self._plugin.open_config_dir() | [
"def",
"on_Browse_button_clicked",
"(",
"self",
",",
"button",
")",
":",
"LOGGER",
".",
"log",
"(",
")",
"self",
".",
"_plugin",
".",
"open_config_dir",
"(",
")"
] | https://github.com/gmate/gmate/blob/83312e64e0c115a9842500e4eb8617d3f5f4025b/plugins/gedit2/clickconfig/clickconfig/ui.py#L214-L217 | ||
smilejay/python | 4fd141161273d3b423544da21c6d1ba720a0b184 | py-libvirt/destroy_domains.py | python | destroy_domains | () | destroy all domains() via libvirt python API. | destroy all domains() via libvirt python API. | [
"destroy",
"all",
"domains",
"()",
"via",
"libvirt",
"python",
"API",
"."
] | def destroy_domains():
'''
destroy all domains() via libvirt python API.
'''
conn = libvirt.open(None)
if conn:
for i in conn.listDomainsID():
dom = conn.lookupByID(i)
dom.destroy()
time.sleep(1)
if conn.listDomainsID():
print 'ERROR! there are live domains.'
else:
print 'Failed to open connection to the hypervisor' | [
"def",
"destroy_domains",
"(",
")",
":",
"conn",
"=",
"libvirt",
".",
"open",
"(",
"None",
")",
"if",
"conn",
":",
"for",
"i",
"in",
"conn",
".",
"listDomainsID",
"(",
")",
":",
"dom",
"=",
"conn",
".",
"lookupByID",
"(",
"i",
")",
"dom",
".",
"d... | https://github.com/smilejay/python/blob/4fd141161273d3b423544da21c6d1ba720a0b184/py-libvirt/destroy_domains.py#L6-L19 | ||
materialsproject/pymatgen | 8128f3062a334a2edd240e4062b5b9bdd1ae6f58 | pymatgen/core/spectrum.py | python | Spectrum.smear | (self, sigma: float = 0.0, func: Union[str, Callable] = "gaussian") | Apply Gaussian/Lorentzian smearing to spectrum y value.
Args:
sigma: Std dev for Gaussian smear function
func: "gaussian" or "lorentzian" or a callable. If this is a callable, the sigma value is ignored. The
callable should only take a single argument (a numpy array) and return a set of weights. | Apply Gaussian/Lorentzian smearing to spectrum y value. | [
"Apply",
"Gaussian",
"/",
"Lorentzian",
"smearing",
"to",
"spectrum",
"y",
"value",
"."
] | def smear(self, sigma: float = 0.0, func: Union[str, Callable] = "gaussian"):
"""
Apply Gaussian/Lorentzian smearing to spectrum y value.
Args:
sigma: Std dev for Gaussian smear function
func: "gaussian" or "lorentzian" or a callable. If this is a callable, the sigma value is ignored. The
callable should only take a single argument (a numpy array) and return a set of weights.
"""
points = np.linspace(np.min(self.x) - np.mean(self.x), np.max(self.x) - np.mean(self.x), len(self.x))
if callable(func):
weights = func(points)
elif func.lower() == "gaussian":
weights = stats.norm.pdf(points, scale=sigma)
elif func.lower() == "lorentzian":
weights = lorentzian(points, sigma=sigma)
else:
raise ValueError(f"Invalid func {func}")
weights /= np.sum(weights)
if len(self.ydim) == 1:
total = np.sum(self.y)
self.y = convolve1d(self.y, weights)
self.y *= total / np.sum(self.y) # renormalize to maintain the same integrated sum as before.
else:
total = np.sum(self.y, axis=0)
self.y = np.array([convolve1d(self.y[:, k], weights) for k in range(self.ydim[1])]).T
self.y *= total / np.sum(self.y, axis=0) | [
"def",
"smear",
"(",
"self",
",",
"sigma",
":",
"float",
"=",
"0.0",
",",
"func",
":",
"Union",
"[",
"str",
",",
"Callable",
"]",
"=",
"\"gaussian\"",
")",
":",
"points",
"=",
"np",
".",
"linspace",
"(",
"np",
".",
"min",
"(",
"self",
".",
"x",
... | https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/core/spectrum.py#L101-L127 | ||
sahana/eden | 1696fa50e90ce967df69f66b571af45356cc18da | controllers/br.py | python | assistance_offer | () | return s3_rest_controller() | Offers of Assistance: RESTful CRUD controller | Offers of Assistance: RESTful CRUD controller | [
"Offers",
"of",
"Assistance",
":",
"RESTful",
"CRUD",
"controller"
] | def assistance_offer():
""" Offers of Assistance: RESTful CRUD controller """
return s3_rest_controller() | [
"def",
"assistance_offer",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/controllers/br.py#L1216-L1219 | |
meduza-corp/interstellar | 40a801ccd7856491726f5a126621d9318cabe2e1 | gsutil/third_party/boto/boto/redshift/layer1.py | python | RedshiftConnection.describe_cluster_parameter_groups | (self, parameter_group_name=None,
max_records=None, marker=None) | return self._make_request(
action='DescribeClusterParameterGroups',
verb='POST',
path='/', params=params) | Returns a list of Amazon Redshift parameter groups, including
parameter groups you created and the default parameter group.
For each parameter group, the response includes the parameter
group name, description, and parameter group family name. You
can optionally specify a name to retrieve the description of a
specific parameter group.
For more information about managing parameter groups, go to
`Amazon Redshift Parameter Groups`_ in the Amazon Redshift
Management Guide .
:type parameter_group_name: string
:param parameter_group_name: The name of a specific parameter group for
which to return details. By default, details about all parameter
groups and the default parameter group are returned.
:type max_records: integer
:param max_records: The maximum number of parameter group records to
include in the response. If more records exist than the specified
`MaxRecords` value, the response includes a marker that you can use
in a subsequent DescribeClusterParameterGroups request to retrieve
the next set of records.
Default: `100`
Constraints: Value must be at least 20 and no more than 100.
:type marker: string
:param marker: An optional marker returned by a previous
DescribeClusterParameterGroups request to indicate the first
parameter group that the current request will return. | Returns a list of Amazon Redshift parameter groups, including
parameter groups you created and the default parameter group.
For each parameter group, the response includes the parameter
group name, description, and parameter group family name. You
can optionally specify a name to retrieve the description of a
specific parameter group. | [
"Returns",
"a",
"list",
"of",
"Amazon",
"Redshift",
"parameter",
"groups",
"including",
"parameter",
"groups",
"you",
"created",
"and",
"the",
"default",
"parameter",
"group",
".",
"For",
"each",
"parameter",
"group",
"the",
"response",
"includes",
"the",
"param... | def describe_cluster_parameter_groups(self, parameter_group_name=None,
max_records=None, marker=None):
"""
Returns a list of Amazon Redshift parameter groups, including
parameter groups you created and the default parameter group.
For each parameter group, the response includes the parameter
group name, description, and parameter group family name. You
can optionally specify a name to retrieve the description of a
specific parameter group.
For more information about managing parameter groups, go to
`Amazon Redshift Parameter Groups`_ in the Amazon Redshift
Management Guide .
:type parameter_group_name: string
:param parameter_group_name: The name of a specific parameter group for
which to return details. By default, details about all parameter
groups and the default parameter group are returned.
:type max_records: integer
:param max_records: The maximum number of parameter group records to
include in the response. If more records exist than the specified
`MaxRecords` value, the response includes a marker that you can use
in a subsequent DescribeClusterParameterGroups request to retrieve
the next set of records.
Default: `100`
Constraints: Value must be at least 20 and no more than 100.
:type marker: string
:param marker: An optional marker returned by a previous
DescribeClusterParameterGroups request to indicate the first
parameter group that the current request will return.
"""
params = {}
if parameter_group_name is not None:
params['ParameterGroupName'] = parameter_group_name
if max_records is not None:
params['MaxRecords'] = max_records
if marker is not None:
params['Marker'] = marker
return self._make_request(
action='DescribeClusterParameterGroups',
verb='POST',
path='/', params=params) | [
"def",
"describe_cluster_parameter_groups",
"(",
"self",
",",
"parameter_group_name",
"=",
"None",
",",
"max_records",
"=",
"None",
",",
"marker",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"parameter_group_name",
"is",
"not",
"None",
":",
"params",... | https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/third_party/boto/boto/redshift/layer1.py#L1207-L1252 | |
pymedusa/Medusa | 1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38 | ext/soupsieve/util.py | python | upper | (string) | return ''.join(new_string) | Lower. | Lower. | [
"Lower",
"."
] | def upper(string): # pragma: no cover
"""Lower."""
new_string = []
for c in string:
o = ord(c)
new_string.append(chr(o - 32) if LC_A <= o <= LC_Z else c)
return ''.join(new_string) | [
"def",
"upper",
"(",
"string",
")",
":",
"# pragma: no cover",
"new_string",
"=",
"[",
"]",
"for",
"c",
"in",
"string",
":",
"o",
"=",
"ord",
"(",
"c",
")",
"new_string",
".",
"append",
"(",
"chr",
"(",
"o",
"-",
"32",
")",
"if",
"LC_A",
"<=",
"o... | https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/soupsieve/util.py#L52-L59 | |
openhatch/oh-mainline | ce29352a034e1223141dcc2f317030bbc3359a51 | vendor/packages/amqp/amqp/channel.py | python | Channel._basic_cancel_notify | (self, args) | Consumer cancelled by server.
Most likely the queue was deleted. | Consumer cancelled by server. | [
"Consumer",
"cancelled",
"by",
"server",
"."
] | def _basic_cancel_notify(self, args):
"""Consumer cancelled by server.
Most likely the queue was deleted.
"""
consumer_tag = args.read_shortstr()
callback = self._on_cancel(consumer_tag)
if callback:
callback(consumer_tag)
else:
raise ConsumerCancelled(consumer_tag, (60, 30)) | [
"def",
"_basic_cancel_notify",
"(",
"self",
",",
"args",
")",
":",
"consumer_tag",
"=",
"args",
".",
"read_shortstr",
"(",
")",
"callback",
"=",
"self",
".",
"_on_cancel",
"(",
"consumer_tag",
")",
"if",
"callback",
":",
"callback",
"(",
"consumer_tag",
")",... | https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/amqp/amqp/channel.py#L1635-L1646 | ||
fabioz/PyDev.Debugger | 0f8c02a010fe5690405da1dd30ed72326191ce63 | pydevd_attach_to_process/winappdbg/debug.py | python | Debug.attach | (self, dwProcessId) | return aProcess | Attaches to an existing process for debugging.
@see: L{detach}, L{execv}, L{execl}
@type dwProcessId: int
@param dwProcessId: Global ID of a process to attach to.
@rtype: L{Process}
@return: A new Process object. Normally you don't need to use it now,
it's best to interact with the process from the event handler.
@raise WindowsError: Raises an exception on error.
Depending on the circumstances, the debugger may or may not have
attached to the target process. | Attaches to an existing process for debugging. | [
"Attaches",
"to",
"an",
"existing",
"process",
"for",
"debugging",
"."
] | def attach(self, dwProcessId):
"""
Attaches to an existing process for debugging.
@see: L{detach}, L{execv}, L{execl}
@type dwProcessId: int
@param dwProcessId: Global ID of a process to attach to.
@rtype: L{Process}
@return: A new Process object. Normally you don't need to use it now,
it's best to interact with the process from the event handler.
@raise WindowsError: Raises an exception on error.
Depending on the circumstances, the debugger may or may not have
attached to the target process.
"""
# Get the Process object from the snapshot,
# if missing create a new one.
try:
aProcess = self.system.get_process(dwProcessId)
except KeyError:
aProcess = Process(dwProcessId)
# Warn when mixing 32 and 64 bits.
# This also allows the user to stop attaching altogether,
# depending on how the warnings are configured.
if System.bits != aProcess.get_bits():
msg = "Mixture of 32 and 64 bits is considered experimental." \
" Use at your own risk!"
warnings.warn(msg, MixedBitsWarning)
# Attach to the process.
win32.DebugActiveProcess(dwProcessId)
# Add the new PID to the set of debugees.
self.__attachedDebugees.add(dwProcessId)
# Match the system kill-on-exit flag to our own.
self.__setSystemKillOnExitMode()
# If the Process object was not in the snapshot, add it now.
if not self.system.has_process(dwProcessId):
self.system._add_process(aProcess)
# Scan the process threads and loaded modules.
# This is prefered because the thread and library events do not
# properly give some information, like the filename for each module.
aProcess.scan_threads()
aProcess.scan_modules()
# Return the Process object, like the execv() and execl() methods.
return aProcess | [
"def",
"attach",
"(",
"self",
",",
"dwProcessId",
")",
":",
"# Get the Process object from the snapshot,",
"# if missing create a new one.",
"try",
":",
"aProcess",
"=",
"self",
".",
"system",
".",
"get_process",
"(",
"dwProcessId",
")",
"except",
"KeyError",
":",
"... | https://github.com/fabioz/PyDev.Debugger/blob/0f8c02a010fe5690405da1dd30ed72326191ce63/pydevd_attach_to_process/winappdbg/debug.py#L211-L264 | |
pfalcon/pycopy-lib | 56ebf2110f3caa63a3785d439ce49b11e13c75c0 | email.message/email/message.py | python | Message.items | (self) | return [(k, self.policy.header_fetch_parse(k, v))
for k, v in self._headers] | Get all the message's header fields and values.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list. | Get all the message's header fields and values. | [
"Get",
"all",
"the",
"message",
"s",
"header",
"fields",
"and",
"values",
"."
] | def items(self):
"""Get all the message's header fields and values.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
"""
return [(k, self.policy.header_fetch_parse(k, v))
for k, v in self._headers] | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"[",
"(",
"k",
",",
"self",
".",
"policy",
".",
"header_fetch_parse",
"(",
"k",
",",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_headers",
"]"
] | https://github.com/pfalcon/pycopy-lib/blob/56ebf2110f3caa63a3785d439ce49b11e13c75c0/email.message/email/message.py#L403-L412 | |
openedx/edx-platform | 68dd185a0ab45862a2a61e0f803d7e03d2be71b5 | lms/djangoapps/experiments/utils.py | python | get_base_experiment_metadata_context | (course, user, enrollment, user_enrollments) | return {
'upgrade_link': upgrade_link,
'upgrade_price': str(get_cosmetic_verified_display_price(course)),
'enrollment_mode': enrollment_mode,
'enrollment_time': enrollment_time,
'schedule_start': schedule_start,
'pacing_type': 'self_paced' if course.self_paced else 'instructor_paced',
'dynamic_upgrade_deadline': dynamic_upgrade_deadline,
'course_upgrade_deadline': course_upgrade_deadline,
'audit_access_deadline': deadline,
'course_duration': duration,
'course_key': course.id,
'course_display_name': course.display_name_with_default,
'course_start': course.start,
'course_end': course.end,
# TODO: clean up as part of REVEM-199 (START)
'program_key_fields': program_key,
# TODO: clean up as part of REVEM-199 (END)
} | Return a context dictionary with the keys used by dashboard_metadata.html and user_metadata.html | Return a context dictionary with the keys used by dashboard_metadata.html and user_metadata.html | [
"Return",
"a",
"context",
"dictionary",
"with",
"the",
"keys",
"used",
"by",
"dashboard_metadata",
".",
"html",
"and",
"user_metadata",
".",
"html"
] | def get_base_experiment_metadata_context(course, user, enrollment, user_enrollments):
"""
Return a context dictionary with the keys used by dashboard_metadata.html and user_metadata.html
"""
enrollment_mode = None
enrollment_time = None
# TODO: clean up as part of REVEM-199 (START)
program_key = get_program_context(course, user_enrollments)
# TODO: clean up as part of REVEM-199 (END)
schedule_start = None
if enrollment and enrollment.is_active:
enrollment_mode = enrollment.mode
enrollment_time = enrollment.created
try:
schedule_start = enrollment.schedule.start_date
except Schedule.DoesNotExist:
pass
# upgrade_link, dynamic_upgrade_deadline and course_upgrade_deadline should be None
# if user has passed their dynamic pacing deadline.
upgrade_link, dynamic_upgrade_deadline, course_upgrade_deadline = check_and_get_upgrade_link_and_date(
user, enrollment, course
)
duration = get_user_course_duration(user, course)
deadline = duration and get_user_course_expiration_date(user, course)
return {
'upgrade_link': upgrade_link,
'upgrade_price': str(get_cosmetic_verified_display_price(course)),
'enrollment_mode': enrollment_mode,
'enrollment_time': enrollment_time,
'schedule_start': schedule_start,
'pacing_type': 'self_paced' if course.self_paced else 'instructor_paced',
'dynamic_upgrade_deadline': dynamic_upgrade_deadline,
'course_upgrade_deadline': course_upgrade_deadline,
'audit_access_deadline': deadline,
'course_duration': duration,
'course_key': course.id,
'course_display_name': course.display_name_with_default,
'course_start': course.start,
'course_end': course.end,
# TODO: clean up as part of REVEM-199 (START)
'program_key_fields': program_key,
# TODO: clean up as part of REVEM-199 (END)
} | [
"def",
"get_base_experiment_metadata_context",
"(",
"course",
",",
"user",
",",
"enrollment",
",",
"user_enrollments",
")",
":",
"enrollment_mode",
"=",
"None",
"enrollment_time",
"=",
"None",
"# TODO: clean up as part of REVEM-199 (START)",
"program_key",
"=",
"get_program... | https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/experiments/utils.py#L376-L422 | |
bpython/bpython | 189da3ecbaa30212b8ba73aeb321b6a6a324348b | bpython/curtsiesfrontend/repl.py | python | BaseRepl.getstdout | (self) | return s | Returns a string of the current bpython session, wrapped, WITH prompts. | Returns a string of the current bpython session, wrapped, WITH prompts. | [
"Returns",
"a",
"string",
"of",
"the",
"current",
"bpython",
"session",
"wrapped",
"WITH",
"prompts",
"."
] | def getstdout(self):
"""
Returns a string of the current bpython session, wrapped, WITH prompts.
"""
lines = self.lines_for_display + [self.current_line_formatted]
s = (
"\n".join(x.s if isinstance(x, FmtStr) else x for x in lines)
if lines
else ""
)
return s | [
"def",
"getstdout",
"(",
"self",
")",
":",
"lines",
"=",
"self",
".",
"lines_for_display",
"+",
"[",
"self",
".",
"current_line_formatted",
"]",
"s",
"=",
"(",
"\"\\n\"",
".",
"join",
"(",
"x",
".",
"s",
"if",
"isinstance",
"(",
"x",
",",
"FmtStr",
"... | https://github.com/bpython/bpython/blob/189da3ecbaa30212b8ba73aeb321b6a6a324348b/bpython/curtsiesfrontend/repl.py#L2051-L2061 | |
PaddlePaddle/Research | 2da0bd6c72d60e9df403aff23a7802779561c4a1 | NLP/ACL2021-PAIR/metric/msmarco_eval.py | python | load_candidate_from_stream | (f) | return qid_to_ranked_candidate_passages | Load candidate data from a stream.
Args:f (stream): stream to load.
Returns:qid_to_ranked_candidate_passages (dict): dictionary mapping from query_id (int) to a list of 1000 passage ids(int) ranked by relevance and importance | Load candidate data from a stream.
Args:f (stream): stream to load.
Returns:qid_to_ranked_candidate_passages (dict): dictionary mapping from query_id (int) to a list of 1000 passage ids(int) ranked by relevance and importance | [
"Load",
"candidate",
"data",
"from",
"a",
"stream",
".",
"Args",
":",
"f",
"(",
"stream",
")",
":",
"stream",
"to",
"load",
".",
"Returns",
":",
"qid_to_ranked_candidate_passages",
"(",
"dict",
")",
":",
"dictionary",
"mapping",
"from",
"query_id",
"(",
"i... | def load_candidate_from_stream(f):
"""Load candidate data from a stream.
Args:f (stream): stream to load.
Returns:qid_to_ranked_candidate_passages (dict): dictionary mapping from query_id (int) to a list of 1000 passage ids(int) ranked by relevance and importance
"""
qid_to_ranked_candidate_passages = {}
for l in f:
try:
l = l.strip().split('\t')
qid = int(l[0])
pid = int(l[1])
rank = int(l[2])
if qid in qid_to_ranked_candidate_passages:
pass
else:
# By default, all PIDs in the list of 1000 are 0. Only override those that are given
tmp = [0] * 1000
qid_to_ranked_candidate_passages[qid] = tmp
qid_to_ranked_candidate_passages[qid][rank - 1] = pid
except:
raise IOError('\"%s\" is not valid format' % l)
return qid_to_ranked_candidate_passages | [
"def",
"load_candidate_from_stream",
"(",
"f",
")",
":",
"qid_to_ranked_candidate_passages",
"=",
"{",
"}",
"for",
"l",
"in",
"f",
":",
"try",
":",
"l",
"=",
"l",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"qid",
"=",
"int",
"(",
"l",
... | https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/NLP/ACL2021-PAIR/metric/msmarco_eval.py#L45-L66 | |
DataBiosphere/toil | 2e148eee2114ece8dcc3ec8a83f36333266ece0d | src/toil/common.py | python | Toil._cacheAllJobs | (self) | Downloads all jobs in the current job store into self.jobCache. | Downloads all jobs in the current job store into self.jobCache. | [
"Downloads",
"all",
"jobs",
"in",
"the",
"current",
"job",
"store",
"into",
"self",
".",
"jobCache",
"."
] | def _cacheAllJobs(self):
"""
Downloads all jobs in the current job store into self.jobCache.
"""
logger.debug('Caching all jobs in job store')
self._jobCache = {jobDesc.jobStoreID: jobDesc for jobDesc in self._jobStore.jobs()}
logger.debug('{} jobs downloaded.'.format(len(self._jobCache))) | [
"def",
"_cacheAllJobs",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Caching all jobs in job store'",
")",
"self",
".",
"_jobCache",
"=",
"{",
"jobDesc",
".",
"jobStoreID",
":",
"jobDesc",
"for",
"jobDesc",
"in",
"self",
".",
"_jobStore",
".",
"jobs... | https://github.com/DataBiosphere/toil/blob/2e148eee2114ece8dcc3ec8a83f36333266ece0d/src/toil/common.py#L1199-L1205 | ||
vintasoftware/django-role-permissions | 8a75582741819e4d8b66ab76381acd6fc50da442 | rolepermissions/checkers.py | python | _check_superpowers | (user) | return user and user.is_superuser | Check if user is superuser and should have superpowers.
Default is true to maintain backward compatibility. | Check if user is superuser and should have superpowers. | [
"Check",
"if",
"user",
"is",
"superuser",
"and",
"should",
"have",
"superpowers",
"."
] | def _check_superpowers(user):
"""
Check if user is superuser and should have superpowers.
Default is true to maintain backward compatibility.
"""
key = 'ROLEPERMISSIONS_SUPERUSER_SUPERPOWERS'
superpowers = getattr(settings, key, True)
if not superpowers:
return False
return user and user.is_superuser | [
"def",
"_check_superpowers",
"(",
"user",
")",
":",
"key",
"=",
"'ROLEPERMISSIONS_SUPERUSER_SUPERPOWERS'",
"superpowers",
"=",
"getattr",
"(",
"settings",
",",
"key",
",",
"True",
")",
"if",
"not",
"superpowers",
":",
"return",
"False",
"return",
"user",
"and",
... | https://github.com/vintasoftware/django-role-permissions/blob/8a75582741819e4d8b66ab76381acd6fc50da442/rolepermissions/checkers.py#L53-L65 | |
lazylibrarian/LazyLibrarian | ae3c14e9db9328ce81765e094ab2a14ed7155624 | lib/httplib2/__init__.py | python | HTTPSConnectionWithTimeout._ValidateCertificateHostname | (self, cert, hostname) | return False | Validates that a given hostname is valid for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
hostname: The hostname to test.
Returns:
bool: Whether or not the hostname is valid for this certificate. | Validates that a given hostname is valid for an SSL certificate. | [
"Validates",
"that",
"a",
"given",
"hostname",
"is",
"valid",
"for",
"an",
"SSL",
"certificate",
"."
] | def _ValidateCertificateHostname(self, cert, hostname):
"""Validates that a given hostname is valid for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
hostname: The hostname to test.
Returns:
bool: Whether or not the hostname is valid for this certificate.
"""
hosts = self._GetValidHostsForCert(cert)
for host in hosts:
host_re = host.replace('.', '\.').replace('*', '[^.]*')
if re.search('^%s$' % (host_re,), hostname, re.I):
return True
return False | [
"def",
"_ValidateCertificateHostname",
"(",
"self",
",",
"cert",
",",
"hostname",
")",
":",
"hosts",
"=",
"self",
".",
"_GetValidHostsForCert",
"(",
"cert",
")",
"for",
"host",
"in",
"hosts",
":",
"host_re",
"=",
"host",
".",
"replace",
"(",
"'.'",
",",
... | https://github.com/lazylibrarian/LazyLibrarian/blob/ae3c14e9db9328ce81765e094ab2a14ed7155624/lib/httplib2/__init__.py#L1027-L1041 | |
google-research/pegasus | 649a5978e45a078e1574ed01c92fc12d3aa05f7f | pegasus/params/public_params.py | python | aeslc_transformer | (param_overrides) | return transformer_params(
{
"train_pattern": "tfds:aeslc-train",
"dev_pattern": "tfds:aeslc-validation",
"test_pattern": "tfds:aeslc-test",
"max_input_len": 512,
"max_output_len": 32,
"train_steps": 32000,
"learning_rate": 0.0001,
"batch_size": 8,
}, param_overrides) | [] | def aeslc_transformer(param_overrides):
return transformer_params(
{
"train_pattern": "tfds:aeslc-train",
"dev_pattern": "tfds:aeslc-validation",
"test_pattern": "tfds:aeslc-test",
"max_input_len": 512,
"max_output_len": 32,
"train_steps": 32000,
"learning_rate": 0.0001,
"batch_size": 8,
}, param_overrides) | [
"def",
"aeslc_transformer",
"(",
"param_overrides",
")",
":",
"return",
"transformer_params",
"(",
"{",
"\"train_pattern\"",
":",
"\"tfds:aeslc-train\"",
",",
"\"dev_pattern\"",
":",
"\"tfds:aeslc-validation\"",
",",
"\"test_pattern\"",
":",
"\"tfds:aeslc-test\"",
",",
"\... | https://github.com/google-research/pegasus/blob/649a5978e45a078e1574ed01c92fc12d3aa05f7f/pegasus/params/public_params.py#L151-L162 | |||
mesalock-linux/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | pypy/interpreter/function.py | python | descr_function_get | (space, w_function, w_obj, w_cls=None) | functionobject.__get__(obj[, type]) -> method | functionobject.__get__(obj[, type]) -> method | [
"functionobject",
".",
"__get__",
"(",
"obj",
"[",
"type",
"]",
")",
"-",
">",
"method"
] | def descr_function_get(space, w_function, w_obj, w_cls=None):
"""functionobject.__get__(obj[, type]) -> method"""
# this is not defined as a method on Function because it's generally
# useful logic: w_function can be any callable. It is used by Method too.
asking_for_bound = (space.is_none(w_cls) or
not space.is_w(w_obj, space.w_None) or
space.is_w(w_cls, space.type(space.w_None)))
if asking_for_bound:
return Method(space, w_function, w_obj, w_cls)
else:
return Method(space, w_function, None, w_cls) | [
"def",
"descr_function_get",
"(",
"space",
",",
"w_function",
",",
"w_obj",
",",
"w_cls",
"=",
"None",
")",
":",
"# this is not defined as a method on Function because it's generally",
"# useful logic: w_function can be any callable. It is used by Method too.",
"asking_for_bound",
... | https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/pypy/interpreter/function.py#L429-L439 | ||
ethereum/trinity | 6383280c5044feb06695ac2f7bc1100b7bcf4fe0 | trinity/_utils/datastructures.py | python | BaseTaskPrerequisites.task | (self) | return self._task | [] | def task(self) -> TTask:
return self._task | [
"def",
"task",
"(",
"self",
")",
"->",
"TTask",
":",
"return",
"self",
".",
"_task"
] | https://github.com/ethereum/trinity/blob/6383280c5044feb06695ac2f7bc1100b7bcf4fe0/trinity/_utils/datastructures.py#L293-L294 | |||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Parser/asdl_c.py | python | Obj2ModVisitor.isSimpleSum | (self, field) | return field.type.value in ('expr_context', 'boolop', 'operator',
'unaryop', 'cmpop') | [] | def isSimpleSum(self, field):
# XXX can the members of this list be determined automatically?
return field.type.value in ('expr_context', 'boolop', 'operator',
'unaryop', 'cmpop') | [
"def",
"isSimpleSum",
"(",
"self",
",",
"field",
")",
":",
"# XXX can the members of this list be determined automatically?",
"return",
"field",
".",
"type",
".",
"value",
"in",
"(",
"'expr_context'",
",",
"'boolop'",
",",
"'operator'",
",",
"'unaryop'",
",",
"'cmpo... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Parser/asdl_c.py#L477-L480 | |||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-1.4/django/db/models/options.py | python | Options.get_ancestor_link | (self, ancestor) | Returns the field on the current model which points to the given
"ancestor". This is possible an indirect link (a pointer to a parent
model, which points, eventually, to the ancestor). Used when
constructing table joins for model inheritance.
Returns None if the model isn't an ancestor of this one. | Returns the field on the current model which points to the given
"ancestor". This is possible an indirect link (a pointer to a parent
model, which points, eventually, to the ancestor). Used when
constructing table joins for model inheritance. | [
"Returns",
"the",
"field",
"on",
"the",
"current",
"model",
"which",
"points",
"to",
"the",
"given",
"ancestor",
".",
"This",
"is",
"possible",
"an",
"indirect",
"link",
"(",
"a",
"pointer",
"to",
"a",
"parent",
"model",
"which",
"points",
"eventually",
"t... | def get_ancestor_link(self, ancestor):
"""
Returns the field on the current model which points to the given
"ancestor". This is possible an indirect link (a pointer to a parent
model, which points, eventually, to the ancestor). Used when
constructing table joins for model inheritance.
Returns None if the model isn't an ancestor of this one.
"""
if ancestor in self.parents:
return self.parents[ancestor]
for parent in self.parents:
# Tries to get a link field from the immediate parent
parent_link = parent._meta.get_ancestor_link(ancestor)
if parent_link:
# In case of a proxied model, the first link
# of the chain to the ancestor is that parent
# links
return self.parents[parent] or parent_link | [
"def",
"get_ancestor_link",
"(",
"self",
",",
"ancestor",
")",
":",
"if",
"ancestor",
"in",
"self",
".",
"parents",
":",
"return",
"self",
".",
"parents",
"[",
"ancestor",
"]",
"for",
"parent",
"in",
"self",
".",
"parents",
":",
"# Tries to get a link field ... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/db/models/options.py#L480-L498 | ||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/min/mailbox.py | python | Mailbox.__setitem__ | (self, key, message) | Replace the keyed message; raise KeyError if it doesn't exist. | Replace the keyed message; raise KeyError if it doesn't exist. | [
"Replace",
"the",
"keyed",
"message",
";",
"raise",
"KeyError",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | def __setitem__(self, key, message):
"""Replace the keyed message; raise KeyError if it doesn't exist."""
raise NotImplementedError('Method must be implemented by subclass') | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"message",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Method must be implemented by subclass'",
")"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/mailbox.py#L60-L62 | ||
awslabs/mxboard | 432d4df2489ecf6dbb251d7f96f1ccadb368997a | python/mxboard/event_file_writer.py | python | EventFileWriter.reopen | (self) | Reopens the EventFileWriter.
Can be called after `close()` to add more events in the same directory.
The events will go into a new events file.
Does nothing if the `EventFileWriter` was not closed. | Reopens the EventFileWriter.
Can be called after `close()` to add more events in the same directory.
The events will go into a new events file.
Does nothing if the `EventFileWriter` was not closed. | [
"Reopens",
"the",
"EventFileWriter",
".",
"Can",
"be",
"called",
"after",
"close",
"()",
"to",
"add",
"more",
"events",
"in",
"the",
"same",
"directory",
".",
"The",
"events",
"will",
"go",
"into",
"a",
"new",
"events",
"file",
".",
"Does",
"nothing",
"i... | def reopen(self):
"""Reopens the EventFileWriter.
Can be called after `close()` to add more events in the same directory.
The events will go into a new events file.
Does nothing if the `EventFileWriter` was not closed.
"""
if self._closed:
self._worker = _EventLoggerThread(self._event_queue, self._ev_writer,
self._flush_secs, self._sentinel_event)
self._worker.start()
self._closed = False | [
"def",
"reopen",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_worker",
"=",
"_EventLoggerThread",
"(",
"self",
".",
"_event_queue",
",",
"self",
".",
"_ev_writer",
",",
"self",
".",
"_flush_secs",
",",
"self",
".",
"_sentinel_... | https://github.com/awslabs/mxboard/blob/432d4df2489ecf6dbb251d7f96f1ccadb368997a/python/mxboard/event_file_writer.py#L151-L161 | ||
Qirky/Troop | 529c5eb14e456f683e6d23fd4adcddc8446aa115 | src/interface/interface.py | python | Interface.key_up | (self) | return self.key_direction(self.move_marker_up) | Called when the up arrow key is pressed; decrases the local peer index
and updates the location of the label then sends a message to the server
with the new location | Called when the up arrow key is pressed; decrases the local peer index
and updates the location of the label then sends a message to the server
with the new location | [
"Called",
"when",
"the",
"up",
"arrow",
"key",
"is",
"pressed",
";",
"decrases",
"the",
"local",
"peer",
"index",
"and",
"updates",
"the",
"location",
"of",
"the",
"label",
"then",
"sends",
"a",
"message",
"to",
"the",
"server",
"with",
"the",
"new",
"lo... | def key_up(self):
""" Called when the up arrow key is pressed; decrases the local peer index
and updates the location of the label then sends a message to the server
with the new location """
return self.key_direction(self.move_marker_up) | [
"def",
"key_up",
"(",
"self",
")",
":",
"return",
"self",
".",
"key_direction",
"(",
"self",
".",
"move_marker_up",
")"
] | https://github.com/Qirky/Troop/blob/529c5eb14e456f683e6d23fd4adcddc8446aa115/src/interface/interface.py#L824-L828 | |
SpockBotMC/SpockBot | f89911551f18357720034fbaa52837a0d09f66ea | spockbot/mcp/datautils.py | python | unpack_fixed_point | (mc_type, bbuff) | return val | [] | def unpack_fixed_point(mc_type, bbuff):
val = unpack(mc_type, bbuff)
val = float(val) / (1 << 5)
return val | [
"def",
"unpack_fixed_point",
"(",
"mc_type",
",",
"bbuff",
")",
":",
"val",
"=",
"unpack",
"(",
"mc_type",
",",
"bbuff",
")",
"val",
"=",
"float",
"(",
"val",
")",
"/",
"(",
"1",
"<<",
"5",
")",
"return",
"val"
] | https://github.com/SpockBotMC/SpockBot/blob/f89911551f18357720034fbaa52837a0d09f66ea/spockbot/mcp/datautils.py#L105-L108 | |||
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/plat-irix5/torgb.py | python | torgb | (filename) | return ret | [] | def torgb(filename):
temps = []
ret = None
try:
ret = _torgb(filename, temps)
finally:
for temp in temps[:]:
if temp != ret:
try:
os.unlink(temp)
except os.error:
pass
temps.remove(temp)
return ret | [
"def",
"torgb",
"(",
"filename",
")",
":",
"temps",
"=",
"[",
"]",
"ret",
"=",
"None",
"try",
":",
"ret",
"=",
"_torgb",
"(",
"filename",
",",
"temps",
")",
"finally",
":",
"for",
"temp",
"in",
"temps",
"[",
":",
"]",
":",
"if",
"temp",
"!=",
"... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/plat-irix5/torgb.py#L59-L72 | |||
mesonbuild/meson | a22d0f9a0a787df70ce79b05d0c45de90a970048 | mesonbuild/interpreter/compiler.py | python | CompilerHolder.first_supported_argument_method | (self, args: T.Tuple[T.List[str]], kwargs: 'TYPE_kwargs') | return [] | [] | def first_supported_argument_method(self, args: T.Tuple[T.List[str]], kwargs: 'TYPE_kwargs') -> T.List[str]:
for arg in args[0]:
if self._has_argument_impl([arg]):
mlog.log('First supported argument:', mlog.bold(arg))
return [arg]
mlog.log('First supported argument:', mlog.red('None'))
return [] | [
"def",
"first_supported_argument_method",
"(",
"self",
",",
"args",
":",
"T",
".",
"Tuple",
"[",
"T",
".",
"List",
"[",
"str",
"]",
"]",
",",
"kwargs",
":",
"'TYPE_kwargs'",
")",
"->",
"T",
".",
"List",
"[",
"str",
"]",
":",
"for",
"arg",
"in",
"ar... | https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/interpreter/compiler.py#L679-L685 | |||
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/idlelib/ScrolledList.py | python | ScrolledList.make_menu | (self) | [] | def make_menu(self):
menu = Menu(self.listbox, tearoff=0)
self.menu = menu
self.fill_menu() | [
"def",
"make_menu",
"(",
"self",
")",
":",
"menu",
"=",
"Menu",
"(",
"self",
".",
"listbox",
",",
"tearoff",
"=",
"0",
")",
"self",
".",
"menu",
"=",
"menu",
"self",
".",
"fill_menu",
"(",
")"
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/idlelib/ScrolledList.py#L77-L80 | ||||
pulb/mailnag | 7ef91050cf3ccea2eeca13aefdbac29716806487 | Mailnag/common/imaplib2.py | python | IMAP4.namespace | (self, **kw) | return self._simple_command(name, **kw) | (typ, [data, ...]) = namespace()
Returns IMAP namespaces ala rfc2342. | (typ, [data, ...]) = namespace()
Returns IMAP namespaces ala rfc2342. | [
"(",
"typ",
"[",
"data",
"...",
"]",
")",
"=",
"namespace",
"()",
"Returns",
"IMAP",
"namespaces",
"ala",
"rfc2342",
"."
] | def namespace(self, **kw):
"""(typ, [data, ...]) = namespace()
Returns IMAP namespaces ala rfc2342."""
name = 'NAMESPACE'
kw['untagged_response'] = name
return self._simple_command(name, **kw) | [
"def",
"namespace",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"name",
"=",
"'NAMESPACE'",
"kw",
"[",
"'untagged_response'",
"]",
"=",
"name",
"return",
"self",
".",
"_simple_command",
"(",
"name",
",",
"*",
"*",
"kw",
")"
] | https://github.com/pulb/mailnag/blob/7ef91050cf3ccea2eeca13aefdbac29716806487/Mailnag/common/imaplib2.py#L968-L974 | |
ondyari/FaceForensics | b952e41cba017eb37593c39e12bd884a934791e1 | dataset/DeepFakes/faceswap-master/lib/face_alignment/extractor.py | python | Extract.get_bounding_boxes | (self) | return bounding_boxes | Return the corner points of the bounding box scaled
to original image | Return the corner points of the bounding box scaled
to original image | [
"Return",
"the",
"corner",
"points",
"of",
"the",
"bounding",
"box",
"scaled",
"to",
"original",
"image"
] | def get_bounding_boxes(self):
""" Return the corner points of the bounding box scaled
to original image """
bounding_boxes = list()
for d_rect in self.detector.detected_faces:
d_rect = self.convert_to_dlib_rectangle(d_rect)
bounding_box = {
'left': int(d_rect.left() / self.frame.input_scale),
'top': int(d_rect.top() / self.frame.input_scale),
'right': int(d_rect.right() / self.frame.input_scale),
'bottom': int(d_rect.bottom() / self.frame.input_scale)}
bounding_boxes.append(bounding_box)
return bounding_boxes | [
"def",
"get_bounding_boxes",
"(",
"self",
")",
":",
"bounding_boxes",
"=",
"list",
"(",
")",
"for",
"d_rect",
"in",
"self",
".",
"detector",
".",
"detected_faces",
":",
"d_rect",
"=",
"self",
".",
"convert_to_dlib_rectangle",
"(",
"d_rect",
")",
"bounding_box"... | https://github.com/ondyari/FaceForensics/blob/b952e41cba017eb37593c39e12bd884a934791e1/dataset/DeepFakes/faceswap-master/lib/face_alignment/extractor.py#L330-L342 | |
merkremont/LineVodka | c2fa74107cecf00dd17416b62e4eb579e2c7bbaf | LineAlpha/LineThrift/TalkService.py | python | Iface.registerDeviceWithoutPhoneNumber | (self, region, udidHash, deviceInfo) | Parameters:
- region
- udidHash
- deviceInfo | Parameters:
- region
- udidHash
- deviceInfo | [
"Parameters",
":",
"-",
"region",
"-",
"udidHash",
"-",
"deviceInfo"
] | def registerDeviceWithoutPhoneNumber(self, region, udidHash, deviceInfo):
"""
Parameters:
- region
- udidHash
- deviceInfo
"""
pass | [
"def",
"registerDeviceWithoutPhoneNumber",
"(",
"self",
",",
"region",
",",
"udidHash",
",",
"deviceInfo",
")",
":",
"pass"
] | https://github.com/merkremont/LineVodka/blob/c2fa74107cecf00dd17416b62e4eb579e2c7bbaf/LineAlpha/LineThrift/TalkService.py#L832-L839 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_process.py | python | OpenShiftCLI._replace_content | (self, resource, rname, content, edits=None, force=False, sep='.') | return {'returncode': 0, 'updated': False} | replace the current object with the content | replace the current object with the content | [
"replace",
"the",
"current",
"object",
"with",
"the",
"content"
] | def _replace_content(self, resource, rname, content, edits=None, force=False, sep='.'):
''' replace the current object with the content '''
res = self._get(resource, rname)
if not res['results']:
return res
fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, res['results'][0], separator=sep)
updated = False
if content is not None:
changes = []
for key, value in content.items():
changes.append(yed.put(key, value))
if any([change[0] for change in changes]):
updated = True
elif edits is not None:
results = Yedit.process_edits(edits, yed)
if results['changed']:
updated = True
if updated:
yed.write()
atexit.register(Utils.cleanup, [fname])
return self._replace(fname, force)
return {'returncode': 0, 'updated': False} | [
"def",
"_replace_content",
"(",
"self",
",",
"resource",
",",
"rname",
",",
"content",
",",
"edits",
"=",
"None",
",",
"force",
"=",
"False",
",",
"sep",
"=",
"'.'",
")",
":",
"res",
"=",
"self",
".",
"_get",
"(",
"resource",
",",
"rname",
")",
"if... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_process.py#L897-L928 | |
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/preview/understand/assistant/query.py | python | QueryInstance.update | (self, sample_sid=values.unset, status=values.unset) | return self._proxy.update(sample_sid=sample_sid, status=status, ) | Update the QueryInstance
:param unicode sample_sid: An optional reference to the Sample created from this query.
:param unicode status: A string that described the query status. The values can be: pending_review, reviewed, discarded
:returns: The updated QueryInstance
:rtype: twilio.rest.preview.understand.assistant.query.QueryInstance | Update the QueryInstance | [
"Update",
"the",
"QueryInstance"
] | def update(self, sample_sid=values.unset, status=values.unset):
"""
Update the QueryInstance
:param unicode sample_sid: An optional reference to the Sample created from this query.
:param unicode status: A string that described the query status. The values can be: pending_review, reviewed, discarded
:returns: The updated QueryInstance
:rtype: twilio.rest.preview.understand.assistant.query.QueryInstance
"""
return self._proxy.update(sample_sid=sample_sid, status=status, ) | [
"def",
"update",
"(",
"self",
",",
"sample_sid",
"=",
"values",
".",
"unset",
",",
"status",
"=",
"values",
".",
"unset",
")",
":",
"return",
"self",
".",
"_proxy",
".",
"update",
"(",
"sample_sid",
"=",
"sample_sid",
",",
"status",
"=",
"status",
",",... | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/preview/understand/assistant/query.py#L489-L499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.