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 |
|---|---|---|---|---|---|---|---|---|
callowayproject/Transmogrify | transmogrify/images2gif.py | https://github.com/callowayproject/Transmogrify/blob/f1f891b8b923b3a1ede5eac7f60531c1c472379e/transmogrify/images2gif.py#L154-L164 | def get_header_anim(self, im):
""" get_header_anim(im)
Get animation header. To replace PILs getheader()[0]
"""
bb = "GIF89a"
bb += int_to_bin(im.size[0])
bb += int_to_bin(im.size[1])
bb += "\x87\x00\x00"
return bb | [
"def",
"get_header_anim",
"(",
"self",
",",
"im",
")",
":",
"bb",
"=",
"\"GIF89a\"",
"bb",
"+=",
"int_to_bin",
"(",
"im",
".",
"size",
"[",
"0",
"]",
")",
"bb",
"+=",
"int_to_bin",
"(",
"im",
".",
"size",
"[",
"1",
"]",
")",
"bb",
"+=",
"\"\\x87\... | get_header_anim(im)
Get animation header. To replace PILs getheader()[0] | [
"get_header_anim",
"(",
"im",
")"
] | python | train |
saimn/sigal | sigal/writer.py | https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/writer.py#L98-L111 | def generate_context(self, album):
"""Generate the context dict for the given path."""
from . import __url__ as sigal_link
self.logger.info("Output album : %r", album)
return {
'album': album,
'index_title': self.index_title,
'settings': self.settings... | [
"def",
"generate_context",
"(",
"self",
",",
"album",
")",
":",
"from",
".",
"import",
"__url__",
"as",
"sigal_link",
"self",
".",
"logger",
".",
"info",
"(",
"\"Output album : %r\"",
",",
"album",
")",
"return",
"{",
"'album'",
":",
"album",
",",
"'index_... | Generate the context dict for the given path. | [
"Generate",
"the",
"context",
"dict",
"for",
"the",
"given",
"path",
"."
] | python | valid |
inveniosoftware-contrib/invenio-workflows | invenio_workflows/engine.py | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L222-L230 | def has_completed(self):
"""Return True if workflow is fully completed."""
objects_in_db = WorkflowObjectModel.query.filter(
WorkflowObjectModel.id_workflow == self.uuid,
WorkflowObjectModel.id_parent == None, # noqa
).filter(WorkflowObjectModel.status.in_([
... | [
"def",
"has_completed",
"(",
"self",
")",
":",
"objects_in_db",
"=",
"WorkflowObjectModel",
".",
"query",
".",
"filter",
"(",
"WorkflowObjectModel",
".",
"id_workflow",
"==",
"self",
".",
"uuid",
",",
"WorkflowObjectModel",
".",
"id_parent",
"==",
"None",
",",
... | Return True if workflow is fully completed. | [
"Return",
"True",
"if",
"workflow",
"is",
"fully",
"completed",
"."
] | python | train |
planetlabs/planet-client-python | planet/scripts/v1.py | https://github.com/planetlabs/planet-client-python/blob/1c62ce7d416819951dddee0c22068fef6d40b027/planet/scripts/v1.py#L97-L101 | def create_search(pretty, **kw):
'''Create a saved search'''
req = search_req_from_opts(**kw)
cl = clientv1()
echo_json_response(call_and_wrap(cl.create_search, req), pretty) | [
"def",
"create_search",
"(",
"pretty",
",",
"*",
"*",
"kw",
")",
":",
"req",
"=",
"search_req_from_opts",
"(",
"*",
"*",
"kw",
")",
"cl",
"=",
"clientv1",
"(",
")",
"echo_json_response",
"(",
"call_and_wrap",
"(",
"cl",
".",
"create_search",
",",
"req",
... | Create a saved search | [
"Create",
"a",
"saved",
"search"
] | python | train |
raiden-network/raiden | raiden/utils/echo_node.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/echo_node.py#L87-L132 | def poll_all_received_events(self):
""" This will be triggered once for each `echo_node_alarm_callback`.
It polls all channels for `EventPaymentReceivedSuccess` events,
adds all new events to the `self.received_transfers` queue and
respawns `self.echo_node_worker`, if it died. """
... | [
"def",
"poll_all_received_events",
"(",
"self",
")",
":",
"locked",
"=",
"False",
"try",
":",
"with",
"Timeout",
"(",
"10",
")",
":",
"locked",
"=",
"self",
".",
"lock",
".",
"acquire",
"(",
"blocking",
"=",
"False",
")",
"if",
"not",
"locked",
":",
... | This will be triggered once for each `echo_node_alarm_callback`.
It polls all channels for `EventPaymentReceivedSuccess` events,
adds all new events to the `self.received_transfers` queue and
respawns `self.echo_node_worker`, if it died. | [
"This",
"will",
"be",
"triggered",
"once",
"for",
"each",
"echo_node_alarm_callback",
".",
"It",
"polls",
"all",
"channels",
"for",
"EventPaymentReceivedSuccess",
"events",
"adds",
"all",
"new",
"events",
"to",
"the",
"self",
".",
"received_transfers",
"queue",
"a... | python | train |
wishtack/pysynthetic | synthetic/synthetic_constructor_factory.py | https://github.com/wishtack/pysynthetic/blob/f37a4a2f1e0313b8c544f60d37c93726bc806ec6/synthetic/synthetic_constructor_factory.py#L85-L112 | def _positionalArgumentKeyValueList(self,
originalConstructorExpectedArgList,
syntheticMemberList,
argTuple):
"""Transforms args tuple to a dictionary mapping argument names to values using or... | [
"def",
"_positionalArgumentKeyValueList",
"(",
"self",
",",
"originalConstructorExpectedArgList",
",",
"syntheticMemberList",
",",
"argTuple",
")",
":",
"# First, the list of expected arguments is set to original constructor's arg spec. ",
"expectedArgList",
"=",
"copy",
".",
"copy... | Transforms args tuple to a dictionary mapping argument names to values using original constructor
positional args specification, then it adds synthesized members at the end if they are not already present.
:type syntheticMemberList: list(SyntheticMember)
:type argTuple: tuple | [
"Transforms",
"args",
"tuple",
"to",
"a",
"dictionary",
"mapping",
"argument",
"names",
"to",
"values",
"using",
"original",
"constructor",
"positional",
"args",
"specification",
"then",
"it",
"adds",
"synthesized",
"members",
"at",
"the",
"end",
"if",
"they",
"... | python | train |
bxlab/bx-python | lib/bx/align/score.py | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/score.py#L105-L196 | def build_scoring_scheme( s, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ):
"""
Initialize scoring scheme from a blastz style text blob, first line
specifies the bases for each row/col, subsequent lines contain the
corresponding scores. Slaw extensions allow for unusual and/or
asymmetric al... | [
"def",
"build_scoring_scheme",
"(",
"s",
",",
"gap_open",
",",
"gap_extend",
",",
"gap1",
"=",
"\"-\"",
",",
"gap2",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# perform initial parse to determine alphabets and locate scores",
"bad_matrix",
"=",
"\"invalid sco... | Initialize scoring scheme from a blastz style text blob, first line
specifies the bases for each row/col, subsequent lines contain the
corresponding scores. Slaw extensions allow for unusual and/or
asymmetric alphabets. Symbols can be two digit hex, and each row
begins with symbol. Note that a row co... | [
"Initialize",
"scoring",
"scheme",
"from",
"a",
"blastz",
"style",
"text",
"blob",
"first",
"line",
"specifies",
"the",
"bases",
"for",
"each",
"row",
"/",
"col",
"subsequent",
"lines",
"contain",
"the",
"corresponding",
"scores",
".",
"Slaw",
"extensions",
"a... | python | train |
titilambert/pyhydroquebec | pyhydroquebec/client.py | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L395-L468 | def fetch_data(self):
"""Get the latest data from HydroQuebec."""
# Get http session
yield from self._get_httpsession()
# Get login page
login_url = yield from self._get_login_page()
# Post login page
yield from self._post_login_page(login_url)
# Get p_p_i... | [
"def",
"fetch_data",
"(",
"self",
")",
":",
"# Get http session",
"yield",
"from",
"self",
".",
"_get_httpsession",
"(",
")",
"# Get login page",
"login_url",
"=",
"yield",
"from",
"self",
".",
"_get_login_page",
"(",
")",
"# Post login page",
"yield",
"from",
"... | Get the latest data from HydroQuebec. | [
"Get",
"the",
"latest",
"data",
"from",
"HydroQuebec",
"."
] | python | train |
saltstack/salt | salt/states/cimc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cimc.py#L103-L165 | def logging_levels(name, remote=None, local=None):
'''
Ensures that the logging levels are set on the device. The logging levels
must match the following options: emergency, alert, critical, error, warning,
notice, informational, debug.
.. versionadded:: 2019.2.0
name: The name of the module f... | [
"def",
"logging_levels",
"(",
"name",
",",
"remote",
"=",
"None",
",",
"local",
"=",
"None",
")",
":",
"ret",
"=",
"_default_ret",
"(",
"name",
")",
"syslog_conf",
"=",
"__salt__",
"[",
"'cimc.get_syslog_settings'",
"]",
"(",
")",
"req_change",
"=",
"False... | Ensures that the logging levels are set on the device. The logging levels
must match the following options: emergency, alert, critical, error, warning,
notice, informational, debug.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
remote(str): The logging level for SYS... | [
"Ensures",
"that",
"the",
"logging",
"levels",
"are",
"set",
"on",
"the",
"device",
".",
"The",
"logging",
"levels",
"must",
"match",
"the",
"following",
"options",
":",
"emergency",
"alert",
"critical",
"error",
"warning",
"notice",
"informational",
"debug",
... | python | train |
ajk8/hatchery | hatchery/project.py | https://github.com/ajk8/hatchery/blob/e068c9f5366d2c98225babb03d4cde36c710194f/hatchery/project.py#L106-L113 | def set_version(package_name, version_str):
""" Set the version in _version.py to version_str """
current_version = get_version(package_name)
version_file_path = helpers.package_file_path('_version.py', package_name)
version_file_content = helpers.get_file_content(version_file_path)
version_file_con... | [
"def",
"set_version",
"(",
"package_name",
",",
"version_str",
")",
":",
"current_version",
"=",
"get_version",
"(",
"package_name",
")",
"version_file_path",
"=",
"helpers",
".",
"package_file_path",
"(",
"'_version.py'",
",",
"package_name",
")",
"version_file_conte... | Set the version in _version.py to version_str | [
"Set",
"the",
"version",
"in",
"_version",
".",
"py",
"to",
"version_str"
] | python | train |
mvcisback/py-aiger-bv | aigerbv/common.py | https://github.com/mvcisback/py-aiger-bv/blob/855819844c429c35cdd8dc0b134bcd11f7b2fda3/aigerbv/common.py#L430-L464 | def kmodels(wordlen: int, k: int, input=None, output=None):
"""Return a circuit taking a wordlen bitvector where only k
valuations return True. Uses encoding from [1].
Note that this is equivalent to (~x < k).
- TODO: Add automated simplification so that the circuits
are equiv.
[1]: Ch... | [
"def",
"kmodels",
"(",
"wordlen",
":",
"int",
",",
"k",
":",
"int",
",",
"input",
"=",
"None",
",",
"output",
"=",
"None",
")",
":",
"assert",
"0",
"<=",
"k",
"<",
"2",
"**",
"wordlen",
"if",
"output",
"is",
"None",
":",
"output",
"=",
"_fresh",
... | Return a circuit taking a wordlen bitvector where only k
valuations return True. Uses encoding from [1].
Note that this is equivalent to (~x < k).
- TODO: Add automated simplification so that the circuits
are equiv.
[1]: Chakraborty, Supratik, et al. "From Weighted to Unweighted Model
... | [
"Return",
"a",
"circuit",
"taking",
"a",
"wordlen",
"bitvector",
"where",
"only",
"k",
"valuations",
"return",
"True",
".",
"Uses",
"encoding",
"from",
"[",
"1",
"]",
"."
] | python | train |
FujiMakoto/AgentML | agentml/__init__.py | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/__init__.py#L295-L321 | def parse_substitutions(self, messages):
"""
Parse substitutions in a supplied message
:param messages: A tuple messages being parsed (normalized, case preserved, raw)
:type messages: tuple of (str, str, str)
:return: Substituted messages (normalized, case preserved, raw)
... | [
"def",
"parse_substitutions",
"(",
"self",
",",
"messages",
")",
":",
"# If no substitutions have been defined, just normalize the message",
"if",
"not",
"self",
".",
"_substitutions",
":",
"self",
".",
"_log",
".",
"info",
"(",
"'No substitutions to process'",
")",
"re... | Parse substitutions in a supplied message
:param messages: A tuple messages being parsed (normalized, case preserved, raw)
:type messages: tuple of (str, str, str)
:return: Substituted messages (normalized, case preserved, raw)
:rtype : tuple of (str, str, str) | [
"Parse",
"substitutions",
"in",
"a",
"supplied",
"message",
":",
"param",
"messages",
":",
"A",
"tuple",
"messages",
"being",
"parsed",
"(",
"normalized",
"case",
"preserved",
"raw",
")",
":",
"type",
"messages",
":",
"tuple",
"of",
"(",
"str",
"str",
"str... | python | train |
hubo1016/vlcp | vlcp/event/event.py | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/event.py#L166-L202 | def two_way_difference(self, b, extra_add = (), extra_remove = ()):
"""
Return (self - b, b - self)
"""
if self is b:
return ((), ())
if isinstance(b, DiffRef_):
extra_remove = extra_remove + b.add
b = b.origin
if extra_add == extra_rem... | [
"def",
"two_way_difference",
"(",
"self",
",",
"b",
",",
"extra_add",
"=",
"(",
")",
",",
"extra_remove",
"=",
"(",
")",
")",
":",
"if",
"self",
"is",
"b",
":",
"return",
"(",
"(",
")",
",",
"(",
")",
")",
"if",
"isinstance",
"(",
"b",
",",
"Di... | Return (self - b, b - self) | [
"Return",
"(",
"self",
"-",
"b",
"b",
"-",
"self",
")"
] | python | train |
brbsix/subsystem | subsystem/subsystem.py | https://github.com/brbsix/subsystem/blob/57705bc20d71ceaed9e22e21246265d717e98eb8/subsystem/subsystem.py#L183-L189 | def failure(path, downloader):
"""Display warning message via stderr or GUI."""
base = os.path.basename(path)
if sys.stdin.isatty():
print('INFO [{}]: Failed to download {!r}'.format(downloader, base))
else:
notify_failure(base, downloader) | [
"def",
"failure",
"(",
"path",
",",
"downloader",
")",
":",
"base",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"if",
"sys",
".",
"stdin",
".",
"isatty",
"(",
")",
":",
"print",
"(",
"'INFO [{}]: Failed to download {!r}'",
".",
"format",
... | Display warning message via stderr or GUI. | [
"Display",
"warning",
"message",
"via",
"stderr",
"or",
"GUI",
"."
] | python | train |
TomasTomecek/sen | sen/tui/ui.py | https://github.com/TomasTomecek/sen/blob/239b4868125814e8bf5527708119fc08b35f6cc0/sen/tui/ui.py#L93-L104 | def _set_main_widget(self, widget, redraw):
"""
add provided widget to widget list and display it
:param widget:
:return:
"""
self.set_body(widget)
self.reload_footer()
if redraw:
logger.debug("redraw main widget")
self.refresh() | [
"def",
"_set_main_widget",
"(",
"self",
",",
"widget",
",",
"redraw",
")",
":",
"self",
".",
"set_body",
"(",
"widget",
")",
"self",
".",
"reload_footer",
"(",
")",
"if",
"redraw",
":",
"logger",
".",
"debug",
"(",
"\"redraw main widget\"",
")",
"self",
... | add provided widget to widget list and display it
:param widget:
:return: | [
"add",
"provided",
"widget",
"to",
"widget",
"list",
"and",
"display",
"it"
] | python | train |
garenchan/policy | policy/enforcer.py | https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/enforcer.py#L39-L46 | def from_dict(cls, rules_dict: dict, default_rule=None, raise_error=False):
"""Allow loading of rule data from a dictionary."""
# Parse the rules stored in the dictionary
rules = {k: _parser.parse_rule(v, raise_error)
for k, v in rules_dict.items()}
return cls(rules, d... | [
"def",
"from_dict",
"(",
"cls",
",",
"rules_dict",
":",
"dict",
",",
"default_rule",
"=",
"None",
",",
"raise_error",
"=",
"False",
")",
":",
"# Parse the rules stored in the dictionary",
"rules",
"=",
"{",
"k",
":",
"_parser",
".",
"parse_rule",
"(",
"v",
"... | Allow loading of rule data from a dictionary. | [
"Allow",
"loading",
"of",
"rule",
"data",
"from",
"a",
"dictionary",
"."
] | python | train |
phaethon/kamene | kamene/contrib/gsm_um.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2689-L2695 | def requestPdpContextActivationReject():
"""REQUEST PDP CONTEXT ACTIVATION REJECT Section 9.5.5"""
a = TpPd(pd=0x8)
b = MessageType(mesType=0x45) # 01000101
c = SmCause()
packet = a / b / c
return packet | [
"def",
"requestPdpContextActivationReject",
"(",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x8",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x45",
")",
"# 01000101",
"c",
"=",
"SmCause",
"(",
")",
"packet",
"=",
"a",
"/",
"b",
"/",
"c",
... | REQUEST PDP CONTEXT ACTIVATION REJECT Section 9.5.5 | [
"REQUEST",
"PDP",
"CONTEXT",
"ACTIVATION",
"REJECT",
"Section",
"9",
".",
"5",
".",
"5"
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/header_ecc.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/header_ecc.py#L92-L124 | def entry_fields(entry, field_delim="\xFF"):
'''From a raw ecc entry (a string), extract the metadata fields (filename, filesize, ecc for both), and the rest being blocks of hash and ecc per blocks of the original file's header'''
entry = entry.lstrip(field_delim) # if there was some slight adjustment error (ex... | [
"def",
"entry_fields",
"(",
"entry",
",",
"field_delim",
"=",
"\"\\xFF\"",
")",
":",
"entry",
"=",
"entry",
".",
"lstrip",
"(",
"field_delim",
")",
"# if there was some slight adjustment error (example: the last ecc block of the last file was the field_delim, then we will start w... | From a raw ecc entry (a string), extract the metadata fields (filename, filesize, ecc for both), and the rest being blocks of hash and ecc per blocks of the original file's header | [
"From",
"a",
"raw",
"ecc",
"entry",
"(",
"a",
"string",
")",
"extract",
"the",
"metadata",
"fields",
"(",
"filename",
"filesize",
"ecc",
"for",
"both",
")",
"and",
"the",
"rest",
"being",
"blocks",
"of",
"hash",
"and",
"ecc",
"per",
"blocks",
"of",
"th... | python | train |
aaren/notedown | notedown/notedown.py | https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L536-L551 | def data2uri(data, data_type):
"""Convert base64 data into a data uri with the given data_type."""
MIME_MAP = {
'image/jpeg': 'jpeg',
'image/png': 'png',
'text/plain': 'text',
'text/html': 'html',
'text/latex': 'latex',
'application... | [
"def",
"data2uri",
"(",
"data",
",",
"data_type",
")",
":",
"MIME_MAP",
"=",
"{",
"'image/jpeg'",
":",
"'jpeg'",
",",
"'image/png'",
":",
"'png'",
",",
"'text/plain'",
":",
"'text'",
",",
"'text/html'",
":",
"'html'",
",",
"'text/latex'",
":",
"'latex'",
"... | Convert base64 data into a data uri with the given data_type. | [
"Convert",
"base64",
"data",
"into",
"a",
"data",
"uri",
"with",
"the",
"given",
"data_type",
"."
] | python | train |
nephila/djangocms-blog | djangocms_blog/cms_menus.py | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/cms_menus.py#L29-L122 | def get_nodes(self, request):
"""
Generates the nodelist
:param request:
:return: list of nodes
"""
nodes = []
language = get_language_from_request(request, check_path=True)
current_site = get_current_site(request)
page_site = self.instance.node... | [
"def",
"get_nodes",
"(",
"self",
",",
"request",
")",
":",
"nodes",
"=",
"[",
"]",
"language",
"=",
"get_language_from_request",
"(",
"request",
",",
"check_path",
"=",
"True",
")",
"current_site",
"=",
"get_current_site",
"(",
"request",
")",
"page_site",
"... | Generates the nodelist
:param request:
:return: list of nodes | [
"Generates",
"the",
"nodelist"
] | python | train |
trailofbits/manticore | manticore/native/cpu/x86.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L1135-L1177 | def AAS(cpu):
"""
ASCII Adjust AL after subtraction.
Adjusts the result of the subtraction of two unpacked BCD values to create a unpacked
BCD result. The AL register is the implied source and destination operand for this instruction.
The AAS instruction is only useful when it ... | [
"def",
"AAS",
"(",
"cpu",
")",
":",
"if",
"(",
"cpu",
".",
"AL",
"&",
"0x0F",
">",
"9",
")",
"or",
"cpu",
".",
"AF",
"==",
"1",
":",
"cpu",
".",
"AX",
"=",
"cpu",
".",
"AX",
"-",
"6",
"cpu",
".",
"AH",
"=",
"cpu",
".",
"AH",
"-",
"1",
... | ASCII Adjust AL after subtraction.
Adjusts the result of the subtraction of two unpacked BCD values to create a unpacked
BCD result. The AL register is the implied source and destination operand for this instruction.
The AAS instruction is only useful when it follows a SUB instruction that sub... | [
"ASCII",
"Adjust",
"AL",
"after",
"subtraction",
"."
] | python | valid |
tanghaibao/jcvi | jcvi/utils/brewer2mpl.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/brewer2mpl.py#L300-L336 | def _load_maps_by_type(map_type):
"""
Load all maps of a given type into a dictionary.
Color maps are loaded as BrewerMap objects. Dictionary is
keyed by map name and then integer numbers of defined
colors. There is an additional 'max' key that points to the
color map with the largest number of... | [
"def",
"_load_maps_by_type",
"(",
"map_type",
")",
":",
"seq_maps",
"=",
"COLOR_MAPS",
"[",
"map_type",
"]",
"loaded_maps",
"=",
"{",
"}",
"for",
"map_name",
"in",
"seq_maps",
":",
"loaded_maps",
"[",
"map_name",
"]",
"=",
"{",
"}",
"for",
"num",
"in",
"... | Load all maps of a given type into a dictionary.
Color maps are loaded as BrewerMap objects. Dictionary is
keyed by map name and then integer numbers of defined
colors. There is an additional 'max' key that points to the
color map with the largest number of defined colors.
Parameters
---------... | [
"Load",
"all",
"maps",
"of",
"a",
"given",
"type",
"into",
"a",
"dictionary",
"."
] | python | train |
peshay/tpm | tpm.py | https://github.com/peshay/tpm/blob/8e64a4d8b89d54bdd2c92d965463a7508aa3d0bc/tpm.py#L301-L306 | def change_parent_of_project(self, ID, NewParrentID):
"""Change parent of project."""
# http://teampasswordmanager.com/docs/api-projects/#change_parent
log.info('Change parrent for project %s to %s' % (ID, NewParrentID))
data = {'parent_id': NewParrentID}
self.put('projects/%s/ch... | [
"def",
"change_parent_of_project",
"(",
"self",
",",
"ID",
",",
"NewParrentID",
")",
":",
"# http://teampasswordmanager.com/docs/api-projects/#change_parent",
"log",
".",
"info",
"(",
"'Change parrent for project %s to %s'",
"%",
"(",
"ID",
",",
"NewParrentID",
")",
")",
... | Change parent of project. | [
"Change",
"parent",
"of",
"project",
"."
] | python | train |
libtcod/python-tcod | tcod/random.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/random.py#L76-L86 | def uniform(self, low: float, high: float) -> float:
"""Return a random floating number in the range: low <= n <= high.
Args:
low (float): The lower bound of the random range.
high (float): The upper bound of the random range.
Returns:
float: A random float.... | [
"def",
"uniform",
"(",
"self",
",",
"low",
":",
"float",
",",
"high",
":",
"float",
")",
"->",
"float",
":",
"return",
"float",
"(",
"lib",
".",
"TCOD_random_get_double",
"(",
"self",
".",
"random_c",
",",
"low",
",",
"high",
")",
")"
] | Return a random floating number in the range: low <= n <= high.
Args:
low (float): The lower bound of the random range.
high (float): The upper bound of the random range.
Returns:
float: A random float. | [
"Return",
"a",
"random",
"floating",
"number",
"in",
"the",
"range",
":",
"low",
"<",
"=",
"n",
"<",
"=",
"high",
"."
] | python | train |
google/textfsm | textfsm/parser.py | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L628-L657 | def _AppendRecord(self):
"""Adds current record to result if well formed."""
# If no Values then don't output.
if not self.values:
return
cur_record = []
for value in self.values:
try:
value.OnSaveRecord()
except SkipRecord:
self._ClearRecord()
return
... | [
"def",
"_AppendRecord",
"(",
"self",
")",
":",
"# If no Values then don't output.",
"if",
"not",
"self",
".",
"values",
":",
"return",
"cur_record",
"=",
"[",
"]",
"for",
"value",
"in",
"self",
".",
"values",
":",
"try",
":",
"value",
".",
"OnSaveRecord",
... | Adds current record to result if well formed. | [
"Adds",
"current",
"record",
"to",
"result",
"if",
"well",
"formed",
"."
] | python | train |
gregoil/ipdbugger | ipdbugger/__init__.py | https://github.com/gregoil/ipdbugger/blob/9575734ec26f6be86ae263496d50eb60bb988b21/ipdbugger/__init__.py#L85-L105 | def start_debugging():
"""Start a debugging session after catching an exception.
This prints the traceback and start ipdb session in the frame of the error.
"""
exc_type, exc_value, exc_tb = sys.exc_info()
# If the exception has been annotated to be re-raised, raise the exception
if hasattr(ex... | [
"def",
"start_debugging",
"(",
")",
":",
"exc_type",
",",
"exc_value",
",",
"exc_tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"# If the exception has been annotated to be re-raised, raise the exception",
"if",
"hasattr",
"(",
"exc_value",
",",
"'_ipdbugger_let_raise'",
"... | Start a debugging session after catching an exception.
This prints the traceback and start ipdb session in the frame of the error. | [
"Start",
"a",
"debugging",
"session",
"after",
"catching",
"an",
"exception",
"."
] | python | train |
9wfox/tornadoweb | tornadoweb/utility.py | https://github.com/9wfox/tornadoweb/blob/2286b66fbe10e4d9f212b979664c15fa17adf378/tornadoweb/utility.py#L131-L138 | def args_length(min_len, max_len, *args):
"""
检查参数长度
"""
not_null(*args)
if not all(map(lambda v: min_len <= len(v) <= max_len, args)):
raise ValueError("Argument length must be between {0} and {1}!".format(min_len, max_len)) | [
"def",
"args_length",
"(",
"min_len",
",",
"max_len",
",",
"*",
"args",
")",
":",
"not_null",
"(",
"*",
"args",
")",
"if",
"not",
"all",
"(",
"map",
"(",
"lambda",
"v",
":",
"min_len",
"<=",
"len",
"(",
"v",
")",
"<=",
"max_len",
",",
"args",
")"... | 检查参数长度 | [
"检查参数长度"
] | python | train |
gagneurlab/concise | concise/legacy/concise.py | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L642-L651 | def _predict_in_session(self, sess, other_var, X_feat, X_seq, variable="y_pred"):
"""
Predict y (or any other variable) from inside the tf session. Variable has to be in other_var
"""
# other_var["tf_X_seq"]: X_seq, tf_y: y,
feed_dict = {other_var["tf_X_feat"]: X_feat,
... | [
"def",
"_predict_in_session",
"(",
"self",
",",
"sess",
",",
"other_var",
",",
"X_feat",
",",
"X_seq",
",",
"variable",
"=",
"\"y_pred\"",
")",
":",
"# other_var[\"tf_X_seq\"]: X_seq, tf_y: y,",
"feed_dict",
"=",
"{",
"other_var",
"[",
"\"tf_X_feat\"",
"]",
":",
... | Predict y (or any other variable) from inside the tf session. Variable has to be in other_var | [
"Predict",
"y",
"(",
"or",
"any",
"other",
"variable",
")",
"from",
"inside",
"the",
"tf",
"session",
".",
"Variable",
"has",
"to",
"be",
"in",
"other_var"
] | python | train |
tjcsl/cslbot | cslbot/commands/gcc.py | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/gcc.py#L26-L59 | def cmd(send, msg, args):
"""Compiles stuff.
Syntax: {command} <code>
"""
if args['type'] == 'privmsg':
send('GCC is a group exercise!')
return
if 'include' in msg:
send("We're not a terribly inclusive community around here.")
return
if 'import' in msg:
... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"args",
"[",
"'type'",
"]",
"==",
"'privmsg'",
":",
"send",
"(",
"'GCC is a group exercise!'",
")",
"return",
"if",
"'include'",
"in",
"msg",
":",
"send",
"(",
"\"We're not a terribly incl... | Compiles stuff.
Syntax: {command} <code> | [
"Compiles",
"stuff",
"."
] | python | train |
genialis/resolwe-runtime-utils | resolwe_runtime_utils.py | https://github.com/genialis/resolwe-runtime-utils/blob/5657d7cf981972a5259b9b475eae220479401001/resolwe_runtime_utils.py#L73-L98 | def save_file(key, file_path, *refs):
"""Convert the given parameters to a special JSON object.
JSON object is of the form:
{ key: {"file": file_path}}, or
{ key: {"file": file_path, "refs": [refs[0], refs[1], ... ]}}
"""
if not os.path.isfile(file_path):
return error("Output '{}' set ... | [
"def",
"save_file",
"(",
"key",
",",
"file_path",
",",
"*",
"refs",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"return",
"error",
"(",
"\"Output '{}' set to a missing file: '{}'.\"",
".",
"format",
"(",
"key",
",",... | Convert the given parameters to a special JSON object.
JSON object is of the form:
{ key: {"file": file_path}}, or
{ key: {"file": file_path, "refs": [refs[0], refs[1], ... ]}} | [
"Convert",
"the",
"given",
"parameters",
"to",
"a",
"special",
"JSON",
"object",
"."
] | python | train |
akfullfo/taskforce | taskforce/watch_modules.py | https://github.com/akfullfo/taskforce/blob/bc6dd744bd33546447d085dbd18a350532220193/taskforce/watch_modules.py#L67-L102 | def _build(self, name, **params):
"""
Rebuild operations by removing open modules that no longer need to be
watched, and adding new modules if they are not currently being watched.
This is done by comparing self.modules to watch_files.paths_open
"""
log = self._getparam('log... | [
"def",
"_build",
"(",
"self",
",",
"name",
",",
"*",
"*",
"params",
")",
":",
"log",
"=",
"self",
".",
"_getparam",
"(",
"'log'",
",",
"self",
".",
"_discard",
",",
"*",
"*",
"params",
")",
"# Find all the modules that no longer need watching",
"#",
"rebu... | Rebuild operations by removing open modules that no longer need to be
watched, and adding new modules if they are not currently being watched.
This is done by comparing self.modules to watch_files.paths_open | [
"Rebuild",
"operations",
"by",
"removing",
"open",
"modules",
"that",
"no",
"longer",
"need",
"to",
"be",
"watched",
"and",
"adding",
"new",
"modules",
"if",
"they",
"are",
"not",
"currently",
"being",
"watched",
"."
] | python | train |
waqasbhatti/astrobase | astrobase/plotbase.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/plotbase.py#L97-L443 | def plot_magseries(times,
mags,
magsarefluxes=False,
errs=None,
out=None,
sigclip=30.0,
normto='globalmedian',
normmingap=4.0,
timebin=None,
yrange=N... | [
"def",
"plot_magseries",
"(",
"times",
",",
"mags",
",",
"magsarefluxes",
"=",
"False",
",",
"errs",
"=",
"None",
",",
"out",
"=",
"None",
",",
"sigclip",
"=",
"30.0",
",",
"normto",
"=",
"'globalmedian'",
",",
"normmingap",
"=",
"4.0",
",",
"timebin",
... | This plots a magnitude/flux time-series.
Parameters
----------
times,mags : np.array
The mag/flux time-series to plot as a function of time.
magsarefluxes : bool
Indicates if the input `mags` array is actually an array of flux
measurements instead of magnitude measurements. If... | [
"This",
"plots",
"a",
"magnitude",
"/",
"flux",
"time",
"-",
"series",
"."
] | python | valid |
tensorflow/datasets | tensorflow_datasets/core/utils/py_utils.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/py_utils.py#L55-L60 | def temporary_assignment(obj, attr, value):
"""Temporarily assign obj.attr to value."""
original = getattr(obj, attr, None)
setattr(obj, attr, value)
yield
setattr(obj, attr, original) | [
"def",
"temporary_assignment",
"(",
"obj",
",",
"attr",
",",
"value",
")",
":",
"original",
"=",
"getattr",
"(",
"obj",
",",
"attr",
",",
"None",
")",
"setattr",
"(",
"obj",
",",
"attr",
",",
"value",
")",
"yield",
"setattr",
"(",
"obj",
",",
"attr",... | Temporarily assign obj.attr to value. | [
"Temporarily",
"assign",
"obj",
".",
"attr",
"to",
"value",
"."
] | python | train |
spyder-ide/spyder-kernels | spyder_kernels/utils/nsview.py | https://github.com/spyder-ide/spyder-kernels/blob/2c5b36cdb797b8aba77bc406ca96f5e079c4aaca/spyder_kernels/utils/nsview.py#L533-L544 | def get_human_readable_type(item):
"""Return human-readable type string of an item"""
if isinstance(item, (ndarray, MaskedArray)):
return item.dtype.name
elif isinstance(item, Image):
return "Image"
else:
text = get_type_string(item)
if text is None:
text = to... | [
"def",
"get_human_readable_type",
"(",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"(",
"ndarray",
",",
"MaskedArray",
")",
")",
":",
"return",
"item",
".",
"dtype",
".",
"name",
"elif",
"isinstance",
"(",
"item",
",",
"Image",
")",
":",
"r... | Return human-readable type string of an item | [
"Return",
"human",
"-",
"readable",
"type",
"string",
"of",
"an",
"item"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L361-L365 | def drop_matching_records(self, check):
"""Remove a record from the DB."""
expr,args = self._render_expression(check)
query = "DELETE FROM %s WHERE %s"%(self.table, expr)
self._db.execute(query,args) | [
"def",
"drop_matching_records",
"(",
"self",
",",
"check",
")",
":",
"expr",
",",
"args",
"=",
"self",
".",
"_render_expression",
"(",
"check",
")",
"query",
"=",
"\"DELETE FROM %s WHERE %s\"",
"%",
"(",
"self",
".",
"table",
",",
"expr",
")",
"self",
".",... | Remove a record from the DB. | [
"Remove",
"a",
"record",
"from",
"the",
"DB",
"."
] | python | test |
mattloper/opendr | opendr/geometry.py | https://github.com/mattloper/opendr/blob/bc16a6a51771d6e062d088ba5cede66649b7c7ec/opendr/geometry.py#L411-L429 | def Bx(self):
"""Compute a stack of skew-symmetric matrices which can be multiplied
by 'a' to get the cross product. See:
http://en.wikipedia.org/wiki/Cross_product#Conversion_to_matrix_multiplication
"""
# 0 self.b3 -self.b2
# -self.b3 0 self... | [
"def",
"Bx",
"(",
"self",
")",
":",
"# 0 self.b3 -self.b2",
"# -self.b3 0 self.b1",
"# self.b2 -self.b1 0",
"m",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"self",
".",
"b1",
")",
",",
"3",
",",
"3",
")",
")",
"m",
"[",
":",
"... | Compute a stack of skew-symmetric matrices which can be multiplied
by 'a' to get the cross product. See:
http://en.wikipedia.org/wiki/Cross_product#Conversion_to_matrix_multiplication | [
"Compute",
"a",
"stack",
"of",
"skew",
"-",
"symmetric",
"matrices",
"which",
"can",
"be",
"multiplied",
"by",
"a",
"to",
"get",
"the",
"cross",
"product",
".",
"See",
":"
] | python | train |
desbma/sacad | sacad/cover.py | https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L320-L325 | def setSizeMetadata(self, size):
""" Set size image metadata to what has been reliably identified. """
assert((self.needMetadataUpdate(CoverImageMetadata.SIZE)) or
(self.size == size))
self.size = size
self.check_metadata &= ~CoverImageMetadata.SIZE | [
"def",
"setSizeMetadata",
"(",
"self",
",",
"size",
")",
":",
"assert",
"(",
"(",
"self",
".",
"needMetadataUpdate",
"(",
"CoverImageMetadata",
".",
"SIZE",
")",
")",
"or",
"(",
"self",
".",
"size",
"==",
"size",
")",
")",
"self",
".",
"size",
"=",
"... | Set size image metadata to what has been reliably identified. | [
"Set",
"size",
"image",
"metadata",
"to",
"what",
"has",
"been",
"reliably",
"identified",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/server/background.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/server/background.py#L66-L85 | def stat( self, *args ):
'''Check process completion and consume pending I/O data'''
self.pipe.poll()
if not self.pipe.returncode is None:
'''cleanup handlers and timeouts'''
if not self.expiration is None:
self.ioloop.remove_timeout(self.expiration)
... | [
"def",
"stat",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"pipe",
".",
"poll",
"(",
")",
"if",
"not",
"self",
".",
"pipe",
".",
"returncode",
"is",
"None",
":",
"'''cleanup handlers and timeouts'''",
"if",
"not",
"self",
".",
"expiration",
"... | Check process completion and consume pending I/O data | [
"Check",
"process",
"completion",
"and",
"consume",
"pending",
"I",
"/",
"O",
"data"
] | python | train |
heikomuller/sco-datastore | scodata/image.py | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/image.py#L879-L906 | def get_image_files(directory, files):
"""Recursively iterate through directory tree and list all files that have a
valid image file suffix
Parameters
----------
directory : directory
Path to directory on disk
files : List(string)
List of file names
Returns
-------
... | [
"def",
"get_image_files",
"(",
"directory",
",",
"files",
")",
":",
"# For each file in the directory test if it is a valid image file or a",
"# sub-directory.",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"abs_file",
"=",
"os",
".",
"path",
... | Recursively iterate through directory tree and list all files that have a
valid image file suffix
Parameters
----------
directory : directory
Path to directory on disk
files : List(string)
List of file names
Returns
-------
List(string)
List of files that have a... | [
"Recursively",
"iterate",
"through",
"directory",
"tree",
"and",
"list",
"all",
"files",
"that",
"have",
"a",
"valid",
"image",
"file",
"suffix"
] | python | train |
s0lst1c3/grey_harvest | grey_harvest.py | https://github.com/s0lst1c3/grey_harvest/blob/811e5787ce7e613bc489b8e5e475eaa8790f4d66/grey_harvest.py#L176-L190 | def _extract_ajax_endpoints(self):
''' make a GET request to freeproxylists.com/elite.html '''
url = '/'.join([DOC_ROOT, ELITE_PAGE])
response = requests.get(url)
''' extract the raw HTML doc from the response '''
raw_html = response.text
''' convert raw ht... | [
"def",
"_extract_ajax_endpoints",
"(",
"self",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"[",
"DOC_ROOT",
",",
"ELITE_PAGE",
"]",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"''' extract the raw HTML doc from the response '''",
"raw_html"... | make a GET request to freeproxylists.com/elite.html | [
"make",
"a",
"GET",
"request",
"to",
"freeproxylists",
".",
"com",
"/",
"elite",
".",
"html"
] | python | train |
letuananh/chirptext | chirptext/leutile.py | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L629-L637 | def read_file(self, file_path):
''' Read a configuration file and return configuration data '''
getLogger().info("Loading app config from {} file: {}".format(self.__mode, file_path))
if self.__mode == AppConfig.JSON:
return json.loads(FileHelper.read(file_path), object_pairs_hook=Ord... | [
"def",
"read_file",
"(",
"self",
",",
"file_path",
")",
":",
"getLogger",
"(",
")",
".",
"info",
"(",
"\"Loading app config from {} file: {}\"",
".",
"format",
"(",
"self",
".",
"__mode",
",",
"file_path",
")",
")",
"if",
"self",
".",
"__mode",
"==",
"AppC... | Read a configuration file and return configuration data | [
"Read",
"a",
"configuration",
"file",
"and",
"return",
"configuration",
"data"
] | python | train |
pinterest/thrift-tools | examples/methods_per_port.py | https://github.com/pinterest/thrift-tools/blob/64e74aec89e2491c781fc62d1c45944dc15aba28/examples/methods_per_port.py#L37-L56 | def listening_ports():
""" Reads listening ports from /proc/net/tcp """
ports = []
if not os.path.exists(PROC_TCP):
return ports
with open(PROC_TCP) as fh:
for line in fh:
if '00000000:0000' not in line:
continue
parts = line.lstrip(' ').split(' ... | [
"def",
"listening_ports",
"(",
")",
":",
"ports",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"PROC_TCP",
")",
":",
"return",
"ports",
"with",
"open",
"(",
"PROC_TCP",
")",
"as",
"fh",
":",
"for",
"line",
"in",
"fh",
":",
"... | Reads listening ports from /proc/net/tcp | [
"Reads",
"listening",
"ports",
"from",
"/",
"proc",
"/",
"net",
"/",
"tcp"
] | python | valid |
shaunduncan/helga-facts | helga_facts.py | https://github.com/shaunduncan/helga-facts/blob/956b1d93abccdaaf318d7cac4451edc7e73bf5e9/helga_facts.py#L89-L95 | def replace_fact(term, fact, author=''):
"""
Replaces an existing fact by removing it, then adding the new definition
"""
forget_fact(term)
add_fact(term, fact, author)
return random.choice(ACKS) | [
"def",
"replace_fact",
"(",
"term",
",",
"fact",
",",
"author",
"=",
"''",
")",
":",
"forget_fact",
"(",
"term",
")",
"add_fact",
"(",
"term",
",",
"fact",
",",
"author",
")",
"return",
"random",
".",
"choice",
"(",
"ACKS",
")"
] | Replaces an existing fact by removing it, then adding the new definition | [
"Replaces",
"an",
"existing",
"fact",
"by",
"removing",
"it",
"then",
"adding",
"the",
"new",
"definition"
] | python | train |
quantumlib/Cirq | cirq/circuits/_block_diagram_drawer.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/_block_diagram_drawer.py#L53-L107 | def draw_curve(self,
grid_characters: BoxDrawCharacterSet,
*,
top: bool = False,
left: bool = False,
right: bool = False,
bottom: bool = False,
crossing_char: Optional[str] = None):
... | [
"def",
"draw_curve",
"(",
"self",
",",
"grid_characters",
":",
"BoxDrawCharacterSet",
",",
"*",
",",
"top",
":",
"bool",
"=",
"False",
",",
"left",
":",
"bool",
"=",
"False",
",",
"right",
":",
"bool",
"=",
"False",
",",
"bottom",
":",
"bool",
"=",
"... | Draws lines in the box using the given character set.
Supports merging the new lines with the lines from a previous call to
draw_curve, including when they have different character sets (assuming
there exist characters merging the two).
Args:
grid_characters: The character ... | [
"Draws",
"lines",
"in",
"the",
"box",
"using",
"the",
"given",
"character",
"set",
"."
] | python | train |
senaite/senaite.jsonapi | src/senaite/jsonapi/request.py | https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/request.py#L67-L77 | def is_true(key, default=False):
""" Check if the value is in TRUE_VALUES
"""
value = get(key, default)
if isinstance(value, list):
value = value[0]
if isinstance(value, bool):
return value
if value is default:
return default
return value.lower() in TRUE_VALUES | [
"def",
"is_true",
"(",
"key",
",",
"default",
"=",
"False",
")",
":",
"value",
"=",
"get",
"(",
"key",
",",
"default",
")",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"value",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"v... | Check if the value is in TRUE_VALUES | [
"Check",
"if",
"the",
"value",
"is",
"in",
"TRUE_VALUES"
] | python | train |
gwastro/pycbc | pycbc/workflow/segment.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L1287-L1297 | def parse_cat_ini_opt(cat_str):
""" Parse a cat str from the ini file into a list of sets """
if cat_str == "":
return []
cat_groups = cat_str.split(',')
cat_sets = []
for group in cat_groups:
group = group.strip()
cat_sets += [set(c for c in group)]
return cat_sets | [
"def",
"parse_cat_ini_opt",
"(",
"cat_str",
")",
":",
"if",
"cat_str",
"==",
"\"\"",
":",
"return",
"[",
"]",
"cat_groups",
"=",
"cat_str",
".",
"split",
"(",
"','",
")",
"cat_sets",
"=",
"[",
"]",
"for",
"group",
"in",
"cat_groups",
":",
"group",
"=",... | Parse a cat str from the ini file into a list of sets | [
"Parse",
"a",
"cat",
"str",
"from",
"the",
"ini",
"file",
"into",
"a",
"list",
"of",
"sets"
] | python | train |
d11wtq/dockerpty | dockerpty/io.py | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L127-L140 | def write(self, data):
"""
Write `data` to the Stream. Not all data may be written right away.
Use select to find when the stream is writeable, and call do_write()
to flush the internal buffer.
"""
if not data:
return None
self.buffer += data
... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"None",
"self",
".",
"buffer",
"+=",
"data",
"self",
".",
"do_write",
"(",
")",
"return",
"len",
"(",
"data",
")"
] | Write `data` to the Stream. Not all data may be written right away.
Use select to find when the stream is writeable, and call do_write()
to flush the internal buffer. | [
"Write",
"data",
"to",
"the",
"Stream",
".",
"Not",
"all",
"data",
"may",
"be",
"written",
"right",
"away",
".",
"Use",
"select",
"to",
"find",
"when",
"the",
"stream",
"is",
"writeable",
"and",
"call",
"do_write",
"()",
"to",
"flush",
"the",
"internal",... | python | train |
sirfoga/pyhal | hal/internet/parser.py | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/internet/parser.py#L64-L76 | def parse(self):
"""Parses data in table
:return: List of list of values in table
"""
data = [] # add name of section
for row in self.soup.find_all("tr"): # cycle through all rows
parsed = self._parse_row(row)
if parsed:
data.append(par... | [
"def",
"parse",
"(",
"self",
")",
":",
"data",
"=",
"[",
"]",
"# add name of section",
"for",
"row",
"in",
"self",
".",
"soup",
".",
"find_all",
"(",
"\"tr\"",
")",
":",
"# cycle through all rows",
"parsed",
"=",
"self",
".",
"_parse_row",
"(",
"row",
")... | Parses data in table
:return: List of list of values in table | [
"Parses",
"data",
"in",
"table"
] | python | train |
angr/angr | angr/analyses/vfg.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/vfg.py#L1789-L1813 | def _widening_points(self, function_address):
"""
Return the ordered widening points for a specific function.
:param int function_address: Address of the querying function.
:return: A list of sorted merge points (addresses).
:rtype: list
"""
# we are entering a ... | [
"def",
"_widening_points",
"(",
"self",
",",
"function_address",
")",
":",
"# we are entering a new function. now it's time to figure out how to optimally traverse the control flow",
"# graph by generating the sorted merge points",
"try",
":",
"new_function",
"=",
"self",
".",
"kb",
... | Return the ordered widening points for a specific function.
:param int function_address: Address of the querying function.
:return: A list of sorted merge points (addresses).
:rtype: list | [
"Return",
"the",
"ordered",
"widening",
"points",
"for",
"a",
"specific",
"function",
"."
] | python | train |
neithere/argh | argh/assembling.py | https://github.com/neithere/argh/blob/dcd3253f2994400a6a58a700c118c53765bc50a4/argh/assembling.py#L321-L459 | def add_commands(parser, functions, namespace=None, namespace_kwargs=None,
func_kwargs=None,
# deprecated args:
title=None, description=None, help=None):
"""
Adds given functions as commands to given parser.
:param parser:
an :class:`argparse.Argu... | [
"def",
"add_commands",
"(",
"parser",
",",
"functions",
",",
"namespace",
"=",
"None",
",",
"namespace_kwargs",
"=",
"None",
",",
"func_kwargs",
"=",
"None",
",",
"# deprecated args:",
"title",
"=",
"None",
",",
"description",
"=",
"None",
",",
"help",
"=",
... | Adds given functions as commands to given parser.
:param parser:
an :class:`argparse.ArgumentParser` instance.
:param functions:
a list of functions. A subparser is created for each of them.
If the function is decorated with :func:`~argh.decorators.arg`, the
arguments are pas... | [
"Adds",
"given",
"functions",
"as",
"commands",
"to",
"given",
"parser",
"."
] | python | test |
watson-developer-cloud/python-sdk | ibm_watson/visual_recognition_v3.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/visual_recognition_v3.py#L94-L186 | def classify(self,
images_file=None,
images_filename=None,
images_file_content_type=None,
url=None,
threshold=None,
owners=None,
classifier_ids=None,
accept_language=None,
... | [
"def",
"classify",
"(",
"self",
",",
"images_file",
"=",
"None",
",",
"images_filename",
"=",
"None",
",",
"images_file_content_type",
"=",
"None",
",",
"url",
"=",
"None",
",",
"threshold",
"=",
"None",
",",
"owners",
"=",
"None",
",",
"classifier_ids",
"... | Classify images.
Classify images with built-in or custom classifiers.
:param file images_file: An image file (.gif, .jpg, .png, .tif) or .zip file with
images. Maximum image size is 10 MB. Include no more than 20 images and limit the
.zip file to 100 MB. Encode the image and .zip file ... | [
"Classify",
"images",
"."
] | python | train |
bcbio/bcbio-nextgen | scripts/utils/upload_to_synapse.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/upload_to_synapse.py#L38-L48 | def _accumulate_remotes(synapse_parent_id, syn):
"""Retrieve references to all remote directories and files.
"""
remotes = {}
s_base_folder = syn.get(synapse_parent_id)
for (s_dirpath, s_dirpath_id), _, s_filenames in synapseutils.walk(syn, synapse_parent_id):
remotes[s_dirpath] = s_dirpath_... | [
"def",
"_accumulate_remotes",
"(",
"synapse_parent_id",
",",
"syn",
")",
":",
"remotes",
"=",
"{",
"}",
"s_base_folder",
"=",
"syn",
".",
"get",
"(",
"synapse_parent_id",
")",
"for",
"(",
"s_dirpath",
",",
"s_dirpath_id",
")",
",",
"_",
",",
"s_filenames",
... | Retrieve references to all remote directories and files. | [
"Retrieve",
"references",
"to",
"all",
"remote",
"directories",
"and",
"files",
"."
] | python | train |
aspiers/git-deps | git_deps/detector.py | https://github.com/aspiers/git-deps/blob/a00380b8bf1451d8c3405dace8d5927428506eb0/git_deps/detector.py#L134-L147 | def find_dependencies_with_parent(self, dependent, parent):
"""Find all dependencies of the given revision caused by the
given parent commit. This will be called multiple times for
merge commits which have multiple parents.
"""
self.logger.info(" Finding dependencies of %s vi... | [
"def",
"find_dependencies_with_parent",
"(",
"self",
",",
"dependent",
",",
"parent",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\" Finding dependencies of %s via parent %s\"",
"%",
"(",
"dependent",
".",
"hex",
"[",
":",
"8",
"]",
",",
"parent",
"... | Find all dependencies of the given revision caused by the
given parent commit. This will be called multiple times for
merge commits which have multiple parents. | [
"Find",
"all",
"dependencies",
"of",
"the",
"given",
"revision",
"caused",
"by",
"the",
"given",
"parent",
"commit",
".",
"This",
"will",
"be",
"called",
"multiple",
"times",
"for",
"merge",
"commits",
"which",
"have",
"multiple",
"parents",
"."
] | python | train |
opendatateam/udata | udata/harvest/commands.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/commands.py#L55-L59 | def delete(identifier):
'''Delete a harvest source'''
log.info('Deleting source "%s"', identifier)
actions.delete_source(identifier)
log.info('Deleted source "%s"', identifier) | [
"def",
"delete",
"(",
"identifier",
")",
":",
"log",
".",
"info",
"(",
"'Deleting source \"%s\"'",
",",
"identifier",
")",
"actions",
".",
"delete_source",
"(",
"identifier",
")",
"log",
".",
"info",
"(",
"'Deleted source \"%s\"'",
",",
"identifier",
")"
] | Delete a harvest source | [
"Delete",
"a",
"harvest",
"source"
] | python | train |
SmokinCaterpillar/pypet | pypet/utils/decorators.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L75-L102 | def copydoc(fromfunc, sep="\n"):
"""Decorator: Copy the docstring of `fromfunc`
If the doc contains a line with the keyword `ABSTRACT`,
like `ABSTRACT: Needs to be defined in subclass`, this line and the line after are removed.
"""
def _decorator(func):
sourcedoc = fromfunc.__doc__
... | [
"def",
"copydoc",
"(",
"fromfunc",
",",
"sep",
"=",
"\"\\n\"",
")",
":",
"def",
"_decorator",
"(",
"func",
")",
":",
"sourcedoc",
"=",
"fromfunc",
".",
"__doc__",
"# Remove the ABSTRACT line:",
"split_doc",
"=",
"sourcedoc",
".",
"split",
"(",
"'\\n'",
")",
... | Decorator: Copy the docstring of `fromfunc`
If the doc contains a line with the keyword `ABSTRACT`,
like `ABSTRACT: Needs to be defined in subclass`, this line and the line after are removed. | [
"Decorator",
":",
"Copy",
"the",
"docstring",
"of",
"fromfunc"
] | python | test |
jeffh/rpi_courses | rpi_courses/scheduler.py | https://github.com/jeffh/rpi_courses/blob/c97176f73f866f112c785910ebf3ff8a790e8e9a/rpi_courses/scheduler.py#L82-L95 | def exclude_times(self, *tuples):
"""Adds multiple excluded times by tuple of (start, end, days) or by
TimeRange instance.
``start`` and ``end`` are in military integer times (e.g. - 1200 1430).
``days`` is a collection of integers or strings of fully-spelt, lowercased days
... | [
"def",
"exclude_times",
"(",
"self",
",",
"*",
"tuples",
")",
":",
"for",
"item",
"in",
"tuples",
":",
"if",
"isinstance",
"(",
"item",
",",
"TimeRange",
")",
":",
"self",
".",
"_excluded_times",
".",
"append",
"(",
"item",
")",
"else",
":",
"self",
... | Adds multiple excluded times by tuple of (start, end, days) or by
TimeRange instance.
``start`` and ``end`` are in military integer times (e.g. - 1200 1430).
``days`` is a collection of integers or strings of fully-spelt, lowercased days
of the week. | [
"Adds",
"multiple",
"excluded",
"times",
"by",
"tuple",
"of",
"(",
"start",
"end",
"days",
")",
"or",
"by",
"TimeRange",
"instance",
"."
] | python | train |
Xion/taipan | taipan/collections/lists.py | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/lists.py#L102-L122 | def index(*args, **kwargs):
"""Search a list for an exact element, or element satisfying a predicate.
Usage::
index(element, list_)
index(of=element, in_=list_)
index(where=predicate, in_=list_)
:param element, of: Element to search for (by equality comparison)
:param where: P... | [
"def",
"index",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_",
",",
"idx",
"=",
"_index",
"(",
"*",
"args",
",",
"start",
"=",
"0",
",",
"step",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
"return",
"idx"
] | Search a list for an exact element, or element satisfying a predicate.
Usage::
index(element, list_)
index(of=element, in_=list_)
index(where=predicate, in_=list_)
:param element, of: Element to search for (by equality comparison)
:param where: Predicate defining an element to sea... | [
"Search",
"a",
"list",
"for",
"an",
"exact",
"element",
"or",
"element",
"satisfying",
"a",
"predicate",
"."
] | python | train |
gitenberg-dev/gitberg | gitenberg/util/tenprintcover.py | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/util/tenprintcover.py#L110-L117 | def rect(self, x, y, width, height, color):
"""
See the Processing function rect():
https://processing.org/reference/rect_.html
"""
self.context.set_source_rgb(*color)
self.context.rectangle(self.tx(x), self.ty(y), self.tx(width), self.ty(height))
self.context.fil... | [
"def",
"rect",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"color",
")",
":",
"self",
".",
"context",
".",
"set_source_rgb",
"(",
"*",
"color",
")",
"self",
".",
"context",
".",
"rectangle",
"(",
"self",
".",
"tx",
"(",
"x"... | See the Processing function rect():
https://processing.org/reference/rect_.html | [
"See",
"the",
"Processing",
"function",
"rect",
"()",
":",
"https",
":",
"//",
"processing",
".",
"org",
"/",
"reference",
"/",
"rect_",
".",
"html"
] | python | train |
kervi/kervi-devices | kervi/devices/sensors/BMP085.py | https://github.com/kervi/kervi-devices/blob/c6aaddc6da1d0bce0ea2b0c6eb8393ba10aefa56/kervi/devices/sensors/BMP085.py#L130-L141 | def read_temperature(self):
"""Gets the compensated temperature in degrees celsius."""
UT = self.read_raw_temp()
# Datasheet value for debugging:
#UT = 27898
# Calculations below are taken straight from section 3.5 of the datasheet.
X1 = ((UT - self.cal_AC6) * self.cal_AC... | [
"def",
"read_temperature",
"(",
"self",
")",
":",
"UT",
"=",
"self",
".",
"read_raw_temp",
"(",
")",
"# Datasheet value for debugging:",
"#UT = 27898",
"# Calculations below are taken straight from section 3.5 of the datasheet.",
"X1",
"=",
"(",
"(",
"UT",
"-",
"self",
... | Gets the compensated temperature in degrees celsius. | [
"Gets",
"the",
"compensated",
"temperature",
"in",
"degrees",
"celsius",
"."
] | python | train |
pypyr/pypyr-cli | pypyr/log/logger.py | https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/log/logger.py#L22-L39 | def set_root_logger(root_log_level, log_path=None):
"""Set the root logger 'pypyr'. Do this before you do anything else.
Run once and only once at initialization.
"""
handlers = []
console_handler = logging.StreamHandler()
handlers.append(console_handler)
if log_path:
file_handler ... | [
"def",
"set_root_logger",
"(",
"root_log_level",
",",
"log_path",
"=",
"None",
")",
":",
"handlers",
"=",
"[",
"]",
"console_handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"handlers",
".",
"append",
"(",
"console_handler",
")",
"if",
"log_path",
"... | Set the root logger 'pypyr'. Do this before you do anything else.
Run once and only once at initialization. | [
"Set",
"the",
"root",
"logger",
"pypyr",
".",
"Do",
"this",
"before",
"you",
"do",
"anything",
"else",
"."
] | python | train |
apache/incubator-mxnet | example/gluon/lipnet/BeamSearch.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/BeamSearch.py#L76-L81 | def addBeam(beamState, labeling):
"""
add beam if it does not yet exist
"""
if labeling not in beamState.entries:
beamState.entries[labeling] = BeamEntry() | [
"def",
"addBeam",
"(",
"beamState",
",",
"labeling",
")",
":",
"if",
"labeling",
"not",
"in",
"beamState",
".",
"entries",
":",
"beamState",
".",
"entries",
"[",
"labeling",
"]",
"=",
"BeamEntry",
"(",
")"
] | add beam if it does not yet exist | [
"add",
"beam",
"if",
"it",
"does",
"not",
"yet",
"exist"
] | python | train |
google/dotty | efilter/dispatch.py | https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/dispatch.py#L51-L68 | def call_audit(func):
"""Print a detailed audit of all calls to this function."""
def audited_func(*args, **kwargs):
import traceback
stack = traceback.extract_stack()
r = func(*args, **kwargs)
func_name = func.__name__
print("@depth %d, trace %s -> %s(*%r, **%r) => %r" ... | [
"def",
"call_audit",
"(",
"func",
")",
":",
"def",
"audited_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"traceback",
"stack",
"=",
"traceback",
".",
"extract_stack",
"(",
")",
"r",
"=",
"func",
"(",
"*",
"args",
",",
"*",
... | Print a detailed audit of all calls to this function. | [
"Print",
"a",
"detailed",
"audit",
"of",
"all",
"calls",
"to",
"this",
"function",
"."
] | python | train |
googleapis/google-cloud-python | bigquery/google/cloud/bigquery/table.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L263-L279 | def from_api_repr(cls, resource):
"""Factory: construct a table reference given its API representation
Args:
resource (Dict[str, object]):
Table reference representation returned from the API
Returns:
google.cloud.bigquery.table.TableReference:
... | [
"def",
"from_api_repr",
"(",
"cls",
",",
"resource",
")",
":",
"from",
"google",
".",
"cloud",
".",
"bigquery",
".",
"dataset",
"import",
"DatasetReference",
"project",
"=",
"resource",
"[",
"\"projectId\"",
"]",
"dataset_id",
"=",
"resource",
"[",
"\"datasetI... | Factory: construct a table reference given its API representation
Args:
resource (Dict[str, object]):
Table reference representation returned from the API
Returns:
google.cloud.bigquery.table.TableReference:
Table reference parsed from ``resourc... | [
"Factory",
":",
"construct",
"a",
"table",
"reference",
"given",
"its",
"API",
"representation"
] | python | train |
nvbn/thefuck | thefuck/utils.py | https://github.com/nvbn/thefuck/blob/40ab4eb62db57627bff10cf029d29c94704086a2/thefuck/utils.py#L73-L87 | def default_settings(params):
"""Adds default values to settings if it not presented.
Usage:
@default_settings({'apt': '/usr/bin/apt'})
def match(command):
print(settings.apt)
"""
def _default_settings(fn, command):
for k, w in params.items():
settings.... | [
"def",
"default_settings",
"(",
"params",
")",
":",
"def",
"_default_settings",
"(",
"fn",
",",
"command",
")",
":",
"for",
"k",
",",
"w",
"in",
"params",
".",
"items",
"(",
")",
":",
"settings",
".",
"setdefault",
"(",
"k",
",",
"w",
")",
"return",
... | Adds default values to settings if it not presented.
Usage:
@default_settings({'apt': '/usr/bin/apt'})
def match(command):
print(settings.apt) | [
"Adds",
"default",
"values",
"to",
"settings",
"if",
"it",
"not",
"presented",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/pkg_resources.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/pkg_resources.py#L2056-L2085 | def parse(cls, src, dist=None):
"""Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1,extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional
""... | [
"def",
"parse",
"(",
"cls",
",",
"src",
",",
"dist",
"=",
"None",
")",
":",
"try",
":",
"attrs",
"=",
"extras",
"=",
"(",
")",
"name",
",",
"value",
"=",
"src",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"'['",
"in",
"value",
":",
"value"... | Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1,extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional | [
"Parse",
"a",
"single",
"entry",
"point",
"from",
"string",
"src"
] | python | test |
juju/charm-helpers | charmhelpers/core/hookenv.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1018-L1035 | def status_get():
"""Retrieve the previously set juju workload state and message
If the status-get command is not found then assume this is juju < 1.23 and
return 'unknown', ""
"""
cmd = ['status-get', "--format=json", "--include-data"]
try:
raw_status = subprocess.check_output(cmd)
... | [
"def",
"status_get",
"(",
")",
":",
"cmd",
"=",
"[",
"'status-get'",
",",
"\"--format=json\"",
",",
"\"--include-data\"",
"]",
"try",
":",
"raw_status",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e"... | Retrieve the previously set juju workload state and message
If the status-get command is not found then assume this is juju < 1.23 and
return 'unknown', "" | [
"Retrieve",
"the",
"previously",
"set",
"juju",
"workload",
"state",
"and",
"message"
] | python | train |
mdgoldberg/sportsref | sportsref/nba/pbp.py | https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nba/pbp.py#L415-L434 | def clean_multigame_features(df):
"""TODO: Docstring for clean_multigame_features.
:df: TODO
:returns: TODO
"""
df = pd.DataFrame(df)
if df.index.value_counts().max() > 1:
df.reset_index(drop=True, inplace=True)
df = clean_features(df)
# if it's many games in one DataFrame, ma... | [
"def",
"clean_multigame_features",
"(",
"df",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"df",
")",
"if",
"df",
".",
"index",
".",
"value_counts",
"(",
")",
".",
"max",
"(",
")",
">",
"1",
":",
"df",
".",
"reset_index",
"(",
"drop",
"=",
"... | TODO: Docstring for clean_multigame_features.
:df: TODO
:returns: TODO | [
"TODO",
":",
"Docstring",
"for",
"clean_multigame_features",
"."
] | python | test |
OpenKMIP/PyKMIP | kmip/pie/client.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/pie/client.py#L777-L844 | def get(self, uid=None, key_wrapping_specification=None):
"""
Get a managed object from a KMIP appliance.
Args:
uid (string): The unique ID of the managed object to retrieve.
key_wrapping_specification (dict): A dictionary containing various
settings to b... | [
"def",
"get",
"(",
"self",
",",
"uid",
"=",
"None",
",",
"key_wrapping_specification",
"=",
"None",
")",
":",
"# Check input",
"if",
"uid",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"uid",
",",
"six",
".",
"string_types",
")",
":",
"rai... | Get a managed object from a KMIP appliance.
Args:
uid (string): The unique ID of the managed object to retrieve.
key_wrapping_specification (dict): A dictionary containing various
settings to be used when wrapping the key during retrieval.
See Note below.... | [
"Get",
"a",
"managed",
"object",
"from",
"a",
"KMIP",
"appliance",
"."
] | python | test |
pysathq/pysat | examples/hitman.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/hitman.py#L296-L315 | def get(self):
"""
This method computes and returns a hitting set. The hitting set is
obtained using the underlying oracle operating the MaxSAT problem
formulation. The computed solution is mapped back to objects of the
problem domain.
:rtype: list(ob... | [
"def",
"get",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"oracle",
".",
"compute",
"(",
")",
"if",
"model",
":",
"if",
"self",
".",
"htype",
"==",
"'rc2'",
":",
"# extracting a hitting set",
"self",
".",
"hset",
"=",
"filter",
"(",
"lambda",
"... | This method computes and returns a hitting set. The hitting set is
obtained using the underlying oracle operating the MaxSAT problem
formulation. The computed solution is mapped back to objects of the
problem domain.
:rtype: list(obj) | [
"This",
"method",
"computes",
"and",
"returns",
"a",
"hitting",
"set",
".",
"The",
"hitting",
"set",
"is",
"obtained",
"using",
"the",
"underlying",
"oracle",
"operating",
"the",
"MaxSAT",
"problem",
"formulation",
".",
"The",
"computed",
"solution",
"is",
"ma... | python | train |
saltstack/salt | salt/returners/couchdb_return.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchdb_return.py#L215-L269 | def returner(ret):
'''
Take in the return and shove it into the couchdb database.
'''
options = _get_options(ret)
# Check to see if the database exists.
_response = _request("GET",
options['url'] + "_all_dbs",
user=options['user'],
... | [
"def",
"returner",
"(",
"ret",
")",
":",
"options",
"=",
"_get_options",
"(",
"ret",
")",
"# Check to see if the database exists.",
"_response",
"=",
"_request",
"(",
"\"GET\"",
",",
"options",
"[",
"'url'",
"]",
"+",
"\"_all_dbs\"",
",",
"user",
"=",
"options... | Take in the return and shove it into the couchdb database. | [
"Take",
"in",
"the",
"return",
"and",
"shove",
"it",
"into",
"the",
"couchdb",
"database",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/visualization/utils.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/utils.py#L40-L48 | def _trim(image):
"""Trim a PIL image and remove white space."""
background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))
diff = PIL.ImageChops.difference(image, background)
diff = PIL.ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
image = image.cr... | [
"def",
"_trim",
"(",
"image",
")",
":",
"background",
"=",
"PIL",
".",
"Image",
".",
"new",
"(",
"image",
".",
"mode",
",",
"image",
".",
"size",
",",
"image",
".",
"getpixel",
"(",
"(",
"0",
",",
"0",
")",
")",
")",
"diff",
"=",
"PIL",
".",
... | Trim a PIL image and remove white space. | [
"Trim",
"a",
"PIL",
"image",
"and",
"remove",
"white",
"space",
"."
] | python | test |
nuagenetworks/monolithe | monolithe/specifications/specification.py | https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/specifications/specification.py#L101-L131 | def to_dict(self):
""" Transform the current specification to a dictionary
"""
data = {"model": {}}
data["model"]["description"] = self.description
data["model"]["entity_name"] = self.entity_name
data["model"]["package"] = self.package
data["model"]["resource_n... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"data",
"=",
"{",
"\"model\"",
":",
"{",
"}",
"}",
"data",
"[",
"\"model\"",
"]",
"[",
"\"description\"",
"]",
"=",
"self",
".",
"description",
"data",
"[",
"\"model\"",
"]",
"[",
"\"entity_name\"",
"]",
"=",
... | Transform the current specification to a dictionary | [
"Transform",
"the",
"current",
"specification",
"to",
"a",
"dictionary"
] | python | train |
saltstack/salt | salt/pillar/hg_pillar.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/hg_pillar.py#L69-L84 | def ext_pillar(minion_id, pillar, repo, branch='default', root=None):
'''
Extract pillar from an hg repository
'''
with Repo(repo) as repo:
repo.update(branch)
envname = 'base' if branch == 'default' else branch
if root:
path = os.path.normpath(os.path.join(repo.working_dir, root... | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"repo",
",",
"branch",
"=",
"'default'",
",",
"root",
"=",
"None",
")",
":",
"with",
"Repo",
"(",
"repo",
")",
"as",
"repo",
":",
"repo",
".",
"update",
"(",
"branch",
")",
"envname",
"=",
... | Extract pillar from an hg repository | [
"Extract",
"pillar",
"from",
"an",
"hg",
"repository"
] | python | train |
cloudsight/cloudsight-python | cloudsight/api.py | https://github.com/cloudsight/cloudsight-python/blob/f9bb43dfd468d5f5d50cc89bfcfb12d5c4abdb1e/cloudsight/api.py#L92-L114 | def image_request(self, image, filename, params=None):
"""
Send an image for classification. The image is a file-like object. The
params parameter is optional.
On success this method will immediately return a job information. Its
status will initially be :py:data:`clouds... | [
"def",
"image_request",
"(",
"self",
",",
"image",
",",
"filename",
",",
"params",
"=",
"None",
")",
":",
"data",
"=",
"self",
".",
"_init_data",
"(",
"params",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"REQUESTS_URL",
",",
"headers",
"=",
"{... | Send an image for classification. The image is a file-like object. The
params parameter is optional.
On success this method will immediately return a job information. Its
status will initially be :py:data:`cloudsight.STATUS_NOT_COMPLETED` as
it usually takes 6-12 seconds for the... | [
"Send",
"an",
"image",
"for",
"classification",
".",
"The",
"image",
"is",
"a",
"file",
"-",
"like",
"object",
".",
"The",
"params",
"parameter",
"is",
"optional",
".",
"On",
"success",
"this",
"method",
"will",
"immediately",
"return",
"a",
"job",
"inform... | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py#L738-L763 | def install_script(self, dist, script_name, script_text, dev_path=None):
"""Generate a legacy script wrapper and install it"""
spec = str(dist.as_requirement())
is_script = is_python_script(script_text, script_name)
def get_template(filename):
"""
There are a cou... | [
"def",
"install_script",
"(",
"self",
",",
"dist",
",",
"script_name",
",",
"script_text",
",",
"dev_path",
"=",
"None",
")",
":",
"spec",
"=",
"str",
"(",
"dist",
".",
"as_requirement",
"(",
")",
")",
"is_script",
"=",
"is_python_script",
"(",
"script_tex... | Generate a legacy script wrapper and install it | [
"Generate",
"a",
"legacy",
"script",
"wrapper",
"and",
"install",
"it"
] | python | test |
opendatateam/udata | udata/utils.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L30-L35 | def multi_to_dict(multi):
'''Transform a Werkzeug multidictionnary into a flat dictionnary'''
return dict(
(key, value[0] if len(value) == 1 else value)
for key, value in multi.to_dict(False).items()
) | [
"def",
"multi_to_dict",
"(",
"multi",
")",
":",
"return",
"dict",
"(",
"(",
"key",
",",
"value",
"[",
"0",
"]",
"if",
"len",
"(",
"value",
")",
"==",
"1",
"else",
"value",
")",
"for",
"key",
",",
"value",
"in",
"multi",
".",
"to_dict",
"(",
"Fals... | Transform a Werkzeug multidictionnary into a flat dictionnary | [
"Transform",
"a",
"Werkzeug",
"multidictionnary",
"into",
"a",
"flat",
"dictionnary"
] | python | train |
dropbox/stone | ez_setup.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/ez_setup.py#L321-L329 | def main():
"""Install or upgrade setuptools and EasyInstall"""
options = _parse_args()
archive = download_setuptools(
version=options.version,
download_base=options.download_base,
downloader_factory=options.downloader_factory,
)
return _install(archive, _build_install_args(o... | [
"def",
"main",
"(",
")",
":",
"options",
"=",
"_parse_args",
"(",
")",
"archive",
"=",
"download_setuptools",
"(",
"version",
"=",
"options",
".",
"version",
",",
"download_base",
"=",
"options",
".",
"download_base",
",",
"downloader_factory",
"=",
"options",... | Install or upgrade setuptools and EasyInstall | [
"Install",
"or",
"upgrade",
"setuptools",
"and",
"EasyInstall"
] | python | train |
thiezn/iperf3-python | iperf3/iperf3.py | https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L311-L326 | def json_output(self):
"""Toggles json output of libiperf
Turning this off will output the iperf3 instance results to
stdout/stderr
:rtype: bool
"""
enabled = self.lib.iperf_get_test_json_output(self._test)
if enabled:
self._json_output = True
... | [
"def",
"json_output",
"(",
"self",
")",
":",
"enabled",
"=",
"self",
".",
"lib",
".",
"iperf_get_test_json_output",
"(",
"self",
".",
"_test",
")",
"if",
"enabled",
":",
"self",
".",
"_json_output",
"=",
"True",
"else",
":",
"self",
".",
"_json_output",
... | Toggles json output of libiperf
Turning this off will output the iperf3 instance results to
stdout/stderr
:rtype: bool | [
"Toggles",
"json",
"output",
"of",
"libiperf"
] | python | train |
ilgarm/pyzimbra | pyzimbra/z/client.py | https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/z/client.py#L72-L90 | def get_account_info(self):
"""
Gets account info.
@return: AccountInfo
"""
attrs = {sconstant.A_BY: sconstant.V_NAME}
account = SOAPpy.Types.stringType(data=self.auth_token.account_name,
attrs=attrs)
params = {sconstant.... | [
"def",
"get_account_info",
"(",
"self",
")",
":",
"attrs",
"=",
"{",
"sconstant",
".",
"A_BY",
":",
"sconstant",
".",
"V_NAME",
"}",
"account",
"=",
"SOAPpy",
".",
"Types",
".",
"stringType",
"(",
"data",
"=",
"self",
".",
"auth_token",
".",
"account_nam... | Gets account info.
@return: AccountInfo | [
"Gets",
"account",
"info",
"."
] | python | train |
brainiak/brainiak | brainiak/image.py | https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/image.py#L107-L137 | def mask_image(image: SpatialImage, mask: np.ndarray, data_type: type = None
) -> np.ndarray:
"""Mask image after optionally casting its type.
Parameters
----------
image
Image to mask. Can include time as the last dimension.
mask
Mask to apply. Must have the same sha... | [
"def",
"mask_image",
"(",
"image",
":",
"SpatialImage",
",",
"mask",
":",
"np",
".",
"ndarray",
",",
"data_type",
":",
"type",
"=",
"None",
")",
"->",
"np",
".",
"ndarray",
":",
"image_data",
"=",
"image",
".",
"get_data",
"(",
")",
"if",
"image_data",... | Mask image after optionally casting its type.
Parameters
----------
image
Image to mask. Can include time as the last dimension.
mask
Mask to apply. Must have the same shape as the image data.
data_type
Type to cast image to.
Returns
-------
np.ndarray
M... | [
"Mask",
"image",
"after",
"optionally",
"casting",
"its",
"type",
"."
] | python | train |
xi/ldif3 | ldif3.py | https://github.com/xi/ldif3/blob/debc4222bb48492de0d3edcc3c71fdae5bc612a4/ldif3.py#L43-L48 | def is_dn(s):
"""Return True if s is a LDAP DN."""
if s == '':
return True
rm = DN_REGEX.match(s)
return rm is not None and rm.group(0) == s | [
"def",
"is_dn",
"(",
"s",
")",
":",
"if",
"s",
"==",
"''",
":",
"return",
"True",
"rm",
"=",
"DN_REGEX",
".",
"match",
"(",
"s",
")",
"return",
"rm",
"is",
"not",
"None",
"and",
"rm",
".",
"group",
"(",
"0",
")",
"==",
"s"
] | Return True if s is a LDAP DN. | [
"Return",
"True",
"if",
"s",
"is",
"a",
"LDAP",
"DN",
"."
] | python | train |
alexa/alexa-skills-kit-sdk-for-python | django-ask-sdk/django_ask_sdk/skill_adapter.py | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/django-ask-sdk/django_ask_sdk/skill_adapter.py#L152-L173 | def dispatch(self, request, *args, **kwargs):
# type: (HttpRequest, object, object) -> HttpResponse
"""Inspect the HTTP method and delegate to the view method.
This is the default implementation of the
:py:class:`django.views.View` method, which will inspect the
HTTP method in t... | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (HttpRequest, object, object) -> HttpResponse",
"return",
"super",
"(",
"SkillAdapter",
",",
"self",
")",
".",
"dispatch",
"(",
"request",
")"
] | Inspect the HTTP method and delegate to the view method.
This is the default implementation of the
:py:class:`django.views.View` method, which will inspect the
HTTP method in the input request and delegate it to the
corresponding method in the view. The only allowed method on
th... | [
"Inspect",
"the",
"HTTP",
"method",
"and",
"delegate",
"to",
"the",
"view",
"method",
"."
] | python | train |
dagster-io/dagster | python_modules/dagster/dagster/core/execution.py | https://github.com/dagster-io/dagster/blob/4119f8c773089de64831b1dfb9e168e353d401dc/python_modules/dagster/dagster/core/execution.py#L731-L757 | def execute_pipeline_iterator(pipeline, environment_dict=None, run_config=None):
'''Returns iterator that yields :py:class:`SolidExecutionResult` for each
solid executed in the pipeline.
This is intended to allow the caller to do things between each executed
node. For the 'synchronous' API, see :py:fun... | [
"def",
"execute_pipeline_iterator",
"(",
"pipeline",
",",
"environment_dict",
"=",
"None",
",",
"run_config",
"=",
"None",
")",
":",
"check",
".",
"inst_param",
"(",
"pipeline",
",",
"'pipeline'",
",",
"PipelineDefinition",
")",
"environment_dict",
"=",
"check",
... | Returns iterator that yields :py:class:`SolidExecutionResult` for each
solid executed in the pipeline.
This is intended to allow the caller to do things between each executed
node. For the 'synchronous' API, see :py:func:`execute_pipeline`.
Parameters:
pipeline (PipelineDefinition): Pipeline to ... | [
"Returns",
"iterator",
"that",
"yields",
":",
"py",
":",
"class",
":",
"SolidExecutionResult",
"for",
"each",
"solid",
"executed",
"in",
"the",
"pipeline",
"."
] | python | test |
celery/django-celery | djcelery/backends/database.py | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/backends/database.py#L46-L50 | def _restore_group(self, group_id):
"""Get group metadata for a group by id."""
meta = self.TaskSetModel._default_manager.restore_taskset(group_id)
if meta:
return meta.to_dict() | [
"def",
"_restore_group",
"(",
"self",
",",
"group_id",
")",
":",
"meta",
"=",
"self",
".",
"TaskSetModel",
".",
"_default_manager",
".",
"restore_taskset",
"(",
"group_id",
")",
"if",
"meta",
":",
"return",
"meta",
".",
"to_dict",
"(",
")"
] | Get group metadata for a group by id. | [
"Get",
"group",
"metadata",
"for",
"a",
"group",
"by",
"id",
"."
] | python | train |
openvax/varcode | varcode/variant.py | https://github.com/openvax/varcode/blob/981633db45ca2b31f76c06894a7360ea5d70a9b8/varcode/variant.py#L382-L391 | def is_deletion(self):
"""
Does this variant represent the deletion of nucleotides from the
reference genome?
"""
# A deletion would appear in a VCF like CT>C, so that the
# reference allele starts with the alternate nucleotides.
# This is true even in the normali... | [
"def",
"is_deletion",
"(",
"self",
")",
":",
"# A deletion would appear in a VCF like CT>C, so that the",
"# reference allele starts with the alternate nucleotides.",
"# This is true even in the normalized case, where the alternate",
"# nucleotides are an empty string.",
"return",
"(",
"len"... | Does this variant represent the deletion of nucleotides from the
reference genome? | [
"Does",
"this",
"variant",
"represent",
"the",
"deletion",
"of",
"nucleotides",
"from",
"the",
"reference",
"genome?"
] | python | train |
merll/docker-map | dockermap/build/buffer.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/build/buffer.py#L102-L114 | def save(self, name):
"""
Save the string buffer to a file. Finalizes prior to saving.
:param name: File path.
:type name: unicode | str
"""
self.finalize()
with open(name, 'wb+') as f:
if six.PY3:
f.write(self.fileobj.getbuffer())
... | [
"def",
"save",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"finalize",
"(",
")",
"with",
"open",
"(",
"name",
",",
"'wb+'",
")",
"as",
"f",
":",
"if",
"six",
".",
"PY3",
":",
"f",
".",
"write",
"(",
"self",
".",
"fileobj",
".",
"getbuffer"... | Save the string buffer to a file. Finalizes prior to saving.
:param name: File path.
:type name: unicode | str | [
"Save",
"the",
"string",
"buffer",
"to",
"a",
"file",
".",
"Finalizes",
"prior",
"to",
"saving",
"."
] | python | train |
pyviz/holoviews | holoviews/core/spaces.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/spaces.py#L85-L101 | def layout(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and lay out groups
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a NdLayout.
Args:
dimensions: Dimension(s) to group by
Returns:
NdLayo... | [
"def",
"layout",
"(",
"self",
",",
"dimensions",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"dimensions",
"=",
"self",
".",
"_valid_dimensions",
"(",
"dimensions",
")",
"if",
"len",
"(",
"dimensions",
")",
"==",
"self",
".",
"ndims",
":",
"with",
... | Group by supplied dimension(s) and lay out groups
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a NdLayout.
Args:
dimensions: Dimension(s) to group by
Returns:
NdLayout with supplied dimensions | [
"Group",
"by",
"supplied",
"dimension",
"(",
"s",
")",
"and",
"lay",
"out",
"groups"
] | python | train |
tanghaibao/jcvi | jcvi/assembly/unitig.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/unitig.py#L161-L192 | def cnsfix(args):
"""
%prog cnsfix consensus-fix.out.FAILED > blacklist.ids
Parse consensus-fix.out to extract layouts for fixed unitigs. This will
mark all the failed fragments detected by utgcnsfix and pop them out of the
existing unitigs.
"""
from jcvi.formats.base import read_block
... | [
"def",
"cnsfix",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"read_block",
"p",
"=",
"OptionParser",
"(",
"cnsfix",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len"... | %prog cnsfix consensus-fix.out.FAILED > blacklist.ids
Parse consensus-fix.out to extract layouts for fixed unitigs. This will
mark all the failed fragments detected by utgcnsfix and pop them out of the
existing unitigs. | [
"%prog",
"cnsfix",
"consensus",
"-",
"fix",
".",
"out",
".",
"FAILED",
">",
"blacklist",
".",
"ids"
] | python | train |
fedora-python/pyp2rpm | pyp2rpm/dependency_parser.py | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/dependency_parser.py#L75-L123 | def deps_from_pydit_json(requires, runtime=True):
"""Parses dependencies returned by pydist.json, since versions
uses brackets we can't use pkg_resources to parse and we need a separate
method
Args:
requires: list of dependencies as written in pydist.json of the package
runtime: are the ... | [
"def",
"deps_from_pydit_json",
"(",
"requires",
",",
"runtime",
"=",
"True",
")",
":",
"parsed",
"=",
"[",
"]",
"for",
"req",
"in",
"requires",
":",
"# req looks like 'some-name (>=X.Y,!=Y.X)' or 'someme-name' where",
"# 'some-name' is the name of required package and '(>=X.Y... | Parses dependencies returned by pydist.json, since versions
uses brackets we can't use pkg_resources to parse and we need a separate
method
Args:
requires: list of dependencies as written in pydist.json of the package
runtime: are the dependencies runtime (True) or build time (False)
Ret... | [
"Parses",
"dependencies",
"returned",
"by",
"pydist",
".",
"json",
"since",
"versions",
"uses",
"brackets",
"we",
"can",
"t",
"use",
"pkg_resources",
"to",
"parse",
"and",
"we",
"need",
"a",
"separate",
"method",
"Args",
":",
"requires",
":",
"list",
"of",
... | python | train |
shazow/unstdlib.py | unstdlib/standard/string_.py | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L294-L329 | def to_float(s, default=0.0, allow_nan=False):
"""
Return input converted into a float. If failed, then return ``default``.
Note that, by default, ``allow_nan=False``, so ``to_float`` will not return
``nan``, ``inf``, or ``-inf``.
Examples::
>>> to_float('1.5')
1.5
>>> to_... | [
"def",
"to_float",
"(",
"s",
",",
"default",
"=",
"0.0",
",",
"allow_nan",
"=",
"False",
")",
":",
"try",
":",
"f",
"=",
"float",
"(",
"s",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"default",
"if",
"not",
"allow_nan",
... | Return input converted into a float. If failed, then return ``default``.
Note that, by default, ``allow_nan=False``, so ``to_float`` will not return
``nan``, ``inf``, or ``-inf``.
Examples::
>>> to_float('1.5')
1.5
>>> to_float(1)
1.0
>>> to_float('')
0.0
... | [
"Return",
"input",
"converted",
"into",
"a",
"float",
".",
"If",
"failed",
"then",
"return",
"default",
"."
] | python | train |
Iotic-Labs/py-IoticAgent | src/IoticAgent/Core/Validation.py | https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Validation.py#L248-L257 | def search_location_check(cls, location):
"""Core.Client.request_search location parameter should be a dictionary that contains lat, lon and radius floats
"""
if not (isinstance(location, Mapping) and set(location.keys()) == _LOCATION_SEARCH_ARGS):
raise ValueError('Search location s... | [
"def",
"search_location_check",
"(",
"cls",
",",
"location",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"location",
",",
"Mapping",
")",
"and",
"set",
"(",
"location",
".",
"keys",
"(",
")",
")",
"==",
"_LOCATION_SEARCH_ARGS",
")",
":",
"raise",
"Val... | Core.Client.request_search location parameter should be a dictionary that contains lat, lon and radius floats | [
"Core",
".",
"Client",
".",
"request_search",
"location",
"parameter",
"should",
"be",
"a",
"dictionary",
"that",
"contains",
"lat",
"lon",
"and",
"radius",
"floats"
] | python | train |
dshean/pygeotools | pygeotools/lib/geolib.py | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/geolib.py#L1922-L1938 | def get_xy_ma(bma, gt, stride=1, origmask=True, newmask=None):
"""Return arrays of x and y map coordinates for input array and geotransform
"""
pX = np.arange(0, bma.shape[1], stride)
pY = np.arange(0, bma.shape[0], stride)
psamp = np.meshgrid(pX, pY)
#if origmask:
# psamp = np.ma.array(p... | [
"def",
"get_xy_ma",
"(",
"bma",
",",
"gt",
",",
"stride",
"=",
"1",
",",
"origmask",
"=",
"True",
",",
"newmask",
"=",
"None",
")",
":",
"pX",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"bma",
".",
"shape",
"[",
"1",
"]",
",",
"stride",
")",
"p... | Return arrays of x and y map coordinates for input array and geotransform | [
"Return",
"arrays",
"of",
"x",
"and",
"y",
"map",
"coordinates",
"for",
"input",
"array",
"and",
"geotransform"
] | python | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QASetting/executor.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASetting/executor.py#L33-L71 | def execute(command, shell=None, working_dir=".", echo=False, echo_indent=0):
"""Execute a command on the command-line.
:param str,list command: The command to run
:param bool shell: Whether or not to use the shell. This is optional; if
``command`` is a basestring, shell will be set to True, otherw... | [
"def",
"execute",
"(",
"command",
",",
"shell",
"=",
"None",
",",
"working_dir",
"=",
"\".\"",
",",
"echo",
"=",
"False",
",",
"echo_indent",
"=",
"0",
")",
":",
"if",
"shell",
"is",
"None",
":",
"shell",
"=",
"True",
"if",
"isinstance",
"(",
"comman... | Execute a command on the command-line.
:param str,list command: The command to run
:param bool shell: Whether or not to use the shell. This is optional; if
``command`` is a basestring, shell will be set to True, otherwise it will
be false. You can override this behavior by setting this paramet... | [
"Execute",
"a",
"command",
"on",
"the",
"command",
"-",
"line",
".",
":",
"param",
"str",
"list",
"command",
":",
"The",
"command",
"to",
"run",
":",
"param",
"bool",
"shell",
":",
"Whether",
"or",
"not",
"to",
"use",
"the",
"shell",
".",
"This",
"is... | python | train |
CityOfZion/neo-python-core | neocore/Cryptography/Helper.py | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L28-L42 | def double_sha256(ba):
"""
Perform two SHA256 operations on the input.
Args:
ba (bytes): data to hash.
Returns:
str: hash as a double digit hex string.
"""
d1 = hashlib.sha256(ba)
d2 = hashlib.sha256()
d1.hexdigest()
d2.update(d1.digest())
return d2.hexdigest() | [
"def",
"double_sha256",
"(",
"ba",
")",
":",
"d1",
"=",
"hashlib",
".",
"sha256",
"(",
"ba",
")",
"d2",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"d1",
".",
"hexdigest",
"(",
")",
"d2",
".",
"update",
"(",
"d1",
".",
"digest",
"(",
")",
")",
"re... | Perform two SHA256 operations on the input.
Args:
ba (bytes): data to hash.
Returns:
str: hash as a double digit hex string. | [
"Perform",
"two",
"SHA256",
"operations",
"on",
"the",
"input",
"."
] | python | train |
raymontag/kppy | kppy/database.py | https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L461-L473 | def lock(self):
"""This method locks the database."""
self.password = None
self.keyfile = None
self.groups[:] = []
self.entries[:] = []
self._group_order[:] = []
self._entry_order[:] = []
self.root_group = v1Group()
self._num_groups = 1
... | [
"def",
"lock",
"(",
"self",
")",
":",
"self",
".",
"password",
"=",
"None",
"self",
".",
"keyfile",
"=",
"None",
"self",
".",
"groups",
"[",
":",
"]",
"=",
"[",
"]",
"self",
".",
"entries",
"[",
":",
"]",
"=",
"[",
"]",
"self",
".",
"_group_ord... | This method locks the database. | [
"This",
"method",
"locks",
"the",
"database",
"."
] | python | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L423-L426 | def contextMenuEvent(self, event):
"""Reimplement Qt method"""
self.opt_menu.popup(event.globalPos())
event.accept() | [
"def",
"contextMenuEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"opt_menu",
".",
"popup",
"(",
"event",
".",
"globalPos",
"(",
")",
")",
"event",
".",
"accept",
"(",
")"
] | Reimplement Qt method | [
"Reimplement",
"Qt",
"method"
] | python | train |
pallets/werkzeug | src/werkzeug/wrappers/base_response.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_response.py#L366-L372 | def calculate_content_length(self):
"""Returns the content length if available or `None` otherwise."""
try:
self._ensure_sequence()
except RuntimeError:
return None
return sum(len(x) for x in self.iter_encoded()) | [
"def",
"calculate_content_length",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_ensure_sequence",
"(",
")",
"except",
"RuntimeError",
":",
"return",
"None",
"return",
"sum",
"(",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"iter_encoded",
"... | Returns the content length if available or `None` otherwise. | [
"Returns",
"the",
"content",
"length",
"if",
"available",
"or",
"None",
"otherwise",
"."
] | python | train |
ricobl/django-importer | sample_project/tasks/importers.py | https://github.com/ricobl/django-importer/blob/6967adfa7a286be7aaf59d3f33c6637270bd9df6/sample_project/tasks/importers.py#L64-L88 | def parse_date(self, item, field_name, source_name):
"""
Converts the date in the format: Thu 03.
As only the day is provided, tries to find the best match
based on the current date, considering that dates are on
the past.
"""
# Get the current date
now =... | [
"def",
"parse_date",
"(",
"self",
",",
"item",
",",
"field_name",
",",
"source_name",
")",
":",
"# Get the current date",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"date",
"(",
")",
"# Get the date from the source",
"val",
"=",
"self",
".",
"get_val... | Converts the date in the format: Thu 03.
As only the day is provided, tries to find the best match
based on the current date, considering that dates are on
the past. | [
"Converts",
"the",
"date",
"in",
"the",
"format",
":",
"Thu",
"03",
"."
] | python | test |
Nekroze/partpy | partpy/sourcestring.py | https://github.com/Nekroze/partpy/blob/dbb7d2fb285464fc43d85bc31f5af46192d301f6/partpy/sourcestring.py#L322-L345 | def match_any_string(self, strings, word=0, offset=0):
"""Attempts to match each string in strings in order.
Will return the string that matches or an empty string if no match.
If word arg >= 1 then only match if string is followed by a whitespace
which is much higher performance.
... | [
"def",
"match_any_string",
"(",
"self",
",",
"strings",
",",
"word",
"=",
"0",
",",
"offset",
"=",
"0",
")",
":",
"if",
"word",
":",
"current",
"=",
"self",
".",
"get_string",
"(",
"offset",
")",
"return",
"current",
"if",
"current",
"in",
"strings",
... | Attempts to match each string in strings in order.
Will return the string that matches or an empty string if no match.
If word arg >= 1 then only match if string is followed by a whitespace
which is much higher performance.
If word is 0 then you should sort the strings argument yoursel... | [
"Attempts",
"to",
"match",
"each",
"string",
"in",
"strings",
"in",
"order",
".",
"Will",
"return",
"the",
"string",
"that",
"matches",
"or",
"an",
"empty",
"string",
"if",
"no",
"match",
"."
] | python | train |
wgnet/webium | webium/controls/select.py | https://github.com/wgnet/webium/blob/ccb09876a201e75f5c5810392d4db7a8708b90cb/webium/controls/select.py#L57-L87 | def select_by_visible_text(self, text):
"""
Performs search of selected item from Web List
@params text - string visible text
"""
xpath = './/option[normalize-space(.) = {0}]'.format(self._escape_string(text))
opts = self.find_elements_by_xpath(xpath)
matched = F... | [
"def",
"select_by_visible_text",
"(",
"self",
",",
"text",
")",
":",
"xpath",
"=",
"'.//option[normalize-space(.) = {0}]'",
".",
"format",
"(",
"self",
".",
"_escape_string",
"(",
"text",
")",
")",
"opts",
"=",
"self",
".",
"find_elements_by_xpath",
"(",
"xpath"... | Performs search of selected item from Web List
@params text - string visible text | [
"Performs",
"search",
"of",
"selected",
"item",
"from",
"Web",
"List"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.