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 |
|---|---|---|---|---|---|---|---|---|
user-cont/conu | conu/backend/docker/backend.py | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/docker/backend.py#L85-L106 | def list_containers(self):
"""
List all available docker containers.
Container objects returned from this methods will contain a limited
amount of metadata in property `short_metadata`. These are just a subset
of `.inspect()`, but don't require an API call against dockerd.
:return: collection of instances of :class:`conu.DockerContainer`
"""
result = []
for c in self.d.containers(all=True):
name = None
names = c.get("Names", None)
if names:
name = names[0]
i = DockerImage(None, identifier=c["ImageID"])
cont = DockerContainer(i, c["Id"], name=name)
# TODO: docker_client.containers produces different metadata than inspect
inspect_to_container_metadata(cont.metadata, c, i)
result.append(cont)
return result | [
"def",
"list_containers",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"d",
".",
"containers",
"(",
"all",
"=",
"True",
")",
":",
"name",
"=",
"None",
"names",
"=",
"c",
".",
"get",
"(",
"\"Names\"",
",",
"None",... | List all available docker containers.
Container objects returned from this methods will contain a limited
amount of metadata in property `short_metadata`. These are just a subset
of `.inspect()`, but don't require an API call against dockerd.
:return: collection of instances of :class:`conu.DockerContainer` | [
"List",
"all",
"available",
"docker",
"containers",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe.py#L119-L131 | def fcoe_fcoe_fabric_map_fcoe_fip_keep_alive_fcoe_fip_keep_alive_timeout(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade.com:mgmt:brocade-fcoe")
fcoe_fabric_map = ET.SubElement(fcoe, "fcoe-fabric-map")
fcoe_fabric_map_name_key = ET.SubElement(fcoe_fabric_map, "fcoe-fabric-map-name")
fcoe_fabric_map_name_key.text = kwargs.pop('fcoe_fabric_map_name')
fcoe_fip_keep_alive = ET.SubElement(fcoe_fabric_map, "fcoe-fip-keep-alive")
fcoe_fip_keep_alive_timeout = ET.SubElement(fcoe_fip_keep_alive, "fcoe-fip-keep-alive-timeout")
callback = kwargs.pop('callback', self._callback)
return callback(config) | [
"def",
"fcoe_fcoe_fabric_map_fcoe_fip_keep_alive_fcoe_fip_keep_alive_timeout",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"fcoe",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"fcoe\"",
",",... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
mozilla/socorrolib | socorrolib/lib/transform_rules.py | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L241-L251 | def function_invocation_proxy(fn, proxy_args, proxy_kwargs):
"""execute the fuction if it is one, else evaluate the fn as a boolean
and return that value.
Sometimes rather than providing a predicate, we just give the value of
True. This is shorthand for writing a predicate that always returns
true."""
try:
return fn(*proxy_args, **proxy_kwargs)
except TypeError:
return bool(fn) | [
"def",
"function_invocation_proxy",
"(",
"fn",
",",
"proxy_args",
",",
"proxy_kwargs",
")",
":",
"try",
":",
"return",
"fn",
"(",
"*",
"proxy_args",
",",
"*",
"*",
"proxy_kwargs",
")",
"except",
"TypeError",
":",
"return",
"bool",
"(",
"fn",
")"
] | execute the fuction if it is one, else evaluate the fn as a boolean
and return that value.
Sometimes rather than providing a predicate, we just give the value of
True. This is shorthand for writing a predicate that always returns
true. | [
"execute",
"the",
"fuction",
"if",
"it",
"is",
"one",
"else",
"evaluate",
"the",
"fn",
"as",
"a",
"boolean",
"and",
"return",
"that",
"value",
"."
] | python | train |
apache/spark | python/pyspark/context.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/context.py#L482-L529 | def parallelize(self, c, numSlices=None):
"""
Distribute a local Python collection to form an RDD. Using xrange
is recommended if the input represents a range for performance.
>>> sc.parallelize([0, 2, 3, 4, 6], 5).glom().collect()
[[0], [2], [3], [4], [6]]
>>> sc.parallelize(xrange(0, 6, 2), 5).glom().collect()
[[], [0], [], [2], [4]]
"""
numSlices = int(numSlices) if numSlices is not None else self.defaultParallelism
if isinstance(c, xrange):
size = len(c)
if size == 0:
return self.parallelize([], numSlices)
step = c[1] - c[0] if size > 1 else 1
start0 = c[0]
def getStart(split):
return start0 + int((split * size / numSlices)) * step
def f(split, iterator):
# it's an empty iterator here but we need this line for triggering the
# logic of signal handling in FramedSerializer.load_stream, for instance,
# SpecialLengths.END_OF_DATA_SECTION in _read_with_length. Since
# FramedSerializer.load_stream produces a generator, the control should
# at least be in that function once. Here we do it by explicitly converting
# the empty iterator to a list, thus make sure worker reuse takes effect.
# See more details in SPARK-26549.
assert len(list(iterator)) == 0
return xrange(getStart(split), getStart(split + 1), step)
return self.parallelize([], numSlices).mapPartitionsWithIndex(f)
# Make sure we distribute data evenly if it's smaller than self.batchSize
if "__len__" not in dir(c):
c = list(c) # Make it a list so we can compute its length
batchSize = max(1, min(len(c) // numSlices, self._batchSize or 1024))
serializer = BatchedSerializer(self._unbatched_serializer, batchSize)
def reader_func(temp_filename):
return self._jvm.PythonRDD.readRDDFromFile(self._jsc, temp_filename, numSlices)
def createRDDServer():
return self._jvm.PythonParallelizeServer(self._jsc.sc(), numSlices)
jrdd = self._serialize_to_jvm(c, serializer, reader_func, createRDDServer)
return RDD(jrdd, self, serializer) | [
"def",
"parallelize",
"(",
"self",
",",
"c",
",",
"numSlices",
"=",
"None",
")",
":",
"numSlices",
"=",
"int",
"(",
"numSlices",
")",
"if",
"numSlices",
"is",
"not",
"None",
"else",
"self",
".",
"defaultParallelism",
"if",
"isinstance",
"(",
"c",
",",
... | Distribute a local Python collection to form an RDD. Using xrange
is recommended if the input represents a range for performance.
>>> sc.parallelize([0, 2, 3, 4, 6], 5).glom().collect()
[[0], [2], [3], [4], [6]]
>>> sc.parallelize(xrange(0, 6, 2), 5).glom().collect()
[[], [0], [], [2], [4]] | [
"Distribute",
"a",
"local",
"Python",
"collection",
"to",
"form",
"an",
"RDD",
".",
"Using",
"xrange",
"is",
"recommended",
"if",
"the",
"input",
"represents",
"a",
"range",
"for",
"performance",
"."
] | python | train |
chrisspen/burlap | burlap/apache.py | https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/apache.py#L366-L400 | def install_auth_basic_user_file(self, site=None):
"""
Installs users for basic httpd auth.
"""
r = self.local_renderer
hostname = self.current_hostname
target_sites = self.genv.available_sites_by_host.get(hostname, None)
for _site, site_data in self.iter_sites(site=site, setter=self.set_site_specifics):
if self.verbose:
print('~'*80, file=sys.stderr)
print('Site:', _site, file=sys.stderr)
print('env.apache_auth_basic:', r.env.auth_basic, file=sys.stderr)
# Only load site configurations that are allowed for this host.
if target_sites is not None:
assert isinstance(target_sites, (tuple, list))
if _site not in target_sites:
continue
if not r.env.auth_basic:
continue
assert r.env.auth_basic_users, 'No apache auth users specified.'
for username, password in r.env.auth_basic_users:
r.env.auth_basic_username = username
r.env.auth_basic_password = password
r.env.apache_site = _site
r.env.fn = r.format(r.env.auth_basic_authuserfile)
if self.files.exists(r.env.fn):
r.sudo('htpasswd -b {fn} {auth_basic_username} {auth_basic_password}')
else:
r.sudo('htpasswd -b -c {fn} {auth_basic_username} {auth_basic_password}') | [
"def",
"install_auth_basic_user_file",
"(",
"self",
",",
"site",
"=",
"None",
")",
":",
"r",
"=",
"self",
".",
"local_renderer",
"hostname",
"=",
"self",
".",
"current_hostname",
"target_sites",
"=",
"self",
".",
"genv",
".",
"available_sites_by_host",
".",
"g... | Installs users for basic httpd auth. | [
"Installs",
"users",
"for",
"basic",
"httpd",
"auth",
"."
] | python | valid |
gccxml/pygccxml | pygccxml/declarations/namespace.py | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/namespace.py#L109-L122 | def namespace(self, name=None, function=None, recursive=None):
"""
Returns reference to namespace declaration that matches
a defined criteria.
"""
return (
self._find_single(
scopedef.scopedef_t._impl_matchers[namespace_t.namespace],
name=name,
function=function,
recursive=recursive)
) | [
"def",
"namespace",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"recursive",
"=",
"None",
")",
":",
"return",
"(",
"self",
".",
"_find_single",
"(",
"scopedef",
".",
"scopedef_t",
".",
"_impl_matchers",
"[",
"namespace_t",
"... | Returns reference to namespace declaration that matches
a defined criteria. | [
"Returns",
"reference",
"to",
"namespace",
"declaration",
"that",
"matches",
"a",
"defined",
"criteria",
"."
] | python | train |
jtpaasch/simplygithub | simplygithub/files.py | https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/files.py#L9-L16 | def prepare(data):
"""Restructure/prepare data about a blob for output."""
result = {}
result["mode"] = data.get("mode")
result["path"] = data.get("path")
result["type"] = data.get("type")
result["sha"] = data.get("sha")
return result | [
"def",
"prepare",
"(",
"data",
")",
":",
"result",
"=",
"{",
"}",
"result",
"[",
"\"mode\"",
"]",
"=",
"data",
".",
"get",
"(",
"\"mode\"",
")",
"result",
"[",
"\"path\"",
"]",
"=",
"data",
".",
"get",
"(",
"\"path\"",
")",
"result",
"[",
"\"type\"... | Restructure/prepare data about a blob for output. | [
"Restructure",
"/",
"prepare",
"data",
"about",
"a",
"blob",
"for",
"output",
"."
] | python | train |
shoebot/shoebot | lib/graph/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L672-L700 | def load(self, id):
""" Rebuilds the graph around the given node id.
"""
self.clear()
# Root node.
self.add_node(id, root=True)
# Directly connected nodes have priority.
for w, id2 in self.get_links(id):
self.add_edge(id, id2, weight=w)
if len(self) > self.max:
break
# Now get all the other nodes in the cluster.
for w, id2, links in self.get_cluster(id):
for id3 in links:
self.add_edge(id3, id2, weight=w)
self.add_edge(id, id3, weight=w)
#if len(links) == 0:
# self.add_edge(id, id2)
if len(self) > self.max:
break
# Provide a backlink to the previous root.
if self.event.clicked:
g.add_node(self.event.clicked) | [
"def",
"load",
"(",
"self",
",",
"id",
")",
":",
"self",
".",
"clear",
"(",
")",
"# Root node.",
"self",
".",
"add_node",
"(",
"id",
",",
"root",
"=",
"True",
")",
"# Directly connected nodes have priority.",
"for",
"w",
",",
"id2",
"in",
"self",
".",
... | Rebuilds the graph around the given node id. | [
"Rebuilds",
"the",
"graph",
"around",
"the",
"given",
"node",
"id",
"."
] | python | valid |
dswah/pyGAM | pygam/utils.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/utils.py#L307-L322 | def check_X_y(X, y):
"""
tool to ensure input and output data have the same number of samples
Parameters
----------
X : array-like
y : array-like
Returns
-------
None
"""
if len(X) != len(y):
raise ValueError('Inconsistent input and output data shapes. '\
'found X: {} and y: {}'.format(X.shape, y.shape)) | [
"def",
"check_X_y",
"(",
"X",
",",
"y",
")",
":",
"if",
"len",
"(",
"X",
")",
"!=",
"len",
"(",
"y",
")",
":",
"raise",
"ValueError",
"(",
"'Inconsistent input and output data shapes. '",
"'found X: {} and y: {}'",
".",
"format",
"(",
"X",
".",
"shape",
",... | tool to ensure input and output data have the same number of samples
Parameters
----------
X : array-like
y : array-like
Returns
-------
None | [
"tool",
"to",
"ensure",
"input",
"and",
"output",
"data",
"have",
"the",
"same",
"number",
"of",
"samples"
] | python | train |
pyroscope/pyrocore | src/pyrocore/daemon/webapp.py | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/daemon/webapp.py#L112-L121 | def guarded(self, func, *args, **kwargs):
""" Call a function, return None on errors.
"""
try:
return func(*args, **kwargs)
except (EnvironmentError, error.LoggableError, xmlrpc.ERRORS) as g_exc:
if func.__name__ not in self.ERRORS_LOGGED:
self.LOG.warn("While calling '%s': %s" % (func.__name__, g_exc))
self.ERRORS_LOGGED.add(func.__name__)
return None | [
"def",
"guarded",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"(",
"EnvironmentError",
",",
"error",
".",
"LoggableError",
",... | Call a function, return None on errors. | [
"Call",
"a",
"function",
"return",
"None",
"on",
"errors",
"."
] | python | train |
midasplatform/pydas | pydas/drivers.py | https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L684-L711 | def download_item(self, item_id, token=None, revision=None):
"""
Download an item to disk.
:param item_id: The id of the item to be downloaded.
:type item_id: int | long
:param token: (optional) The authentication token of the user
requesting the download.
:type token: None | string
:param revision: (optional) The revision of the item to download, this
defaults to HEAD.
:type revision: None | int | long
:returns: A tuple of the filename and the content iterator.
:rtype: (string, unknown)
"""
parameters = dict()
parameters['id'] = item_id
if token:
parameters['token'] = token
if revision:
parameters['revision'] = revision
method_url = self.full_url + 'midas.item.download'
request = requests.get(method_url,
params=parameters,
stream=True,
verify=self._verify_ssl_certificate)
filename = request.headers['content-disposition'][21:].strip('"')
return filename, request.iter_content(chunk_size=10 * 1024) | [
"def",
"download_item",
"(",
"self",
",",
"item_id",
",",
"token",
"=",
"None",
",",
"revision",
"=",
"None",
")",
":",
"parameters",
"=",
"dict",
"(",
")",
"parameters",
"[",
"'id'",
"]",
"=",
"item_id",
"if",
"token",
":",
"parameters",
"[",
"'token'... | Download an item to disk.
:param item_id: The id of the item to be downloaded.
:type item_id: int | long
:param token: (optional) The authentication token of the user
requesting the download.
:type token: None | string
:param revision: (optional) The revision of the item to download, this
defaults to HEAD.
:type revision: None | int | long
:returns: A tuple of the filename and the content iterator.
:rtype: (string, unknown) | [
"Download",
"an",
"item",
"to",
"disk",
"."
] | python | valid |
PyMySQL/PyMySQL | pymysql/cursors.py | https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/cursors.py#L47-L58 | def close(self):
"""
Closing a cursor just exhausts all remaining data.
"""
conn = self.connection
if conn is None:
return
try:
while self.nextset():
pass
finally:
self.connection = None | [
"def",
"close",
"(",
"self",
")",
":",
"conn",
"=",
"self",
".",
"connection",
"if",
"conn",
"is",
"None",
":",
"return",
"try",
":",
"while",
"self",
".",
"nextset",
"(",
")",
":",
"pass",
"finally",
":",
"self",
".",
"connection",
"=",
"None"
] | Closing a cursor just exhausts all remaining data. | [
"Closing",
"a",
"cursor",
"just",
"exhausts",
"all",
"remaining",
"data",
"."
] | python | train |
pywbem/pywbem | pywbem/mof_compiler.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L2507-L2536 | def find_mof(self, classname):
"""
Find the MOF file that defines a particular CIM class, in the search
path of the MOF compiler.
The MOF file is found based on its file name: It is assumed that the
base part of the file name is the CIM class name.
Example: The class "CIM_ComputerSystem" is expected to be in a file
"CIM_ComputerSystem.mof".
Parameters:
classame (:term:`string`):
The name of the CIM class to look up.
Returns:
:term:`string`: Path name of the MOF file defining the CIM class, if
it was found. `None`, if it was not found.
"""
classname = classname.lower()
for search in self.parser.search_paths:
for root, dummy_dirs, files in os.walk(search):
for file_ in files:
if file_.endswith('.mof') and \
file_[:-4].lower() == classname:
return os.path.join(root, file_)
return None | [
"def",
"find_mof",
"(",
"self",
",",
"classname",
")",
":",
"classname",
"=",
"classname",
".",
"lower",
"(",
")",
"for",
"search",
"in",
"self",
".",
"parser",
".",
"search_paths",
":",
"for",
"root",
",",
"dummy_dirs",
",",
"files",
"in",
"os",
".",
... | Find the MOF file that defines a particular CIM class, in the search
path of the MOF compiler.
The MOF file is found based on its file name: It is assumed that the
base part of the file name is the CIM class name.
Example: The class "CIM_ComputerSystem" is expected to be in a file
"CIM_ComputerSystem.mof".
Parameters:
classame (:term:`string`):
The name of the CIM class to look up.
Returns:
:term:`string`: Path name of the MOF file defining the CIM class, if
it was found. `None`, if it was not found. | [
"Find",
"the",
"MOF",
"file",
"that",
"defines",
"a",
"particular",
"CIM",
"class",
"in",
"the",
"search",
"path",
"of",
"the",
"MOF",
"compiler",
"."
] | python | train |
plandes/actioncli | src/python/zensols/actioncli/factory.py | https://github.com/plandes/actioncli/blob/d1c4ea27e6f3394b30a1652ddd4b916160662773/src/python/zensols/actioncli/factory.py#L33-L41 | def parse_module_class(self):
"""Parse the module and class name part of the fully qualifed class name.
"""
cname = self.class_name
match = re.match(self.CLASS_REGEX, cname)
if not match:
raise ValueError(f'not a fully qualified class name: {cname}')
return match.groups() | [
"def",
"parse_module_class",
"(",
"self",
")",
":",
"cname",
"=",
"self",
".",
"class_name",
"match",
"=",
"re",
".",
"match",
"(",
"self",
".",
"CLASS_REGEX",
",",
"cname",
")",
"if",
"not",
"match",
":",
"raise",
"ValueError",
"(",
"f'not a fully qualifi... | Parse the module and class name part of the fully qualifed class name. | [
"Parse",
"the",
"module",
"and",
"class",
"name",
"part",
"of",
"the",
"fully",
"qualifed",
"class",
"name",
"."
] | python | train |
push-things/django-th | th_trello/my_trello.py | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_trello/my_trello.py#L89-L153 | def save_data(self, trigger_id, **data):
"""
let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean
"""
data['output_format'] = 'md'
title, content = super(ServiceTrello, self).save_data(trigger_id, **data)
if len(title):
# get the data of this trigger
t = Trello.objects.get(trigger_id=trigger_id)
# footer of the card
footer = self.set_card_footer(data, t)
content += footer
# 1 - we need to search the list and board where we will
# store the card so ...
# 1.a search the board_id by its name
# by retrieving all the boards
boards = self.trello_instance.list_boards()
board_id = ''
my_list = ''
for board in boards:
if t.board_name == board.name:
board_id = board.id
break
if board_id:
# 1.b search the list_id by its name
my_board = self.trello_instance.get_board(board_id)
lists = my_board.open_lists()
# just get the open list ; not all the archive ones
for list_in_board in lists:
# search the name of the list we set in the form
if t.list_name == list_in_board.name:
# return the (trello) list object to be able to add card at step 3
my_list = my_board.get_list(list_in_board.id)
break
# we didnt find the list in that board -> create it
if my_list == '':
my_list = my_board.add_list(t.list_name)
else:
# 2 if board_id and/or list_id does not exist, create it/them
my_board = self.trello_instance.add_board(t.board_name)
# add the list that didn't exists and return a (trello) list object
my_list = my_board.add_list(t.list_name)
# 3 create the card
my_list.add_card(title, content)
logger.debug(str('trello {} created').format(data['link']))
status = True
else:
sentence = "no token or link provided for trigger ID {}".format(trigger_id)
update_result(trigger_id, msg=sentence, status=False)
status = False
return status | [
"def",
"save_data",
"(",
"self",
",",
"trigger_id",
",",
"*",
"*",
"data",
")",
":",
"data",
"[",
"'output_format'",
"]",
"=",
"'md'",
"title",
",",
"content",
"=",
"super",
"(",
"ServiceTrello",
",",
"self",
")",
".",
"save_data",
"(",
"trigger_id",
"... | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | [
"let",
"s",
"save",
"the",
"data"
] | python | train |
gpoulter/fablib | fablib.py | https://github.com/gpoulter/fablib/blob/5d14c4d998f79dd1aa3207063c3d06e30e3e2bf9/fablib.py#L178-L189 | def install_deb(pkgname, url):
"""Install package from custom deb hosted on S3.
Return true if package was installed by this invocation."""
status = run("dpkg-query -W -f='${{Status}}' {p}; true".format(p=pkgname))
if ('installed' not in status) or ('not-installed' in status):
deb = url.rpartition('/')[2]
debtmp = '/tmp/{}'.format(deb)
run("wget --no-check-certificate -qc -O '{}' '{}'".format(debtmp, url))
sudo("dpkg -i '{0}' && rm -f '{0}'".format(debtmp))
return True
else:
return False | [
"def",
"install_deb",
"(",
"pkgname",
",",
"url",
")",
":",
"status",
"=",
"run",
"(",
"\"dpkg-query -W -f='${{Status}}' {p}; true\"",
".",
"format",
"(",
"p",
"=",
"pkgname",
")",
")",
"if",
"(",
"'installed'",
"not",
"in",
"status",
")",
"or",
"(",
"'not... | Install package from custom deb hosted on S3.
Return true if package was installed by this invocation. | [
"Install",
"package",
"from",
"custom",
"deb",
"hosted",
"on",
"S3",
".",
"Return",
"true",
"if",
"package",
"was",
"installed",
"by",
"this",
"invocation",
"."
] | python | train |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L655-L672 | def is_parent_of(self, parent, child):
"""Return whether ``child`` is a branch descended from ``parent`` at
any remove.
"""
if parent == 'trunk':
return True
if child == 'trunk':
return False
if child not in self._branches:
raise ValueError(
"The branch {} seems not to have ever been created".format(
child
)
)
if self._branches[child][0] == parent:
return True
return self.is_parent_of(parent, self._branches[child][0]) | [
"def",
"is_parent_of",
"(",
"self",
",",
"parent",
",",
"child",
")",
":",
"if",
"parent",
"==",
"'trunk'",
":",
"return",
"True",
"if",
"child",
"==",
"'trunk'",
":",
"return",
"False",
"if",
"child",
"not",
"in",
"self",
".",
"_branches",
":",
"raise... | Return whether ``child`` is a branch descended from ``parent`` at
any remove. | [
"Return",
"whether",
"child",
"is",
"a",
"branch",
"descended",
"from",
"parent",
"at",
"any",
"remove",
"."
] | python | train |
buildbot/buildbot | master/buildbot/scripts/runner.py | https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/scripts/runner.py#L38-L54 | def validateMasterOption(master):
"""
Validate master (-m, --master) command line option.
Checks that option is a string of the 'hostname:port' form, otherwise
raises an UsageError exception.
@type master: string
@param master: master option
@raise usage.UsageError: on invalid master option
"""
try:
hostname, port = master.split(":")
port = int(port)
except (TypeError, ValueError):
raise usage.UsageError("master must have the form 'hostname:port'") | [
"def",
"validateMasterOption",
"(",
"master",
")",
":",
"try",
":",
"hostname",
",",
"port",
"=",
"master",
".",
"split",
"(",
"\":\"",
")",
"port",
"=",
"int",
"(",
"port",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"usage"... | Validate master (-m, --master) command line option.
Checks that option is a string of the 'hostname:port' form, otherwise
raises an UsageError exception.
@type master: string
@param master: master option
@raise usage.UsageError: on invalid master option | [
"Validate",
"master",
"(",
"-",
"m",
"--",
"master",
")",
"command",
"line",
"option",
"."
] | python | train |
timkpaine/pyEX | pyEX/common.py | https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/common.py#L133-L139 | def _strOrDate(st):
'''internal'''
if isinstance(st, string_types):
return st
elif isinstance(st, datetime):
return st.strftime('%Y%m%d')
raise PyEXception('Not a date: %s', str(st)) | [
"def",
"_strOrDate",
"(",
"st",
")",
":",
"if",
"isinstance",
"(",
"st",
",",
"string_types",
")",
":",
"return",
"st",
"elif",
"isinstance",
"(",
"st",
",",
"datetime",
")",
":",
"return",
"st",
".",
"strftime",
"(",
"'%Y%m%d'",
")",
"raise",
"PyEXcep... | internal | [
"internal"
] | python | valid |
gwpy/gwpy | gwpy/signal/filter_design.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/signal/filter_design.py#L102-L132 | def num_taps(sample_rate, transitionwidth, gpass, gstop):
"""Returns the number of taps for an FIR filter with the given shape
Parameters
----------
sample_rate : `float`
sampling rate of target data
transitionwidth : `float`
the width (in the same units as `sample_rate` of the transition
from stop-band to pass-band
gpass : `float`
the maximum loss in the passband (dB)
gstop : `float`
the minimum attenuation in the stopband (dB)
Returns
-------
numtaps : `int`
the number of taps for an FIR filter
Notes
-----
Credit: http://dsp.stackexchange.com/a/31077/8223
"""
gpass = 10 ** (-gpass / 10.)
gstop = 10 ** (-gstop / 10.)
return int(2/3. * log10(1 / (10 * gpass * gstop)) *
sample_rate / transitionwidth) | [
"def",
"num_taps",
"(",
"sample_rate",
",",
"transitionwidth",
",",
"gpass",
",",
"gstop",
")",
":",
"gpass",
"=",
"10",
"**",
"(",
"-",
"gpass",
"/",
"10.",
")",
"gstop",
"=",
"10",
"**",
"(",
"-",
"gstop",
"/",
"10.",
")",
"return",
"int",
"(",
... | Returns the number of taps for an FIR filter with the given shape
Parameters
----------
sample_rate : `float`
sampling rate of target data
transitionwidth : `float`
the width (in the same units as `sample_rate` of the transition
from stop-band to pass-band
gpass : `float`
the maximum loss in the passband (dB)
gstop : `float`
the minimum attenuation in the stopband (dB)
Returns
-------
numtaps : `int`
the number of taps for an FIR filter
Notes
-----
Credit: http://dsp.stackexchange.com/a/31077/8223 | [
"Returns",
"the",
"number",
"of",
"taps",
"for",
"an",
"FIR",
"filter",
"with",
"the",
"given",
"shape"
] | python | train |
saltstack/salt | salt/thorium/calc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L273-L293 | def mode(name, num, minimum=0, maximum=0, ref=None):
'''
Calculates the mode of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.mode:
- name: myregentry
- num: 5
'''
return calc(
name=name,
num=num,
oper='mode',
minimum=minimum,
maximum=maximum,
ref=ref
) | [
"def",
"mode",
"(",
"name",
",",
"num",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"0",
",",
"ref",
"=",
"None",
")",
":",
"return",
"calc",
"(",
"name",
"=",
"name",
",",
"num",
"=",
"num",
",",
"oper",
"=",
"'mode'",
",",
"minimum",
"=",
... | Calculates the mode of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.mode:
- name: myregentry
- num: 5 | [
"Calculates",
"the",
"mode",
"of",
"the",
"num",
"most",
"recent",
"values",
".",
"Requires",
"a",
"list",
"."
] | python | train |
idlesign/uwsgiconf | uwsgiconf/contrib/django/uwsgify/toolbox.py | https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/contrib/django/uwsgify/toolbox.py#L201-L231 | def mutate(self):
"""Mutates current section."""
section = self.section
project_name = self.project_name
section.project_name = project_name
self.contribute_runtime_dir()
main = section.main_process
main.set_naming_params(prefix='[%s] ' % project_name)
main.set_pid_file(
self.get_pid_filepath(),
before_priv_drop=False, # For vacuum to cleanup properly.
safe=True,
)
section.master_process.set_basic_params(
fifo_file=self.get_fifo_filepath(),
)
# todo maybe autoreload in debug
apps = section.applications
apps.set_basic_params(
manage_script_name=True,
)
self.contribute_error_pages()
self.contribute_static() | [
"def",
"mutate",
"(",
"self",
")",
":",
"section",
"=",
"self",
".",
"section",
"project_name",
"=",
"self",
".",
"project_name",
"section",
".",
"project_name",
"=",
"project_name",
"self",
".",
"contribute_runtime_dir",
"(",
")",
"main",
"=",
"section",
".... | Mutates current section. | [
"Mutates",
"current",
"section",
"."
] | python | train |
gwastro/pycbc | pycbc/workflow/coincidence.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/coincidence.py#L549-L592 | def setup_interval_coinc(workflow, hdfbank, trig_files, stat_files,
veto_files, veto_names, out_dir, tags=None):
"""
This function sets up exact match coincidence and background estimation
using a folded interval technique.
"""
if tags is None:
tags = []
make_analysis_dir(out_dir)
logging.info('Setting up coincidence')
if len(hdfbank) != 1:
raise ValueError('Must use exactly 1 bank file for this coincidence '
'method, I got %i !' % len(hdfbank))
hdfbank = hdfbank[0]
if len(workflow.ifos) > 2:
raise ValueError('This coincidence method only supports two-ifo searches')
findcoinc_exe = PyCBCFindCoincExecutable(workflow.cp, 'coinc',
ifos=workflow.ifos,
tags=tags, out_dir=out_dir)
# Wall time knob and memory knob
factor = int(workflow.cp.get_opt_tags('workflow-coincidence', 'parallelization-factor', tags))
statmap_files = []
for veto_file, veto_name in zip(veto_files, veto_names):
bg_files = FileList()
for i in range(factor):
group_str = '%s/%s' % (i, factor)
coinc_node = findcoinc_exe.create_node(trig_files, hdfbank,
stat_files,
veto_file, veto_name,
group_str,
tags=[veto_name, str(i)])
bg_files += coinc_node.output_files
workflow.add_node(coinc_node)
statmap_files += [setup_statmap(workflow, bg_files, hdfbank, out_dir, tags=tags + [veto_name])]
logging.info('...leaving coincidence ')
return statmap_files | [
"def",
"setup_interval_coinc",
"(",
"workflow",
",",
"hdfbank",
",",
"trig_files",
",",
"stat_files",
",",
"veto_files",
",",
"veto_names",
",",
"out_dir",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"make_... | This function sets up exact match coincidence and background estimation
using a folded interval technique. | [
"This",
"function",
"sets",
"up",
"exact",
"match",
"coincidence",
"and",
"background",
"estimation"
] | python | train |
waqasbhatti/astrobase | astrobase/services/lccs.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/lccs.py#L492-L715 | def retrieve_dataset_files(searchresult,
getpickle=False,
outdir=None,
apikey=None):
'''This retrieves a search result dataset's CSV and any LC zip files.
Takes the output from the `submit_post_searchquery` function above or a
pickle file generated from that function's output if the query timed out.
Parameters
----------
searchresult : str or tuple
If provided as a str, points to the pickle file created using the output
from the `submit_post_searchquery` function. If provided as a tuple,
this is the result tuple from the `submit_post_searchquery` function.
getpickle : False
If this is True, will also download the dataset's pickle. Note that
LCC-Server is a Python 3.6+ package (while lccs.py still works with
Python 2.7) and it saves its pickles in pickle.HIGHEST_PROTOCOL for
efficiency, so these pickles may be unreadable in lower Pythons. As an
alternative, the dataset CSV contains the full data table and all the
information about the dataset in its header, which is JSON
parseable. You can also use the function `get_dataset` below to get the
dataset pickle information in JSON form.
outdir : None or str
If this is a str, points to the output directory where the results will
be placed. If it's None, they will be placed in the current directory.
apikey : str or None
If this is a str, uses the given API key to authenticate the download
request. This is useful when you have a private dataset you want to get
products for.
Returns
-------
(local_dataset_csv, local_dataset_lczip, local_dataset_pickle) : tuple
This returns a tuple containing paths to the dataset CSV, LC zipfile,
and the dataset pickle if getpickle was set to True (None otherwise).
'''
# this handles the direct result case from submit_*_query functions
if isinstance(searchresult, tuple):
info, setid = searchresult[1:]
# handles the case where we give the function a existing query pickle
elif isinstance(searchresult, str) and os.path.exists(searchresult):
with open(searchresult,'rb') as infd:
info = pickle.load(infd)
setid = info['result']['setid']
else:
LOGERROR('could not understand input, '
'we need a searchresult from the '
'lccs.submit_post_searchquery function or '
'the path to an existing query pickle')
return None, None, None
# now that we have everything, let's download some files!
dataset_pickle = 'dataset-%s.pkl.gz' % setid
dataset_csv = 'dataset-%s.csv' % setid
dataset_lczip = 'lightcurves-%s.zip' % setid
if outdir is None:
localdir = os.getcwd()
else:
localdir = outdir
server_scheme, server_netloc = urlparse(info['result']['seturl'])[:2]
dataset_pickle_link = '%s://%s/d/%s' % (server_scheme,
server_netloc,
dataset_pickle)
dataset_csv_link = '%s://%s/d/%s' % (server_scheme,
server_netloc,
dataset_csv)
dataset_lczip_link = '%s://%s/p/%s' % (server_scheme,
server_netloc,
dataset_lczip)
if getpickle:
# get the dataset pickle
LOGINFO('getting %s...' % dataset_pickle_link)
try:
if os.path.exists(os.path.join(localdir, dataset_pickle)):
LOGWARNING('dataset pickle already exists, '
'not downloading again..')
local_dataset_pickle = os.path.join(localdir,
dataset_pickle)
else:
# if apikey is not None, add it in as an Authorization: Bearer
# [apikey] header
if apikey:
headers = {'Authorization':'Bearer: %s' % apikey}
else:
headers = {}
req = Request(
dataset_pickle_link,
data=None,
headers=headers
)
resp = urlopen(req)
# save the file
LOGINFO('saving %s' % dataset_pickle)
localf = os.path.join(localdir, dataset_pickle)
with open(localf, 'wb') as outfd:
with resp:
data = resp.read()
outfd.write(data)
LOGINFO('OK -> %s' % localf)
local_dataset_pickle = localf
except HTTPError as e:
LOGERROR('could not download %s, '
'HTTP status code was: %s, reason: %s' %
(dataset_pickle_link, e.code, e.reason))
local_dataset_pickle = None
else:
local_dataset_pickle = None
# get the dataset CSV
LOGINFO('getting %s...' % dataset_csv_link)
try:
if os.path.exists(os.path.join(localdir, dataset_csv)):
LOGWARNING('dataset CSV already exists, not downloading again...')
local_dataset_csv = os.path.join(localdir, dataset_csv)
else:
# if apikey is not None, add it in as an Authorization: Bearer
# [apikey] header
if apikey:
headers = {'Authorization':'Bearer: %s' % apikey}
else:
headers = {}
req = Request(
dataset_csv_link,
data=None,
headers=headers
)
resp = urlopen(req)
# save the file
LOGINFO('saving %s' % dataset_csv)
localf = os.path.join(localdir, dataset_csv)
with open(localf, 'wb') as outfd:
with resp:
data = resp.read()
outfd.write(data)
LOGINFO('OK -> %s' % localf)
local_dataset_csv = localf
except HTTPError as e:
LOGERROR('could not download %s, HTTP status code was: %s, reason: %s' %
(dataset_csv_link, e.code, e.reason))
local_dataset_csv = None
# get the dataset LC zip
LOGINFO('getting %s...' % dataset_lczip_link)
try:
if os.path.exists(os.path.join(localdir, dataset_lczip)):
LOGWARNING('dataset LC ZIP already exists, '
'not downloading again...')
local_dataset_lczip = os.path.join(localdir, dataset_lczip)
else:
# if apikey is not None, add it in as an Authorization: Bearer
# [apikey] header
if apikey:
headers = {'Authorization':'Bearer: %s' % apikey}
else:
headers = {}
req = Request(
dataset_lczip_link,
data=None,
headers=headers
)
resp = urlopen(req)
# save the file
LOGINFO('saving %s' % dataset_lczip)
localf = os.path.join(localdir, dataset_lczip)
with open(localf, 'wb') as outfd:
with resp:
data = resp.read()
outfd.write(data)
LOGINFO('OK -> %s' % localf)
local_dataset_lczip = localf
except HTTPError as e:
LOGERROR('could not download %s, HTTP status code was: %s, reason: %s' %
(dataset_lczip_link, e.code, e.reason))
local_dataset_lczip = None
return local_dataset_csv, local_dataset_lczip, local_dataset_pickle | [
"def",
"retrieve_dataset_files",
"(",
"searchresult",
",",
"getpickle",
"=",
"False",
",",
"outdir",
"=",
"None",
",",
"apikey",
"=",
"None",
")",
":",
"# this handles the direct result case from submit_*_query functions",
"if",
"isinstance",
"(",
"searchresult",
",",
... | This retrieves a search result dataset's CSV and any LC zip files.
Takes the output from the `submit_post_searchquery` function above or a
pickle file generated from that function's output if the query timed out.
Parameters
----------
searchresult : str or tuple
If provided as a str, points to the pickle file created using the output
from the `submit_post_searchquery` function. If provided as a tuple,
this is the result tuple from the `submit_post_searchquery` function.
getpickle : False
If this is True, will also download the dataset's pickle. Note that
LCC-Server is a Python 3.6+ package (while lccs.py still works with
Python 2.7) and it saves its pickles in pickle.HIGHEST_PROTOCOL for
efficiency, so these pickles may be unreadable in lower Pythons. As an
alternative, the dataset CSV contains the full data table and all the
information about the dataset in its header, which is JSON
parseable. You can also use the function `get_dataset` below to get the
dataset pickle information in JSON form.
outdir : None or str
If this is a str, points to the output directory where the results will
be placed. If it's None, they will be placed in the current directory.
apikey : str or None
If this is a str, uses the given API key to authenticate the download
request. This is useful when you have a private dataset you want to get
products for.
Returns
-------
(local_dataset_csv, local_dataset_lczip, local_dataset_pickle) : tuple
This returns a tuple containing paths to the dataset CSV, LC zipfile,
and the dataset pickle if getpickle was set to True (None otherwise). | [
"This",
"retrieves",
"a",
"search",
"result",
"dataset",
"s",
"CSV",
"and",
"any",
"LC",
"zip",
"files",
"."
] | python | valid |
south-coast-science/scs_core | src/scs_core/gas/pid_datum.py | https://github.com/south-coast-science/scs_core/blob/a4152b0bbed6acbbf257e1bba6a912f6ebe578e5/src/scs_core/gas/pid_datum.py#L62-L74 | def __cnc(cls, calib, we_c):
"""
Compute cnc from weC
"""
if we_c is None:
return None
offset_v = calib.pid_elc_mv / 1000.0
response_c = we_c - offset_v # remove electronic zero
cnc = response_c / calib.pid_sens_mv # pid_sens_mv set for ppb or ppm - see PID.init()
return cnc | [
"def",
"__cnc",
"(",
"cls",
",",
"calib",
",",
"we_c",
")",
":",
"if",
"we_c",
"is",
"None",
":",
"return",
"None",
"offset_v",
"=",
"calib",
".",
"pid_elc_mv",
"/",
"1000.0",
"response_c",
"=",
"we_c",
"-",
"offset_v",
"# remove electronic zero",
"cnc",
... | Compute cnc from weC | [
"Compute",
"cnc",
"from",
"weC"
] | python | train |
emirozer/bowshock | bowshock/techport.py | https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/techport.py#L19-L47 | def techport(Id):
'''
In order to use this capability, queries can be issued to the system with the following URI
format:
GET /xml-api/id_parameter
Parameter Required? Value Description
id_parameter Yes Type: String
Default: None
The id value of the TechPort record.
TechPort values range from 0-20000.
Not all values will yield results. Id
values can be obtained through the
standard TechPort search feature and
are visible in the website URLs, e.g.
http://techport.nasa.gov/view/0000,
where 0000 is the id value.
Example usage:
http://techport.nasa.gov/xml-api/4795
Output: The output of this query is an XML file with all field data of the TechPort record.
'''
base_url = 'http://techport.nasa.gov/xml-api/'
if not isinstance(Id, str):
raise ValueError("The Id arg you provided is not the type of str")
else:
base_url += Id
return dispatch_http_get(base_url) | [
"def",
"techport",
"(",
"Id",
")",
":",
"base_url",
"=",
"'http://techport.nasa.gov/xml-api/'",
"if",
"not",
"isinstance",
"(",
"Id",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"\"The Id arg you provided is not the type of str\"",
")",
"else",
":",
"base_url"... | In order to use this capability, queries can be issued to the system with the following URI
format:
GET /xml-api/id_parameter
Parameter Required? Value Description
id_parameter Yes Type: String
Default: None
The id value of the TechPort record.
TechPort values range from 0-20000.
Not all values will yield results. Id
values can be obtained through the
standard TechPort search feature and
are visible in the website URLs, e.g.
http://techport.nasa.gov/view/0000,
where 0000 is the id value.
Example usage:
http://techport.nasa.gov/xml-api/4795
Output: The output of this query is an XML file with all field data of the TechPort record. | [
"In",
"order",
"to",
"use",
"this",
"capability",
"queries",
"can",
"be",
"issued",
"to",
"the",
"system",
"with",
"the",
"following",
"URI",
"format",
":",
"GET",
"/",
"xml",
"-",
"api",
"/",
"id_parameter",
"Parameter",
"Required?",
"Value",
"Description",... | python | train |
gitpython-developers/GitPython | git/refs/head.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/refs/head.py#L190-L223 | def checkout(self, force=False, **kwargs):
"""Checkout this head by setting the HEAD to this reference, by updating the index
to reflect the tree we point to and by updating the working tree to reflect
the latest index.
The command will fail if changed working tree files would be overwritten.
:param force:
If True, changes to the index and the working tree will be discarded.
If False, GitCommandError will be raised in that situation.
:param kwargs:
Additional keyword arguments to be passed to git checkout, i.e.
b='new_branch' to create a new branch at the given spot.
:return:
The active branch after the checkout operation, usually self unless
a new branch has been created.
If there is no active branch, as the HEAD is now detached, the HEAD
reference will be returned instead.
:note:
By default it is only allowed to checkout heads - everything else
will leave the HEAD detached which is allowed and possible, but remains
a special state that some tools might not be able to handle."""
kwargs['f'] = force
if kwargs['f'] is False:
kwargs.pop('f')
self.repo.git.checkout(self, **kwargs)
if self.repo.head.is_detached:
return self.repo.head
else:
return self.repo.active_branch | [
"def",
"checkout",
"(",
"self",
",",
"force",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'f'",
"]",
"=",
"force",
"if",
"kwargs",
"[",
"'f'",
"]",
"is",
"False",
":",
"kwargs",
".",
"pop",
"(",
"'f'",
")",
"self",
".",
"re... | Checkout this head by setting the HEAD to this reference, by updating the index
to reflect the tree we point to and by updating the working tree to reflect
the latest index.
The command will fail if changed working tree files would be overwritten.
:param force:
If True, changes to the index and the working tree will be discarded.
If False, GitCommandError will be raised in that situation.
:param kwargs:
Additional keyword arguments to be passed to git checkout, i.e.
b='new_branch' to create a new branch at the given spot.
:return:
The active branch after the checkout operation, usually self unless
a new branch has been created.
If there is no active branch, as the HEAD is now detached, the HEAD
reference will be returned instead.
:note:
By default it is only allowed to checkout heads - everything else
will leave the HEAD detached which is allowed and possible, but remains
a special state that some tools might not be able to handle. | [
"Checkout",
"this",
"head",
"by",
"setting",
"the",
"HEAD",
"to",
"this",
"reference",
"by",
"updating",
"the",
"index",
"to",
"reflect",
"the",
"tree",
"we",
"point",
"to",
"and",
"by",
"updating",
"the",
"working",
"tree",
"to",
"reflect",
"the",
"latest... | python | train |
ergoithz/browsepy | browsepy/file.py | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L767-L778 | def abspath_to_urlpath(path, base, os_sep=os.sep):
'''
Make filesystem absolute path uri relative using given absolute base path.
:param path: absolute path
:param base: absolute base path
:param os_sep: path component separator, defaults to current OS separator
:return: relative uri
:rtype: str or unicode
:raises OutsideDirectoryBase: if resulting path is not below base
'''
return relativize_path(path, base, os_sep).replace(os_sep, '/') | [
"def",
"abspath_to_urlpath",
"(",
"path",
",",
"base",
",",
"os_sep",
"=",
"os",
".",
"sep",
")",
":",
"return",
"relativize_path",
"(",
"path",
",",
"base",
",",
"os_sep",
")",
".",
"replace",
"(",
"os_sep",
",",
"'/'",
")"
] | Make filesystem absolute path uri relative using given absolute base path.
:param path: absolute path
:param base: absolute base path
:param os_sep: path component separator, defaults to current OS separator
:return: relative uri
:rtype: str or unicode
:raises OutsideDirectoryBase: if resulting path is not below base | [
"Make",
"filesystem",
"absolute",
"path",
"uri",
"relative",
"using",
"given",
"absolute",
"base",
"path",
"."
] | python | train |
nickmckay/LiPD-utilities | Python/lipd/lpd_noaa.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L296-L321 | def __generate_study_name(self):
"""
When a study name is not given, generate one with the format of " author - site name - year "
:return str study_name: generated study name
"""
study_name = ""
_exist = False
try:
if self.noaa_data_sorted["Top"]["Study_Name"]:
_exist = True
except KeyError:
pass
if not _exist:
try:
_site = self.noaa_data_sorted["Site_Information"]["properties"]["siteName"]
_year = self.noaa_data_sorted["Publication"][0]["pubYear"]
_author = self.noaa_data_sorted["Publication"][0]["author"]
_author = self.__get_author_last_name(_author)
study_name = "{}.{}.{}".format(_author, _site, _year)
study_name = study_name.replace(" ", "_").replace(",", "_")
except (KeyError, Exception):
pass
self.noaa_data_sorted["Top"]["Study_Name"] = study_name
self.noaa_data_sorted["Title"]["Study_Name"] = study_name
return | [
"def",
"__generate_study_name",
"(",
"self",
")",
":",
"study_name",
"=",
"\"\"",
"_exist",
"=",
"False",
"try",
":",
"if",
"self",
".",
"noaa_data_sorted",
"[",
"\"Top\"",
"]",
"[",
"\"Study_Name\"",
"]",
":",
"_exist",
"=",
"True",
"except",
"KeyError",
... | When a study name is not given, generate one with the format of " author - site name - year "
:return str study_name: generated study name | [
"When",
"a",
"study",
"name",
"is",
"not",
"given",
"generate",
"one",
"with",
"the",
"format",
"of",
"author",
"-",
"site",
"name",
"-",
"year",
":",
"return",
"str",
"study_name",
":",
"generated",
"study",
"name"
] | python | train |
krukas/Trionyx | trionyx/navigation.py | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/navigation.py#L359-L371 | def get_layout(self, object):
"""Get complete layout for given object"""
layout = self.create_layout(object)
if isinstance(layout, Component):
layout = Layout(layout)
if isinstance(layout, list):
layout = Layout(*layout)
for update_layout in self.layout_updates:
update_layout(layout, object)
layout.set_object(object)
return layout | [
"def",
"get_layout",
"(",
"self",
",",
"object",
")",
":",
"layout",
"=",
"self",
".",
"create_layout",
"(",
"object",
")",
"if",
"isinstance",
"(",
"layout",
",",
"Component",
")",
":",
"layout",
"=",
"Layout",
"(",
"layout",
")",
"if",
"isinstance",
... | Get complete layout for given object | [
"Get",
"complete",
"layout",
"for",
"given",
"object"
] | python | train |
scanny/python-pptx | pptx/oxml/chart/datalabel.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/oxml/chart/datalabel.py#L157-L165 | def get_or_add_dLbl_for_point(self, idx):
"""
Return the `c:dLbl` element representing the label of the point at
index *idx*.
"""
matches = self.xpath('c:dLbl[c:idx[@val="%d"]]' % idx)
if matches:
return matches[0]
return self._insert_dLbl_in_sequence(idx) | [
"def",
"get_or_add_dLbl_for_point",
"(",
"self",
",",
"idx",
")",
":",
"matches",
"=",
"self",
".",
"xpath",
"(",
"'c:dLbl[c:idx[@val=\"%d\"]]'",
"%",
"idx",
")",
"if",
"matches",
":",
"return",
"matches",
"[",
"0",
"]",
"return",
"self",
".",
"_insert_dLbl_... | Return the `c:dLbl` element representing the label of the point at
index *idx*. | [
"Return",
"the",
"c",
":",
"dLbl",
"element",
"representing",
"the",
"label",
"of",
"the",
"point",
"at",
"index",
"*",
"idx",
"*",
"."
] | python | train |
ssalentin/plip | plip/modules/preparation.py | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L503-L512 | def find_hba(self, all_atoms):
"""Find all possible hydrogen bond acceptors"""
data = namedtuple('hbondacceptor', 'a a_orig_atom a_orig_idx type')
a_set = []
for atom in filter(lambda at: at.OBAtom.IsHbondAcceptor(), all_atoms):
if atom.atomicnum not in [9, 17, 35, 53] and atom.idx not in self.altconf: # Exclude halogen atoms
a_orig_idx = self.Mapper.mapid(atom.idx, mtype=self.mtype, bsid=self.bsid)
a_orig_atom = self.Mapper.id_to_atom(a_orig_idx)
a_set.append(data(a=atom, a_orig_atom=a_orig_atom, a_orig_idx=a_orig_idx, type='regular'))
return a_set | [
"def",
"find_hba",
"(",
"self",
",",
"all_atoms",
")",
":",
"data",
"=",
"namedtuple",
"(",
"'hbondacceptor'",
",",
"'a a_orig_atom a_orig_idx type'",
")",
"a_set",
"=",
"[",
"]",
"for",
"atom",
"in",
"filter",
"(",
"lambda",
"at",
":",
"at",
".",
"OBAtom"... | Find all possible hydrogen bond acceptors | [
"Find",
"all",
"possible",
"hydrogen",
"bond",
"acceptors"
] | python | train |
dsoprea/PySchedules | pyschedules/examples/read.py | https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/examples/read.py#L98-L106 | def new_crew_member(self, program, role, fullname, givenname, surname):
"""Callback run for each new crew member entry. 'fullname' is a
derived full-name, based on the presence of 'givenname' and/or
'surname'.
"""
if self.__v_crew_member:
# [Crew: EP000036710112, Actor, Estelle Parsons]
print("[Crew: %s, %s, %s]" % (program, role, fullname)) | [
"def",
"new_crew_member",
"(",
"self",
",",
"program",
",",
"role",
",",
"fullname",
",",
"givenname",
",",
"surname",
")",
":",
"if",
"self",
".",
"__v_crew_member",
":",
"# [Crew: EP000036710112, Actor, Estelle Parsons]",
"print",
"(",
"\"[Crew: %s, %s, %s]\"",
"%... | Callback run for each new crew member entry. 'fullname' is a
derived full-name, based on the presence of 'givenname' and/or
'surname'. | [
"Callback",
"run",
"for",
"each",
"new",
"crew",
"member",
"entry",
".",
"fullname",
"is",
"a",
"derived",
"full",
"-",
"name",
"based",
"on",
"the",
"presence",
"of",
"givenname",
"and",
"/",
"or",
"surname",
"."
] | python | train |
cloud9ers/pylxc | lxc/__init__.py | https://github.com/cloud9ers/pylxc/blob/588961dd37ce6e14fd7c1cc76d1970e48fccba34/lxc/__init__.py#L184-L192 | def kill(name, signal):
'''
sends a kill signal to process 1 of ths container <name>
:param signal: numeric signal
'''
if not exists(name):
raise ContainerNotExists("The container (%s) does not exist!" % name)
cmd = ['lxc-kill', '--name=%s' % name, signal]
subprocess.check_call(cmd) | [
"def",
"kill",
"(",
"name",
",",
"signal",
")",
":",
"if",
"not",
"exists",
"(",
"name",
")",
":",
"raise",
"ContainerNotExists",
"(",
"\"The container (%s) does not exist!\"",
"%",
"name",
")",
"cmd",
"=",
"[",
"'lxc-kill'",
",",
"'--name=%s'",
"%",
"name",... | sends a kill signal to process 1 of ths container <name>
:param signal: numeric signal | [
"sends",
"a",
"kill",
"signal",
"to",
"process",
"1",
"of",
"ths",
"container",
"<name",
">",
":",
"param",
"signal",
":",
"numeric",
"signal"
] | python | train |
OpenTreeOfLife/peyotl | peyotl/collections_store/git_actions.py | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/collections_store/git_actions.py#L92-L107 | def remove_collection(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None):
"""Remove a collection
Given a collection_id, branch and optionally an
author, remove a collection on the given branch
and attribute the commit to author.
Returns the SHA of the commit on branch.
"""
if fourth_arg is None:
collection_id, branch_name, author = first_arg, sec_arg, third_arg
gh_user = branch_name.split('_collection_')[0]
parent_sha = self.get_master_sha()
else:
gh_user, collection_id, parent_sha, author = first_arg, sec_arg, third_arg, fourth_arg
if commit_msg is None:
commit_msg = "Delete Collection '%s' via OpenTree API" % collection_id
return self._remove_document(gh_user, collection_id, parent_sha, author, commit_msg) | [
"def",
"remove_collection",
"(",
"self",
",",
"first_arg",
",",
"sec_arg",
",",
"third_arg",
",",
"fourth_arg",
"=",
"None",
",",
"commit_msg",
"=",
"None",
")",
":",
"if",
"fourth_arg",
"is",
"None",
":",
"collection_id",
",",
"branch_name",
",",
"author",
... | Remove a collection
Given a collection_id, branch and optionally an
author, remove a collection on the given branch
and attribute the commit to author.
Returns the SHA of the commit on branch. | [
"Remove",
"a",
"collection",
"Given",
"a",
"collection_id",
"branch",
"and",
"optionally",
"an",
"author",
"remove",
"a",
"collection",
"on",
"the",
"given",
"branch",
"and",
"attribute",
"the",
"commit",
"to",
"author",
".",
"Returns",
"the",
"SHA",
"of",
"... | python | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/reference_controller.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_controller.py#L216-L219 | def controller_info(self):
"""Get the controller UUID, app tag and os tag."""
return [self._device.iotile_id, _pack_version(*self.os_info), _pack_version(*self.app_info)] | [
"def",
"controller_info",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"_device",
".",
"iotile_id",
",",
"_pack_version",
"(",
"*",
"self",
".",
"os_info",
")",
",",
"_pack_version",
"(",
"*",
"self",
".",
"app_info",
")",
"]"
] | Get the controller UUID, app tag and os tag. | [
"Get",
"the",
"controller",
"UUID",
"app",
"tag",
"and",
"os",
"tag",
"."
] | python | train |
jbloomlab/phydms | phydmslib/models.py | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L319-L329 | def PARAMLIMITS(self, value):
"""Set new `PARAMLIMITS` dictionary."""
assert set(value.keys()) == set(self.PARAMLIMITS.keys()), "The \
new parameter limits are not defined for the same set \
of parameters as before."
for param in value.keys():
assert value[param][0] < value[param][1], "The new \
minimum value for {0}, {1}, is equal to or \
larger than the new maximum value, {2}"\
.format(param, value[param][0], value[param][1])
self._PARAMLIMITS = value.copy() | [
"def",
"PARAMLIMITS",
"(",
"self",
",",
"value",
")",
":",
"assert",
"set",
"(",
"value",
".",
"keys",
"(",
")",
")",
"==",
"set",
"(",
"self",
".",
"PARAMLIMITS",
".",
"keys",
"(",
")",
")",
",",
"\"The \\\n new parameter limits are not defin... | Set new `PARAMLIMITS` dictionary. | [
"Set",
"new",
"PARAMLIMITS",
"dictionary",
"."
] | python | train |
seibert-media/Highton | highton/models/task.py | https://github.com/seibert-media/Highton/blob/1519e4fb105f62882c2e7bc81065d994649558d8/highton/models/task.py#L71-L83 | def list_upcoming(cls):
"""
Returns a collection of upcoming tasks (tasks that have not yet been completed,
regardless of whether they’re overdue) for the authenticated user
:return:
:rtype: list
"""
return fields.ListField(name=cls.ENDPOINT, init_class=cls).decode(
cls.element_from_string(
cls._get_request(endpoint=cls.ENDPOINT + '/upcoming').text
)
) | [
"def",
"list_upcoming",
"(",
"cls",
")",
":",
"return",
"fields",
".",
"ListField",
"(",
"name",
"=",
"cls",
".",
"ENDPOINT",
",",
"init_class",
"=",
"cls",
")",
".",
"decode",
"(",
"cls",
".",
"element_from_string",
"(",
"cls",
".",
"_get_request",
"(",... | Returns a collection of upcoming tasks (tasks that have not yet been completed,
regardless of whether they’re overdue) for the authenticated user
:return:
:rtype: list | [
"Returns",
"a",
"collection",
"of",
"upcoming",
"tasks",
"(",
"tasks",
"that",
"have",
"not",
"yet",
"been",
"completed",
"regardless",
"of",
"whether",
"they’re",
"overdue",
")",
"for",
"the",
"authenticated",
"user"
] | python | train |
zimeon/iiif | iiif/manipulator.py | https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L245-L313 | def size_to_apply(self):
"""Calculate size of image scaled using size parameters.
Assumes current image width and height are available in self.width and
self.height, and self.request is IIIFRequest object.
Formats are: w, ,h w,h pct:p !w,h full max
Returns (None,None) if no scaling is required.
If max is requested and neither max_area or max_width are
specified then this is the same as full. Otherwise the limits
are used to determine the size.
"""
if (self.request.size_full or self.request.size_pct == 100.0):
# full size
return(None, None)
# Not trivially full size, look at possibilities in turn
w = self.width
h = self.height
if (self.request.size_max):
# use size limits if present, else full
if (self.max_area and self.max_area < (w * h)):
scale = (float(self.max_area) / float(w * h)) ** 0.5
w = int(w * scale + 0.5)
h = int(h * scale + 0.5)
if (self.max_width):
max_height = self.max_height if self.max_height is not None else self.max_width
if (self.max_width < w):
# calculate wrt original width, height rather than
# w, h to avoid compounding rounding issues
scale = float(self.max_width) / float(self.width)
w = int(self.width * scale + 0.5)
h = int(self.height * scale + 0.5)
if (max_height < h):
scale = float(max_height) / float(self.height)
w = int(self.width * scale + 0.5)
h = int(self.height * scale + 0.5)
elif (self.request.size_pct is not None):
w = int(self.width * self.request.size_pct / 100.0 + 0.5)
h = int(self.height * self.request.size_pct / 100.0 + 0.5)
elif (self.request.size_bang):
# Have "!w,h" form
(mw, mh) = self.request.size_wh
# Pick smaller fraction and then work from that...
frac = min((float(mw) / float(self.width)),
(float(mh) / float(self.height)))
w = int(self.width * frac + 0.5)
h = int(self.height * frac + 0.5)
else:
# Must now be "w,h", "w," or ",h". If both are specified then this will the size,
# otherwise find other to keep aspect ratio
(w, h) = self.request.size_wh
if (w is None):
w = int(self.width * h / self.height + 0.5)
elif (h is None):
h = int(self.height * w / self.width + 0.5)
# Now have w,h, sanity check and return
if (w == 0 or h == 0):
raise IIIFZeroSizeError(
code=400, parameter='size',
text="Size parameter would result in zero size result image (%d,%d)." % (w, h))
# Below would be test for scaling up image size, this is allowed by spec
# if ( w>self.width or h>self.height ):
# raise IIIFError(code=400,parameter='size',
# text="Size requests scaling up image to larger than orginal.")
if (w == self.width and h == self.height):
return(None, None)
return(w, h) | [
"def",
"size_to_apply",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"request",
".",
"size_full",
"or",
"self",
".",
"request",
".",
"size_pct",
"==",
"100.0",
")",
":",
"# full size",
"return",
"(",
"None",
",",
"None",
")",
"# Not trivially full size, ... | Calculate size of image scaled using size parameters.
Assumes current image width and height are available in self.width and
self.height, and self.request is IIIFRequest object.
Formats are: w, ,h w,h pct:p !w,h full max
Returns (None,None) if no scaling is required.
If max is requested and neither max_area or max_width are
specified then this is the same as full. Otherwise the limits
are used to determine the size. | [
"Calculate",
"size",
"of",
"image",
"scaled",
"using",
"size",
"parameters",
"."
] | python | train |
six8/corona-cipr | src/cipr/commands/core.py | https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/core.py#L161-L170 | def packages(ciprcfg, env, opts, console):
"""
List installed packages for this project
"""
for name, source in ciprcfg.packages.items():
console.normal('- %s' % name)
if opts.long_details:
console.normal(' - directory: %s' % path.join(env.package_dir, name))
console.normal(' - source: %s' % source) | [
"def",
"packages",
"(",
"ciprcfg",
",",
"env",
",",
"opts",
",",
"console",
")",
":",
"for",
"name",
",",
"source",
"in",
"ciprcfg",
".",
"packages",
".",
"items",
"(",
")",
":",
"console",
".",
"normal",
"(",
"'- %s'",
"%",
"name",
")",
"if",
"opt... | List installed packages for this project | [
"List",
"installed",
"packages",
"for",
"this",
"project"
] | python | train |
PyProphet/pyprophet | pyprophet/pyprophet.py | https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/pyprophet.py#L49-L58 | def unwrap_self_for_multiprocessing(arg):
""" You can not call methods with multiprocessing, but free functions,
If you want to call inst.method(arg0, arg1),
unwrap_self_for_multiprocessing(inst, "method", (arg0, arg1))
does the trick.
"""
(inst, method_name, args) = arg
return getattr(inst, method_name)(*args) | [
"def",
"unwrap_self_for_multiprocessing",
"(",
"arg",
")",
":",
"(",
"inst",
",",
"method_name",
",",
"args",
")",
"=",
"arg",
"return",
"getattr",
"(",
"inst",
",",
"method_name",
")",
"(",
"*",
"args",
")"
] | You can not call methods with multiprocessing, but free functions,
If you want to call inst.method(arg0, arg1),
unwrap_self_for_multiprocessing(inst, "method", (arg0, arg1))
does the trick. | [
"You",
"can",
"not",
"call",
"methods",
"with",
"multiprocessing",
"but",
"free",
"functions",
"If",
"you",
"want",
"to",
"call",
"inst",
".",
"method",
"(",
"arg0",
"arg1",
")"
] | python | test |
PyCQA/astroid | astroid/as_string.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L155-L174 | def visit_classdef(self, node):
"""return an astroid.ClassDef node as string"""
decorate = node.decorators.accept(self) if node.decorators else ""
bases = ", ".join(n.accept(self) for n in node.bases)
metaclass = node.metaclass()
if metaclass and not node.has_metaclass_hack():
if bases:
bases = "(%s, metaclass=%s)" % (bases, metaclass.name)
else:
bases = "(metaclass=%s)" % metaclass.name
else:
bases = "(%s)" % bases if bases else ""
docs = self._docs_dedent(node.doc) if node.doc else ""
return "\n\n%sclass %s%s:%s\n%s\n" % (
decorate,
node.name,
bases,
docs,
self._stmt_list(node.body),
) | [
"def",
"visit_classdef",
"(",
"self",
",",
"node",
")",
":",
"decorate",
"=",
"node",
".",
"decorators",
".",
"accept",
"(",
"self",
")",
"if",
"node",
".",
"decorators",
"else",
"\"\"",
"bases",
"=",
"\", \"",
".",
"join",
"(",
"n",
".",
"accept",
"... | return an astroid.ClassDef node as string | [
"return",
"an",
"astroid",
".",
"ClassDef",
"node",
"as",
"string"
] | python | train |
ianepperson/telnetsrvlib | telnetsrv/telnetsrvlib.py | https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L619-L622 | def _readline_echo(self, char, echo):
"""Echo a recieved character, move cursor etc..."""
if self._readline_do_echo(echo):
self.write(char) | [
"def",
"_readline_echo",
"(",
"self",
",",
"char",
",",
"echo",
")",
":",
"if",
"self",
".",
"_readline_do_echo",
"(",
"echo",
")",
":",
"self",
".",
"write",
"(",
"char",
")"
] | Echo a recieved character, move cursor etc... | [
"Echo",
"a",
"recieved",
"character",
"move",
"cursor",
"etc",
"..."
] | python | train |
O365/python-o365 | O365/sharepoint.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/sharepoint.py#L429-L445 | def get_subsites(self):
""" Returns a list of subsites defined for this site
:rtype: list[Site]
"""
url = self.build_url(
self._endpoints.get('get_subsites').format(id=self.object_id))
response = self.con.get(url)
if not response:
return []
data = response.json()
# Everything received from cloud must be passed as self._cloud_data_key
return [self.__class__(parent=self, **{self._cloud_data_key: site}) for
site in data.get('value', [])] | [
"def",
"get_subsites",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'get_subsites'",
")",
".",
"format",
"(",
"id",
"=",
"self",
".",
"object_id",
")",
")",
"response",
"=",
"self",
".... | Returns a list of subsites defined for this site
:rtype: list[Site] | [
"Returns",
"a",
"list",
"of",
"subsites",
"defined",
"for",
"this",
"site"
] | python | train |
usc-isi-i2/etk | etk/ontology_api.py | https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/ontology_api.py#L599-L606 | def get_entity(self, uri: str) -> OntologyClass:
"""
Find an ontology entity based on URI
:param uri: URIRef or str
:return: the OntologyEntity having the specified uri, or None
"""
return self.entities.get(str(uri), None) | [
"def",
"get_entity",
"(",
"self",
",",
"uri",
":",
"str",
")",
"->",
"OntologyClass",
":",
"return",
"self",
".",
"entities",
".",
"get",
"(",
"str",
"(",
"uri",
")",
",",
"None",
")"
] | Find an ontology entity based on URI
:param uri: URIRef or str
:return: the OntologyEntity having the specified uri, or None | [
"Find",
"an",
"ontology",
"entity",
"based",
"on",
"URI"
] | python | train |
pmacosta/peng | peng/wave_functions.py | https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1351-L1390 | def integral(wave, indep_min=None, indep_max=None):
r"""
Return the running integral of a waveform's dependent variable vector.
The method used is the `trapezoidal
<https://en.wikipedia.org/wiki/Trapezoidal_rule>`_ method
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.integral
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
.. [[[end]]]
"""
ret = copy.copy(wave)
_bound_waveform(ret, indep_min, indep_max)
ret._dep_vector = _running_area(ret._indep_vector, ret._dep_vector)
ret.dep_name = "integral({0})".format(ret._dep_name)
ret.dep_units = _build_units(ret.indep_units, ret.dep_units, "*")
return ret | [
"def",
"integral",
"(",
"wave",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"ret",
"=",
"copy",
".",
"copy",
"(",
"wave",
")",
"_bound_waveform",
"(",
"ret",
",",
"indep_min",
",",
"indep_max",
")",
"ret",
".",
"_dep_vector"... | r"""
Return the running integral of a waveform's dependent variable vector.
The method used is the `trapezoidal
<https://en.wikipedia.org/wiki/Trapezoidal_rule>`_ method
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: integer or float
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.integral
:raises:
* RuntimeError (Argument \`indep_max\` is not valid)
* RuntimeError (Argument \`indep_min\` is not valid)
* RuntimeError (Argument \`wave\` is not valid)
* RuntimeError (Incongruent \`indep_min\` and \`indep_max\`
arguments)
.. [[[end]]] | [
"r",
"Return",
"the",
"running",
"integral",
"of",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"."
] | python | test |
saltstack/salt | salt/modules/parted_partition.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L366-L384 | def system_types():
'''
List the system types that are supported by the installed version of sfdisk
CLI Example:
.. code-block:: bash
salt '*' partition.system_types
'''
ret = {}
for line in __salt__['cmd.run']('sfdisk -T').splitlines():
if not line:
continue
if line.startswith('Id'):
continue
comps = line.strip().split()
ret[comps[0]] = comps[1]
return ret | [
"def",
"system_types",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"line",
"in",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'sfdisk -T'",
")",
".",
"splitlines",
"(",
")",
":",
"if",
"not",
"line",
":",
"continue",
"if",
"line",
".",
"startswith",
"(",... | List the system types that are supported by the installed version of sfdisk
CLI Example:
.. code-block:: bash
salt '*' partition.system_types | [
"List",
"the",
"system",
"types",
"that",
"are",
"supported",
"by",
"the",
"installed",
"version",
"of",
"sfdisk"
] | python | train |
chaoss/grimoirelab-elk | grimoire_elk/enriched/ceres_base.py | https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/ceres_base.py#L205-L225 | def write(self, items):
"""Upload items to ElasticSearch.
:param items: items to be uploaded.
"""
if self._read_only:
raise IOError("Cannot write, Connector created as Read Only")
# Uploading info to the new ES
docs = []
for item in items:
doc = {
"_index": self._es_index,
"_type": "item",
"_id": item["_id"],
"_source": item["_source"]
}
docs.append(doc)
# TODO exception and error handling
helpers.bulk(self._es_conn, docs)
logger.info(self.__log_prefix + " Written: " + str(len(docs))) | [
"def",
"write",
"(",
"self",
",",
"items",
")",
":",
"if",
"self",
".",
"_read_only",
":",
"raise",
"IOError",
"(",
"\"Cannot write, Connector created as Read Only\"",
")",
"# Uploading info to the new ES",
"docs",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":... | Upload items to ElasticSearch.
:param items: items to be uploaded. | [
"Upload",
"items",
"to",
"ElasticSearch",
"."
] | python | train |
fedora-infra/fedora-messaging | fedora_messaging/twisted/consumer.py | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/twisted/consumer.py#L70-L106 | def cancel(self):
"""
Cancel the consumer and clean up resources associated with it.
Consumers that are canceled are allowed to finish processing any
messages before halting.
Returns:
defer.Deferred: A deferred that fires when the consumer has finished
processing any message it was in the middle of and has been successfully
canceled.
"""
# Remove it from protocol and factory so it doesn't restart later.
try:
del self._protocol._consumers[self.queue]
except (KeyError, AttributeError):
pass
try:
del self._protocol.factory._consumers[self.queue]
except (KeyError, AttributeError):
pass
# Signal to the _read loop it's time to stop and wait for it to finish
# with whatever message it might be working on, then wait for the deferred
# to fire which indicates it is done.
self._running = False
yield self._read_loop
try:
yield self._channel.basic_cancel(consumer_tag=self._tag)
except pika.exceptions.AMQPChannelError:
# Consumers are tied to channels, so if this channel is dead the
# consumer should already be canceled (and we can't get to it anyway)
pass
try:
yield self._channel.close()
except pika.exceptions.AMQPChannelError:
pass
if not self.result.called:
self.result.callback(self) | [
"def",
"cancel",
"(",
"self",
")",
":",
"# Remove it from protocol and factory so it doesn't restart later.",
"try",
":",
"del",
"self",
".",
"_protocol",
".",
"_consumers",
"[",
"self",
".",
"queue",
"]",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":"... | Cancel the consumer and clean up resources associated with it.
Consumers that are canceled are allowed to finish processing any
messages before halting.
Returns:
defer.Deferred: A deferred that fires when the consumer has finished
processing any message it was in the middle of and has been successfully
canceled. | [
"Cancel",
"the",
"consumer",
"and",
"clean",
"up",
"resources",
"associated",
"with",
"it",
".",
"Consumers",
"that",
"are",
"canceled",
"are",
"allowed",
"to",
"finish",
"processing",
"any",
"messages",
"before",
"halting",
"."
] | python | train |
inveniosoftware/kwalitee | kwalitee/cli/check.py | https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/cli/check.py#L179-L278 | def files(obj, commit='HEAD', skip_merge_commits=False):
"""Check the files of the commits."""
from ..kwalitee import check_file, SUPPORTED_FILES
from ..hooks import run
options = obj.options
repository = obj.repository
if options.get('colors') is not False:
colorama.init(autoreset=True)
reset = colorama.Style.RESET_ALL
yellow = colorama.Fore.YELLOW
green = colorama.Fore.GREEN
red = colorama.Fore.RED
else:
reset = yellow = green = red = ''
try:
sha = 'oid'
commits = _pygit2_commits(commit, repository)
except ImportError:
try:
sha = 'hexsha'
commits = _git_commits(commit, repository)
except ImportError:
click.echo(
'To use this feature, please install pygit2. GitPython will '
'also work but is not recommended (python <= 2.7 only).',
file=sys.stderr)
click.exit(2)
template = '{0}commit {{commit.{1}}}{2}\n\n'.format(yellow, sha, reset)
template += '{message}{errors}\n'
error_template = '\n{0}{{filename}}\n{1}{{errors}}{0}'.format(reset, red)
no_errors = ['\n{0}Everything is OK.{1}'.format(green, reset)]
msg_file_excluded = '\n{0}{{filename}} excluded.{1}'.format(yellow, reset)
def _get_files_modified(commit):
"""Get the list of modified files that are Python or Jinja2."""
cmd = "git show --no-commit-id --name-only --diff-filter=ACMRTUXB {0}"
_, files_modified, _ = run(cmd.format(commit))
extensions = [re.escape(ext)
for ext in list(SUPPORTED_FILES) + [".rst"]]
test = "(?:{0})$".format("|".join(extensions))
return list(filter(lambda f: re.search(test, f), files_modified))
def _ensure_directory(filename):
dir_ = os.path.dirname(filename)
if not os.path.exists(dir_):
os.makedirs(dir_)
def _format_errors(args):
filename, errors = args
if errors is None:
return msg_file_excluded.format(filename=filename)
else:
return error_template.format(filename=filename, errors='\n'.join(
errors if len(errors) else no_errors))
count = 0
ident = ' '
re_line = re.compile('^', re.MULTILINE)
for commit in commits:
if skip_merge_commits and _is_merge_commit(commit):
continue
message = commit.message
commit_sha = getattr(commit, sha)
tmpdir = mkdtemp()
errors = {}
try:
for filename in _get_files_modified(commit):
cmd = "git show {commit_sha}:{filename}"
_, out, _ = run(cmd.format(commit_sha=commit_sha,
filename=filename),
raw_output=True)
destination = os.path.join(tmpdir, filename)
_ensure_directory(destination)
with open(destination, 'w+') as f:
f.write(out)
errors[filename] = check_file(destination, **options)
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
message = re.sub(re_line, ident, message)
if len(errors):
count += 1
errors = map(_format_errors, errors.items())
else:
errors = no_errors
click.echo(template.format(commit=commit,
message=message.encode('utf-8'),
errors='\n'.join(errors)))
if min(count, 1):
raise click.Abort | [
"def",
"files",
"(",
"obj",
",",
"commit",
"=",
"'HEAD'",
",",
"skip_merge_commits",
"=",
"False",
")",
":",
"from",
".",
".",
"kwalitee",
"import",
"check_file",
",",
"SUPPORTED_FILES",
"from",
".",
".",
"hooks",
"import",
"run",
"options",
"=",
"obj",
... | Check the files of the commits. | [
"Check",
"the",
"files",
"of",
"the",
"commits",
"."
] | python | train |
priestc/moneywagon | moneywagon/__init__.py | https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/__init__.py#L637-L661 | def service_table(format='simple', authenticated=False):
"""
Returns a string depicting all services currently installed.
"""
if authenticated:
all_services = ExchangeUniverse.get_authenticated_services()
else:
all_services = ALL_SERVICES
if format == 'html':
linkify = lambda x: "<a href='{0}' target='_blank'>{0}</a>".format(x)
else:
linkify = lambda x: x
ret = []
for service in sorted(all_services, key=lambda x: x.service_id):
ret.append([
service.service_id,
service.__name__, linkify(service.api_homepage.format(
domain=service.domain, protocol=service.protocol
)),
", ".join(service.supported_cryptos or [])
])
return tabulate(ret, headers=['ID', 'Name', 'URL', 'Supported Currencies'], tablefmt=format) | [
"def",
"service_table",
"(",
"format",
"=",
"'simple'",
",",
"authenticated",
"=",
"False",
")",
":",
"if",
"authenticated",
":",
"all_services",
"=",
"ExchangeUniverse",
".",
"get_authenticated_services",
"(",
")",
"else",
":",
"all_services",
"=",
"ALL_SERVICES"... | Returns a string depicting all services currently installed. | [
"Returns",
"a",
"string",
"depicting",
"all",
"services",
"currently",
"installed",
"."
] | python | train |
sibirrer/lenstronomy | lenstronomy/LensModel/Profiles/tnfw.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/LensModel/Profiles/tnfw.py#L170-L185 | def nfwPot(self, R, Rs, rho0, r_trunc):
"""
lensing potential of NFW profile
:param R: radius of interest
:type R: float/numpy array
:param Rs: scale radius
:type Rs: float
:param rho0: density normalization (characteristic density)
:type rho0: float
:return: Epsilon(R) projected density at radius R
"""
x = R / Rs
tau = float(r_trunc) / Rs
hx = self._h(x, tau)
return 2 * rho0 * Rs ** 3 * hx | [
"def",
"nfwPot",
"(",
"self",
",",
"R",
",",
"Rs",
",",
"rho0",
",",
"r_trunc",
")",
":",
"x",
"=",
"R",
"/",
"Rs",
"tau",
"=",
"float",
"(",
"r_trunc",
")",
"/",
"Rs",
"hx",
"=",
"self",
".",
"_h",
"(",
"x",
",",
"tau",
")",
"return",
"2",... | lensing potential of NFW profile
:param R: radius of interest
:type R: float/numpy array
:param Rs: scale radius
:type Rs: float
:param rho0: density normalization (characteristic density)
:type rho0: float
:return: Epsilon(R) projected density at radius R | [
"lensing",
"potential",
"of",
"NFW",
"profile"
] | python | train |
soimort/you-get | src/you_get/util/fs.py | https://github.com/soimort/you-get/blob/b746ac01c9f39de94cac2d56f665285b0523b974/src/you_get/util/fs.py#L5-L47 | def legitimize(text, os=detect_os()):
"""Converts a string to a valid filename.
"""
# POSIX systems
text = text.translate({
0: None,
ord('/'): '-',
ord('|'): '-',
})
# FIXME: do some filesystem detection
if os == 'windows' or os == 'cygwin' or os == 'wsl':
# Windows (non-POSIX namespace)
text = text.translate({
# Reserved in Windows VFAT and NTFS
ord(':'): '-',
ord('*'): '-',
ord('?'): '-',
ord('\\'): '-',
ord('\"'): '\'',
# Reserved in Windows VFAT
ord('+'): '-',
ord('<'): '-',
ord('>'): '-',
ord('['): '(',
ord(']'): ')',
ord('\t'): ' ',
})
else:
# *nix
if os == 'mac':
# Mac OS HFS+
text = text.translate({
ord(':'): '-',
})
# Remove leading .
if text.startswith("."):
text = text[1:]
text = text[:80] # Trim to 82 Unicode characters long
return text | [
"def",
"legitimize",
"(",
"text",
",",
"os",
"=",
"detect_os",
"(",
")",
")",
":",
"# POSIX systems",
"text",
"=",
"text",
".",
"translate",
"(",
"{",
"0",
":",
"None",
",",
"ord",
"(",
"'/'",
")",
":",
"'-'",
",",
"ord",
"(",
"'|'",
")",
":",
... | Converts a string to a valid filename. | [
"Converts",
"a",
"string",
"to",
"a",
"valid",
"filename",
"."
] | python | test |
DataDog/integrations-core | datadog_checks_base/datadog_checks/base/checks/prometheus/mixins.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_base/datadog_checks/base/checks/prometheus/mixins.py#L239-L253 | def _text_filter_input(self, input_gen):
"""
Filters out the text input line by line to avoid parsing and processing
metrics we know we don't want to process. This only works on `text/plain`
payloads, and is an INTERNAL FEATURE implemented for the kubelet check
:param input_get: line generator
:output: generator of filtered lines
"""
for line in input_gen:
for item in self._text_filter_blacklist:
if item in line:
break
else:
# No blacklist matches, passing the line through
yield line | [
"def",
"_text_filter_input",
"(",
"self",
",",
"input_gen",
")",
":",
"for",
"line",
"in",
"input_gen",
":",
"for",
"item",
"in",
"self",
".",
"_text_filter_blacklist",
":",
"if",
"item",
"in",
"line",
":",
"break",
"else",
":",
"# No blacklist matches, passin... | Filters out the text input line by line to avoid parsing and processing
metrics we know we don't want to process. This only works on `text/plain`
payloads, and is an INTERNAL FEATURE implemented for the kubelet check
:param input_get: line generator
:output: generator of filtered lines | [
"Filters",
"out",
"the",
"text",
"input",
"line",
"by",
"line",
"to",
"avoid",
"parsing",
"and",
"processing",
"metrics",
"we",
"know",
"we",
"don",
"t",
"want",
"to",
"process",
".",
"This",
"only",
"works",
"on",
"text",
"/",
"plain",
"payloads",
"and"... | python | train |
Ezhil-Language-Foundation/open-tamil | tamil/numeral.py | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/numeral.py#L216-L317 | def num2tamilstr_american( *args ):
number = args[0]
""" work till 1000 trillion - 1 - i.e = 1e12*1e3 - 1.
turn number into a numeral, American style. Fractions upto 1e-30. """
if not any( filter( lambda T: isinstance( number, T), [int, str, unicode, long, float]) ) or isinstance(number,complex):
raise Exception('num2tamilstr_american input has to be long or integer')
if float(number) >= long(1e15):
raise Exception('num2tamilstr input is too large')
if float(number) < 0:
return u"- "+num2tamilstr_american( -float(number) )
units = (u'பூஜ்ஜியம்', u'ஒன்று', u'இரண்டு', u'மூன்று', u'நான்கு', u'ஐந்து', u'ஆறு', u'ஏழு', u'எட்டு', u'ஒன்பது', u'பத்து') # 0-10
hundreds = ( u'நூறு', u'இருநூறு', u'முன்னூறு', u'நாநூறு',u'ஐநூறு', u'அறுநூறு', u'எழுநூறு', u'எண்ணூறு', u'தொள்ளாயிரம்') #100 - 900
one_thousand_prefix = u'ஓர்'
thousands = (u'ஆயிரம்',u'ஆயிரத்து')
one_prefix = u'ஒரு'
mil = u'மில்லியன்'
million = (mil,mil)
bil = u'பில்லியன்'
billion = (bil,bil)
tril = u'டிரில்லியன்'
trillion = (tril,tril)
n_one = 1
n_ten = 10
n_hundred = 100
n_thousand = 1000
n_million = 1000*n_thousand
n_billion = long(1000*n_million)
n_trillion = long(1000*n_billion)
suffix_base = { n_trillion: trillion,
n_billion : billion,
n_million : million,
n_thousand : thousands}
num_map = {n_trillion : [one_prefix,trillion[0]],
n_billion : [one_prefix,billion[0]],
n_million : [one_prefix,million[0]],
n_thousand : [one_thousand_prefix, thousands[0]],
n_hundred : [hundreds[0]], #special
n_ten : [units[10]],
n_one : [units[1]]}
all_bases = [n_trillion,n_billion, n_million, n_thousand, n_hundred, n_ten,n_one]
allowed_bases = list(filter( lambda base: float(number) >= base, all_bases ))
# handle fractional parts
if float(number) > 0.0 and float(number) <= 1000.0:
return num2tamilstr(number)
if isinstance(number,str) or isinstance(number,unicode):
result = u""
number = number.strip()
assert(len(args) == 1)
assert(len(number) > 0)
is_negative = number[0] == "-"
if is_negative:
number = number[1:]
frac_part = u""
if number.find(".") >= 0:
rat_part,frac_part = number.split(".")
frac_part = num2tamilstr_american(u"0."+frac_part)
else:
rat_part = number
if len(rat_part) > 0:
result = num2tamilstr_american(float(rat_part))
result = result +u" "+ frac_part
return result.strip()
if len(allowed_bases) >= 1:
n_base = allowed_bases[0]
if number == n_base:
return u" ".join(num_map[n_base])
quotient_number = long( number/n_base )
residue_number = number - n_base*quotient_number
if n_base < n_thousand:
raise Exception("This can never happen")
else:
if ( quotient_number == 1 ):
if n_base == n_thousand:
numeral = one_thousand_prefix+u' '
else:
numeral = one_prefix+u' '
else:
numeral = num2tamilstr( quotient_number )
if n_base >= n_thousand:
suffix = suffix_base[n_base][long(residue_number >= 1)]
if residue_number == 0:
return numeral + u' ' + suffix
numeral = numeral + u' ' + suffix
residue_numeral = num2tamilstr_american( residue_number )
return numeral+u' '+residue_numeral
# number has to be zero
return units[0] | [
"def",
"num2tamilstr_american",
"(",
"*",
"args",
")",
":",
"number",
"=",
"args",
"[",
"0",
"]",
"if",
"not",
"any",
"(",
"filter",
"(",
"lambda",
"T",
":",
"isinstance",
"(",
"number",
",",
"T",
")",
",",
"[",
"int",
",",
"str",
",",
"unicode",
... | work till 1000 trillion - 1 - i.e = 1e12*1e3 - 1.
turn number into a numeral, American style. Fractions upto 1e-30. | [
"work",
"till",
"1000",
"trillion",
"-",
"1",
"-",
"i",
".",
"e",
"=",
"1e12",
"*",
"1e3",
"-",
"1",
".",
"turn",
"number",
"into",
"a",
"numeral",
"American",
"style",
".",
"Fractions",
"upto",
"1e",
"-",
"30",
"."
] | python | train |
aio-libs/aiomcache | aiomcache/client.py | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L240-L253 | def set(self, conn, key, value, exptime=0):
"""Sets a key to a value on the server
with an optional exptime (0 means don't auto-expire)
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int``, is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
"""
flags = 0 # TODO: fix when exception removed
resp = yield from self._storage_command(
conn, b'set', key, value, flags, exptime)
return resp | [
"def",
"set",
"(",
"self",
",",
"conn",
",",
"key",
",",
"value",
",",
"exptime",
"=",
"0",
")",
":",
"flags",
"=",
"0",
"# TODO: fix when exception removed",
"resp",
"=",
"yield",
"from",
"self",
".",
"_storage_command",
"(",
"conn",
",",
"b'set'",
",",... | Sets a key to a value on the server
with an optional exptime (0 means don't auto-expire)
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int``, is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success. | [
"Sets",
"a",
"key",
"to",
"a",
"value",
"on",
"the",
"server",
"with",
"an",
"optional",
"exptime",
"(",
"0",
"means",
"don",
"t",
"auto",
"-",
"expire",
")"
] | python | train |
bmihelac/django-cruds | cruds/urls.py | https://github.com/bmihelac/django-cruds/blob/7828aac3eb2b4c02e5f3843c4cbff654d57cf1e7/cruds/urls.py#L112-L122 | def crud_for_app(app_label, urlprefix=None):
"""
Returns list of ``url`` items to CRUD an app.
"""
if urlprefix is None:
urlprefix = app_label + '/'
app = apps.get_app_config(app_label)
urls = []
for model in app.get_models():
urls += crud_for_model(model, urlprefix)
return urls | [
"def",
"crud_for_app",
"(",
"app_label",
",",
"urlprefix",
"=",
"None",
")",
":",
"if",
"urlprefix",
"is",
"None",
":",
"urlprefix",
"=",
"app_label",
"+",
"'/'",
"app",
"=",
"apps",
".",
"get_app_config",
"(",
"app_label",
")",
"urls",
"=",
"[",
"]",
... | Returns list of ``url`` items to CRUD an app. | [
"Returns",
"list",
"of",
"url",
"items",
"to",
"CRUD",
"an",
"app",
"."
] | python | train |
Kronuz/pyScss | scss/extension/compass/helpers.py | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/compass/helpers.py#L87-L96 | def reject(lst, *values):
"""Removes the given values from the list"""
lst = List.from_maybe(lst)
values = frozenset(List.from_maybe_starargs(values))
ret = []
for item in lst:
if item not in values:
ret.append(item)
return List(ret, use_comma=lst.use_comma) | [
"def",
"reject",
"(",
"lst",
",",
"*",
"values",
")",
":",
"lst",
"=",
"List",
".",
"from_maybe",
"(",
"lst",
")",
"values",
"=",
"frozenset",
"(",
"List",
".",
"from_maybe_starargs",
"(",
"values",
")",
")",
"ret",
"=",
"[",
"]",
"for",
"item",
"i... | Removes the given values from the list | [
"Removes",
"the",
"given",
"values",
"from",
"the",
"list"
] | python | train |
timothydmorton/isochrones | isochrones/mist/grid.py | https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/mist/grid.py#L92-L147 | def get_band(cls, b, **kwargs):
"""Defines what a "shortcut" band name refers to. Returns phot_system, band
"""
phot = None
# Default to SDSS for these
if b in ['u','g','r','i','z']:
phot = 'SDSS'
band = 'SDSS_{}'.format(b)
elif b in ['U','B','V','R','I']:
phot = 'UBVRIplus'
band = 'Bessell_{}'.format(b)
elif b in ['J','H','Ks']:
phot = 'UBVRIplus'
band = '2MASS_{}'.format(b)
elif b=='K':
phot = 'UBVRIplus'
band = '2MASS_Ks'
elif b in ['kep','Kepler','Kp']:
phot = 'UBVRIplus'
band = 'Kepler_Kp'
elif b=='TESS':
phot = 'UBVRIplus'
band = 'TESS'
elif b in ['W1','W2','W3','W4']:
phot = 'WISE'
band = 'WISE_{}'.format(b)
elif b in ('G', 'BP', 'RP'):
phot = 'UBVRIplus'
band = 'Gaia_{}'.format(b)
if 'version' in kwargs:
if kwargs['version']=='1.1':
band += '_DR2Rev'
else:
m = re.match('([a-zA-Z]+)_([a-zA-Z_]+)',b)
if m:
if m.group(1) in cls.phot_systems:
phot = m.group(1)
if phot=='PanSTARRS':
band = 'PS_{}'.format(m.group(2))
else:
band = m.group(0)
elif m.group(1) in ['UK','UKIRT']:
phot = 'UKIDSS'
band = 'UKIDSS_{}'.format(m.group(2))
if phot is None:
for system, bands in cls.phot_bands.items():
if b in bands:
phot = system
band = b
break
if phot is None:
raise ValueError('MIST grids cannot resolve band {}!'.format(b))
return phot, band | [
"def",
"get_band",
"(",
"cls",
",",
"b",
",",
"*",
"*",
"kwargs",
")",
":",
"phot",
"=",
"None",
"# Default to SDSS for these",
"if",
"b",
"in",
"[",
"'u'",
",",
"'g'",
",",
"'r'",
",",
"'i'",
",",
"'z'",
"]",
":",
"phot",
"=",
"'SDSS'",
"band",
... | Defines what a "shortcut" band name refers to. Returns phot_system, band | [
"Defines",
"what",
"a",
"shortcut",
"band",
"name",
"refers",
"to",
".",
"Returns",
"phot_system",
"band"
] | python | train |
senaite/senaite.core | bika/lims/exportimport/instruments/panalytical/omnia/__init__.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/exportimport/instruments/panalytical/omnia/__init__.py#L61-L118 | def parse_headerline(self, line):
#Process incoming header line
"""11/03/2014 14:46:46
PANalytical
Results quantitative - Omnian 2013,
Selected archive:,Omnian 2013
Number of results selected:,4
"""
# Save each header field (that we know) and its own value in the dict
if line.startswith('Results quantitative'):
line = to_unicode(line)
if len(self._header) == 0:
self.err("Unexpected header format", numline=self._numline)
return -1
line = line.replace(',', "")
splitted = line.split(' - ')
self._header['Quantitative'] = splitted[1]
return 1
if line.startswith('Selected archive'):
if len(self._header) == 0:
self.err("No header found", numline=self._numline)
return -1
splitted = self.splitLine(line)
if len(splitted) > 1:
self._header['Archive'] = splitted[1].replace('"', '').strip()
else:
self.warn('Unexpected header format', numline=self._numline)
return 0
if line.startswith('Number of'):
if len(self._header) == 0:
self.err("No header found", numline=self._numline)
return -1
splitted = self.splitLine(line)
if len(splitted) > 1:
self._header['NumResults'] = splitted[1].replace('"', '').strip()
else:
self.warn('Unexpected header format', numline=self._numline)
return 0
if line.startswith('Seq.'):
if len(self._header) == 0:
self.err("No header found", numline=self._numline)
return -1
#Grab column names
self._columns = line.split(',')
self._end_header = True
return 1
else:
self._header['Date'] = line
return 1 | [
"def",
"parse_headerline",
"(",
"self",
",",
"line",
")",
":",
"#Process incoming header line",
"# Save each header field (that we know) and its own value in the dict ",
"if",
"line",
".",
"startswith",
"(",
"'Results quantitative'",
")",
":",
"line",
"=",
"to_unicode"... | 11/03/2014 14:46:46
PANalytical
Results quantitative - Omnian 2013,
Selected archive:,Omnian 2013
Number of results selected:,4 | [
"11",
"/",
"03",
"/",
"2014",
"14",
":",
"46",
":",
"46",
"PANalytical",
"Results",
"quantitative",
"-",
"Omnian",
"2013"
] | python | train |
101Loop/drf-addons | drfaddons/utils.py | https://github.com/101Loop/drf-addons/blob/62392c72e8bce237f4140a2b7171e89984cb15c5/drfaddons/utils.py#L105-L123 | def get_mobile_number(mobile):
"""
Returns a mobile number after removing blanks
Author: Himanshu Shankar (https://himanshus.com)
Parameters
----------
mobile: str
Returns
-------
str
"""
blanks = [' ', '.', ',', '(', ')', '-']
for b in blanks:
mobile = mobile.replace(b, '')
return mobile | [
"def",
"get_mobile_number",
"(",
"mobile",
")",
":",
"blanks",
"=",
"[",
"' '",
",",
"'.'",
",",
"','",
",",
"'('",
",",
"')'",
",",
"'-'",
"]",
"for",
"b",
"in",
"blanks",
":",
"mobile",
"=",
"mobile",
".",
"replace",
"(",
"b",
",",
"''",
")",
... | Returns a mobile number after removing blanks
Author: Himanshu Shankar (https://himanshus.com)
Parameters
----------
mobile: str
Returns
-------
str | [
"Returns",
"a",
"mobile",
"number",
"after",
"removing",
"blanks"
] | python | train |
fy0/slim | slim_cli/template/model/user.py | https://github.com/fy0/slim/blob/9951a910750888dbe7dd3e98acae9c40efae0689/slim_cli/template/model/user.py#L91-L96 | def set_password(self, new_password):
""" 设置密码 """
info = self.gen_password_and_salt(new_password)
self.password = info['password']
self.salt = info['salt']
self.save() | [
"def",
"set_password",
"(",
"self",
",",
"new_password",
")",
":",
"info",
"=",
"self",
".",
"gen_password_and_salt",
"(",
"new_password",
")",
"self",
".",
"password",
"=",
"info",
"[",
"'password'",
"]",
"self",
".",
"salt",
"=",
"info",
"[",
"'salt'",
... | 设置密码 | [
"设置密码"
] | python | valid |
h2oai/h2o-3 | h2o-py/h2o/assembly.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/assembly.py#L131-L142 | def fit(self, fr):
"""
To perform the munging operations on a frame specified in steps on the frame fr.
:param fr: H2OFrame where munging operations are to be performed on.
:return: H2OFrame after munging operations are completed.
"""
assert_is_type(fr, H2OFrame)
steps = "[%s]" % ",".join(quoted(step[1].to_rest(step[0]).replace('"', "'")) for step in self.steps)
j = h2o.api("POST /99/Assembly", data={"steps": steps, "frame": fr.frame_id})
self.id = j["assembly"]["name"]
return H2OFrame.get_frame(j["result"]["name"]) | [
"def",
"fit",
"(",
"self",
",",
"fr",
")",
":",
"assert_is_type",
"(",
"fr",
",",
"H2OFrame",
")",
"steps",
"=",
"\"[%s]\"",
"%",
"\",\"",
".",
"join",
"(",
"quoted",
"(",
"step",
"[",
"1",
"]",
".",
"to_rest",
"(",
"step",
"[",
"0",
"]",
")",
... | To perform the munging operations on a frame specified in steps on the frame fr.
:param fr: H2OFrame where munging operations are to be performed on.
:return: H2OFrame after munging operations are completed. | [
"To",
"perform",
"the",
"munging",
"operations",
"on",
"a",
"frame",
"specified",
"in",
"steps",
"on",
"the",
"frame",
"fr",
"."
] | python | test |
synw/dataswim | dataswim/maps/__init__.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/maps/__init__.py#L13-L22 | def tmarker(self, lat, long, text, color=None, icon=None, style=None):
"""
Returns the map with a text marker to the default map
"""
try:
self.dsmap = self._marker(
lat, long, text, self.dsmap, color, icon, True, style)
return self.dsmap
except Exception as e:
self.err(e, self.tmarker, "Can not get text marker") | [
"def",
"tmarker",
"(",
"self",
",",
"lat",
",",
"long",
",",
"text",
",",
"color",
"=",
"None",
",",
"icon",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"dsmap",
"=",
"self",
".",
"_marker",
"(",
"lat",
",",
"long... | Returns the map with a text marker to the default map | [
"Returns",
"the",
"map",
"with",
"a",
"text",
"marker",
"to",
"the",
"default",
"map"
] | python | train |
mosdef-hub/mbuild | mbuild/compound.py | https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1806-L1821 | def spin(self, theta, around):
"""Rotate Compound in place around an arbitrary vector.
Parameters
----------
theta : float
The angle by which to rotate the Compound, in radians.
around : np.ndarray, shape=(3,), dtype=float
The axis about which to spin the Compound.
"""
around = np.asarray(around).reshape(3)
center_pos = self.center
self.translate(-center_pos)
self.rotate(theta, around)
self.translate(center_pos) | [
"def",
"spin",
"(",
"self",
",",
"theta",
",",
"around",
")",
":",
"around",
"=",
"np",
".",
"asarray",
"(",
"around",
")",
".",
"reshape",
"(",
"3",
")",
"center_pos",
"=",
"self",
".",
"center",
"self",
".",
"translate",
"(",
"-",
"center_pos",
"... | Rotate Compound in place around an arbitrary vector.
Parameters
----------
theta : float
The angle by which to rotate the Compound, in radians.
around : np.ndarray, shape=(3,), dtype=float
The axis about which to spin the Compound. | [
"Rotate",
"Compound",
"in",
"place",
"around",
"an",
"arbitrary",
"vector",
"."
] | python | train |
zhmcclient/python-zhmcclient | zhmcclient_mock/_urihandler.py | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_urihandler.py#L888-L903 | def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: List LDAP Server Definitions."""
query_str = uri_parms[0]
try:
console = hmc.consoles.lookup_by_oid(None)
except KeyError:
raise InvalidResourceError(method, uri)
result_ldap_srv_defs = []
filter_args = parse_query_parms(method, uri, query_str)
for ldap_srv_def in console.ldap_server_definitions.list(filter_args):
result_ldap_srv_def = {}
for prop in ldap_srv_def.properties:
if prop in ('element-uri', 'name', 'type'):
result_ldap_srv_def[prop] = ldap_srv_def.properties[prop]
result_ldap_srv_defs.append(result_ldap_srv_def)
return {'ldap-server-definitions': result_ldap_srv_defs} | [
"def",
"get",
"(",
"method",
",",
"hmc",
",",
"uri",
",",
"uri_parms",
",",
"logon_required",
")",
":",
"query_str",
"=",
"uri_parms",
"[",
"0",
"]",
"try",
":",
"console",
"=",
"hmc",
".",
"consoles",
".",
"lookup_by_oid",
"(",
"None",
")",
"except",
... | Operation: List LDAP Server Definitions. | [
"Operation",
":",
"List",
"LDAP",
"Server",
"Definitions",
"."
] | python | train |
wadda/gps3 | gps3/gps3.py | https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/gps3/gps3.py#L50-L64 | def connect(self, host=HOST, port=GPSD_PORT):
"""Connect to a host on a given port.
Arguments:
host: default host='127.0.0.1'
port: default port=2947
"""
for alotta_stuff in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
family, socktype, proto, _canonname, host_port = alotta_stuff
try:
self.streamSock = socket.socket(family, socktype, proto)
self.streamSock.connect(host_port)
self.streamSock.setblocking(False)
except (OSError, IOError) as error:
sys.stderr.write('\r\nGPSDSocket.connect exception is--> {}'.format(error))
sys.stderr.write('\r\nGPS3 gpsd connection at \'{0}\' on port \'{1}\' failed\r\n'.format(host, port)) | [
"def",
"connect",
"(",
"self",
",",
"host",
"=",
"HOST",
",",
"port",
"=",
"GPSD_PORT",
")",
":",
"for",
"alotta_stuff",
"in",
"socket",
".",
"getaddrinfo",
"(",
"host",
",",
"port",
",",
"0",
",",
"socket",
".",
"SOCK_STREAM",
")",
":",
"family",
",... | Connect to a host on a given port.
Arguments:
host: default host='127.0.0.1'
port: default port=2947 | [
"Connect",
"to",
"a",
"host",
"on",
"a",
"given",
"port",
".",
"Arguments",
":",
"host",
":",
"default",
"host",
"=",
"127",
".",
"0",
".",
"0",
".",
"1",
"port",
":",
"default",
"port",
"=",
"2947"
] | python | train |
xtuml/pyxtuml | xtuml/meta.py | https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L1053-L1061 | def delete(instance, disconnect=True):
'''
Delete an *instance* from its metaclass instance pool and optionally
*disconnect* it from any links it might be connected to.
'''
if not isinstance(instance, Class):
raise DeleteException("the provided argument is not an xtuml instance")
return get_metaclass(instance).delete(instance, disconnect) | [
"def",
"delete",
"(",
"instance",
",",
"disconnect",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"instance",
",",
"Class",
")",
":",
"raise",
"DeleteException",
"(",
"\"the provided argument is not an xtuml instance\"",
")",
"return",
"get_metaclass",
"... | Delete an *instance* from its metaclass instance pool and optionally
*disconnect* it from any links it might be connected to. | [
"Delete",
"an",
"*",
"instance",
"*",
"from",
"its",
"metaclass",
"instance",
"pool",
"and",
"optionally",
"*",
"disconnect",
"*",
"it",
"from",
"any",
"links",
"it",
"might",
"be",
"connected",
"to",
"."
] | python | test |
bitesofcode/projexui | projexui/widgets/xorbbrowserwidget/xorbquerywidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbbrowserwidget/xorbquerywidget.py#L267-L279 | def columnType( self ):
"""
Returns the column type for this item based on the current column.
:return <orb.ColumnType>
"""
schema = self.treeWidget().parent().schema()
if ( not schema ):
return 0
column = schema.column(self.text(0))
if ( column ):
return column.columnType()
return ColumnType.String | [
"def",
"columnType",
"(",
"self",
")",
":",
"schema",
"=",
"self",
".",
"treeWidget",
"(",
")",
".",
"parent",
"(",
")",
".",
"schema",
"(",
")",
"if",
"(",
"not",
"schema",
")",
":",
"return",
"0",
"column",
"=",
"schema",
".",
"column",
"(",
"s... | Returns the column type for this item based on the current column.
:return <orb.ColumnType> | [
"Returns",
"the",
"column",
"type",
"for",
"this",
"item",
"based",
"on",
"the",
"current",
"column",
".",
":",
"return",
"<orb",
".",
"ColumnType",
">"
] | python | train |
tensorflow/tensorboard | tensorboard/plugins/custom_scalar/custom_scalars_plugin.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/custom_scalar/custom_scalars_plugin.py#L244-L258 | def layout_route(self, request):
r"""Fetches the custom layout specified by the config file in the logdir.
If more than 1 run contains a layout, this method merges the layouts by
merging charts within individual categories. If 2 categories with the same
name are found, the charts within are merged. The merging is based on the
order of the runs to which the layouts are written.
The response is a JSON object mirroring properties of the Layout proto if a
layout for any run is found.
The response is an empty object if no layout could be found.
"""
body = self.layout_impl()
return http_util.Respond(request, body, 'application/json') | [
"def",
"layout_route",
"(",
"self",
",",
"request",
")",
":",
"body",
"=",
"self",
".",
"layout_impl",
"(",
")",
"return",
"http_util",
".",
"Respond",
"(",
"request",
",",
"body",
",",
"'application/json'",
")"
] | r"""Fetches the custom layout specified by the config file in the logdir.
If more than 1 run contains a layout, this method merges the layouts by
merging charts within individual categories. If 2 categories with the same
name are found, the charts within are merged. The merging is based on the
order of the runs to which the layouts are written.
The response is a JSON object mirroring properties of the Layout proto if a
layout for any run is found.
The response is an empty object if no layout could be found. | [
"r",
"Fetches",
"the",
"custom",
"layout",
"specified",
"by",
"the",
"config",
"file",
"in",
"the",
"logdir",
"."
] | python | train |
influxdata/influxdb-python | influxdb/client.py | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L878-L888 | def revoke_admin_privileges(self, username):
"""Revoke cluster administration privileges from a user.
:param username: the username to revoke privileges from
:type username: str
.. note:: Only a cluster administrator can create/ drop databases
and manage users.
"""
text = "REVOKE ALL PRIVILEGES FROM {0}".format(quote_ident(username))
self.query(text, method="POST") | [
"def",
"revoke_admin_privileges",
"(",
"self",
",",
"username",
")",
":",
"text",
"=",
"\"REVOKE ALL PRIVILEGES FROM {0}\"",
".",
"format",
"(",
"quote_ident",
"(",
"username",
")",
")",
"self",
".",
"query",
"(",
"text",
",",
"method",
"=",
"\"POST\"",
")"
] | Revoke cluster administration privileges from a user.
:param username: the username to revoke privileges from
:type username: str
.. note:: Only a cluster administrator can create/ drop databases
and manage users. | [
"Revoke",
"cluster",
"administration",
"privileges",
"from",
"a",
"user",
"."
] | python | train |
rochacbruno/python-pagseguro | pagseguro/__init__.py | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L255-L258 | def check_transaction(self, code):
""" check a transaction by its code """
response = self.get(url=self.config.TRANSACTION_URL % code)
return PagSeguroNotificationResponse(response.content, self.config) | [
"def",
"check_transaction",
"(",
"self",
",",
"code",
")",
":",
"response",
"=",
"self",
".",
"get",
"(",
"url",
"=",
"self",
".",
"config",
".",
"TRANSACTION_URL",
"%",
"code",
")",
"return",
"PagSeguroNotificationResponse",
"(",
"response",
".",
"content",... | check a transaction by its code | [
"check",
"a",
"transaction",
"by",
"its",
"code"
] | python | train |
juju/python-libjuju | juju/client/_client3.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/_client3.py#L5690-L5707 | async def CreatePool(self, attrs, name, provider):
'''
attrs : typing.Mapping[str, typing.Any]
name : str
provider : str
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Storage',
request='CreatePool',
version=3,
params=_params)
_params['attrs'] = attrs
_params['name'] = name
_params['provider'] = provider
reply = await self.rpc(msg)
return reply | [
"async",
"def",
"CreatePool",
"(",
"self",
",",
"attrs",
",",
"name",
",",
"provider",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Storage'",
",",
"request",
"=",
"'CreatePool'",
",",
... | attrs : typing.Mapping[str, typing.Any]
name : str
provider : str
Returns -> None | [
"attrs",
":",
"typing",
".",
"Mapping",
"[",
"str",
"typing",
".",
"Any",
"]",
"name",
":",
"str",
"provider",
":",
"str",
"Returns",
"-",
">",
"None"
] | python | train |
GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_watcher.py#L155-L183 | def _HandleMetadataUpdate(
self, metadata_key='', recursive=True, wait=True, timeout=None,
retry=True):
"""Wait for a successful metadata response.
Args:
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadata changes.
wait: bool, True if we should wait for a metadata change.
timeout: int, timeout in seconds for returning metadata output.
retry: bool, True if we should retry on failure.
Returns:
json, the deserialized contents of the metadata server.
"""
exception = None
while True:
try:
return self._GetMetadataUpdate(
metadata_key=metadata_key, recursive=recursive, wait=wait,
timeout=timeout)
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
if not isinstance(e, type(exception)):
exception = e
self.logger.error('GET request error retrieving metadata. %s.', e)
if retry:
continue
else:
break | [
"def",
"_HandleMetadataUpdate",
"(",
"self",
",",
"metadata_key",
"=",
"''",
",",
"recursive",
"=",
"True",
",",
"wait",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"retry",
"=",
"True",
")",
":",
"exception",
"=",
"None",
"while",
"True",
":",
"try... | Wait for a successful metadata response.
Args:
metadata_key: string, the metadata key to watch for changes.
recursive: bool, True if we should recursively watch for metadata changes.
wait: bool, True if we should wait for a metadata change.
timeout: int, timeout in seconds for returning metadata output.
retry: bool, True if we should retry on failure.
Returns:
json, the deserialized contents of the metadata server. | [
"Wait",
"for",
"a",
"successful",
"metadata",
"response",
"."
] | python | train |
inspirehep/harvesting-kit | harvestingkit/etree_utils.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/etree_utils.py#L60-L81 | def element_tree_collection_to_records(tree):
"""Take an ElementTree and converts the nodes into BibRecord records.
This function is for a tree root of collection as such:
<collection>
<record>
<!-- MARCXML -->
</record>
<record> ... </record>
</collection>
"""
from .bibrecord import create_record
records = []
collection = tree.getroot()
for record_element in collection.getchildren():
marcxml = ET.tostring(record_element, encoding="utf-8")
record, status, errors = create_record(marcxml)
if errors:
print(str(status))
records.append(record)
return records | [
"def",
"element_tree_collection_to_records",
"(",
"tree",
")",
":",
"from",
".",
"bibrecord",
"import",
"create_record",
"records",
"=",
"[",
"]",
"collection",
"=",
"tree",
".",
"getroot",
"(",
")",
"for",
"record_element",
"in",
"collection",
".",
"getchildren... | Take an ElementTree and converts the nodes into BibRecord records.
This function is for a tree root of collection as such:
<collection>
<record>
<!-- MARCXML -->
</record>
<record> ... </record>
</collection> | [
"Take",
"an",
"ElementTree",
"and",
"converts",
"the",
"nodes",
"into",
"BibRecord",
"records",
"."
] | python | valid |
astrorafael/twisted-mqtt | mqtt/client/base.py | https://github.com/astrorafael/twisted-mqtt/blob/5b322f7c2b82a502b1e1b70703ae45f1f668d07d/mqtt/client/base.py#L138-L143 | def handleCONNACK(self, response):
'''
Handles CONNACK packet from the server
'''
state = self.__class__.__name__
log.error("Unexpected {packet:7} packet received in {log_source}", packet="CONNACK") | [
"def",
"handleCONNACK",
"(",
"self",
",",
"response",
")",
":",
"state",
"=",
"self",
".",
"__class__",
".",
"__name__",
"log",
".",
"error",
"(",
"\"Unexpected {packet:7} packet received in {log_source}\"",
",",
"packet",
"=",
"\"CONNACK\"",
")"
] | Handles CONNACK packet from the server | [
"Handles",
"CONNACK",
"packet",
"from",
"the",
"server"
] | python | test |
ubccr/pinky | pinky/perception/aromaticity.py | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/perception/aromaticity.py#L78-L88 | def getPyroleLikeAtoms(cycle):
"""cycle->return a dictionary of pyrole nitrogen-like atoms in
a cycle or a molecule The dictionary is keyed on the atom.handle"""
result = {}
# the outgoing bonds might need to be single or aromatic
for atom in cycle.atoms:
lookup = (atom.symbol, atom.charge, atom.hcount, len(atom.bonds))
if PyroleTable.get(lookup, 0):
result[atom.handle] = atom
return result | [
"def",
"getPyroleLikeAtoms",
"(",
"cycle",
")",
":",
"result",
"=",
"{",
"}",
"# the outgoing bonds might need to be single or aromatic",
"for",
"atom",
"in",
"cycle",
".",
"atoms",
":",
"lookup",
"=",
"(",
"atom",
".",
"symbol",
",",
"atom",
".",
"charge",
",... | cycle->return a dictionary of pyrole nitrogen-like atoms in
a cycle or a molecule The dictionary is keyed on the atom.handle | [
"cycle",
"-",
">",
"return",
"a",
"dictionary",
"of",
"pyrole",
"nitrogen",
"-",
"like",
"atoms",
"in",
"a",
"cycle",
"or",
"a",
"molecule",
"The",
"dictionary",
"is",
"keyed",
"on",
"the",
"atom",
".",
"handle"
] | python | train |
gmr/rejected | rejected/statsd.py | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/statsd.py#L109-L117 | def _build_payload(self, key, value, metric_type):
"""Return the """
if self._setting('include_hostname', True):
return self.PAYLOAD_HOSTNAME.format(
self._prefix, self._hostname, self._consumer_name, key, value,
metric_type)
return self.PAYLOAD_NO_HOSTNAME.format(
self._prefix, self._consumer_name, key, value,
metric_type) | [
"def",
"_build_payload",
"(",
"self",
",",
"key",
",",
"value",
",",
"metric_type",
")",
":",
"if",
"self",
".",
"_setting",
"(",
"'include_hostname'",
",",
"True",
")",
":",
"return",
"self",
".",
"PAYLOAD_HOSTNAME",
".",
"format",
"(",
"self",
".",
"_p... | Return the | [
"Return",
"the"
] | python | train |
SavinaRoja/PyUserInput | pykeyboard/base.py | https://github.com/SavinaRoja/PyUserInput/blob/153c1d39b1a41b467b235fd182392d6dcbf07947/pykeyboard/base.py#L47-L52 | def press_keys(self,characters=[]):
"""Press a given character key."""
for character in characters:
self.press_key(character)
for character in characters:
self.release_key(character) | [
"def",
"press_keys",
"(",
"self",
",",
"characters",
"=",
"[",
"]",
")",
":",
"for",
"character",
"in",
"characters",
":",
"self",
".",
"press_key",
"(",
"character",
")",
"for",
"character",
"in",
"characters",
":",
"self",
".",
"release_key",
"(",
"cha... | Press a given character key. | [
"Press",
"a",
"given",
"character",
"key",
"."
] | python | train |
aestrivex/bctpy | bct/algorithms/similarity.py | https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/similarity.py#L167-L245 | def matching_ind(CIJ):
'''
For any two nodes u and v, the matching index computes the amount of
overlap in the connection patterns of u and v. Self-connections and
u-v connections are ignored. The matching index is a symmetric
quantity, similar to a correlation or a dot product.
Parameters
----------
CIJ : NxN np.ndarray
adjacency matrix
Returns
-------
Min : NxN np.ndarray
matching index for incoming connections
Mout : NxN np.ndarray
matching index for outgoing connections
Mall : NxN np.ndarray
matching index for all connections
Notes
-----
Does not use self- or cross connections for comparison.
Does not use connections that are not present in BOTH u and v.
All output matrices are calculated for upper triangular only.
'''
n = len(CIJ)
Min = np.zeros((n, n))
Mout = np.zeros((n, n))
Mall = np.zeros((n, n))
# compare incoming connections
for i in range(n - 1):
for j in range(i + 1, n):
c1i = CIJ[:, i]
c2i = CIJ[:, j]
usei = np.logical_or(c1i, c2i)
usei[i] = 0
usei[j] = 0
nconi = np.sum(c1i[usei]) + np.sum(c2i[usei])
if not nconi:
Min[i, j] = 0
else:
Min[i, j] = 2 * \
np.sum(np.logical_and(c1i[usei], c2i[usei])) / nconi
c1o = CIJ[i, :]
c2o = CIJ[j, :]
useo = np.logical_or(c1o, c2o)
useo[i] = 0
useo[j] = 0
ncono = np.sum(c1o[useo]) + np.sum(c2o[useo])
if not ncono:
Mout[i, j] = 0
else:
Mout[i, j] = 2 * \
np.sum(np.logical_and(c1o[useo], c2o[useo])) / ncono
c1a = np.ravel((c1i, c1o))
c2a = np.ravel((c2i, c2o))
usea = np.logical_or(c1a, c2a)
usea[i] = 0
usea[i + n] = 0
usea[j] = 0
usea[j + n] = 0
ncona = np.sum(c1a[usea]) + np.sum(c2a[usea])
if not ncona:
Mall[i, j] = 0
else:
Mall[i, j] = 2 * \
np.sum(np.logical_and(c1a[usea], c2a[usea])) / ncona
Min = Min + Min.T
Mout = Mout + Mout.T
Mall = Mall + Mall.T
return Min, Mout, Mall | [
"def",
"matching_ind",
"(",
"CIJ",
")",
":",
"n",
"=",
"len",
"(",
"CIJ",
")",
"Min",
"=",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"n",
")",
")",
"Mout",
"=",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"n",
")",
")",
"Mall",
"=",
"np",
".",
... | For any two nodes u and v, the matching index computes the amount of
overlap in the connection patterns of u and v. Self-connections and
u-v connections are ignored. The matching index is a symmetric
quantity, similar to a correlation or a dot product.
Parameters
----------
CIJ : NxN np.ndarray
adjacency matrix
Returns
-------
Min : NxN np.ndarray
matching index for incoming connections
Mout : NxN np.ndarray
matching index for outgoing connections
Mall : NxN np.ndarray
matching index for all connections
Notes
-----
Does not use self- or cross connections for comparison.
Does not use connections that are not present in BOTH u and v.
All output matrices are calculated for upper triangular only. | [
"For",
"any",
"two",
"nodes",
"u",
"and",
"v",
"the",
"matching",
"index",
"computes",
"the",
"amount",
"of",
"overlap",
"in",
"the",
"connection",
"patterns",
"of",
"u",
"and",
"v",
".",
"Self",
"-",
"connections",
"and",
"u",
"-",
"v",
"connections",
... | python | train |
KelSolaar/Foundations | foundations/namespace.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/namespace.py#L146-L163 | def get_leaf(attribute, namespace_splitter=NAMESPACE_SPLITTER):
"""
Returns given attribute leaf.
Usage::
>>> get_leaf("grandParent|parent|child")
u'child'
:param attribute: Attribute.
:type attribute: unicode
:param namespace_splitter: Namespace splitter character.
:type namespace_splitter: unicode
:return: Attribute foundations.namespace.
:rtype: unicode
"""
return foundations.common.get_last_item(attribute.split(namespace_splitter)) | [
"def",
"get_leaf",
"(",
"attribute",
",",
"namespace_splitter",
"=",
"NAMESPACE_SPLITTER",
")",
":",
"return",
"foundations",
".",
"common",
".",
"get_last_item",
"(",
"attribute",
".",
"split",
"(",
"namespace_splitter",
")",
")"
] | Returns given attribute leaf.
Usage::
>>> get_leaf("grandParent|parent|child")
u'child'
:param attribute: Attribute.
:type attribute: unicode
:param namespace_splitter: Namespace splitter character.
:type namespace_splitter: unicode
:return: Attribute foundations.namespace.
:rtype: unicode | [
"Returns",
"given",
"attribute",
"leaf",
"."
] | python | train |
apache/incubator-mxnet | example/rnn/large_word_lm/custom_module.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/custom_module.py#L176-L183 | def rescale_grad(self, scale=None, param_name=None):
""" Rescale the gradient of provided parameters by a certain scale """
if scale is None or param_name is None:
return
param_idx = self._exec_group.param_names.index(param_name)
grad_vals = self._exec_group.grad_arrays[param_idx]
for grad in grad_vals:
grad[:] *= scale | [
"def",
"rescale_grad",
"(",
"self",
",",
"scale",
"=",
"None",
",",
"param_name",
"=",
"None",
")",
":",
"if",
"scale",
"is",
"None",
"or",
"param_name",
"is",
"None",
":",
"return",
"param_idx",
"=",
"self",
".",
"_exec_group",
".",
"param_names",
".",
... | Rescale the gradient of provided parameters by a certain scale | [
"Rescale",
"the",
"gradient",
"of",
"provided",
"parameters",
"by",
"a",
"certain",
"scale"
] | python | train |
squaresLab/BugZoo | bugzoo/mgr/container.py | https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L296-L338 | def patch(self, container: Container, p: Patch) -> bool:
"""
Attempts to apply a given patch to the source code for a program inside
a given container. All patch applications are guaranteed to be atomic;
if the patch fails to apply, no changes will be made to the relevant
source code files.
Returns true if the patch application was successful, and false if
the attempt was unsuccessful.
"""
assert isinstance(p, Patch)
file_container = None
dockerc = self.__dockerc[container.uid]
bug = self.__installation.bugs[container.bug]
logger.debug("Applying patch to container [%s]:\n%s",
container.uid,
str(p))
try:
file_host = NamedTemporaryFile(mode='w', suffix='bugzoo')
file_host.write(str(p))
file_host.flush()
# copy contents to a temporary file on the container
(retcode, file_container) = dockerc.exec_run('mktemp')
assert retcode == 0
file_container = file_container.decode(sys.stdout.encoding).strip()
self.copy_to(container, file_host.name, file_container)
# run patch command inside the source directory
cmd = 'sudo chown $(whoami) "{}" && patch -p0 < "{}"'
cmd = cmd.format(file_container, file_container)
outcome = self.command(container, cmd, context=bug.source_dir)
logger.debug("Patch application outcome [%s]: (retcode=%d)\n%s",
container.uid,
outcome.code,
outcome.output)
return outcome.code == 0
finally:
if file_container:
dockerc.exec_run('rm "{}"'.format(file_container)) | [
"def",
"patch",
"(",
"self",
",",
"container",
":",
"Container",
",",
"p",
":",
"Patch",
")",
"->",
"bool",
":",
"assert",
"isinstance",
"(",
"p",
",",
"Patch",
")",
"file_container",
"=",
"None",
"dockerc",
"=",
"self",
".",
"__dockerc",
"[",
"contain... | Attempts to apply a given patch to the source code for a program inside
a given container. All patch applications are guaranteed to be atomic;
if the patch fails to apply, no changes will be made to the relevant
source code files.
Returns true if the patch application was successful, and false if
the attempt was unsuccessful. | [
"Attempts",
"to",
"apply",
"a",
"given",
"patch",
"to",
"the",
"source",
"code",
"for",
"a",
"program",
"inside",
"a",
"given",
"container",
".",
"All",
"patch",
"applications",
"are",
"guaranteed",
"to",
"be",
"atomic",
";",
"if",
"the",
"patch",
"fails",... | python | train |
cloudmesh/cloudmesh-common | cloudmesh/common/ssh/authorized_keys.py | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/ssh/authorized_keys.py#L68-L77 | def add(self, pubkey):
"""
add a public key.
:param pubkey: the filename to the public key
:return:
"""
f = get_fingerprint_from_public_key(pubkey)
if f not in self._keys:
self._order[len(self._keys)] = f
self._keys[f] = pubkey | [
"def",
"add",
"(",
"self",
",",
"pubkey",
")",
":",
"f",
"=",
"get_fingerprint_from_public_key",
"(",
"pubkey",
")",
"if",
"f",
"not",
"in",
"self",
".",
"_keys",
":",
"self",
".",
"_order",
"[",
"len",
"(",
"self",
".",
"_keys",
")",
"]",
"=",
"f"... | add a public key.
:param pubkey: the filename to the public key
:return: | [
"add",
"a",
"public",
"key",
".",
":",
"param",
"pubkey",
":",
"the",
"filename",
"to",
"the",
"public",
"key",
":",
"return",
":"
] | python | train |
pygobject/pgi | pgi/module.py | https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/module.py#L100-L135 | def get_introspection_module(namespace):
"""Raises ImportError"""
if namespace in _introspection_modules:
return _introspection_modules[namespace]
from . import get_required_version
repository = GIRepository()
version = get_required_version(namespace)
try:
repository.require(namespace, version, 0)
except GIError as e:
raise ImportError(e.message)
# No strictly needed here, but most things will fail during use
library = repository.get_shared_library(namespace)
if library:
library = library.split(",")[0]
try:
util.load_ctypes_library(library)
except OSError:
raise ImportError(
"Couldn't load shared library %r" % library)
# Generate bindings, set up lazy attributes
instance = Module(repository, namespace)
instance.__path__ = repository.get_typelib_path(namespace)
instance.__package__ = const.PREFIX[0]
instance.__file__ = "<%s.%s>" % (const.PREFIX[0], namespace)
instance._version = version or repository.get_version(namespace)
_introspection_modules[namespace] = instance
return instance | [
"def",
"get_introspection_module",
"(",
"namespace",
")",
":",
"if",
"namespace",
"in",
"_introspection_modules",
":",
"return",
"_introspection_modules",
"[",
"namespace",
"]",
"from",
".",
"import",
"get_required_version",
"repository",
"=",
"GIRepository",
"(",
")"... | Raises ImportError | [
"Raises",
"ImportError"
] | python | train |
scot-dev/scot | scot/connectivity_statistics.py | https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity_statistics.py#L252-L295 | def significance_fdr(p, alpha):
"""Calculate significance by controlling for the false discovery rate.
This function determines which of the p-values in `p` can be considered
significant. Correction for multiple comparisons is performed by
controlling the false discovery rate (FDR). The FDR is the maximum fraction
of p-values that are wrongly considered significant [1]_.
Parameters
----------
p : array, shape (channels, channels, nfft)
p-values.
alpha : float
Maximum false discovery rate.
Returns
-------
s : array, dtype=bool, shape (channels, channels, nfft)
Significance of each p-value.
References
----------
.. [1] Y. Benjamini, Y. Hochberg. Controlling the false discovery rate: a
practical and powerful approach to multiple testing. J. Royal Stat.
Soc. Series B 57(1): 289-300, 1995.
"""
i = np.argsort(p, axis=None)
m = i.size - np.sum(np.isnan(p))
j = np.empty(p.shape, int)
j.flat[i] = np.arange(1, i.size + 1)
mask = p <= alpha * j / m
if np.sum(mask) == 0:
return mask
# find largest k so that p_k <= alpha*k/m
k = np.max(j[mask])
# reject all H_i for i = 0...k
s = j <= k
return s | [
"def",
"significance_fdr",
"(",
"p",
",",
"alpha",
")",
":",
"i",
"=",
"np",
".",
"argsort",
"(",
"p",
",",
"axis",
"=",
"None",
")",
"m",
"=",
"i",
".",
"size",
"-",
"np",
".",
"sum",
"(",
"np",
".",
"isnan",
"(",
"p",
")",
")",
"j",
"=",
... | Calculate significance by controlling for the false discovery rate.
This function determines which of the p-values in `p` can be considered
significant. Correction for multiple comparisons is performed by
controlling the false discovery rate (FDR). The FDR is the maximum fraction
of p-values that are wrongly considered significant [1]_.
Parameters
----------
p : array, shape (channels, channels, nfft)
p-values.
alpha : float
Maximum false discovery rate.
Returns
-------
s : array, dtype=bool, shape (channels, channels, nfft)
Significance of each p-value.
References
----------
.. [1] Y. Benjamini, Y. Hochberg. Controlling the false discovery rate: a
practical and powerful approach to multiple testing. J. Royal Stat.
Soc. Series B 57(1): 289-300, 1995. | [
"Calculate",
"significance",
"by",
"controlling",
"for",
"the",
"false",
"discovery",
"rate",
"."
] | python | train |
Netflix-Skunkworks/historical | historical/common/cloudwatch.py | https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/common/cloudwatch.py#L14-L33 | def filter_request_parameters(field_name, msg, look_in_response=False):
"""
From an event, extract the field name from the message.
Different API calls put this information in different places, so check a few places.
"""
val = msg['detail'].get(field_name, None)
try:
if not val:
val = msg['detail'].get('requestParameters', {}).get(field_name, None)
# If we STILL didn't find it -- check if it's in the response element (default off)
if not val and look_in_response:
if msg['detail'].get('responseElements'):
val = msg['detail']['responseElements'].get(field_name, None)
# Just in case... We didn't find the value, so just make it None:
except AttributeError:
val = None
return val | [
"def",
"filter_request_parameters",
"(",
"field_name",
",",
"msg",
",",
"look_in_response",
"=",
"False",
")",
":",
"val",
"=",
"msg",
"[",
"'detail'",
"]",
".",
"get",
"(",
"field_name",
",",
"None",
")",
"try",
":",
"if",
"not",
"val",
":",
"val",
"=... | From an event, extract the field name from the message.
Different API calls put this information in different places, so check a few places. | [
"From",
"an",
"event",
"extract",
"the",
"field",
"name",
"from",
"the",
"message",
".",
"Different",
"API",
"calls",
"put",
"this",
"information",
"in",
"different",
"places",
"so",
"check",
"a",
"few",
"places",
"."
] | python | train |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L254-L274 | def catch_end_signal(self, signum, frame):
"""
When a SIGINT/SIGTERM signal is caught, this method is called, asking
for the worker to terminate as soon as possible.
"""
if self.end_signal_caught:
self.log('Previous signal caught, will end soon')
return
signal_name = dict((getattr(signal, n), n) for n in dir(signal)
if n.startswith('SIG') and '_' not in n).get(signum, signum)
if self.status == 'running':
self.log('Catched %s signal: stopping after current job' % signal_name,
level='critical')
else:
delay = self.timeout if self.status == 'waiting' else self.fetch_priorities_delay
self.log('Catched %s signal: stopping in max %d seconds' % (
signal_name, delay), level='critical')
self.end_signal_caught = self.end_forced = True | [
"def",
"catch_end_signal",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"if",
"self",
".",
"end_signal_caught",
":",
"self",
".",
"log",
"(",
"'Previous signal caught, will end soon'",
")",
"return",
"signal_name",
"=",
"dict",
"(",
"(",
"getattr",
"(",... | When a SIGINT/SIGTERM signal is caught, this method is called, asking
for the worker to terminate as soon as possible. | [
"When",
"a",
"SIGINT",
"/",
"SIGTERM",
"signal",
"is",
"caught",
"this",
"method",
"is",
"called",
"asking",
"for",
"the",
"worker",
"to",
"terminate",
"as",
"soon",
"as",
"possible",
"."
] | python | train |
inspirehep/harvesting-kit | harvestingkit/inspire_cds_package/base.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/base.py#L194-L198 | def add_control_number(self, tag, value):
"""Add a control-number 00x for given tag with value."""
record_add_field(self.record,
tag,
controlfield_value=value) | [
"def",
"add_control_number",
"(",
"self",
",",
"tag",
",",
"value",
")",
":",
"record_add_field",
"(",
"self",
".",
"record",
",",
"tag",
",",
"controlfield_value",
"=",
"value",
")"
] | Add a control-number 00x for given tag with value. | [
"Add",
"a",
"control",
"-",
"number",
"00x",
"for",
"given",
"tag",
"with",
"value",
"."
] | python | valid |
numenta/htmresearch | htmresearch/algorithms/TM.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1672-L1680 | def getSegmentActivityLevel(self, seg, activeState, connectedSynapsesOnly =False):
"""This routine computes the activity level of a segment given activeState.
It can tally up only connected synapses (permanence >= connectedPerm), or
all the synapses of the segment, at either t or t-1.
"""
# todo: Computing in C, use function getSegmentActivityLevel
return getSegmentActivityLevel(seg.syns, activeState, connectedSynapsesOnly,
self.connectedPerm) | [
"def",
"getSegmentActivityLevel",
"(",
"self",
",",
"seg",
",",
"activeState",
",",
"connectedSynapsesOnly",
"=",
"False",
")",
":",
"# todo: Computing in C, use function getSegmentActivityLevel",
"return",
"getSegmentActivityLevel",
"(",
"seg",
".",
"syns",
",",
"activeS... | This routine computes the activity level of a segment given activeState.
It can tally up only connected synapses (permanence >= connectedPerm), or
all the synapses of the segment, at either t or t-1. | [
"This",
"routine",
"computes",
"the",
"activity",
"level",
"of",
"a",
"segment",
"given",
"activeState",
".",
"It",
"can",
"tally",
"up",
"only",
"connected",
"synapses",
"(",
"permanence",
">",
"=",
"connectedPerm",
")",
"or",
"all",
"the",
"synapses",
"of"... | python | train |
drkjam/pydba | pydba/postgres.py | https://github.com/drkjam/pydba/blob/986c4b1315d6b128947c3bc3494513d8e5380ff0/pydba/postgres.py#L243-L256 | def connection_dsn(self, name=None):
"""
Provides a connection string for database.
Parameters
----------
name: str, optional
an override database name for the connection string.
Returns
-------
str: the connection string (e.g. 'dbname=db1 user=user1 host=localhost port=5432')
"""
return ' '.join("%s=%s" % (param, value) for param, value in self._connect_options(name)) | [
"def",
"connection_dsn",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"' '",
".",
"join",
"(",
"\"%s=%s\"",
"%",
"(",
"param",
",",
"value",
")",
"for",
"param",
",",
"value",
"in",
"self",
".",
"_connect_options",
"(",
"name",
")",
")"... | Provides a connection string for database.
Parameters
----------
name: str, optional
an override database name for the connection string.
Returns
-------
str: the connection string (e.g. 'dbname=db1 user=user1 host=localhost port=5432') | [
"Provides",
"a",
"connection",
"string",
"for",
"database",
"."
] | python | valid |
fake-name/ChromeController | ChromeController/manager.py | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L527-L546 | def get_unpacked_response_body(self, requestId, mimetype="application/unknown"):
'''
Return a unpacked, decoded resposne body from Network_getResponseBody()
'''
content = self.Network_getResponseBody(requestId)
assert 'result' in content
result = content['result']
assert 'base64Encoded' in result
assert 'body' in result
if result['base64Encoded']:
content = base64.b64decode(result['body'])
else:
content = result['body']
self.log.info("Navigate complete. Received %s byte response with type %s.", len(content), mimetype)
return {'binary' : result['base64Encoded'], 'mimetype' : mimetype, 'content' : content} | [
"def",
"get_unpacked_response_body",
"(",
"self",
",",
"requestId",
",",
"mimetype",
"=",
"\"application/unknown\"",
")",
":",
"content",
"=",
"self",
".",
"Network_getResponseBody",
"(",
"requestId",
")",
"assert",
"'result'",
"in",
"content",
"result",
"=",
"con... | Return a unpacked, decoded resposne body from Network_getResponseBody() | [
"Return",
"a",
"unpacked",
"decoded",
"resposne",
"body",
"from",
"Network_getResponseBody",
"()"
] | python | train |
ninuxorg/nodeshot | nodeshot/interop/sync/models/node_external.py | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/interop/sync/models/node_external.py#L36-L44 | def save_external_nodes(sender, **kwargs):
""" sync by creating nodes in external layers when needed """
node = kwargs['instance']
operation = 'add' if kwargs['created'] is True else 'change'
if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_path is None:
return False
push_changes_to_external_layers.delay(node=node, external_layer=node.layer.external, operation=operation) | [
"def",
"save_external_nodes",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"node",
"=",
"kwargs",
"[",
"'instance'",
"]",
"operation",
"=",
"'add'",
"if",
"kwargs",
"[",
"'created'",
"]",
"is",
"True",
"else",
"'change'",
"if",
"node",
".",
"layer",... | sync by creating nodes in external layers when needed | [
"sync",
"by",
"creating",
"nodes",
"in",
"external",
"layers",
"when",
"needed"
] | python | train |
StackStorm/pybind | pybind/slxos/v17r_1_01a/cpu_state/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/cpu_state/__init__.py#L252-L275 | def _set_process_list(self, v, load=False):
"""
Setter method for process_list, mapped from YANG variable /cpu_state/process_list (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_process_list is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_process_list() directly.
YANG Description: CPU utilization summary and list of all the process
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=process_list.process_list, is_container='container', presence=False, yang_name="process-list", rest_name="process-list", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'RAS-process-cpu', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-RAS-operational', defining_module='brocade-RAS-operational', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """process_list must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=process_list.process_list, is_container='container', presence=False, yang_name="process-list", rest_name="process-list", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'RAS-process-cpu', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-RAS-operational', defining_module='brocade-RAS-operational', yang_type='container', is_config=False)""",
})
self.__process_list = t
if hasattr(self, '_set'):
self._set() | [
"def",
"_set_process_list",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | Setter method for process_list, mapped from YANG variable /cpu_state/process_list (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_process_list is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_process_list() directly.
YANG Description: CPU utilization summary and list of all the process | [
"Setter",
"method",
"for",
"process_list",
"mapped",
"from",
"YANG",
"variable",
"/",
"cpu_state",
"/",
"process_list",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YA... | python | train |
slimkrazy/python-google-places | googleplaces/__init__.py | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L893-L897 | def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"if",
"self",
".",
"_icon",
"==",
"''",
"and",
"self",
".",
"details",
"!=",
"None",
"and",
"'icon'",
"in",
"self",
".",
"details",
":",
"self",
".",
"_icon",
"=",
"self",
".",
"details",
"[",
"'icon'",
"]",
... | Returns the URL of a recommended icon for display. | [
"Returns",
"the",
"URL",
"of",
"a",
"recommended",
"icon",
"for",
"display",
"."
] | python | train |
e7dal/bubble3 | bubble3/commands/cmd_init.py | https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/bubble3/commands/cmd_init.py#L28-L92 | def cli(ctx, given_name, demo):
"""Initializes a bubble."""
path = None
if path is None:
path = ctx.home
bubble_file_name = path + '/.bubble'
config_file = path + '/config/config.yaml'
if os.path.exists(bubble_file_name) and os.path.isfile(bubble_file_name):
ctx.say_yellow(
'There is already a bubble present, will not initialize bubble in:' + path)
return
else:
given_name = '(((' + given_name + ')))'
with open(bubble_file_name, 'w') as dot_bubble:
dot_bubble.write('bubble=' + metadata.version + '\n')
dot_bubble.write('name=' + given_name + '\n')
dot_bubble.write('home=' + ctx.home + '\n')
dot_bubble.write(
'local_init_timestamp=' + str(arrow.utcnow()) + '\n')
# aka date_of_birth
dot_bubble.write(
'local_creator_user=' + str(os.getenv('USER')) + '\n')
dot_bubble.write(
'local_created_in_env=' + str(os.environ) + '\n')
ctx.say_green('Initialised a new bubble in [%s]' %
click.format_filename(bubble_file_name))
create_dir(ctx, path + '/config/')
create_dir(ctx, path + '/logs/')
create_dir(ctx, path + '/export/')
create_dir(ctx, path + '/import/')
create_dir(ctx, path + '/remember/')
create_dir(ctx, path + '/remember/archive')
with open(config_file, 'w') as cfg_file:
cfg_file.write(get_example_configuration())
ctx.say_green('Created an example configuration in %s' %
click.format_filename(config_file))
rules_file = path + '/config/rules.bubble'
with open(rules_file, 'w') as rules:
rules.write(get_example_rules_bubble())
ctx.say_green('Created an example rules in [%s]' %
click.format_filename(rules_file))
rule_functions_file = path + '/custom_rule_functions.py'
with open(rule_functions_file, 'w') as rule_functions:
rule_functions.write(get_example_rule_functions())
ctx.say_green('Created an example rule_functions in [%s]' %
click.format_filename(rule_functions_file))
src_client_file = path + '/mysrcclient.py'
with open(src_client_file, 'w') as src_client:
src_client.write(get_example_client_pull())
ctx.say_green('Created source example client with pull method [%s]' %
click.format_filename(src_client_file))
tgt_client_file = path + '/mytgtclient.py'
with open(tgt_client_file, 'w') as tgt_client:
tgt_client.write(get_example_client_push())
ctx.say_green('Created an target example client with push method [%s]' %
click.format_filename(src_client_file))
ctx.say_green(
'Bubble initialized, please adjust your configuration file') | [
"def",
"cli",
"(",
"ctx",
",",
"given_name",
",",
"demo",
")",
":",
"path",
"=",
"None",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"ctx",
".",
"home",
"bubble_file_name",
"=",
"path",
"+",
"'/.bubble'",
"config_file",
"=",
"path",
"+",
"'/config/co... | Initializes a bubble. | [
"Initializes",
"a",
"bubble",
"."
] | python | train |
noxdafox/clipspy | clips/agenda.py | https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L366-L368 | def salience(self, salience):
"""Activation salience value."""
lib.EnvSetActivationSalience(self._env, self._act, salience) | [
"def",
"salience",
"(",
"self",
",",
"salience",
")",
":",
"lib",
".",
"EnvSetActivationSalience",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_act",
",",
"salience",
")"
] | Activation salience value. | [
"Activation",
"salience",
"value",
"."
] | python | train |
bunq/sdk_python | bunq/sdk/model/core.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/core.py#L507-L521 | def get_referenced_user(self):
"""
:rtype: BunqModel
"""
if self._user_person is not None:
return self._user_person
if self._user_company is not None:
return self._user_company
if self._user_api_key is not None:
return self._user_api_key
raise BunqException(self._ERROR_ALL_FIELD_IS_NULL) | [
"def",
"get_referenced_user",
"(",
"self",
")",
":",
"if",
"self",
".",
"_user_person",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_user_person",
"if",
"self",
".",
"_user_company",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_user_company",
"... | :rtype: BunqModel | [
":",
"rtype",
":",
"BunqModel"
] | python | train |
cloudify-cosmo/wagon | wagon.py | https://github.com/cloudify-cosmo/wagon/blob/9876d33a0aece01df2421a87e3b398d13f660fe6/wagon.py#L247-L282 | def install_package(package,
wheels_path,
venv=None,
requirement_files=None,
upgrade=False,
install_args=None):
"""Install a Python package.
Can specify a specific version.
Can specify a prerelease.
Can specify a venv to install in.
Can specify a list of paths or urls to requirement txt files.
Can specify a local wheels_path to use for offline installation.
Can request an upgrade.
"""
requirement_files = requirement_files or []
logger.info('Installing %s...', package)
if venv and not os.path.isdir(venv):
raise WagonError('virtualenv {0} does not exist'.format(venv))
pip_command = _construct_pip_command(
package,
wheels_path,
venv,
requirement_files,
upgrade,
install_args)
if IS_VIRTUALENV and not venv:
logger.info('Installing within current virtualenv')
result = _run(pip_command)
if not result.returncode == 0:
raise WagonError('Could not install package: {0} ({1})'.format(
package, result.aggr_stderr)) | [
"def",
"install_package",
"(",
"package",
",",
"wheels_path",
",",
"venv",
"=",
"None",
",",
"requirement_files",
"=",
"None",
",",
"upgrade",
"=",
"False",
",",
"install_args",
"=",
"None",
")",
":",
"requirement_files",
"=",
"requirement_files",
"or",
"[",
... | Install a Python package.
Can specify a specific version.
Can specify a prerelease.
Can specify a venv to install in.
Can specify a list of paths or urls to requirement txt files.
Can specify a local wheels_path to use for offline installation.
Can request an upgrade. | [
"Install",
"a",
"Python",
"package",
"."
] | python | train |
consbio/ncdjango | ncdjango/geoprocessing/params.py | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L394-L443 | def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if not isinstance(value, six.string_types):
raise ParameterNotValidError
try:
source, value = value.split('://', 1)
except ValueError:
raise ParameterNotValidError
if source == 'service':
if '@' in value:
value, timestamp = value.split('@', 1)
try:
service_time = timestamp_to_date(int(timestamp))
except ValueError:
raise ParameterNotValidError
else:
service_time = None
if ':' in value:
service_name, variable_name = value.split(':', 1)
else:
service_name = value
variable_name = None
try:
self.service = Service.objects.get(name=service_name)
except ObjectDoesNotExist:
raise ParameterNotValidError("Service '{}' not found".format(service_name))
if variable_name:
try:
variable = self.service.variable_set.all().get(variable=variable_name)
except ObjectDoesNotExist:
raise ParameterNotValidError("Variable '{}' not found".format(variable_name))
if service_time is not None:
time_index = best_fit(variable.time_stops, service_time)
else:
time_index = None
data = self.get_grid_for_variable(variable, time_index=time_index)
return Raster(data, variable.full_extent, 1, 0, self.is_y_increasing(variable))
else:
return self.dataset
else:
raise ParameterNotValidError('Invalid source: {}'.format(source)) | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ParameterNotValidError",
"try",
":",
"source",
",",
"value",
"=",
"value",
".",
"split",
"(",
"'://'",
",... | Cleans and returns the given value, or raises a ParameterNotValidError exception | [
"Cleans",
"and",
"returns",
"the",
"given",
"value",
"or",
"raises",
"a",
"ParameterNotValidError",
"exception"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.