repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
oscarbranson/latools | latools/latools.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/latools.py#L2594-L2668 | def optimise_signal(self, analytes, min_points=5,
threshold_mode='kde_first_max',
threshold_mult=1., x_bias=0, filt=True,
weights=None, mode='minimise',
samples=None, subset=None):
"""
Optimise data selectio... | [
"def",
"optimise_signal",
"(",
"self",
",",
"analytes",
",",
"min_points",
"=",
"5",
",",
"threshold_mode",
"=",
"'kde_first_max'",
",",
"threshold_mult",
"=",
"1.",
",",
"x_bias",
"=",
"0",
",",
"filt",
"=",
"True",
",",
"weights",
"=",
"None",
",",
"mo... | Optimise data selection based on specified analytes.
Identifies the longest possible contiguous data region in
the signal where the relative standard deviation (std) and
concentration of all analytes is minimised.
Optimisation is performed via a grid search of all possible
con... | [
"Optimise",
"data",
"selection",
"based",
"on",
"specified",
"analytes",
"."
] | python | test |
apache/spark | python/pyspark/mllib/linalg/__init__.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/linalg/__init__.py#L86-L118 | def _vector_size(v):
"""
Returns the size of the vector.
>>> _vector_size([1., 2., 3.])
3
>>> _vector_size((1., 2., 3.))
3
>>> _vector_size(array.array('d', [1., 2., 3.]))
3
>>> _vector_size(np.zeros(3))
3
>>> _vector_size(np.zeros((3, 1)))
3
>>> _vector_size(np.zero... | [
"def",
"_vector_size",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"Vector",
")",
":",
"return",
"len",
"(",
"v",
")",
"elif",
"type",
"(",
"v",
")",
"in",
"(",
"array",
".",
"array",
",",
"list",
",",
"tuple",
",",
"xrange",
")",
":... | Returns the size of the vector.
>>> _vector_size([1., 2., 3.])
3
>>> _vector_size((1., 2., 3.))
3
>>> _vector_size(array.array('d', [1., 2., 3.]))
3
>>> _vector_size(np.zeros(3))
3
>>> _vector_size(np.zeros((3, 1)))
3
>>> _vector_size(np.zeros((1, 3)))
Traceback (most re... | [
"Returns",
"the",
"size",
"of",
"the",
"vector",
"."
] | python | train |
onnx/onnx | onnx/__init__.py | https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/__init__.py#L102-L122 | def load_model(f, format=None, load_external_data=True): # type: (Union[IO[bytes], Text], Optional[Any], bool) -> ModelProto
'''
Loads a serialized ModelProto into memory
@params
f can be a file-like object (has "read" function) or a string containing a file name
format is for future use
@ret... | [
"def",
"load_model",
"(",
"f",
",",
"format",
"=",
"None",
",",
"load_external_data",
"=",
"True",
")",
":",
"# type: (Union[IO[bytes], Text], Optional[Any], bool) -> ModelProto",
"s",
"=",
"_load_bytes",
"(",
"f",
")",
"model",
"=",
"load_model_from_string",
"(",
"... | Loads a serialized ModelProto into memory
@params
f can be a file-like object (has "read" function) or a string containing a file name
format is for future use
@return
Loaded in-memory ModelProto | [
"Loads",
"a",
"serialized",
"ModelProto",
"into",
"memory"
] | python | train |
funilrys/PyFunceble | PyFunceble/generate.py | https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/generate.py#L652-L706 | def _prints_status_screen(self):
"""
Logic behind the printing (on screen) when generating status file.
"""
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
if PyFunceble.CONFIGURATION["less"]:
# We have to print less ... | [
"def",
"_prints_status_screen",
"(",
"self",
")",
":",
"if",
"not",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"quiet\"",
"]",
":",
"# The quiet mode is not activated.",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"less\"",
"]",
":",
"# We have to print less info... | Logic behind the printing (on screen) when generating status file. | [
"Logic",
"behind",
"the",
"printing",
"(",
"on",
"screen",
")",
"when",
"generating",
"status",
"file",
"."
] | python | test |
theislab/scanpy | scanpy/plotting/_utils.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/plotting/_utils.py#L27-L41 | def matrix(matrix, xlabel=None, ylabel=None, xticks=None, yticks=None,
title=None, colorbar_shrink=0.5, color_map=None, show=None,
save=None, ax=None):
"""Plot a matrix."""
if ax is None: ax = pl.gca()
img = ax.imshow(matrix, cmap=color_map)
if xlabel is not None: ax.set_xlabel(xla... | [
"def",
"matrix",
"(",
"matrix",
",",
"xlabel",
"=",
"None",
",",
"ylabel",
"=",
"None",
",",
"xticks",
"=",
"None",
",",
"yticks",
"=",
"None",
",",
"title",
"=",
"None",
",",
"colorbar_shrink",
"=",
"0.5",
",",
"color_map",
"=",
"None",
",",
"show",... | Plot a matrix. | [
"Plot",
"a",
"matrix",
"."
] | python | train |
rndmcnlly/ansunit | ansunit/__init__.py | https://github.com/rndmcnlly/ansunit/blob/3d45e22ab1ae131b6eda25d5ae2ead2c5cfee02a/ansunit/__init__.py#L78-L95 | def canonicalize_spec(spec, parent_context):
"""Push all context declarations to the leaves of a nested test specification."""
test_specs = {k:v for (k,v) in spec.items() if k.startswith("Test")}
local_context = {k:v for (k,v) in spec.items() if not k.startswith("Test")}
context = reduce_contexts(parent_conte... | [
"def",
"canonicalize_spec",
"(",
"spec",
",",
"parent_context",
")",
":",
"test_specs",
"=",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"spec",
".",
"items",
"(",
")",
"if",
"k",
".",
"startswith",
"(",
"\"Test\"",
")",
"}",
"local_c... | Push all context declarations to the leaves of a nested test specification. | [
"Push",
"all",
"context",
"declarations",
"to",
"the",
"leaves",
"of",
"a",
"nested",
"test",
"specification",
"."
] | python | train |
geopy/geopy | geopy/geocoders/openmapquest.py | https://github.com/geopy/geopy/blob/02c838d965e76497f3c3d61f53808c86b5c58224/geopy/geocoders/openmapquest.py#L117-L129 | def _construct_url(self, base_api, params):
"""
Construct geocoding request url. Overridden.
:param str base_api: Geocoding function base address - self.api
or self.reverse_api.
:param dict params: Geocoding params.
:return: string URL.
"""
params['... | [
"def",
"_construct_url",
"(",
"self",
",",
"base_api",
",",
"params",
")",
":",
"params",
"[",
"'key'",
"]",
"=",
"self",
".",
"api_key",
"return",
"super",
"(",
"OpenMapQuest",
",",
"self",
")",
".",
"_construct_url",
"(",
"base_api",
",",
"params",
")"... | Construct geocoding request url. Overridden.
:param str base_api: Geocoding function base address - self.api
or self.reverse_api.
:param dict params: Geocoding params.
:return: string URL. | [
"Construct",
"geocoding",
"request",
"url",
".",
"Overridden",
"."
] | python | train |
DataBiosphere/toil | src/toil/provisioners/clusterScaler.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/provisioners/clusterScaler.py#L565-L630 | def setNodeCount(self, nodeType, numNodes, preemptable=False, force=False):
"""
Attempt to grow or shrink the number of preemptable or non-preemptable worker nodes in
the cluster to the given value, or as close a value as possible, and, after performing
the necessary additions or removal... | [
"def",
"setNodeCount",
"(",
"self",
",",
"nodeType",
",",
"numNodes",
",",
"preemptable",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"for",
"attempt",
"in",
"retry",
"(",
"predicate",
"=",
"self",
".",
"provisioner",
".",
"retryPredicate",
")",
... | Attempt to grow or shrink the number of preemptable or non-preemptable worker nodes in
the cluster to the given value, or as close a value as possible, and, after performing
the necessary additions or removals of worker nodes, return the resulting number of
preemptable or non-preemptable nodes c... | [
"Attempt",
"to",
"grow",
"or",
"shrink",
"the",
"number",
"of",
"preemptable",
"or",
"non",
"-",
"preemptable",
"worker",
"nodes",
"in",
"the",
"cluster",
"to",
"the",
"given",
"value",
"or",
"as",
"close",
"a",
"value",
"as",
"possible",
"and",
"after",
... | python | train |
CityOfZion/neo-python | neo/Core/TX/InvocationTransaction.py | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/TX/InvocationTransaction.py#L91-L101 | def ToJson(self):
"""
Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict:
"""
jsn = super(InvocationTransaction, self).ToJson()
jsn['script'] = self.Script.hex()
jsn['gas'] = self.Gas.ToNeoJsonString()
return jsn | [
"def",
"ToJson",
"(",
"self",
")",
":",
"jsn",
"=",
"super",
"(",
"InvocationTransaction",
",",
"self",
")",
".",
"ToJson",
"(",
")",
"jsn",
"[",
"'script'",
"]",
"=",
"self",
".",
"Script",
".",
"hex",
"(",
")",
"jsn",
"[",
"'gas'",
"]",
"=",
"s... | Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict: | [
"Convert",
"object",
"members",
"to",
"a",
"dictionary",
"that",
"can",
"be",
"parsed",
"as",
"JSON",
"."
] | python | train |
astropy/astropy-healpix | astropy_healpix/core.py | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L108-L130 | def nside_to_level(nside):
"""
Find the HEALPix level for a given nside.
This is given by ``level = log2(nside)``.
This function is the inverse of `level_to_nside`.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
... | [
"def",
"nside_to_level",
"(",
"nside",
")",
":",
"nside",
"=",
"np",
".",
"asarray",
"(",
"nside",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"_validate_nside",
"(",
"nside",
")",
"return",
"np",
".",
"log2",
"(",
"nside",
")",
".",
"astype",
"(",
... | Find the HEALPix level for a given nside.
This is given by ``level = log2(nside)``.
This function is the inverse of `level_to_nside`.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Must be a power of two.
Returns... | [
"Find",
"the",
"HEALPix",
"level",
"for",
"a",
"given",
"nside",
"."
] | python | train |
todddeluca/dones | dones.py | https://github.com/todddeluca/dones/blob/6ef56565556987e701fed797a405f0825fe2e15a/dones.py#L468-L476 | def remove(self, key):
'''
remove key from the namespace. it is fine to remove a key multiple times.
'''
encodedKey = json.dumps(key)
sql = 'DELETE FROM ' + self.table + ' WHERE name = %s'
with self.connect() as conn:
with doTransaction(conn):
... | [
"def",
"remove",
"(",
"self",
",",
"key",
")",
":",
"encodedKey",
"=",
"json",
".",
"dumps",
"(",
"key",
")",
"sql",
"=",
"'DELETE FROM '",
"+",
"self",
".",
"table",
"+",
"' WHERE name = %s'",
"with",
"self",
".",
"connect",
"(",
")",
"as",
"conn",
... | remove key from the namespace. it is fine to remove a key multiple times. | [
"remove",
"key",
"from",
"the",
"namespace",
".",
"it",
"is",
"fine",
"to",
"remove",
"a",
"key",
"multiple",
"times",
"."
] | python | train |
HumanBrainProject/hbp-service-client | hbp_service_client/request/request_builder.py | https://github.com/HumanBrainProject/hbp-service-client/blob/b338fb41a7f0e7b9d654ff28fcf13a56d03bff4d/hbp_service_client/request/request_builder.py#L115-L126 | def with_headers(self, headers):
'''Adds headers to the request
Args:
headers (dict): The headers to add the request headers
Returns:
The request builder instance in order to chain calls
'''
copy = headers.copy()
copy.update(self._headers)
... | [
"def",
"with_headers",
"(",
"self",
",",
"headers",
")",
":",
"copy",
"=",
"headers",
".",
"copy",
"(",
")",
"copy",
".",
"update",
"(",
"self",
".",
"_headers",
")",
"return",
"self",
".",
"__copy_and_set",
"(",
"'headers'",
",",
"copy",
")"
] | Adds headers to the request
Args:
headers (dict): The headers to add the request headers
Returns:
The request builder instance in order to chain calls | [
"Adds",
"headers",
"to",
"the",
"request"
] | python | test |
explosion/thinc | thinc/extra/_vendorized/keras_data_utils.py | https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/thinc/extra/_vendorized/keras_data_utils.py#L146-L163 | def validate_file(fpath, md5_hash):
'''Validates a file against a MD5 hash
# Arguments
fpath: path to the file being validated
md5_hash: the MD5 hash being validated against
# Returns
Whether the file is valid
'''
hasher = hashlib.md5()
with open(fpath, 'rb') as f:
... | [
"def",
"validate_file",
"(",
"fpath",
",",
"md5_hash",
")",
":",
"hasher",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"fpath",
",",
"'rb'",
")",
"as",
"f",
":",
"buf",
"=",
"f",
".",
"read",
"(",
")",
"hasher",
".",
"update",
"(",... | Validates a file against a MD5 hash
# Arguments
fpath: path to the file being validated
md5_hash: the MD5 hash being validated against
# Returns
Whether the file is valid | [
"Validates",
"a",
"file",
"against",
"a",
"MD5",
"hash"
] | python | train |
mugurbil/gnm | gnm/gnm.py | https://github.com/mugurbil/gnm/blob/4f9711fb9d78cc02820c25234bc3ab9615014f11/gnm/gnm.py#L197-L222 | def dynamic(self, max_steps, opts={}):
"""
Dynamic Switch
Set the sampler parameters for dynamic back off
Inputs :
max_steps :
maximum back-off steps to be taken
Optional Inputs:
opts : ({})
dictionary containing fancy options
"""
self._dy... | [
"def",
"dynamic",
"(",
"self",
",",
"max_steps",
",",
"opts",
"=",
"{",
"}",
")",
":",
"self",
".",
"_dynamic",
"=",
"True",
"# begin checks ",
"try",
":",
"self",
".",
"_max_steps",
"=",
"int",
"(",
"max_steps",
")",
"except",
":",
"raise",
"Type... | Dynamic Switch
Set the sampler parameters for dynamic back off
Inputs :
max_steps :
maximum back-off steps to be taken
Optional Inputs:
opts : ({})
dictionary containing fancy options | [
"Dynamic",
"Switch",
"Set",
"the",
"sampler",
"parameters",
"for",
"dynamic",
"back",
"off",
"Inputs",
":",
"max_steps",
":",
"maximum",
"back",
"-",
"off",
"steps",
"to",
"be",
"taken",
"Optional",
"Inputs",
":",
"opts",
":",
"(",
"{}",
")",
"dictionary",... | python | train |
Wessie/hurler | hurler/filters.py | https://github.com/Wessie/hurler/blob/5719000237e24df9f24fb8229f1153ebfa684972/hurler/filters.py#L48-L61 | def check_filter(self, args, kwargs):
"""
Calls all filters in the :attr:`_filters` list and if all of them
return :const:`True` will return :const:`True`. If any of the filters
return :const:`False` will return :const:`True` instead.
This method is equal to the following snippe... | [
"def",
"check_filter",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"for",
"f",
"in",
"self",
".",
"_filters",
":",
"if",
"not",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"False",
"return",
"True"
] | Calls all filters in the :attr:`_filters` list and if all of them
return :const:`True` will return :const:`True`. If any of the filters
return :const:`False` will return :const:`True` instead.
This method is equal to the following snippet:
`all(f(*args, **kwargs) for f in self.filte... | [
"Calls",
"all",
"filters",
"in",
"the",
":",
"attr",
":",
"_filters",
"list",
"and",
"if",
"all",
"of",
"them",
"return",
":",
"const",
":",
"True",
"will",
"return",
":",
"const",
":",
"True",
".",
"If",
"any",
"of",
"the",
"filters",
"return",
":",... | python | train |
openego/eDisGo | edisgo/grid/network.py | https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/grid/network.py#L2161-L2175 | def generation_dispatchable(self):
"""
Get generation time series of dispatchable generators (only active
power)
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
See class definition for details.
"""
try:
return self._generat... | [
"def",
"generation_dispatchable",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_generation_dispatchable",
".",
"loc",
"[",
"[",
"self",
".",
"timeindex",
"]",
",",
":",
"]",
"except",
":",
"return",
"self",
".",
"_generation_dispatchable",
".",... | Get generation time series of dispatchable generators (only active
power)
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
See class definition for details. | [
"Get",
"generation",
"time",
"series",
"of",
"dispatchable",
"generators",
"(",
"only",
"active",
"power",
")"
] | python | train |
shawnsilva/steamwebapi | steamwebapi/api.py | https://github.com/shawnsilva/steamwebapi/blob/dc16538ebe985cc7ea170f660169ebc2366efbf2/steamwebapi/api.py#L106-L120 | def get_friends_list(self, steamID, relationship='all', format=None):
"""Request the friends list of a given steam ID filtered by role.
steamID: The user ID
relationship: Type of friend to request (all, friend)
format: Return format. None defaults to json. (json, xml, vdf)
"""
... | [
"def",
"get_friends_list",
"(",
"self",
",",
"steamID",
",",
"relationship",
"=",
"'all'",
",",
"format",
"=",
"None",
")",
":",
"parameters",
"=",
"{",
"'steamid'",
":",
"steamID",
",",
"'relationship'",
":",
"relationship",
"}",
"if",
"format",
"is",
"no... | Request the friends list of a given steam ID filtered by role.
steamID: The user ID
relationship: Type of friend to request (all, friend)
format: Return format. None defaults to json. (json, xml, vdf) | [
"Request",
"the",
"friends",
"list",
"of",
"a",
"given",
"steam",
"ID",
"filtered",
"by",
"role",
"."
] | python | train |
softlayer/softlayer-python | SoftLayer/CLI/block/snapshot/list.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/snapshot/list.py#L38-L53 | def cli(env, volume_id, sortby, columns):
"""List block storage snapshots."""
block_manager = SoftLayer.BlockStorageManager(env.client)
snapshots = block_manager.get_block_volume_snapshot_list(
volume_id,
mask=columns.mask()
)
table = formatting.Table(columns.columns)
table.sort... | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"sortby",
",",
"columns",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"snapshots",
"=",
"block_manager",
".",
"get_block_volume_snapshot_list",
"(",
"... | List block storage snapshots. | [
"List",
"block",
"storage",
"snapshots",
"."
] | python | train |
fastai/fastai | old/fastai/plots.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/plots.py#L119-L132 | def most_by_mask(self, mask, y, mult):
""" Extracts the first 4 most correct/incorrect indexes from the ordered list of probabilities
Arguments:
mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contain... | [
"def",
"most_by_mask",
"(",
"self",
",",
"mask",
",",
"y",
",",
"mult",
")",
":",
"idxs",
"=",
"np",
".",
"where",
"(",
"mask",
")",
"[",
"0",
"]",
"cnt",
"=",
"min",
"(",
"4",
",",
"len",
"(",
"idxs",
")",
")",
"return",
"idxs",
"[",
"np",
... | Extracts the first 4 most correct/incorrect indexes from the ordered list of probabilities
Arguments:
mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False every... | [
"Extracts",
"the",
"first",
"4",
"most",
"correct",
"/",
"incorrect",
"indexes",
"from",
"the",
"ordered",
"list",
"of",
"probabilities"
] | python | train |
bitesofcode/projexui | projexui/windows/xdkwindow/xdkwindow.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L220-L244 | def addContentsWidget( self ):
"""
Adds a new contents widget tab into the contents tab.
:return <QWebView>
"""
curr_widget = self.currentContentsWidget()
widget = QWebView(self)
page = widget.page()
page.setLinkDelegationPolicy(page.... | [
"def",
"addContentsWidget",
"(",
"self",
")",
":",
"curr_widget",
"=",
"self",
".",
"currentContentsWidget",
"(",
")",
"widget",
"=",
"QWebView",
"(",
"self",
")",
"page",
"=",
"widget",
".",
"page",
"(",
")",
"page",
".",
"setLinkDelegationPolicy",
"(",
"... | Adds a new contents widget tab into the contents tab.
:return <QWebView> | [
"Adds",
"a",
"new",
"contents",
"widget",
"tab",
"into",
"the",
"contents",
"tab",
".",
":",
"return",
"<QWebView",
">"
] | python | train |
mlperf/training | translation/tensorflow/transformer/utils/metrics.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/metrics.py#L288-L304 | def rouge_2_fscore(logits, labels):
"""ROUGE-2 F1 score computation between labels and predictions.
This is an approximate ROUGE scoring method since we do not glue word pieces
or decode the ids and tokenize the output.
Args:
logits: tensor, model predictions
labels: tensor, gold output.
Returns:
... | [
"def",
"rouge_2_fscore",
"(",
"logits",
",",
"labels",
")",
":",
"predictions",
"=",
"tf",
".",
"to_int32",
"(",
"tf",
".",
"argmax",
"(",
"logits",
",",
"axis",
"=",
"-",
"1",
")",
")",
"# TODO: Look into removing use of py_func",
"rouge_2_f_score",
"=",
"t... | ROUGE-2 F1 score computation between labels and predictions.
This is an approximate ROUGE scoring method since we do not glue word pieces
or decode the ids and tokenize the output.
Args:
logits: tensor, model predictions
labels: tensor, gold output.
Returns:
rouge2_fscore: approx rouge-2 f1 score... | [
"ROUGE",
"-",
"2",
"F1",
"score",
"computation",
"between",
"labels",
"and",
"predictions",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/authorization/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/authorization/sessions.py#L2113-L2134 | def unassign_authorization_from_vault(self, authorization_id, vault_id):
"""Removes an ``Authorization`` from a ``Vault``.
arg: authorization_id (osid.id.Id): the ``Id`` of the
``Authorization``
arg: vault_id (osid.id.Id): the ``Id`` of the ``Vault``
raise: NotFou... | [
"def",
"unassign_authorization_from_vault",
"(",
"self",
",",
"authorization_id",
",",
"vault_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinAssignmentSession.unassign_resource_from_bin",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
"'AUTH... | Removes an ``Authorization`` from a ``Vault``.
arg: authorization_id (osid.id.Id): the ``Id`` of the
``Authorization``
arg: vault_id (osid.id.Id): the ``Id`` of the ``Vault``
raise: NotFound - ``authorization_id`` or ``vault_id`` not
found or ``authorizati... | [
"Removes",
"an",
"Authorization",
"from",
"a",
"Vault",
"."
] | python | train |
couchbase/couchbase-python-client | couchbase/subdocument.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/subdocument.py#L184-L200 | def array_prepend(path, *values, **kwargs):
"""
Add new values to the beginning of an array.
:param path: Path to the array. The path should contain the *array itself*
and not an element *within* the array
:param values: one or more values to append
:param create_parents: Create the array i... | [
"def",
"array_prepend",
"(",
"path",
",",
"*",
"values",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gen_4spec",
"(",
"LCB_SDCMD_ARRAY_ADD_FIRST",
",",
"path",
",",
"MultiValue",
"(",
"*",
"values",
")",
",",
"create_path",
"=",
"kwargs",
".",
"pop",
... | Add new values to the beginning of an array.
:param path: Path to the array. The path should contain the *array itself*
and not an element *within* the array
:param values: one or more values to append
:param create_parents: Create the array if it does not exist
This operation is only valid in... | [
"Add",
"new",
"values",
"to",
"the",
"beginning",
"of",
"an",
"array",
"."
] | python | train |
pysathq/pysat | pysat/solvers.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L3357-L3364 | def get_core(self):
"""
Get an unsatisfiable core if the formula was previously
unsatisfied.
"""
if self.minisat and self.status == False:
return pysolvers.minisatgh_core(self.minisat) | [
"def",
"get_core",
"(",
"self",
")",
":",
"if",
"self",
".",
"minisat",
"and",
"self",
".",
"status",
"==",
"False",
":",
"return",
"pysolvers",
".",
"minisatgh_core",
"(",
"self",
".",
"minisat",
")"
] | Get an unsatisfiable core if the formula was previously
unsatisfied. | [
"Get",
"an",
"unsatisfiable",
"core",
"if",
"the",
"formula",
"was",
"previously",
"unsatisfied",
"."
] | python | train |
stanfordnlp/stanza | stanza/research/config.py | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/config.py#L88-L130 | def options(allow_partial=False, read=False):
'''
Get the object containing the values of the parsed command line options.
:param bool allow_partial: If `True`, ignore unrecognized arguments and allow
the options to be re-parsed next time `options` is called. This
also suppresses overwrite ... | [
"def",
"options",
"(",
"allow_partial",
"=",
"False",
",",
"read",
"=",
"False",
")",
":",
"global",
"_options",
"if",
"allow_partial",
":",
"opts",
",",
"extras",
"=",
"_options_parser",
".",
"parse_known_args",
"(",
")",
"if",
"opts",
".",
"run_dir",
":"... | Get the object containing the values of the parsed command line options.
:param bool allow_partial: If `True`, ignore unrecognized arguments and allow
the options to be re-parsed next time `options` is called. This
also suppresses overwrite checking (the check is performed the first
time `o... | [
"Get",
"the",
"object",
"containing",
"the",
"values",
"of",
"the",
"parsed",
"command",
"line",
"options",
"."
] | python | train |
kervi/kervi-devices | kervi/devices/gpio/MCP230XX.py | https://github.com/kervi/kervi-devices/blob/c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56/kervi/devices/gpio/MCP230XX.py#L116-L125 | def pullup(self, pin, enabled):
"""Turn on the pull-up resistor for the specified pin if enabled is True,
otherwise turn off the pull-up resistor.
"""
self._validate_channel(pin)
if enabled:
self.gppu[int(pin/8)] |= 1 << (int(pin%8))
else:
self.gpp... | [
"def",
"pullup",
"(",
"self",
",",
"pin",
",",
"enabled",
")",
":",
"self",
".",
"_validate_channel",
"(",
"pin",
")",
"if",
"enabled",
":",
"self",
".",
"gppu",
"[",
"int",
"(",
"pin",
"/",
"8",
")",
"]",
"|=",
"1",
"<<",
"(",
"int",
"(",
"pin... | Turn on the pull-up resistor for the specified pin if enabled is True,
otherwise turn off the pull-up resistor. | [
"Turn",
"on",
"the",
"pull",
"-",
"up",
"resistor",
"for",
"the",
"specified",
"pin",
"if",
"enabled",
"is",
"True",
"otherwise",
"turn",
"off",
"the",
"pull",
"-",
"up",
"resistor",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/assessment_authoring/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment_authoring/sessions.py#L2143-L2165 | def get_sequence_rules_by_genus_type(self, sequence_rule_genus_type):
"""Gets a ``SequenceRuleList`` corresponding to the given sequence rule genus ``Type`` which does not include sequence rule of genus types derived from the specified ``Type``.
arg: sequence_rule_genus_type (osid.type.Type): a sequ... | [
"def",
"get_sequence_rules_by_genus_type",
"(",
"self",
",",
"sequence_rule_genus_type",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resources_by_genus_type",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONC... | Gets a ``SequenceRuleList`` corresponding to the given sequence rule genus ``Type`` which does not include sequence rule of genus types derived from the specified ``Type``.
arg: sequence_rule_genus_type (osid.type.Type): a sequence
rule genus type
return: (osid.assessment.authoring.S... | [
"Gets",
"a",
"SequenceRuleList",
"corresponding",
"to",
"the",
"given",
"sequence",
"rule",
"genus",
"Type",
"which",
"does",
"not",
"include",
"sequence",
"rule",
"of",
"genus",
"types",
"derived",
"from",
"the",
"specified",
"Type",
"."
] | python | train |
coderholic/django-cities | cities/util.py | https://github.com/coderholic/django-cities/blob/5e1cf86ff1d05e2d325cb2770c6df279599f5f98/cities/util.py#L27-L34 | def geo_distance(a, b):
"""Distance between two geo points in km. (p.x = long, p.y = lat)"""
a_y = radians(a.y)
b_y = radians(b.y)
delta_x = radians(a.x - b.x)
cos_x = (sin(a_y) * sin(b_y) +
cos(a_y) * cos(b_y) * cos(delta_x))
return acos(cos_x) * earth_radius_km | [
"def",
"geo_distance",
"(",
"a",
",",
"b",
")",
":",
"a_y",
"=",
"radians",
"(",
"a",
".",
"y",
")",
"b_y",
"=",
"radians",
"(",
"b",
".",
"y",
")",
"delta_x",
"=",
"radians",
"(",
"a",
".",
"x",
"-",
"b",
".",
"x",
")",
"cos_x",
"=",
"(",
... | Distance between two geo points in km. (p.x = long, p.y = lat) | [
"Distance",
"between",
"two",
"geo",
"points",
"in",
"km",
".",
"(",
"p",
".",
"x",
"=",
"long",
"p",
".",
"y",
"=",
"lat",
")"
] | python | train |
daniellawrence/graphitesend | graphitesend/graphitesend.py | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L221-L236 | def disconnect(self):
"""
Close the TCP connection with the graphite server.
"""
try:
self.socket.shutdown(1)
# If its currently a socket, set it to None
except AttributeError:
self.socket = None
except Exception:
self.socket =... | [
"def",
"disconnect",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"socket",
".",
"shutdown",
"(",
"1",
")",
"# If its currently a socket, set it to None",
"except",
"AttributeError",
":",
"self",
".",
"socket",
"=",
"None",
"except",
"Exception",
":",
"self... | Close the TCP connection with the graphite server. | [
"Close",
"the",
"TCP",
"connection",
"with",
"the",
"graphite",
"server",
"."
] | python | train |
jupyterhub/kubespawner | kubespawner/spawner.py | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1912-L1926 | def load_user_options(self):
"""Load user options from self.user_options dict
This can be set via POST to the API or via options_from_form
Only supported argument by default is 'profile'.
Override in subclasses to support other options.
"""
if self._profile_list is None... | [
"def",
"load_user_options",
"(",
"self",
")",
":",
"if",
"self",
".",
"_profile_list",
"is",
"None",
":",
"if",
"callable",
"(",
"self",
".",
"profile_list",
")",
":",
"self",
".",
"_profile_list",
"=",
"yield",
"gen",
".",
"maybe_future",
"(",
"self",
"... | Load user options from self.user_options dict
This can be set via POST to the API or via options_from_form
Only supported argument by default is 'profile'.
Override in subclasses to support other options. | [
"Load",
"user",
"options",
"from",
"self",
".",
"user_options",
"dict"
] | python | train |
resonai/ybt | yabt/builders/cpp.py | https://github.com/resonai/ybt/blob/5b40df0922ef3383eb85f2b04a26a2db4b81b3fd/yabt/builders/cpp.py#L268-L304 | def link_cpp_artifacts(build_context, target, workspace_dir,
include_objects: bool):
"""Link required artifacts from dependencies under target workspace dir.
Return list of object files of dependencies (if `include_objects`).
Includes:
- Generated code from proto dependencies
... | [
"def",
"link_cpp_artifacts",
"(",
"build_context",
",",
"target",
",",
"workspace_dir",
",",
"include_objects",
":",
"bool",
")",
":",
"# include the source & header files of the current target",
"# add objects of all dependencies (direct & transitive), if needed",
"source_files",
... | Link required artifacts from dependencies under target workspace dir.
Return list of object files of dependencies (if `include_objects`).
Includes:
- Generated code from proto dependencies
- Header files from all dependencies
- Generated header files from all dependencies
- If `include_objec... | [
"Link",
"required",
"artifacts",
"from",
"dependencies",
"under",
"target",
"workspace",
"dir",
".",
"Return",
"list",
"of",
"object",
"files",
"of",
"dependencies",
"(",
"if",
"include_objects",
")",
"."
] | python | train |
Kozea/pygal | pygal/graph/dot.py | https://github.com/Kozea/pygal/blob/5e25c98a59a0642eecd9fcc5dbfeeb2190fbb5e7/pygal/graph/dot.py#L126-L133 | def _plot(self):
"""Plot all dots for series"""
r_max = min(
self.view.x(1) - self.view.x(0),
(self.view.y(0) or 0) - self.view.y(1)
) / (2 * 1.05)
for serie in self.series:
self.dot(serie, r_max) | [
"def",
"_plot",
"(",
"self",
")",
":",
"r_max",
"=",
"min",
"(",
"self",
".",
"view",
".",
"x",
"(",
"1",
")",
"-",
"self",
".",
"view",
".",
"x",
"(",
"0",
")",
",",
"(",
"self",
".",
"view",
".",
"y",
"(",
"0",
")",
"or",
"0",
")",
"-... | Plot all dots for series | [
"Plot",
"all",
"dots",
"for",
"series"
] | python | train |
google/grr | grr/server/grr_response_server/databases/mysql_clients.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_clients.py#L440-L479 | def MultiReadClientFullInfo(self, client_ids, min_last_ping=None,
cursor=None):
"""Reads full client information for a list of clients."""
if not client_ids:
return {}
query = (
"SELECT "
"c.client_id, c.fleetspeak_enabled, c.certificate, "
"UNIX_... | [
"def",
"MultiReadClientFullInfo",
"(",
"self",
",",
"client_ids",
",",
"min_last_ping",
"=",
"None",
",",
"cursor",
"=",
"None",
")",
":",
"if",
"not",
"client_ids",
":",
"return",
"{",
"}",
"query",
"=",
"(",
"\"SELECT \"",
"\"c.client_id, c.fleetspeak_enabled,... | Reads full client information for a list of clients. | [
"Reads",
"full",
"client",
"information",
"for",
"a",
"list",
"of",
"clients",
"."
] | python | train |
bennylope/pygeocodio | geocodio/client.py | https://github.com/bennylope/pygeocodio/blob/4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3/geocodio/client.py#L242-L254 | def batch_reverse(self, points, **kwargs):
"""
Method for identifying the addresses from a list of lat/lng tuples
"""
fields = ",".join(kwargs.pop("fields", []))
response = self._req(
"post", verb="reverse", params={"fields": fields}, data=json_points(points)
... | [
"def",
"batch_reverse",
"(",
"self",
",",
"points",
",",
"*",
"*",
"kwargs",
")",
":",
"fields",
"=",
"\",\"",
".",
"join",
"(",
"kwargs",
".",
"pop",
"(",
"\"fields\"",
",",
"[",
"]",
")",
")",
"response",
"=",
"self",
".",
"_req",
"(",
"\"post\""... | Method for identifying the addresses from a list of lat/lng tuples | [
"Method",
"for",
"identifying",
"the",
"addresses",
"from",
"a",
"list",
"of",
"lat",
"/",
"lng",
"tuples"
] | python | train |
maas/python-libmaas | maas/client/viscera/sshkeys.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/sshkeys.py#L25-L34 | async def create(cls, key: str):
"""
Create an SSH key in MAAS with the content in `key`.
:param key: The content of the SSH key
:type key: `str`
:returns: The created SSH key
:rtype: `SSHKey`
"""
return cls._object(await cls._handler.create(key=key)) | [
"async",
"def",
"create",
"(",
"cls",
",",
"key",
":",
"str",
")",
":",
"return",
"cls",
".",
"_object",
"(",
"await",
"cls",
".",
"_handler",
".",
"create",
"(",
"key",
"=",
"key",
")",
")"
] | Create an SSH key in MAAS with the content in `key`.
:param key: The content of the SSH key
:type key: `str`
:returns: The created SSH key
:rtype: `SSHKey` | [
"Create",
"an",
"SSH",
"key",
"in",
"MAAS",
"with",
"the",
"content",
"in",
"key",
"."
] | python | train |
inasafe/inasafe | safe/definitions/earthquake.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/earthquake.py#L300-L354 | def erf(z):
"""Approximation to ERF.
:param z: Input array or scalar to perform erf on.
:type z: numpy.ndarray, float
:returns: The approximate error.
:rtype: numpy.ndarray, float
Note:
from:
http://www.cs.princeton.edu/introcs/21function/ErrorFunction.java.html
Implem... | [
"def",
"erf",
"(",
"z",
")",
":",
"# Input check",
"try",
":",
"len",
"(",
"z",
")",
"except",
"TypeError",
":",
"scalar",
"=",
"True",
"z",
"=",
"[",
"z",
"]",
"else",
":",
"scalar",
"=",
"False",
"z",
"=",
"numpy",
".",
"array",
"(",
"z",
")"... | Approximation to ERF.
:param z: Input array or scalar to perform erf on.
:type z: numpy.ndarray, float
:returns: The approximate error.
:rtype: numpy.ndarray, float
Note:
from:
http://www.cs.princeton.edu/introcs/21function/ErrorFunction.java.html
Implements the Gauss erro... | [
"Approximation",
"to",
"ERF",
"."
] | python | train |
mikedh/trimesh | trimesh/ray/ray_pyembree.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/ray/ray_pyembree.py#L254-L274 | def intersects_any(self,
ray_origins,
ray_directions):
"""
Check if a list of rays hits the surface.
Parameters
----------
ray_origins: (n,3) float, origins of rays
ray_directions: (n,3) float, direction (vector) of rays
... | [
"def",
"intersects_any",
"(",
"self",
",",
"ray_origins",
",",
"ray_directions",
")",
":",
"first",
"=",
"self",
".",
"intersects_first",
"(",
"ray_origins",
"=",
"ray_origins",
",",
"ray_directions",
"=",
"ray_directions",
")",
"hit",
"=",
"first",
"!=",
"-",... | Check if a list of rays hits the surface.
Parameters
----------
ray_origins: (n,3) float, origins of rays
ray_directions: (n,3) float, direction (vector) of rays
Returns
----------
hit: (n,) bool, did each ray hit the surface | [
"Check",
"if",
"a",
"list",
"of",
"rays",
"hits",
"the",
"surface",
"."
] | python | train |
inspirehep/harvesting-kit | harvestingkit/utils.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L189-L210 | def add_nations_field(authors_subfields):
"""Add correct nations field according to mapping in NATIONS_DEFAULT_MAP."""
from .config import NATIONS_DEFAULT_MAP
result = []
for field in authors_subfields:
if field[0] == 'v':
values = [x.replace('.', '') for x in field[1].split(', ')]
... | [
"def",
"add_nations_field",
"(",
"authors_subfields",
")",
":",
"from",
".",
"config",
"import",
"NATIONS_DEFAULT_MAP",
"result",
"=",
"[",
"]",
"for",
"field",
"in",
"authors_subfields",
":",
"if",
"field",
"[",
"0",
"]",
"==",
"'v'",
":",
"values",
"=",
... | Add correct nations field according to mapping in NATIONS_DEFAULT_MAP. | [
"Add",
"correct",
"nations",
"field",
"according",
"to",
"mapping",
"in",
"NATIONS_DEFAULT_MAP",
"."
] | python | valid |
msmbuilder/msmbuilder | msmbuilder/cluster/agglomerative.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/cluster/agglomerative.py#L165-L232 | def fit(self, X, y=None):
"""
Compute agglomerative clustering.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Returns
-------
self
"""
if self.max_landmarks is not None:
if self.n_clusters > self.n_landm... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"if",
"self",
".",
"max_landmarks",
"is",
"not",
"None",
":",
"if",
"self",
".",
"n_clusters",
">",
"self",
".",
"n_landmarks",
":",
"self",
".",
"n_landmarks",
"=",
"self",
".",... | Compute agglomerative clustering.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Returns
-------
self | [
"Compute",
"agglomerative",
"clustering",
"."
] | python | train |
koszullab/metaTOR | metator/scripts/hicstuff.py | https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/hicstuff.py#L479-L489 | def GC_partial(portion):
"""Manually compute GC content percentage in a DNA string, taking
ambiguous values into account (according to standard IUPAC notation).
"""
sequence_count = collections.Counter(portion)
gc = ((sum([sequence_count[i] for i in 'gGcCsS']) +
sum([sequence_count[i] for... | [
"def",
"GC_partial",
"(",
"portion",
")",
":",
"sequence_count",
"=",
"collections",
".",
"Counter",
"(",
"portion",
")",
"gc",
"=",
"(",
"(",
"sum",
"(",
"[",
"sequence_count",
"[",
"i",
"]",
"for",
"i",
"in",
"'gGcCsS'",
"]",
")",
"+",
"sum",
"(",
... | Manually compute GC content percentage in a DNA string, taking
ambiguous values into account (according to standard IUPAC notation). | [
"Manually",
"compute",
"GC",
"content",
"percentage",
"in",
"a",
"DNA",
"string",
"taking",
"ambiguous",
"values",
"into",
"account",
"(",
"according",
"to",
"standard",
"IUPAC",
"notation",
")",
"."
] | python | train |
pvlib/pvlib-python | pvlib/pvsystem.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/pvsystem.py#L2467-L2552 | def i_from_v(resistance_shunt, resistance_series, nNsVth, voltage,
saturation_current, photocurrent, method='lambertw'):
'''
Device current at the given device voltage for the single diode model.
Uses the single diode model (SDM) as described in, e.g.,
Jain and Kapoor 2004 [1].
The so... | [
"def",
"i_from_v",
"(",
"resistance_shunt",
",",
"resistance_series",
",",
"nNsVth",
",",
"voltage",
",",
"saturation_current",
",",
"photocurrent",
",",
"method",
"=",
"'lambertw'",
")",
":",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"'lambertw'",
":",
... | Device current at the given device voltage for the single diode model.
Uses the single diode model (SDM) as described in, e.g.,
Jain and Kapoor 2004 [1].
The solution is per Eq 2 of [1] except when resistance_series=0,
in which case the explict solution for current is used.
Ideal device parameter... | [
"Device",
"current",
"at",
"the",
"given",
"device",
"voltage",
"for",
"the",
"single",
"diode",
"model",
"."
] | python | train |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2378-L2389 | def resume(self, uuid):
"""
Resume a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return:
"""
args = {
'uuid': uuid,
}
self._domain_action_chk.check(args)
self._client.sync('kvm.resume', args) | [
"def",
"resume",
"(",
"self",
",",
"uuid",
")",
":",
"args",
"=",
"{",
"'uuid'",
":",
"uuid",
",",
"}",
"self",
".",
"_domain_action_chk",
".",
"check",
"(",
"args",
")",
"self",
".",
"_client",
".",
"sync",
"(",
"'kvm.resume'",
",",
"args",
")"
] | Resume a kvm domain by uuid
:param uuid: uuid of the kvm container (same as the used in create)
:return: | [
"Resume",
"a",
"kvm",
"domain",
"by",
"uuid",
":",
"param",
"uuid",
":",
"uuid",
"of",
"the",
"kvm",
"container",
"(",
"same",
"as",
"the",
"used",
"in",
"create",
")",
":",
"return",
":"
] | python | train |
mitsei/dlkit | dlkit/json_/repository/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/sessions.py#L5601-L5620 | def is_child_of_repository(self, id_, repository_id):
"""Tests if a node is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: repository_id (osid.id.Id): the ``Id`` of a repository
return: (boolean) - ``true`` if the ``id`` is a child of
``repository_... | [
"def",
"is_child_of_repository",
"(",
"self",
",",
"id_",
",",
"repository_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.is_child_of_bin",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_... | Tests if a node is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: repository_id (osid.id.Id): the ``Id`` of a repository
return: (boolean) - ``true`` if the ``id`` is a child of
``repository_id,`` ``false`` otherwise
raise: NotFound - ``repositor... | [
"Tests",
"if",
"a",
"node",
"is",
"a",
"direct",
"child",
"of",
"another",
"."
] | python | train |
broadinstitute/fiss | firecloud/fiss.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/fiss.py#L395-L404 | def meth_new(args):
""" Submit a new workflow (or update) to the methods repository. """
r = fapi.update_repository_method(args.namespace, args.method,
args.synopsis, args.wdl, args.doc,
args.comment)
fapi._check_response_code(r, 20... | [
"def",
"meth_new",
"(",
"args",
")",
":",
"r",
"=",
"fapi",
".",
"update_repository_method",
"(",
"args",
".",
"namespace",
",",
"args",
".",
"method",
",",
"args",
".",
"synopsis",
",",
"args",
".",
"wdl",
",",
"args",
".",
"doc",
",",
"args",
".",
... | Submit a new workflow (or update) to the methods repository. | [
"Submit",
"a",
"new",
"workflow",
"(",
"or",
"update",
")",
"to",
"the",
"methods",
"repository",
"."
] | python | train |
dereneaton/ipyrad | ipyrad/analysis/baba.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/baba.py#L200-L282 | def plot(self,
show_test_labels=True,
use_edge_lengths=True,
collapse_outgroup=False,
pct_tree_x=0.5,
pct_tree_y=0.2,
subset_tests=None,
#toytree_kwargs=None,
*args,
**kwargs):
"""
Draw a multi-panel figure with tree... | [
"def",
"plot",
"(",
"self",
",",
"show_test_labels",
"=",
"True",
",",
"use_edge_lengths",
"=",
"True",
",",
"collapse_outgroup",
"=",
"False",
",",
"pct_tree_x",
"=",
"0.5",
",",
"pct_tree_y",
"=",
"0.2",
",",
"subset_tests",
"=",
"None",
",",
"#toytree_kwa... | Draw a multi-panel figure with tree, tests, and results
Parameters:
-----------
height: int
...
width: int
...
show_test_labels: bool
...
use_edge_lengths: bool
...
collapse_outgroups: bool
...
pct_tre... | [
"Draw",
"a",
"multi",
"-",
"panel",
"figure",
"with",
"tree",
"tests",
"and",
"results",
"Parameters",
":",
"-----------",
"height",
":",
"int",
"..."
] | python | valid |
DMSC-Instrument-Data/lewis | src/lewis/devices/__init__.py | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/__init__.py#L177-L191 | def _override_data(self, overrides):
"""
This method overrides data members of the class, but does not allow for adding new members.
:param overrides: Dict with data overrides.
"""
if overrides is not None:
for name, val in overrides.items():
self.log... | [
"def",
"_override_data",
"(",
"self",
",",
"overrides",
")",
":",
"if",
"overrides",
"is",
"not",
"None",
":",
"for",
"name",
",",
"val",
"in",
"overrides",
".",
"items",
"(",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Trying to override initial ... | This method overrides data members of the class, but does not allow for adding new members.
:param overrides: Dict with data overrides. | [
"This",
"method",
"overrides",
"data",
"members",
"of",
"the",
"class",
"but",
"does",
"not",
"allow",
"for",
"adding",
"new",
"members",
"."
] | python | train |
DerwenAI/pytextrank | pytextrank/pytextrank.py | https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L315-L328 | def write_dot (graph, ranks, path="graph.dot"):
"""
output the graph in Dot file format
"""
dot = Digraph()
for node in graph.nodes():
dot.node(node, "%s %0.3f" % (node, ranks[node]))
for edge in graph.edges():
dot.edge(edge[0], edge[1], constraint="false")
with open(path,... | [
"def",
"write_dot",
"(",
"graph",
",",
"ranks",
",",
"path",
"=",
"\"graph.dot\"",
")",
":",
"dot",
"=",
"Digraph",
"(",
")",
"for",
"node",
"in",
"graph",
".",
"nodes",
"(",
")",
":",
"dot",
".",
"node",
"(",
"node",
",",
"\"%s %0.3f\"",
"%",
"(",... | output the graph in Dot file format | [
"output",
"the",
"graph",
"in",
"Dot",
"file",
"format"
] | python | valid |
Miserlou/Zappa | zappa/cli.py | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1141-L1151 | def update_cognito_triggers(self):
"""
Update any cognito triggers
"""
if self.cognito:
user_pool = self.cognito.get('user_pool')
triggers = self.cognito.get('triggers', [])
lambda_configs = set()
for trigger in triggers:
la... | [
"def",
"update_cognito_triggers",
"(",
"self",
")",
":",
"if",
"self",
".",
"cognito",
":",
"user_pool",
"=",
"self",
".",
"cognito",
".",
"get",
"(",
"'user_pool'",
")",
"triggers",
"=",
"self",
".",
"cognito",
".",
"get",
"(",
"'triggers'",
",",
"[",
... | Update any cognito triggers | [
"Update",
"any",
"cognito",
"triggers"
] | python | train |
PGower/PyCanvas | pycanvas/apis/appointment_groups.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/appointment_groups.py#L341-L359 | def get_next_appointment(self, appointment_group_ids=None):
"""
Get next appointment.
Return the next appointment available to sign up for. The appointment
is returned in a one-element array. If no future appointments are
available, an empty array is returned.
"""... | [
"def",
"get_next_appointment",
"(",
"self",
",",
"appointment_group_ids",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# OPTIONAL - appointment_group_ids\r",
"\"\"\"List of ids of appointment groups to search.\"\"\"",
... | Get next appointment.
Return the next appointment available to sign up for. The appointment
is returned in a one-element array. If no future appointments are
available, an empty array is returned. | [
"Get",
"next",
"appointment",
".",
"Return",
"the",
"next",
"appointment",
"available",
"to",
"sign",
"up",
"for",
".",
"The",
"appointment",
"is",
"returned",
"in",
"a",
"one",
"-",
"element",
"array",
".",
"If",
"no",
"future",
"appointments",
"are",
"av... | python | train |
quantmind/pulsar | pulsar/async/clients.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/clients.py#L180-L188 | def close(self, discard=False):
'''Close this pool connection by releasing the underlying
:attr:`connection` back to the :attr:`pool`.
'''
if self.pool is not None:
self.pool._put(self.connection, discard)
self.pool = None
conn, self.connection = self.... | [
"def",
"close",
"(",
"self",
",",
"discard",
"=",
"False",
")",
":",
"if",
"self",
".",
"pool",
"is",
"not",
"None",
":",
"self",
".",
"pool",
".",
"_put",
"(",
"self",
".",
"connection",
",",
"discard",
")",
"self",
".",
"pool",
"=",
"None",
"co... | Close this pool connection by releasing the underlying
:attr:`connection` back to the :attr:`pool`. | [
"Close",
"this",
"pool",
"connection",
"by",
"releasing",
"the",
"underlying",
":",
"attr",
":",
"connection",
"back",
"to",
"the",
":",
"attr",
":",
"pool",
"."
] | python | train |
flashingpumpkin/django-socialregistration | socialregistration/views.py | https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/views.py#L202-L218 | def post(self, request):
"""
Create a client, store it in the user's session and redirect the user
to the API provider to authorize our app and permissions.
"""
request.session['next'] = self.get_next(request)
client = self.get_client()()
request.session[self.get_... | [
"def",
"post",
"(",
"self",
",",
"request",
")",
":",
"request",
".",
"session",
"[",
"'next'",
"]",
"=",
"self",
".",
"get_next",
"(",
"request",
")",
"client",
"=",
"self",
".",
"get_client",
"(",
")",
"(",
")",
"request",
".",
"session",
"[",
"s... | Create a client, store it in the user's session and redirect the user
to the API provider to authorize our app and permissions. | [
"Create",
"a",
"client",
"store",
"it",
"in",
"the",
"user",
"s",
"session",
"and",
"redirect",
"the",
"user",
"to",
"the",
"API",
"provider",
"to",
"authorize",
"our",
"app",
"and",
"permissions",
"."
] | python | train |
rosshamish/catanlog | catanlog.py | https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L51-L57 | def _log(self, content):
"""
Write a string to the log
"""
self._buffer += content
if self._auto_flush:
self.flush() | [
"def",
"_log",
"(",
"self",
",",
"content",
")",
":",
"self",
".",
"_buffer",
"+=",
"content",
"if",
"self",
".",
"_auto_flush",
":",
"self",
".",
"flush",
"(",
")"
] | Write a string to the log | [
"Write",
"a",
"string",
"to",
"the",
"log"
] | python | train |
saltstack/salt | salt/runners/manage.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L341-L364 | def joined(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to S... | [
"def",
"joined",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"return",
"list_state",
"(",
"subset",
"=",
"subset",
",",
"s... | .. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
... | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | python | train |
orangain/scrapy-s3pipeline | s3pipeline/pipelines.py | https://github.com/orangain/scrapy-s3pipeline/blob/6301a3a057da6407b04a09c717498026f88706a4/s3pipeline/pipelines.py#L104-L125 | def _make_fileobj(self):
"""
Build file object from items.
"""
bio = BytesIO()
f = gzip.GzipFile(mode='wb', fileobj=bio) if self.use_gzip else bio
# Build file object using ItemExporter
exporter = JsonLinesItemExporter(f)
exporter.start_exporting()
... | [
"def",
"_make_fileobj",
"(",
"self",
")",
":",
"bio",
"=",
"BytesIO",
"(",
")",
"f",
"=",
"gzip",
".",
"GzipFile",
"(",
"mode",
"=",
"'wb'",
",",
"fileobj",
"=",
"bio",
")",
"if",
"self",
".",
"use_gzip",
"else",
"bio",
"# Build file object using ItemExp... | Build file object from items. | [
"Build",
"file",
"object",
"from",
"items",
"."
] | python | test |
rchatterjee/pwmodels | src/pwmodel/models.py | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L441-L444 | def normalize(pw):
""" Lower case, and change the symbols to closest characters"""
pw_lower = pw.lower()
return ''.join(helper.L33T.get(c, c) for c in pw_lower) | [
"def",
"normalize",
"(",
"pw",
")",
":",
"pw_lower",
"=",
"pw",
".",
"lower",
"(",
")",
"return",
"''",
".",
"join",
"(",
"helper",
".",
"L33T",
".",
"get",
"(",
"c",
",",
"c",
")",
"for",
"c",
"in",
"pw_lower",
")"
] | Lower case, and change the symbols to closest characters | [
"Lower",
"case",
"and",
"change",
"the",
"symbols",
"to",
"closest",
"characters"
] | python | train |
roclark/sportsreference | sportsreference/ncaab/boxscore.py | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/boxscore.py#L1744-L1791 | def _get_team_names(self, game):
"""
Find the names and abbreviations for both teams in a game.
Using the HTML contents in a boxscore, find the name and abbreviation
for both teams and determine wether or not this is a matchup between
two Division-I teams.
Parameters
... | [
"def",
"_get_team_names",
"(",
"self",
",",
"game",
")",
":",
"# Grab the first <td...> tag for each <tr> row in the boxscore,",
"# representing the name for each participating team.",
"links",
"=",
"[",
"g",
"(",
"'td:first'",
")",
"for",
"g",
"in",
"game",
"(",
"'tr'",
... | Find the names and abbreviations for both teams in a game.
Using the HTML contents in a boxscore, find the name and abbreviation
for both teams and determine wether or not this is a matchup between
two Division-I teams.
Parameters
----------
game : PyQuery object
... | [
"Find",
"the",
"names",
"and",
"abbreviations",
"for",
"both",
"teams",
"in",
"a",
"game",
"."
] | python | train |
PmagPy/PmagPy | dialogs/drop_down_menus2.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/drop_down_menus2.py#L126-L138 | def add_method_drop_down(self, col_number, col_label):
"""
Add drop-down-menu options for magic_method_codes columns
"""
if self.data_type == 'age':
method_list = vocab.age_methods
elif '++' in col_label:
method_list = vocab.pmag_methods
elif self.... | [
"def",
"add_method_drop_down",
"(",
"self",
",",
"col_number",
",",
"col_label",
")",
":",
"if",
"self",
".",
"data_type",
"==",
"'age'",
":",
"method_list",
"=",
"vocab",
".",
"age_methods",
"elif",
"'++'",
"in",
"col_label",
":",
"method_list",
"=",
"vocab... | Add drop-down-menu options for magic_method_codes columns | [
"Add",
"drop",
"-",
"down",
"-",
"menu",
"options",
"for",
"magic_method_codes",
"columns"
] | python | train |
apache/spark | python/pyspark/mllib/clustering.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/clustering.py#L976-L989 | def load(cls, sc, path):
"""Load the LDAModel from disk.
:param sc:
SparkContext.
:param path:
Path to where the model is stored.
"""
if not isinstance(sc, SparkContext):
raise TypeError("sc should be a SparkContext, got type %s" % type(sc))
... | [
"def",
"load",
"(",
"cls",
",",
"sc",
",",
"path",
")",
":",
"if",
"not",
"isinstance",
"(",
"sc",
",",
"SparkContext",
")",
":",
"raise",
"TypeError",
"(",
"\"sc should be a SparkContext, got type %s\"",
"%",
"type",
"(",
"sc",
")",
")",
"if",
"not",
"i... | Load the LDAModel from disk.
:param sc:
SparkContext.
:param path:
Path to where the model is stored. | [
"Load",
"the",
"LDAModel",
"from",
"disk",
"."
] | python | train |
flowersteam/explauto | explauto/models/dataset.py | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/dataset.py#L73-L78 | def _build_tree(self):
"""Build the KDTree for the observed data
"""
if not self.nn_ready:
self.kdtree = scipy.spatial.cKDTree(self.data)
self.nn_ready = True | [
"def",
"_build_tree",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"nn_ready",
":",
"self",
".",
"kdtree",
"=",
"scipy",
".",
"spatial",
".",
"cKDTree",
"(",
"self",
".",
"data",
")",
"self",
".",
"nn_ready",
"=",
"True"
] | Build the KDTree for the observed data | [
"Build",
"the",
"KDTree",
"for",
"the",
"observed",
"data"
] | python | train |
Kortemme-Lab/klab | klab/stats/dataframe.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/stats/dataframe.py#L236-L255 | def get_series_names(self, column_indices = [], column_names = []):
'''Returns the series' names corresponding to column_indices and column_names.
"names" here are:
- strings for single-indexed dataframes; or
- tuples for multi-indexed dataframes.
If both param... | [
"def",
"get_series_names",
"(",
"self",
",",
"column_indices",
"=",
"[",
"]",
",",
"column_names",
"=",
"[",
"]",
")",
":",
"n",
"=",
"[",
"]",
"if",
"not",
"column_indices",
"and",
"not",
"column_names",
":",
"for",
"k",
",",
"v",
"in",
"sorted",
"(... | Returns the series' names corresponding to column_indices and column_names.
"names" here are:
- strings for single-indexed dataframes; or
- tuples for multi-indexed dataframes.
If both parameters are empty then all column names are returned. | [
"Returns",
"the",
"series",
"names",
"corresponding",
"to",
"column_indices",
"and",
"column_names",
".",
"names",
"here",
"are",
":",
"-",
"strings",
"for",
"single",
"-",
"indexed",
"dataframes",
";",
"or",
"-",
"tuples",
"for",
"multi",
"-",
"indexed",
"d... | python | train |
glitchassassin/lackey | lackey/PlatformManagerDarwin.py | https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerDarwin.py#L354-L357 | def _get_window_list(self):
""" Returns a dictionary of details about open windows """
window_list = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListExcludeDesktopElements, Quartz.kCGNullWindowID)
return window_list | [
"def",
"_get_window_list",
"(",
"self",
")",
":",
"window_list",
"=",
"Quartz",
".",
"CGWindowListCopyWindowInfo",
"(",
"Quartz",
".",
"kCGWindowListExcludeDesktopElements",
",",
"Quartz",
".",
"kCGNullWindowID",
")",
"return",
"window_list"
] | Returns a dictionary of details about open windows | [
"Returns",
"a",
"dictionary",
"of",
"details",
"about",
"open",
"windows"
] | python | train |
ejeschke/ginga | ginga/util/wcsmod/common.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/wcsmod/common.py#L291-L307 | def fix_bad_headers(self):
"""
Fix up bad headers that cause problems for the wrapped WCS
module.
Subclass can override this method to fix up issues with the
header for problem FITS files.
"""
# WCSLIB doesn't like "nonstandard" units
unit = self.header.g... | [
"def",
"fix_bad_headers",
"(",
"self",
")",
":",
"# WCSLIB doesn't like \"nonstandard\" units",
"unit",
"=",
"self",
".",
"header",
".",
"get",
"(",
"'CUNIT1'",
",",
"'deg'",
")",
"if",
"unit",
".",
"upper",
"(",
")",
"==",
"'DEGREE'",
":",
"# self.header.upda... | Fix up bad headers that cause problems for the wrapped WCS
module.
Subclass can override this method to fix up issues with the
header for problem FITS files. | [
"Fix",
"up",
"bad",
"headers",
"that",
"cause",
"problems",
"for",
"the",
"wrapped",
"WCS",
"module",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/l3/ha_db.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/l3/ha_db.py#L202-L232 | def _ensure_create_ha_compliant(self, router, router_type):
"""To be called in create_router() BEFORE router is created in DB."""
details = router.pop(ha.DETAILS, {})
if details == ATTR_NOT_SPECIFIED:
details = {}
res = {ha.ENABLED: router.pop(ha.ENABLED, ATTR_NOT_SPECIFIED),... | [
"def",
"_ensure_create_ha_compliant",
"(",
"self",
",",
"router",
",",
"router_type",
")",
":",
"details",
"=",
"router",
".",
"pop",
"(",
"ha",
".",
"DETAILS",
",",
"{",
"}",
")",
"if",
"details",
"==",
"ATTR_NOT_SPECIFIED",
":",
"details",
"=",
"{",
"}... | To be called in create_router() BEFORE router is created in DB. | [
"To",
"be",
"called",
"in",
"create_router",
"()",
"BEFORE",
"router",
"is",
"created",
"in",
"DB",
"."
] | python | train |
dnephin/PyStaticConfiguration | staticconf/validation.py | https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/validation.py#L90-L101 | def _validate_iterable(iterable_type, value):
"""Convert the iterable to iterable_type, or raise a Configuration
exception.
"""
if isinstance(value, six.string_types):
msg = "Invalid iterable of type(%s): %s"
raise ValidationError(msg % (type(value), value))
try:
return iter... | [
"def",
"_validate_iterable",
"(",
"iterable_type",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"msg",
"=",
"\"Invalid iterable of type(%s): %s\"",
"raise",
"ValidationError",
"(",
"msg",
"%",
"(",
"type",
... | Convert the iterable to iterable_type, or raise a Configuration
exception. | [
"Convert",
"the",
"iterable",
"to",
"iterable_type",
"or",
"raise",
"a",
"Configuration",
"exception",
"."
] | python | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/corpus.py | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/corpus.py#L60-L69 | def _make_bound_method(func, self):
"""Magic for creating bound methods (used for _unload)."""
class Foo(object):
def meth(self): pass
f = Foo()
bound_method = type(f.meth)
try:
return bound_method(func, self, self.__class__)
except TypeError: # python3
return bound_metho... | [
"def",
"_make_bound_method",
"(",
"func",
",",
"self",
")",
":",
"class",
"Foo",
"(",
"object",
")",
":",
"def",
"meth",
"(",
"self",
")",
":",
"pass",
"f",
"=",
"Foo",
"(",
")",
"bound_method",
"=",
"type",
"(",
"f",
".",
"meth",
")",
"try",
":"... | Magic for creating bound methods (used for _unload). | [
"Magic",
"for",
"creating",
"bound",
"methods",
"(",
"used",
"for",
"_unload",
")",
"."
] | python | train |
trustar/trustar-python | trustar/indicator_client.py | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L209-L253 | def search_indicators_page(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
indicator_types=None,
tags=None,
ex... | [
"def",
"search_indicators_page",
"(",
"self",
",",
"search_term",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
",",
"indicator_types",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"excluded_tags",
... | Search for indicators containing a search term.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict to indicators found in reports in specific... | [
"Search",
"for",
"indicators",
"containing",
"a",
"search",
"term",
"."
] | python | train |
ForensicArtifacts/artifacts | tools/validator.py | https://github.com/ForensicArtifacts/artifacts/blob/044a63bfb4448af33d085c69066c80f9505ae7ca/tools/validator.py#L303-L379 | def CheckFile(self, filename):
"""Validates the artifacts definition in a specific file.
Args:
filename (str): name of the artifacts definition file.
Returns:
bool: True if the file contains valid artifacts definitions.
"""
result = True
artifact_reader = reader.YamlArtifactsReader... | [
"def",
"CheckFile",
"(",
"self",
",",
"filename",
")",
":",
"result",
"=",
"True",
"artifact_reader",
"=",
"reader",
".",
"YamlArtifactsReader",
"(",
")",
"try",
":",
"for",
"artifact_definition",
"in",
"artifact_reader",
".",
"ReadFile",
"(",
"filename",
")",... | Validates the artifacts definition in a specific file.
Args:
filename (str): name of the artifacts definition file.
Returns:
bool: True if the file contains valid artifacts definitions. | [
"Validates",
"the",
"artifacts",
"definition",
"in",
"a",
"specific",
"file",
"."
] | python | train |
Othernet-Project/bottle-fdsend | fdsend/rangewrapper.py | https://github.com/Othernet-Project/bottle-fdsend/blob/5ff27e605e8cf878e24c71c1446dcf5c8caf4898/fdsend/rangewrapper.py#L44-L58 | def force_seek(fd, offset, chunk=CHUNK):
""" Force adjustment of read cursort to specified offset
This function takes a file descriptor ``fd`` and tries to seek to position
specified by ``offset`` argument. If the descriptor does not support the
``seek()`` method, it will fall back to ``emulate_seek()`... | [
"def",
"force_seek",
"(",
"fd",
",",
"offset",
",",
"chunk",
"=",
"CHUNK",
")",
":",
"try",
":",
"fd",
".",
"seek",
"(",
"offset",
")",
"except",
"(",
"AttributeError",
",",
"io",
".",
"UnsupportedOperation",
")",
":",
"# This file handle probably has no see... | Force adjustment of read cursort to specified offset
This function takes a file descriptor ``fd`` and tries to seek to position
specified by ``offset`` argument. If the descriptor does not support the
``seek()`` method, it will fall back to ``emulate_seek()``.
The optional ``chunk`` argument can be us... | [
"Force",
"adjustment",
"of",
"read",
"cursort",
"to",
"specified",
"offset"
] | python | train |
geronimp/graftM | graftm/pplacer.py | https://github.com/geronimp/graftM/blob/c82576517290167f605fd0bc4facd009cee29f48/graftm/pplacer.py#L145-L244 | def place(self, reverse_pipe, seqs_list, resolve_placements, files, args,
slash_endings, tax_descr, clusterer):
'''
placement - This is the placement pipeline in GraftM, in aligned reads
are placed into phylogenetic trees, and the results interpreted.
... | [
"def",
"place",
"(",
"self",
",",
"reverse_pipe",
",",
"seqs_list",
",",
"resolve_placements",
",",
"files",
",",
"args",
",",
"slash_endings",
",",
"tax_descr",
",",
"clusterer",
")",
":",
"trusted_placements",
"=",
"{",
"}",
"files_to_delete",
"=",
"[",
"]... | placement - This is the placement pipeline in GraftM, in aligned reads
are placed into phylogenetic trees, and the results interpreted.
If reverse reads are used, this is where the comparisons are made
between placements, for the summary tables to be build in ... | [
"placement",
"-",
"This",
"is",
"the",
"placement",
"pipeline",
"in",
"GraftM",
"in",
"aligned",
"reads",
"are",
"placed",
"into",
"phylogenetic",
"trees",
"and",
"the",
"results",
"interpreted",
".",
"If",
"reverse",
"reads",
"are",
"used",
"this",
"is",
"w... | python | train |
KelSolaar/Umbra | umbra/reporter.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/reporter.py#L687-L712 | def report_exception_to_crittercism(self, *args):
"""
Reports given exception to Crittercism.
:param \*args: Arguments.
:type \*args: \*
:return: Method success.
:rtype: bool
"""
if foundations.common.is_internet_available():
cls, instance, t... | [
"def",
"report_exception_to_crittercism",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"foundations",
".",
"common",
".",
"is_internet_available",
"(",
")",
":",
"cls",
",",
"instance",
",",
"trcback",
"=",
"args",
"title",
"=",
"re",
".",
"escape",
"(",... | Reports given exception to Crittercism.
:param \*args: Arguments.
:type \*args: \*
:return: Method success.
:rtype: bool | [
"Reports",
"given",
"exception",
"to",
"Crittercism",
"."
] | python | train |
orbingol/NURBS-Python | geomdl/_utilities.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_utilities.py#L46-L54 | def pool_context(*args, **kwargs):
""" Context manager for multiprocessing.Pool class (for compatibility with Python 2.7.x) """
pool = Pool(*args, **kwargs)
try:
yield pool
except Exception as e:
raise e
finally:
pool.terminate() | [
"def",
"pool_context",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pool",
"=",
"Pool",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"yield",
"pool",
"except",
"Exception",
"as",
"e",
":",
"raise",
"e",
"finally",
":",
"po... | Context manager for multiprocessing.Pool class (for compatibility with Python 2.7.x) | [
"Context",
"manager",
"for",
"multiprocessing",
".",
"Pool",
"class",
"(",
"for",
"compatibility",
"with",
"Python",
"2",
".",
"7",
".",
"x",
")"
] | python | train |
Clinical-Genomics/scout | scout/server/blueprints/variants/views.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/server/blueprints/variants/views.py#L312-L364 | def variant_update(institute_id, case_name, variant_id):
"""Update user-defined information about a variant: manual rank & ACMG."""
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
variant_obj = store.variant(variant_id)
user_obj = store.user(current_user.email)
link = re... | [
"def",
"variant_update",
"(",
"institute_id",
",",
"case_name",
",",
"variant_id",
")",
":",
"institute_obj",
",",
"case_obj",
"=",
"institute_and_case",
"(",
"store",
",",
"institute_id",
",",
"case_name",
")",
"variant_obj",
"=",
"store",
".",
"variant",
"(",
... | Update user-defined information about a variant: manual rank & ACMG. | [
"Update",
"user",
"-",
"defined",
"information",
"about",
"a",
"variant",
":",
"manual",
"rank",
"&",
"ACMG",
"."
] | python | test |
treycucco/bidon | bidon/util/terminal.py | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/terminal.py#L86-L88 | def ratio_and_percentage(current, total, time_remaining):
"""Returns the progress ratio and percentage."""
return "{} / {} ({}% completed)".format(current, total, int(current / total * 100)) | [
"def",
"ratio_and_percentage",
"(",
"current",
",",
"total",
",",
"time_remaining",
")",
":",
"return",
"\"{} / {} ({}% completed)\"",
".",
"format",
"(",
"current",
",",
"total",
",",
"int",
"(",
"current",
"/",
"total",
"*",
"100",
")",
")"
] | Returns the progress ratio and percentage. | [
"Returns",
"the",
"progress",
"ratio",
"and",
"percentage",
"."
] | python | train |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L678-L692 | def summit_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns only those portions of the COVER
result where the maximum number of regions overlap (this is done by returning only
regions ... | [
"def",
"summit_cover",
"(",
"self",
",",
"minAcc",
",",
"maxAcc",
",",
"groupBy",
"=",
"None",
",",
"new_reg_fields",
"=",
"None",
")",
":",
"return",
"self",
".",
"cover",
"(",
"minAcc",
",",
"maxAcc",
",",
"groupBy",
",",
"new_reg_fields",
",",
"cover_... | *Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns only those portions of the COVER
result where the maximum number of regions overlap (this is done by returning only
regions that start from a position after which the number of overlaps does not
increase, and s... | [
"*",
"Wrapper",
"of",
"*",
"COVER"
] | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L364-L385 | def kill(self, dwExitCode = 0):
"""
Terminates the thread execution.
@note: If the C{lpInjectedMemory} member contains a valid pointer,
the memory is freed.
@type dwExitCode: int
@param dwExitCode: (Optional) Thread exit code.
"""
hThread = self.get_han... | [
"def",
"kill",
"(",
"self",
",",
"dwExitCode",
"=",
"0",
")",
":",
"hThread",
"=",
"self",
".",
"get_handle",
"(",
"win32",
".",
"THREAD_TERMINATE",
")",
"win32",
".",
"TerminateThread",
"(",
"hThread",
",",
"dwExitCode",
")",
"# Ugliest hack ever, won't work ... | Terminates the thread execution.
@note: If the C{lpInjectedMemory} member contains a valid pointer,
the memory is freed.
@type dwExitCode: int
@param dwExitCode: (Optional) Thread exit code. | [
"Terminates",
"the",
"thread",
"execution",
"."
] | python | train |
PMEAL/OpenPNM | openpnm/utils/misc.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/utils/misc.py#L313-L356 | def models_to_table(obj, params=True):
r"""
Converts a ModelsDict object to a ReST compatible table
Parameters
----------
obj : OpenPNM object
Any object that has a ``models`` attribute
params : boolean
Indicates whether or not to include a list of parameter
values in t... | [
"def",
"models_to_table",
"(",
"obj",
",",
"params",
"=",
"True",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'models'",
")",
":",
"raise",
"Exception",
"(",
"'Received object does not have any models'",
")",
"row",
"=",
"'+'",
"+",
"'-'",
"*",
"4"... | r"""
Converts a ModelsDict object to a ReST compatible table
Parameters
----------
obj : OpenPNM object
Any object that has a ``models`` attribute
params : boolean
Indicates whether or not to include a list of parameter
values in the table. Set to False for just a list of ... | [
"r",
"Converts",
"a",
"ModelsDict",
"object",
"to",
"a",
"ReST",
"compatible",
"table"
] | python | train |
moderngl/moderngl | moderngl/context.py | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L1072-L1089 | def core_profile_check(self) -> None:
'''
Core profile check.
FOR DEBUG PURPOSES ONLY
'''
profile_mask = self.info['GL_CONTEXT_PROFILE_MASK']
if profile_mask != 1:
warnings.warn('The window should request a CORE OpenGL profile')
version_code... | [
"def",
"core_profile_check",
"(",
"self",
")",
"->",
"None",
":",
"profile_mask",
"=",
"self",
".",
"info",
"[",
"'GL_CONTEXT_PROFILE_MASK'",
"]",
"if",
"profile_mask",
"!=",
"1",
":",
"warnings",
".",
"warn",
"(",
"'The window should request a CORE OpenGL profile'"... | Core profile check.
FOR DEBUG PURPOSES ONLY | [
"Core",
"profile",
"check",
"."
] | python | train |
PSPC-SPAC-buyandsell/von_anchor | von_anchor/anchor/base.py | https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/anchor/base.py#L461-L490 | async def _submit(self, req_json: str) -> str:
"""
Submit (json) request to ledger; return (json) result.
Raise AbsentPool for no pool, ClosedPool if pool is not yet open, or BadLedgerTxn on failure.
:param req_json: json of request to sign and submit
:return: json response
... | [
"async",
"def",
"_submit",
"(",
"self",
",",
"req_json",
":",
"str",
")",
"->",
"str",
":",
"LOGGER",
".",
"debug",
"(",
"'BaseAnchor._submit >>> req_json: %s'",
",",
"req_json",
")",
"if",
"not",
"self",
".",
"pool",
":",
"LOGGER",
".",
"debug",
"(",
"'... | Submit (json) request to ledger; return (json) result.
Raise AbsentPool for no pool, ClosedPool if pool is not yet open, or BadLedgerTxn on failure.
:param req_json: json of request to sign and submit
:return: json response | [
"Submit",
"(",
"json",
")",
"request",
"to",
"ledger",
";",
"return",
"(",
"json",
")",
"result",
"."
] | python | train |
RJT1990/pyflux | pyflux/garch/garch.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/garch/garch.py#L529-L577 | def predict_is(self, h=5, fit_once=True, fit_method='MLE', intervals=False, **kwargs):
""" Makes dynamic in-sample predictions with the estimated model
Parameters
----------
h : int (default : 5)
How many steps would you like to forecast?
fit_once : boolean
... | [
"def",
"predict_is",
"(",
"self",
",",
"h",
"=",
"5",
",",
"fit_once",
"=",
"True",
",",
"fit_method",
"=",
"'MLE'",
",",
"intervals",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"predictions",
"=",
"[",
"]",
"for",
"t",
"in",
"range",
"(",
... | Makes dynamic in-sample predictions with the estimated model
Parameters
----------
h : int (default : 5)
How many steps would you like to forecast?
fit_once : boolean
(default: True) Fits only once before the in-sample prediction; if False, fits after every new ... | [
"Makes",
"dynamic",
"in",
"-",
"sample",
"predictions",
"with",
"the",
"estimated",
"model"
] | python | train |
PX4/pyulog | pyulog/ulog2kml.py | https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/ulog2kml.py#L120-L140 | def _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset):
"""
Add camera trigger points to the map
"""
data = ulog.data_list
topic_instance = 0
cur_dataset = [elem for elem in data
if elem.name == camera_trigger_topic_name and elem.multi_id == topi... | [
"def",
"_kml_add_camera_triggers",
"(",
"kml",
",",
"ulog",
",",
"camera_trigger_topic_name",
",",
"altitude_offset",
")",
":",
"data",
"=",
"ulog",
".",
"data_list",
"topic_instance",
"=",
"0",
"cur_dataset",
"=",
"[",
"elem",
"for",
"elem",
"in",
"data",
"if... | Add camera trigger points to the map | [
"Add",
"camera",
"trigger",
"points",
"to",
"the",
"map"
] | python | train |
Kraymer/high | high/__init__.py | https://github.com/Kraymer/high/blob/11bb86733875ec708264ffb92bf5ef09a9d2f08c/high/__init__.py#L37-L54 | def contacts(github, logins):
"""Extract public contact info from users.
"""
printmp('Fetching contacts')
users = [github.user(login).as_dict() for login in logins]
mails = set()
blogs = set()
for user in users:
contact = user.get('name', 'login')
if user['email']:
... | [
"def",
"contacts",
"(",
"github",
",",
"logins",
")",
":",
"printmp",
"(",
"'Fetching contacts'",
")",
"users",
"=",
"[",
"github",
".",
"user",
"(",
"login",
")",
".",
"as_dict",
"(",
")",
"for",
"login",
"in",
"logins",
"]",
"mails",
"=",
"set",
"(... | Extract public contact info from users. | [
"Extract",
"public",
"contact",
"info",
"from",
"users",
"."
] | python | train |
django-danceschool/django-danceschool | danceschool/core/views.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/views.py#L611-L652 | def get_form_kwargs(self, **kwargs):
'''
Get the list of recent months and recent series to pass to the form
'''
numMonths = 12
lastStart = (
Event.objects.annotate(Min('eventoccurrence__startTime'))
.order_by('-eventoccurrence__startTime__min')
... | [
"def",
"get_form_kwargs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"numMonths",
"=",
"12",
"lastStart",
"=",
"(",
"Event",
".",
"objects",
".",
"annotate",
"(",
"Min",
"(",
"'eventoccurrence__startTime'",
")",
")",
".",
"order_by",
"(",
"'-eventoccu... | Get the list of recent months and recent series to pass to the form | [
"Get",
"the",
"list",
"of",
"recent",
"months",
"and",
"recent",
"series",
"to",
"pass",
"to",
"the",
"form"
] | python | train |
openego/ding0 | ding0/core/__init__.py | https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/core/__init__.py#L106-L268 | def run_ding0(self, session, mv_grid_districts_no=None, debug=False, export_figures=False):
""" Let DING0 run by shouting at this method (or just call
it from NetworkDing0 instance). This method is a wrapper
for the main functionality of DING0.
Parameters
----------
... | [
"def",
"run_ding0",
"(",
"self",
",",
"session",
",",
"mv_grid_districts_no",
"=",
"None",
",",
"debug",
"=",
"False",
",",
"export_figures",
"=",
"False",
")",
":",
"if",
"debug",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"# STEP 1: Import MV Grid... | Let DING0 run by shouting at this method (or just call
it from NetworkDing0 instance). This method is a wrapper
for the main functionality of DING0.
Parameters
----------
session : sqlalchemy.orm.session.Session
Database session
mv_grid_districts_no :... | [
"Let",
"DING0",
"run",
"by",
"shouting",
"at",
"this",
"method",
"(",
"or",
"just",
"call",
"it",
"from",
"NetworkDing0",
"instance",
")",
".",
"This",
"method",
"is",
"a",
"wrapper",
"for",
"the",
"main",
"functionality",
"of",
"DING0",
"."
] | python | train |
rigetti/pyquil | pyquil/quil.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/quil.py#L1002-L1021 | def percolate_declares(program: Program) -> Program:
"""
Move all the DECLARE statements to the top of the program. Return a fresh obejct.
:param program: Perhaps jumbled program.
:return: Program with DECLAREs all at the top and otherwise the same sorted contents.
"""
declare_program = Program... | [
"def",
"percolate_declares",
"(",
"program",
":",
"Program",
")",
"->",
"Program",
":",
"declare_program",
"=",
"Program",
"(",
")",
"instrs_program",
"=",
"Program",
"(",
")",
"for",
"instr",
"in",
"program",
":",
"if",
"isinstance",
"(",
"instr",
",",
"D... | Move all the DECLARE statements to the top of the program. Return a fresh obejct.
:param program: Perhaps jumbled program.
:return: Program with DECLAREs all at the top and otherwise the same sorted contents. | [
"Move",
"all",
"the",
"DECLARE",
"statements",
"to",
"the",
"top",
"of",
"the",
"program",
".",
"Return",
"a",
"fresh",
"obejct",
"."
] | python | train |
rbuffat/pyepw | pyepw/epw.py | https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L5968-L5998 | def dew_point_temperature(self, value=99.9):
"""Corresponds to IDD Field `dew_point_temperature`
Args:
value (float): value for IDD Field `dew_point_temperature`
Unit: C
value > -70.0
value < 70.0
Missing value: 99.9
... | [
"def",
"dew_point_temperature",
"(",
"self",
",",
"value",
"=",
"99.9",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be ... | Corresponds to IDD Field `dew_point_temperature`
Args:
value (float): value for IDD Field `dew_point_temperature`
Unit: C
value > -70.0
value < 70.0
Missing value: 99.9
if `value` is None it will not be checked against ... | [
"Corresponds",
"to",
"IDD",
"Field",
"dew_point_temperature"
] | python | train |
saeschdivara/ArangoPy | arangodb/query/simple.py | https://github.com/saeschdivara/ArangoPy/blob/b924cc57bed71520fc2ef528b917daeb98e10eca/arangodb/query/simple.py#L281-L310 | def range(cls, collection, attribute, left, right, closed, index_id, skip=None, limit=None):
"""
This will find all documents within a given range. In order to execute a range query, a
skip-list index on the queried attribute must be present.
:param collection Collection ins... | [
"def",
"range",
"(",
"cls",
",",
"collection",
",",
"attribute",
",",
"left",
",",
"right",
",",
"closed",
",",
"index_id",
",",
"skip",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"'index'",
":",
"index_id",
",",
"'attribut... | This will find all documents within a given range. In order to execute a range query, a
skip-list index on the queried attribute must be present.
:param collection Collection instance
:param attribute The attribute path to check
:param left The lower bound
:p... | [
"This",
"will",
"find",
"all",
"documents",
"within",
"a",
"given",
"range",
".",
"In",
"order",
"to",
"execute",
"a",
"range",
"query",
"a",
"skip",
"-",
"list",
"index",
"on",
"the",
"queried",
"attribute",
"must",
"be",
"present",
"."
] | python | train |
Jajcus/pyxmpp2 | pyxmpp2/ext/register.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/register.py#L175-L198 | def complete_xml_element(self, xmlnode, doc):
"""Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the elemen... | [
"def",
"complete_xml_element",
"(",
"self",
",",
"xmlnode",
",",
"doc",
")",
":",
"ns",
"=",
"xmlnode",
".",
"ns",
"(",
")",
"if",
"self",
".",
"instructions",
"is",
"not",
"None",
":",
"xmlnode",
".",
"newTextChild",
"(",
"ns",
",",
"\"instructions\"",
... | Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libx... | [
"Complete",
"the",
"XML",
"node",
"with",
"self",
"content",
"."
] | python | valid |
iotile/coretools | iotilesensorgraph/iotile/sg/scripts/iotile_sgrun.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/scripts/iotile_sgrun.py#L77-L114 | def process_mock_rpc(input_string):
"""Process a mock RPC argument.
Args:
input_string (str): The input string that should be in the format
<slot id>:<rpc id> = value
"""
spec, equals, value = input_string.partition(u'=')
if len(equals) == 0:
print("Could not parse moc... | [
"def",
"process_mock_rpc",
"(",
"input_string",
")",
":",
"spec",
",",
"equals",
",",
"value",
"=",
"input_string",
".",
"partition",
"(",
"u'='",
")",
"if",
"len",
"(",
"equals",
")",
"==",
"0",
":",
"print",
"(",
"\"Could not parse mock RPC argument: {}\"",
... | Process a mock RPC argument.
Args:
input_string (str): The input string that should be in the format
<slot id>:<rpc id> = value | [
"Process",
"a",
"mock",
"RPC",
"argument",
"."
] | python | train |
pymc-devs/pymc | pymc/distributions.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2365-L2404 | def rtruncated_poisson(mu, k, size=None):
"""
Random truncated Poisson variates with minimum value k, generated
using rejection sampling.
"""
# Calculate m
try:
m = max(0, np.floor(k - mu))
except (TypeError, ValueError):
# More than one mu
return np.array([rtruncate... | [
"def",
"rtruncated_poisson",
"(",
"mu",
",",
"k",
",",
"size",
"=",
"None",
")",
":",
"# Calculate m",
"try",
":",
"m",
"=",
"max",
"(",
"0",
",",
"np",
".",
"floor",
"(",
"k",
"-",
"mu",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
"... | Random truncated Poisson variates with minimum value k, generated
using rejection sampling. | [
"Random",
"truncated",
"Poisson",
"variates",
"with",
"minimum",
"value",
"k",
"generated",
"using",
"rejection",
"sampling",
"."
] | python | train |
SylvanasSun/python-common-cache | common_cache/__init__.py | https://github.com/SylvanasSun/python-common-cache/blob/f113eb3cd751eed5ab5373e8610a31a444220cf8/common_cache/__init__.py#L521-L534 | def set_capacity(self, new_capacity, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> cache.set_capacity(100)
>>> cache.capacity
100
>>> cache.set_capacity('haha')
>>> cache.capacity
100
"""
if not isinstance(new_capac... | [
"def",
"set_capacity",
"(",
"self",
",",
"new_capacity",
",",
"only_read",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"new_capacity",
",",
"int",
")",
"or",
"new_capacity",
"<=",
"0",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Parame... | >>> cache = Cache(log_level=logging.WARNING)
>>> cache.set_capacity(100)
>>> cache.capacity
100
>>> cache.set_capacity('haha')
>>> cache.capacity
100 | [
">>>",
"cache",
"=",
"Cache",
"(",
"log_level",
"=",
"logging",
".",
"WARNING",
")",
">>>",
"cache",
".",
"set_capacity",
"(",
"100",
")",
">>>",
"cache",
".",
"capacity",
"100",
">>>",
"cache",
".",
"set_capacity",
"(",
"haha",
")",
">>>",
"cache",
".... | python | train |
rraadd88/rohan | rohan/dandage/io_strs.py | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_strs.py#L174-L181 | def get_time():
"""
Gets current time in a form of a formated string. Used in logger function.
"""
import datetime
time=make_pathable_string('%s' % datetime.datetime.now())
return time.replace('-','_').replace(':','_').replace('.','_') | [
"def",
"get_time",
"(",
")",
":",
"import",
"datetime",
"time",
"=",
"make_pathable_string",
"(",
"'%s'",
"%",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
"return",
"time",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
".",
"replace",
"(",
... | Gets current time in a form of a formated string. Used in logger function. | [
"Gets",
"current",
"time",
"in",
"a",
"form",
"of",
"a",
"formated",
"string",
".",
"Used",
"in",
"logger",
"function",
"."
] | python | train |
facelessuser/backrefs | backrefs/uniprops/__init__.py | https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/backrefs/uniprops/__init__.py#L369-L380 | def get_block_property(value, is_bytes=False):
"""Get `BLK` property."""
obj = unidata.ascii_blocks if is_bytes else unidata.unicode_blocks
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_alias['block'].get(negated, negated)
else:
value = unidata.uni... | [
"def",
"get_block_property",
"(",
"value",
",",
"is_bytes",
"=",
"False",
")",
":",
"obj",
"=",
"unidata",
".",
"ascii_blocks",
"if",
"is_bytes",
"else",
"unidata",
".",
"unicode_blocks",
"if",
"value",
".",
"startswith",
"(",
"'^'",
")",
":",
"negated",
"... | Get `BLK` property. | [
"Get",
"BLK",
"property",
"."
] | python | train |
saltstack/salt | salt/modules/bcache.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L404-L448 | def status(stats=False, config=False, internals=False, superblock=False, alldevs=False):
'''
Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' b... | [
"def",
"status",
"(",
"stats",
"=",
"False",
",",
"config",
"=",
"False",
",",
"internals",
"=",
"False",
",",
"superblock",
"=",
"False",
",",
"alldevs",
"=",
"False",
")",
":",
"bdevs",
"=",
"[",
"]",
"for",
"_",
",",
"links",
",",
"_",
"in",
"... | Show the full status of the BCache system and optionally all it's involved devices
CLI example:
.. code-block:: bash
salt '*' bcache.status
salt '*' bcache.status stats=True
salt '*' bcache.status internals=True alldevs=True
:param stats: include statistics
:param config: inc... | [
"Show",
"the",
"full",
"status",
"of",
"the",
"BCache",
"system",
"and",
"optionally",
"all",
"it",
"s",
"involved",
"devices"
] | python | train |
kytos/kytos-utils | kytos/utils/napps.py | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L415-L430 | def create_ui_structure(cls, username, napp_name, ui_templates_path,
context):
"""Create the ui directory structure."""
for section in ['k-info-panel', 'k-toolbar', 'k-action-menu']:
os.makedirs(os.path.join(username, napp_name, 'ui', section))
templates ... | [
"def",
"create_ui_structure",
"(",
"cls",
",",
"username",
",",
"napp_name",
",",
"ui_templates_path",
",",
"context",
")",
":",
"for",
"section",
"in",
"[",
"'k-info-panel'",
",",
"'k-toolbar'",
",",
"'k-action-menu'",
"]",
":",
"os",
".",
"makedirs",
"(",
... | Create the ui directory structure. | [
"Create",
"the",
"ui",
"directory",
"structure",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L660-L675 | def layer_norm_compute(x, epsilon, scale, bias, layer_collection=None):
"""Layer norm raw computation."""
# Save these before they get converted to tensors by the casting below
params = (scale, bias)
epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]]
mean = tf.reduce_mean(x, axis=[-1],... | [
"def",
"layer_norm_compute",
"(",
"x",
",",
"epsilon",
",",
"scale",
",",
"bias",
",",
"layer_collection",
"=",
"None",
")",
":",
"# Save these before they get converted to tensors by the casting below",
"params",
"=",
"(",
"scale",
",",
"bias",
")",
"epsilon",
",",... | Layer norm raw computation. | [
"Layer",
"norm",
"raw",
"computation",
"."
] | python | train |
eonpatapon/contrail-api-cli | contrail_api_cli/utils.py | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/utils.py#L307-L342 | def format_table(rows, sep=' '):
"""Format table
:param sep: separator between columns
:type sep: unicode on python2 | str on python3
Given the table::
table = [
['foo', 'bar', 'foo'],
[1, 2, 3],
['54a5a05d-c83b-4bb5-bd95-d90d6ea4a878'],
['foo'... | [
"def",
"format_table",
"(",
"rows",
",",
"sep",
"=",
"' '",
")",
":",
"max_col_length",
"=",
"[",
"0",
"]",
"*",
"100",
"# calculate max length for each col",
"for",
"row",
"in",
"rows",
":",
"for",
"index",
",",
"(",
"col",
",",
"length",
")",
"in",
... | Format table
:param sep: separator between columns
:type sep: unicode on python2 | str on python3
Given the table::
table = [
['foo', 'bar', 'foo'],
[1, 2, 3],
['54a5a05d-c83b-4bb5-bd95-d90d6ea4a878'],
['foo', 45, 'bar', 2345]
]
`format... | [
"Format",
"table"
] | python | train |
buriburisuri/sugartensor | sugartensor/sg_transform.py | https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L582-L620 | def sg_periodic_shuffle(tensor, opt):
r""" Periodic shuffle transformation for SubPixel CNN.
(see [Shi et al. 2016](http://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Shi_Real-Time_Single_Image_CVPR_2016_paper.pdf)
Args:
tensor: A tensor (automatically given by chain).
... | [
"def",
"sg_periodic_shuffle",
"(",
"tensor",
",",
"opt",
")",
":",
"# default factor",
"opt",
"+=",
"tf",
".",
"sg_opt",
"(",
"factor",
"=",
"2",
")",
"# get current shape",
"batch",
",",
"row",
",",
"col",
",",
"channel",
"=",
"tensor",
".",
"get_shape",
... | r""" Periodic shuffle transformation for SubPixel CNN.
(see [Shi et al. 2016](http://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Shi_Real-Time_Single_Image_CVPR_2016_paper.pdf)
Args:
tensor: A tensor (automatically given by chain).
opt:
factor: factor to multiply s... | [
"r",
"Periodic",
"shuffle",
"transformation",
"for",
"SubPixel",
"CNN",
".",
"(",
"see",
"[",
"Shi",
"et",
"al",
".",
"2016",
"]",
"(",
"http",
":",
"//",
"www",
".",
"cv",
"-",
"foundation",
".",
"org",
"/",
"openaccess",
"/",
"content_cvpr_2016",
"/"... | python | train |
chemlab/chemlab | chemlab/mviewer/api/selections.py | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/selections.py#L137-L150 | def unhide_selected():
'''Unhide the selected objects'''
hidden_state = current_representation().hidden_state
selection_state = current_representation().selection_state
res = {}
# Take the hidden state and flip the selected atoms bits.
for k in selection_state:
visible = hidden_sta... | [
"def",
"unhide_selected",
"(",
")",
":",
"hidden_state",
"=",
"current_representation",
"(",
")",
".",
"hidden_state",
"selection_state",
"=",
"current_representation",
"(",
")",
".",
"selection_state",
"res",
"=",
"{",
"}",
"# Take the hidden state and flip the selecte... | Unhide the selected objects | [
"Unhide",
"the",
"selected",
"objects"
] | python | train |
mfcloud/python-zvm-sdk | zvmsdk/volumeop.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/volumeop.py#L565-L586 | def _detach(self, fcp, assigner_id, target_wwpn, target_lun,
multipath, os_version, mount_point):
"""Detach a volume from a guest"""
LOG.info('Start to detach device from %s' % assigner_id)
connections = self.fcp_mgr.decrease_fcp_usage(fcp, assigner_id)
try:
... | [
"def",
"_detach",
"(",
"self",
",",
"fcp",
",",
"assigner_id",
",",
"target_wwpn",
",",
"target_lun",
",",
"multipath",
",",
"os_version",
",",
"mount_point",
")",
":",
"LOG",
".",
"info",
"(",
"'Start to detach device from %s'",
"%",
"assigner_id",
")",
"conn... | Detach a volume from a guest | [
"Detach",
"a",
"volume",
"from",
"a",
"guest"
] | python | train |
odlgroup/odl | odl/space/fspace.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L638-L658 | def one(self):
"""Function mapping anything to one."""
# See zero() for remarks
def one_vec(x, out=None, **kwargs):
"""One function, vectorized."""
if is_valid_input_meshgrid(x, self.domain.ndim):
scalar_out_shape = out_shape_from_meshgrid(x)
e... | [
"def",
"one",
"(",
"self",
")",
":",
"# See zero() for remarks",
"def",
"one_vec",
"(",
"x",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"One function, vectorized.\"\"\"",
"if",
"is_valid_input_meshgrid",
"(",
"x",
",",
"self",
".",
"do... | Function mapping anything to one. | [
"Function",
"mapping",
"anything",
"to",
"one",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.