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 |
|---|---|---|---|---|---|---|---|---|
Geotab/mygeotab-python | mygeotab/api.py | https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/api.py#L160-L170 | def set(self, type_name, entity):
"""Sets an entity using the API. Shortcut for using call() with the 'Set' method.
:param type_name: The type of entity.
:type type_name: str
:param entity: The entity to set.
:type entity: dict
:raise MyGeotabException: Raises when an ex... | [
"def",
"set",
"(",
"self",
",",
"type_name",
",",
"entity",
")",
":",
"return",
"self",
".",
"call",
"(",
"'Set'",
",",
"type_name",
"=",
"type_name",
",",
"entity",
"=",
"entity",
")"
] | Sets an entity using the API. Shortcut for using call() with the 'Set' method.
:param type_name: The type of entity.
:type type_name: str
:param entity: The entity to set.
:type entity: dict
:raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
... | [
"Sets",
"an",
"entity",
"using",
"the",
"API",
".",
"Shortcut",
"for",
"using",
"call",
"()",
"with",
"the",
"Set",
"method",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_threshold_monitor.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_threshold_monitor.py#L565-L575 | def threshold_monitor_hidden_threshold_monitor_interface_pause(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_... | [
"def",
"threshold_monitor_hidden_threshold_monitor_interface_pause",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"threshold_monitor_hidden",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"thres... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
Qiskit/qiskit-terra | qiskit/compiler/transpiler.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/compiler/transpiler.py#L19-L147 | def transpile(circuits,
backend=None,
basis_gates=None, coupling_map=None, backend_properties=None,
initial_layout=None, seed_transpiler=None,
optimization_level=None,
pass_manager=None,
seed_mapper=None): # deprecated
"""transpile... | [
"def",
"transpile",
"(",
"circuits",
",",
"backend",
"=",
"None",
",",
"basis_gates",
"=",
"None",
",",
"coupling_map",
"=",
"None",
",",
"backend_properties",
"=",
"None",
",",
"initial_layout",
"=",
"None",
",",
"seed_transpiler",
"=",
"None",
",",
"optimi... | transpile one or more circuits, according to some desired
transpilation targets.
All arguments may be given as either singleton or list. In case of list,
the length must be equal to the number of circuits being transpiled.
Transpilation is done in parallel using multiprocessing.
Args:
cir... | [
"transpile",
"one",
"or",
"more",
"circuits",
"according",
"to",
"some",
"desired",
"transpilation",
"targets",
"."
] | python | test |
mcrute/pydora | pandora/models/_base.py | https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pandora/models/_base.py#L120-L147 | def populate_fields(api_client, instance, data):
"""Populate all fields of a model with data
Given a model with a PandoraModel superclass will enumerate all
declared fields on that model and populate the values of their Field
and SyntheticField classes. All declared fields will have a v... | [
"def",
"populate_fields",
"(",
"api_client",
",",
"instance",
",",
"data",
")",
":",
"for",
"key",
",",
"value",
"in",
"instance",
".",
"__class__",
".",
"_fields",
".",
"items",
"(",
")",
":",
"default",
"=",
"getattr",
"(",
"value",
",",
"\"default\"",... | Populate all fields of a model with data
Given a model with a PandoraModel superclass will enumerate all
declared fields on that model and populate the values of their Field
and SyntheticField classes. All declared fields will have a value after
this function runs even if they are missi... | [
"Populate",
"all",
"fields",
"of",
"a",
"model",
"with",
"data"
] | python | valid |
tanghaibao/jcvi | jcvi/utils/cbook.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/cbook.py#L308-L326 | def autoscale(bp, optimal=6):
"""
>>> autoscale(150000000)
20000000
>>> autoscale(97352632)
10000000
"""
slen = str(bp)
tlen = slen[0:2] if len(slen) > 1 else slen[0]
precision = len(slen) - 2 # how many zeros we need to pad?
bp_len_scaled = int(tlen) # scale bp_len to range (0... | [
"def",
"autoscale",
"(",
"bp",
",",
"optimal",
"=",
"6",
")",
":",
"slen",
"=",
"str",
"(",
"bp",
")",
"tlen",
"=",
"slen",
"[",
"0",
":",
"2",
"]",
"if",
"len",
"(",
"slen",
")",
">",
"1",
"else",
"slen",
"[",
"0",
"]",
"precision",
"=",
"... | >>> autoscale(150000000)
20000000
>>> autoscale(97352632)
10000000 | [
">>>",
"autoscale",
"(",
"150000000",
")",
"20000000",
">>>",
"autoscale",
"(",
"97352632",
")",
"10000000"
] | python | train |
camptocamp/Studio | studio/lib/archivefile.py | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/lib/archivefile.py#L22-L55 | def extractall(archive, filename, dstdir):
""" extract zip or tar content to dstdir"""
if zipfile.is_zipfile(archive):
z = zipfile.ZipFile(archive)
for name in z.namelist():
targetname = name
# directories ends with '/' (on Windows as well)
if targetname.... | [
"def",
"extractall",
"(",
"archive",
",",
"filename",
",",
"dstdir",
")",
":",
"if",
"zipfile",
".",
"is_zipfile",
"(",
"archive",
")",
":",
"z",
"=",
"zipfile",
".",
"ZipFile",
"(",
"archive",
")",
"for",
"name",
"in",
"z",
".",
"namelist",
"(",
")"... | extract zip or tar content to dstdir | [
"extract",
"zip",
"or",
"tar",
"content",
"to",
"dstdir"
] | python | train |
jason-weirather/py-seq-tools | seqtools/format/bgzf.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/format/bgzf.py#L138-L154 | def read(self,size):
"""read size bytes and return them"""
done = 0 #number of bytes that have been read so far
v = ''
while True:
if size-done < len(self._buffer['data']) - self._buffer_pos:
v += self._buffer['data'][self._buffer_pos:self._buffer_pos+(size-done)]
self._buffer_pos... | [
"def",
"read",
"(",
"self",
",",
"size",
")",
":",
"done",
"=",
"0",
"#number of bytes that have been read so far",
"v",
"=",
"''",
"while",
"True",
":",
"if",
"size",
"-",
"done",
"<",
"len",
"(",
"self",
".",
"_buffer",
"[",
"'data'",
"]",
")",
"-",
... | read size bytes and return them | [
"read",
"size",
"bytes",
"and",
"return",
"them"
] | python | train |
testing-cabal/mock | mock/mock.py | https://github.com/testing-cabal/mock/blob/2f356b28d42a1fd0057c9d8763d3a2cac2284165/mock/mock.py#L907-L914 | def assert_called_once(_mock_self):
"""assert that the mock was called only once.
"""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to have been called once. Called %s times." %
(self._mock_name or 'mock', self.call_count))
... | [
"def",
"assert_called_once",
"(",
"_mock_self",
")",
":",
"self",
"=",
"_mock_self",
"if",
"not",
"self",
".",
"call_count",
"==",
"1",
":",
"msg",
"=",
"(",
"\"Expected '%s' to have been called once. Called %s times.\"",
"%",
"(",
"self",
".",
"_mock_name",
"or",... | assert that the mock was called only once. | [
"assert",
"that",
"the",
"mock",
"was",
"called",
"only",
"once",
"."
] | python | train |
bkabrda/anymarkup-core | anymarkup_core/__init__.py | https://github.com/bkabrda/anymarkup-core/blob/299935092fc2650cca4e32ec92441786918f9bab/anymarkup_core/__init__.py#L425-L458 | def _guess_fmt_from_bytes(inp):
"""Try to guess format of given bytestring.
Args:
inp: byte string to guess format of
Returns:
guessed format
"""
stripped = inp.strip()
fmt = None
ini_section_header_re = re.compile(b'^\[([\w-]+)\]')
if len(stripped) == 0:
# this... | [
"def",
"_guess_fmt_from_bytes",
"(",
"inp",
")",
":",
"stripped",
"=",
"inp",
".",
"strip",
"(",
")",
"fmt",
"=",
"None",
"ini_section_header_re",
"=",
"re",
".",
"compile",
"(",
"b'^\\[([\\w-]+)\\]'",
")",
"if",
"len",
"(",
"stripped",
")",
"==",
"0",
"... | Try to guess format of given bytestring.
Args:
inp: byte string to guess format of
Returns:
guessed format | [
"Try",
"to",
"guess",
"format",
"of",
"given",
"bytestring",
"."
] | python | train |
jtwhite79/pyemu | pyemu/utils/pp_utils.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/pp_utils.py#L252-L277 | def pp_tpl_to_dataframe(tpl_filename):
""" read a pilot points template file to a pandas dataframe
Parameters
----------
tpl_filename : str
pilot points template file
Returns
-------
df : pandas.DataFrame
a dataframe with "parnme" included
"""
inlines = open(tpl_fi... | [
"def",
"pp_tpl_to_dataframe",
"(",
"tpl_filename",
")",
":",
"inlines",
"=",
"open",
"(",
"tpl_filename",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
"header",
"=",
"inlines",
".",
"pop",
"(",
"0",
")",
"marker",
"=",
"header",
".",
"strip",
"(",
")",... | read a pilot points template file to a pandas dataframe
Parameters
----------
tpl_filename : str
pilot points template file
Returns
-------
df : pandas.DataFrame
a dataframe with "parnme" included | [
"read",
"a",
"pilot",
"points",
"template",
"file",
"to",
"a",
"pandas",
"dataframe"
] | python | train |
frejanordsiek/GeminiMotorDrive | GeminiMotorDrive/__init__.py | https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/__init__.py#L41-L85 | def get_driver(driver='ASCII_RS232', *args, **keywords):
""" Gets a driver for a Parker Motion Gemini drive.
Gets and connects a particular driver in ``drivers`` to a Parker
Motion Gemini GV-6 or GT-6 servo/stepper motor drive.
The only driver currently supported is the ``'ASCII_RS232'`` driver
wh... | [
"def",
"get_driver",
"(",
"driver",
"=",
"'ASCII_RS232'",
",",
"*",
"args",
",",
"*",
"*",
"keywords",
")",
":",
"if",
"driver",
".",
"upper",
"(",
")",
"==",
"'ASCII_RS232'",
":",
"return",
"drivers",
".",
"ASCII_RS232",
"(",
"*",
"args",
",",
"*",
... | Gets a driver for a Parker Motion Gemini drive.
Gets and connects a particular driver in ``drivers`` to a Parker
Motion Gemini GV-6 or GT-6 servo/stepper motor drive.
The only driver currently supported is the ``'ASCII_RS232'`` driver
which corresponds to ``drivers.ASCII_RS232``.
Parameters
-... | [
"Gets",
"a",
"driver",
"for",
"a",
"Parker",
"Motion",
"Gemini",
"drive",
"."
] | python | train |
riga/tfdeploy | tfdeploy.py | https://github.com/riga/tfdeploy/blob/8481f657d6e3a51d76185a195b993e45f448828a/tfdeploy.py#L2159-L2164 | def Conv3D(a, f, strides, padding):
"""
3D conv op.
"""
patches = _conv_patches(a, f, strides, padding.decode("ascii"))
return np.sum(patches, axis=tuple(range(-f.ndim, -1))), | [
"def",
"Conv3D",
"(",
"a",
",",
"f",
",",
"strides",
",",
"padding",
")",
":",
"patches",
"=",
"_conv_patches",
"(",
"a",
",",
"f",
",",
"strides",
",",
"padding",
".",
"decode",
"(",
"\"ascii\"",
")",
")",
"return",
"np",
".",
"sum",
"(",
"patches... | 3D conv op. | [
"3D",
"conv",
"op",
"."
] | python | train |
pybel/pybel | src/pybel/manager/cache_manager.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L1045-L1047 | def get_modification_by_hash(self, sha512: str) -> Optional[Modification]:
"""Get a modification by a SHA512 hash."""
return self.session.query(Modification).filter(Modification.sha512 == sha512).one_or_none() | [
"def",
"get_modification_by_hash",
"(",
"self",
",",
"sha512",
":",
"str",
")",
"->",
"Optional",
"[",
"Modification",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Modification",
")",
".",
"filter",
"(",
"Modification",
".",
"sha512",
"=... | Get a modification by a SHA512 hash. | [
"Get",
"a",
"modification",
"by",
"a",
"SHA512",
"hash",
"."
] | python | train |
nats-io/python-nats | nats/io/client.py | https://github.com/nats-io/python-nats/blob/4a409319c409e7e55ce8377b64b406375c5f455b/nats/io/client.py#L1338-L1354 | def _process_err(self, err=None):
"""
Stores the last received error from the server and dispatches the error callback.
"""
self.stats['errors_received'] += 1
if err == "'Authorization Violation'":
self._err = ErrAuthorization
elif err == "'Slow Consumer'":
... | [
"def",
"_process_err",
"(",
"self",
",",
"err",
"=",
"None",
")",
":",
"self",
".",
"stats",
"[",
"'errors_received'",
"]",
"+=",
"1",
"if",
"err",
"==",
"\"'Authorization Violation'\"",
":",
"self",
".",
"_err",
"=",
"ErrAuthorization",
"elif",
"err",
"==... | Stores the last received error from the server and dispatches the error callback. | [
"Stores",
"the",
"last",
"received",
"error",
"from",
"the",
"server",
"and",
"dispatches",
"the",
"error",
"callback",
"."
] | python | train |
insomnia-lab/libreant | users/__init__.py | https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/users/__init__.py#L83-L107 | def populate_with_defaults():
'''Create user admin and grant him all permission
If the admin user already exists the function will simply return
'''
logging.getLogger(__name__).debug("Populating with default users")
if not User.select().where(User.name == 'admin').exists():
admin = User.cre... | [
"def",
"populate_with_defaults",
"(",
")",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"debug",
"(",
"\"Populating with default users\"",
")",
"if",
"not",
"User",
".",
"select",
"(",
")",
".",
"where",
"(",
"User",
".",
"name",
"==",
"'ad... | Create user admin and grant him all permission
If the admin user already exists the function will simply return | [
"Create",
"user",
"admin",
"and",
"grant",
"him",
"all",
"permission"
] | python | train |
rosenbrockc/fortpy | fortpy/interop/ftypes.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/interop/ftypes.py#L602-L620 | def _py_check_optional(parameter, tab, assign):
"""Returns the code to check for actual values when an out parameter is pure
out/optional and doesn't have anything changed.
:arg assign: the actual variable assignment value if the conditions pass.
"""
if parameter.direction == "(out)":
resu... | [
"def",
"_py_check_optional",
"(",
"parameter",
",",
"tab",
",",
"assign",
")",
":",
"if",
"parameter",
".",
"direction",
"==",
"\"(out)\"",
":",
"result",
"=",
"[",
"]",
"checks",
"=",
"[",
"\"{0}_{1:d}.value==0\"",
".",
"format",
"(",
"parameter",
".",
"l... | Returns the code to check for actual values when an out parameter is pure
out/optional and doesn't have anything changed.
:arg assign: the actual variable assignment value if the conditions pass. | [
"Returns",
"the",
"code",
"to",
"check",
"for",
"actual",
"values",
"when",
"an",
"out",
"parameter",
"is",
"pure",
"out",
"/",
"optional",
"and",
"doesn",
"t",
"have",
"anything",
"changed",
"."
] | python | train |
quikmile/trellio | trellio/utils/decorators.py | https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/utils/decorators.py#L21-L57 | def retry(exceptions, tries=5, delay=1, backoff=2, logger=None):
"""
Retry calling the decorated function using an exponential backoff.
Args:
exceptions: The exception to check. may be a tuple of
exceptions to check.
tries: Number of times to try (not retry) before giving up.
... | [
"def",
"retry",
"(",
"exceptions",
",",
"tries",
"=",
"5",
",",
"delay",
"=",
"1",
",",
"backoff",
"=",
"2",
",",
"logger",
"=",
"None",
")",
":",
"def",
"deco_retry",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"async",
"def",
"f_retr... | Retry calling the decorated function using an exponential backoff.
Args:
exceptions: The exception to check. may be a tuple of
exceptions to check.
tries: Number of times to try (not retry) before giving up.
delay: Initial delay between retries in seconds.
backoff: Backo... | [
"Retry",
"calling",
"the",
"decorated",
"function",
"using",
"an",
"exponential",
"backoff",
"."
] | python | train |
PyCQA/prospector | prospector/blender.py | https://github.com/PyCQA/prospector/blob/7cfc6d587049a786f935a722d6851cd3b72d7972/prospector/blender.py#L19-L77 | def blend_line(messages, blend_combos=None):
"""
Given a list of messages on the same line, blend them together so that we
end up with one message per actual problem. Note that we can still return
more than one message here if there are two or more different errors for
the line.
"""
blend_co... | [
"def",
"blend_line",
"(",
"messages",
",",
"blend_combos",
"=",
"None",
")",
":",
"blend_combos",
"=",
"blend_combos",
"or",
"BLEND_COMBOS",
"blend_lists",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"blend_combos",
")",
")",
"]",
"bl... | Given a list of messages on the same line, blend them together so that we
end up with one message per actual problem. Note that we can still return
more than one message here if there are two or more different errors for
the line. | [
"Given",
"a",
"list",
"of",
"messages",
"on",
"the",
"same",
"line",
"blend",
"them",
"together",
"so",
"that",
"we",
"end",
"up",
"with",
"one",
"message",
"per",
"actual",
"problem",
".",
"Note",
"that",
"we",
"can",
"still",
"return",
"more",
"than",
... | python | train |
hearsaycorp/normalize | normalize/record/__init__.py | https://github.com/hearsaycorp/normalize/blob/8b36522ddca6d41b434580bd848f3bdaa7a999c8/normalize/record/__init__.py#L170-L176 | def diff(self, other, **kwargs):
"""Compare an object with another and return a :py:class:`DiffInfo`
object. Accepts the same arguments as
:py:meth:`normalize.record.Record.diff_iter`
"""
from normalize.diff import diff
return diff(self, other, **kwargs) | [
"def",
"diff",
"(",
"self",
",",
"other",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"normalize",
".",
"diff",
"import",
"diff",
"return",
"diff",
"(",
"self",
",",
"other",
",",
"*",
"*",
"kwargs",
")"
] | Compare an object with another and return a :py:class:`DiffInfo`
object. Accepts the same arguments as
:py:meth:`normalize.record.Record.diff_iter` | [
"Compare",
"an",
"object",
"with",
"another",
"and",
"return",
"a",
":",
"py",
":",
"class",
":",
"DiffInfo",
"object",
".",
"Accepts",
"the",
"same",
"arguments",
"as",
":",
"py",
":",
"meth",
":",
"normalize",
".",
"record",
".",
"Record",
".",
"diff... | python | train |
sorgerlab/indra | indra/sources/hume/processor.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/hume/processor.py#L141-L163 | def _make_concept(self, entity):
"""Return Concept from a Hume entity."""
# Use the canonical name as the name of the Concept by default
name = self._sanitize(entity['canonicalName'])
# But if there is a trigger head text, we prefer that since
# it almost always results in a clea... | [
"def",
"_make_concept",
"(",
"self",
",",
"entity",
")",
":",
"# Use the canonical name as the name of the Concept by default",
"name",
"=",
"self",
".",
"_sanitize",
"(",
"entity",
"[",
"'canonicalName'",
"]",
")",
"# But if there is a trigger head text, we prefer that since... | Return Concept from a Hume entity. | [
"Return",
"Concept",
"from",
"a",
"Hume",
"entity",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_vcs.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_vcs.py#L716-L730 | def get_last_config_update_time_for_xpaths_output_last_config_update_time_for_xpaths_last_config_update_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_last_config_update_time_for_xpaths = ET.Element("get_last_config_update_time_for_xpaths")
con... | [
"def",
"get_last_config_update_time_for_xpaths_output_last_config_update_time_for_xpaths_last_config_update_time",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_last_config_update_time_for_xpaths",
"=",
"ET",... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
Akrog/cinderlib | cinderlib/cinderlib.py | https://github.com/Akrog/cinderlib/blob/6481cd9a34744f80bdba130fe9089f1b8b7cb327/cinderlib/cinderlib.py#L202-L215 | def _update_cinder_config(cls):
"""Parse in-memory file to update OSLO configuration used by Cinder."""
cls._config_string_io.seek(0)
cls._parser.write(cls._config_string_io)
# Check if we have any multiopt
cls._config_string_io.seek(0)
current_cfg = cls._config_string_i... | [
"def",
"_update_cinder_config",
"(",
"cls",
")",
":",
"cls",
".",
"_config_string_io",
".",
"seek",
"(",
"0",
")",
"cls",
".",
"_parser",
".",
"write",
"(",
"cls",
".",
"_config_string_io",
")",
"# Check if we have any multiopt",
"cls",
".",
"_config_string_io",... | Parse in-memory file to update OSLO configuration used by Cinder. | [
"Parse",
"in",
"-",
"memory",
"file",
"to",
"update",
"OSLO",
"configuration",
"used",
"by",
"Cinder",
"."
] | python | train |
ska-sa/katcp-python | katcp/resource_client.py | https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L889-L906 | def reapply_sampling_strategies(self):
"""Reapply all sensor strategies using cached values"""
check_sensor = self._inspecting_client.future_check_sensor
for sensor_name, strategy in list(self._strategy_cache.items()):
try:
sensor_exists = yield check_sensor(sensor_na... | [
"def",
"reapply_sampling_strategies",
"(",
"self",
")",
":",
"check_sensor",
"=",
"self",
".",
"_inspecting_client",
".",
"future_check_sensor",
"for",
"sensor_name",
",",
"strategy",
"in",
"list",
"(",
"self",
".",
"_strategy_cache",
".",
"items",
"(",
")",
")"... | Reapply all sensor strategies using cached values | [
"Reapply",
"all",
"sensor",
"strategies",
"using",
"cached",
"values"
] | python | train |
bapakode/OmMongo | ommongo/fields/ref.py | https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/fields/ref.py#L65-L70 | def dereference(self, session, ref, allow_none=False):
""" Dereference an ObjectID to this field's underlying type """
ref = DBRef(id=ref, collection=self.type.type.get_collection_name(),
database=self.db)
ref.type = self.type.type
return session.dereference(ref, allo... | [
"def",
"dereference",
"(",
"self",
",",
"session",
",",
"ref",
",",
"allow_none",
"=",
"False",
")",
":",
"ref",
"=",
"DBRef",
"(",
"id",
"=",
"ref",
",",
"collection",
"=",
"self",
".",
"type",
".",
"type",
".",
"get_collection_name",
"(",
")",
",",... | Dereference an ObjectID to this field's underlying type | [
"Dereference",
"an",
"ObjectID",
"to",
"this",
"field",
"s",
"underlying",
"type"
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_console.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_console.py#L72-L75 | def unload(self):
'''unload module'''
self.mpstate.console.close()
self.mpstate.console = textconsole.SimpleConsole() | [
"def",
"unload",
"(",
"self",
")",
":",
"self",
".",
"mpstate",
".",
"console",
".",
"close",
"(",
")",
"self",
".",
"mpstate",
".",
"console",
"=",
"textconsole",
".",
"SimpleConsole",
"(",
")"
] | unload module | [
"unload",
"module"
] | python | train |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L12970-L13060 | def attach_device_without_medium(self, name, controller_port, device, type_p):
"""Attaches a device and optionally mounts a medium to the given storage
controller (:py:class:`IStorageController` , identified by @a name),
at the indicated port and device.
This method is intended ... | [
"def",
"attach_device_without_medium",
"(",
"self",
",",
"name",
",",
"controller_port",
",",
"device",
",",
"type_p",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"name can only be an instance of type... | Attaches a device and optionally mounts a medium to the given storage
controller (:py:class:`IStorageController` , identified by @a name),
at the indicated port and device.
This method is intended for managing storage devices in general while a
machine is powered off. It can be ... | [
"Attaches",
"a",
"device",
"and",
"optionally",
"mounts",
"a",
"medium",
"to",
"the",
"given",
"storage",
"controller",
"(",
":",
"py",
":",
"class",
":",
"IStorageController",
"identified",
"by",
"@a",
"name",
")",
"at",
"the",
"indicated",
"port",
"and",
... | python | train |
stovorov/IteratorDecorator | IteratorDecorator/src.py | https://github.com/stovorov/IteratorDecorator/blob/9bc054a50758c19f41da8220f230beba1c2debbb/IteratorDecorator/src.py#L8-L90 | def iter_attribute(iterable_name) -> Union[Iterable, Callable]:
"""Decorator implementing Iterator interface with nicer manner.
Example
-------
@iter_attribute('my_attr'):
class DecoratedClass:
...
Warning:
========
When using PyCharm or MYPY you'll probably see issues with d... | [
"def",
"iter_attribute",
"(",
"iterable_name",
")",
"->",
"Union",
"[",
"Iterable",
",",
"Callable",
"]",
":",
"def",
"create_new_class",
"(",
"decorated_class",
")",
"->",
"Union",
"[",
"Iterable",
",",
"Callable",
"]",
":",
"\"\"\"Class extender implementing __n... | Decorator implementing Iterator interface with nicer manner.
Example
-------
@iter_attribute('my_attr'):
class DecoratedClass:
...
Warning:
========
When using PyCharm or MYPY you'll probably see issues with decorated class not being recognized as Iterator.
That's an issue wh... | [
"Decorator",
"implementing",
"Iterator",
"interface",
"with",
"nicer",
"manner",
"."
] | python | test |
Bogdanp/dramatiq | dramatiq/broker.py | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/broker.py#L26-L44 | def get_broker() -> "Broker":
"""Get the global broker instance. If no global broker is set,
this initializes a RabbitmqBroker and returns it.
Returns:
Broker: The default Broker.
"""
global global_broker
if global_broker is None:
from .brokers.rabbitmq import RabbitmqBroker
... | [
"def",
"get_broker",
"(",
")",
"->",
"\"Broker\"",
":",
"global",
"global_broker",
"if",
"global_broker",
"is",
"None",
":",
"from",
".",
"brokers",
".",
"rabbitmq",
"import",
"RabbitmqBroker",
"set_broker",
"(",
"RabbitmqBroker",
"(",
"host",
"=",
"\"127.0.0.1\... | Get the global broker instance. If no global broker is set,
this initializes a RabbitmqBroker and returns it.
Returns:
Broker: The default Broker. | [
"Get",
"the",
"global",
"broker",
"instance",
".",
"If",
"no",
"global",
"broker",
"is",
"set",
"this",
"initializes",
"a",
"RabbitmqBroker",
"and",
"returns",
"it",
"."
] | python | train |
steder/goose | goose/core.py | https://github.com/steder/goose/blob/e9290b39fdd7b3842052e40995ee833eaf8f15db/goose/core.py#L30-L69 | def executeBatch(cursor, sql,
regex=r"(?mx) ([^';]* (?:'[^']*'[^';]*)*)",
comment_regex=r"(?mx) (?:^\s*$)|(?:--.*$)"):
"""
Takes a SQL file and executes it as many separate statements.
TODO: replace regexes with something easier to grok and extend.
"""
# First, st... | [
"def",
"executeBatch",
"(",
"cursor",
",",
"sql",
",",
"regex",
"=",
"r\"(?mx) ([^';]* (?:'[^']*'[^';]*)*)\"",
",",
"comment_regex",
"=",
"r\"(?mx) (?:^\\s*$)|(?:--.*$)\"",
")",
":",
"# First, strip comments",
"sql",
"=",
"\"\\n\"",
".",
"join",
"(",
"[",
"x",
".",
... | Takes a SQL file and executes it as many separate statements.
TODO: replace regexes with something easier to grok and extend. | [
"Takes",
"a",
"SQL",
"file",
"and",
"executes",
"it",
"as",
"many",
"separate",
"statements",
"."
] | python | train |
evandempsey/porter2-stemmer | porter2stemmer/porter2stemmer.py | https://github.com/evandempsey/porter2-stemmer/blob/949824b7767c25efb014ef738e682442fa70c10b/porter2stemmer/porter2stemmer.py#L124-L136 | def strip_possessives(self, word):
"""
Get rid of apostrophes indicating possession.
"""
if word.endswith("'s'"):
return word[:-3]
elif word.endswith("'s"):
return word[:-2]
elif word.endswith("'"):
return word[:-1]
else:
... | [
"def",
"strip_possessives",
"(",
"self",
",",
"word",
")",
":",
"if",
"word",
".",
"endswith",
"(",
"\"'s'\"",
")",
":",
"return",
"word",
"[",
":",
"-",
"3",
"]",
"elif",
"word",
".",
"endswith",
"(",
"\"'s\"",
")",
":",
"return",
"word",
"[",
":"... | Get rid of apostrophes indicating possession. | [
"Get",
"rid",
"of",
"apostrophes",
"indicating",
"possession",
"."
] | python | train |
scivision/gridaurora | gridaurora/ztanh.py | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/ztanh.py#L22-L27 | def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray:
"""
typically call via setupz instead
"""
x0 = np.linspace(0, 3.14, Np) # arbitrarily picking 3.14 as where tanh gets to 99% of asymptote
return np.tanh(x0)*gridmax+gridmin | [
"def",
"_ztanh",
"(",
"Np",
":",
"int",
",",
"gridmin",
":",
"float",
",",
"gridmax",
":",
"float",
")",
"->",
"np",
".",
"ndarray",
":",
"x0",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"3.14",
",",
"Np",
")",
"# arbitrarily picking 3.14 as where tanh... | typically call via setupz instead | [
"typically",
"call",
"via",
"setupz",
"instead"
] | python | train |
StackStorm/pybind | pybind/nos/v7_2_0/isns/isns_vrf/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/isns/isns_vrf/__init__.py#L217-L240 | def _set_isns_discovery_domain(self, v, load=False):
"""
Setter method for isns_discovery_domain, mapped from YANG variable /isns/isns_vrf/isns_discovery_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_isns_discovery_domain is considered as a private
me... | [
"def",
"_set_isns_discovery_domain",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
... | Setter method for isns_discovery_domain, mapped from YANG variable /isns/isns_vrf/isns_discovery_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_isns_discovery_domain is considered as a private
method. Backends looking to populate this variable should
do so... | [
"Setter",
"method",
"for",
"isns_discovery_domain",
"mapped",
"from",
"YANG",
"variable",
"/",
"isns",
"/",
"isns_vrf",
"/",
"isns_discovery_domain",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in... | python | train |
gitpython-developers/GitPython | git/refs/symbolic.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/refs/symbolic.py#L632-L649 | def iter_items(cls, repo, common_path=None):
"""Find all refs in the repository
:param repo: is the Repo
:param common_path:
Optional keyword argument to the path which is to be shared by all
returned Ref objects.
Defaults to class specific portion if None a... | [
"def",
"iter_items",
"(",
"cls",
",",
"repo",
",",
"common_path",
"=",
"None",
")",
":",
"return",
"(",
"r",
"for",
"r",
"in",
"cls",
".",
"_iter_items",
"(",
"repo",
",",
"common_path",
")",
"if",
"r",
".",
"__class__",
"==",
"SymbolicReference",
"or"... | Find all refs in the repository
:param repo: is the Repo
:param common_path:
Optional keyword argument to the path which is to be shared by all
returned Ref objects.
Defaults to class specific portion if None assuring that only
refs suitable for the actu... | [
"Find",
"all",
"refs",
"in",
"the",
"repository"
] | python | train |
ph4r05/monero-serialize | monero_serialize/xmrrpc.py | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrrpc.py#L961-L972 | async def uint(self, elem, elem_type, params=None):
"""
Integer types
:param elem:
:param elem_type:
:param params:
:return:
"""
if self.writing:
return IntegerModel(elem, elem_type.WIDTH) if self.modelize else elem
else:
re... | [
"async",
"def",
"uint",
"(",
"self",
",",
"elem",
",",
"elem_type",
",",
"params",
"=",
"None",
")",
":",
"if",
"self",
".",
"writing",
":",
"return",
"IntegerModel",
"(",
"elem",
",",
"elem_type",
".",
"WIDTH",
")",
"if",
"self",
".",
"modelize",
"e... | Integer types
:param elem:
:param elem_type:
:param params:
:return: | [
"Integer",
"types",
":",
"param",
"elem",
":",
":",
"param",
"elem_type",
":",
":",
"param",
"params",
":",
":",
"return",
":"
] | python | train |
holgern/pyedflib | pyedflib/edfreader.py | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L644-L685 | def readSignal(self, chn, start=0, n=None):
"""
Returns the physical data of signal chn. When start and n is set, a subset is returned
Parameters
----------
chn : int
channel number
start : int
start pointer (default is 0)
n : int
... | [
"def",
"readSignal",
"(",
"self",
",",
"chn",
",",
"start",
"=",
"0",
",",
"n",
"=",
"None",
")",
":",
"if",
"start",
"<",
"0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
")",
"if",
"n",
"is",
"not",
"None",
"and",
"n",
"<",
"0",
":"... | Returns the physical data of signal chn. When start and n is set, a subset is returned
Parameters
----------
chn : int
channel number
start : int
start pointer (default is 0)
n : int
length of data to read (default is None, by which the comple... | [
"Returns",
"the",
"physical",
"data",
"of",
"signal",
"chn",
".",
"When",
"start",
"and",
"n",
"is",
"set",
"a",
"subset",
"is",
"returned"
] | python | train |
LuqueDaniel/pybooru | pybooru/api_danbooru.py | https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/api_danbooru.py#L1259-L1266 | def forum_topic_undelete(self, topic_id):
"""Un delete a topic (Login requries) (Moderator+) (UNTESTED).
Parameters:
topic_id (int): Where topic_id is the topic id.
"""
return self._get('forum_topics/{0}/undelete.json'.format(topic_id),
method='POST'... | [
"def",
"forum_topic_undelete",
"(",
"self",
",",
"topic_id",
")",
":",
"return",
"self",
".",
"_get",
"(",
"'forum_topics/{0}/undelete.json'",
".",
"format",
"(",
"topic_id",
")",
",",
"method",
"=",
"'POST'",
",",
"auth",
"=",
"True",
")"
] | Un delete a topic (Login requries) (Moderator+) (UNTESTED).
Parameters:
topic_id (int): Where topic_id is the topic id. | [
"Un",
"delete",
"a",
"topic",
"(",
"Login",
"requries",
")",
"(",
"Moderator",
"+",
")",
"(",
"UNTESTED",
")",
"."
] | python | train |
proteanhq/protean | src/protean/core/exceptions.py | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/exceptions.py#L52-L59 | def normalized_messages(self, no_field_name='_entity'):
"""Return all the error messages as a dictionary"""
if isinstance(self.messages, dict):
return self.messages
if not self.field_names:
return {no_field_name: self.messages}
return dict((name, self.messages) f... | [
"def",
"normalized_messages",
"(",
"self",
",",
"no_field_name",
"=",
"'_entity'",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"messages",
",",
"dict",
")",
":",
"return",
"self",
".",
"messages",
"if",
"not",
"self",
".",
"field_names",
":",
"return",... | Return all the error messages as a dictionary | [
"Return",
"all",
"the",
"error",
"messages",
"as",
"a",
"dictionary"
] | python | train |
kivy/python-for-android | pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/debug.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/debug.py#L170-L236 | def fake_exc_info(exc_info, filename, lineno):
"""Helper for `translate_exception`."""
exc_type, exc_value, tb = exc_info
# figure the real context out
if tb is not None:
real_locals = tb.tb_frame.f_locals.copy()
ctx = real_locals.get('context')
if ctx:
locals = ctx.... | [
"def",
"fake_exc_info",
"(",
"exc_info",
",",
"filename",
",",
"lineno",
")",
":",
"exc_type",
",",
"exc_value",
",",
"tb",
"=",
"exc_info",
"# figure the real context out",
"if",
"tb",
"is",
"not",
"None",
":",
"real_locals",
"=",
"tb",
".",
"tb_frame",
"."... | Helper for `translate_exception`. | [
"Helper",
"for",
"translate_exception",
"."
] | python | train |
rytilahti/python-eq3bt | eq3bt/eq3cli.py | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L44-L49 | def temp(dev, target):
""" Gets or sets the target temperature."""
click.echo("Current target temp: %s" % dev.target_temperature)
if target:
click.echo("Setting target temp: %s" % target)
dev.target_temperature = target | [
"def",
"temp",
"(",
"dev",
",",
"target",
")",
":",
"click",
".",
"echo",
"(",
"\"Current target temp: %s\"",
"%",
"dev",
".",
"target_temperature",
")",
"if",
"target",
":",
"click",
".",
"echo",
"(",
"\"Setting target temp: %s\"",
"%",
"target",
")",
"dev"... | Gets or sets the target temperature. | [
"Gets",
"or",
"sets",
"the",
"target",
"temperature",
"."
] | python | train |
dustin/twitty-twister | twittytwister/streaming.py | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/streaming.py#L102-L119 | def fromDict(cls, data):
"""
Fill this objects attributes from a dict for known properties.
"""
obj = cls()
obj.raw = data
for name, value in data.iteritems():
if cls.SIMPLE_PROPS and name in cls.SIMPLE_PROPS:
setattr(obj, name, value)
... | [
"def",
"fromDict",
"(",
"cls",
",",
"data",
")",
":",
"obj",
"=",
"cls",
"(",
")",
"obj",
".",
"raw",
"=",
"data",
"for",
"name",
",",
"value",
"in",
"data",
".",
"iteritems",
"(",
")",
":",
"if",
"cls",
".",
"SIMPLE_PROPS",
"and",
"name",
"in",
... | Fill this objects attributes from a dict for known properties. | [
"Fill",
"this",
"objects",
"attributes",
"from",
"a",
"dict",
"for",
"known",
"properties",
"."
] | python | train |
rix0rrr/gcl | gcl/ast.py | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/ast.py#L516-L525 | def applyIndex(self, lst, right):
"""Apply a list to something else."""
if len(right) != 1:
raise exceptions.EvaluationError('%r can only be applied to one argument, got %r' % (self.left, self.right))
right = right[0]
if isinstance(right, int):
return lst[right]
raise exceptions.Evalua... | [
"def",
"applyIndex",
"(",
"self",
",",
"lst",
",",
"right",
")",
":",
"if",
"len",
"(",
"right",
")",
"!=",
"1",
":",
"raise",
"exceptions",
".",
"EvaluationError",
"(",
"'%r can only be applied to one argument, got %r'",
"%",
"(",
"self",
".",
"left",
",",
... | Apply a list to something else. | [
"Apply",
"a",
"list",
"to",
"something",
"else",
"."
] | python | train |
bitesofcode/projex | projex/xbuild/builder.py | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/xbuild/builder.py#L1713-L1764 | def fromFile(filename):
"""
Parses the inputted xml file information and generates a builder
for it.
:param filename | <str>
:return <Builder> || None
"""
xdata = None
ydata = None
# try parsing an XML file
try:
... | [
"def",
"fromFile",
"(",
"filename",
")",
":",
"xdata",
"=",
"None",
"ydata",
"=",
"None",
"# try parsing an XML file",
"try",
":",
"xdata",
"=",
"ElementTree",
".",
"parse",
"(",
"filename",
")",
".",
"getroot",
"(",
")",
"except",
"StandardError",
":",
"x... | Parses the inputted xml file information and generates a builder
for it.
:param filename | <str>
:return <Builder> || None | [
"Parses",
"the",
"inputted",
"xml",
"file",
"information",
"and",
"generates",
"a",
"builder",
"for",
"it",
".",
":",
"param",
"filename",
"|",
"<str",
">",
":",
"return",
"<Builder",
">",
"||",
"None"
] | python | train |
Anaconda-Platform/anaconda-client | binstar_client/utils/config.py | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/utils/config.py#L101-L128 | def get_server_api(token=None, site=None, cls=None, config=None, **kwargs):
"""
Get the anaconda server api class
"""
if not cls:
from binstar_client import Binstar
cls = Binstar
config = config if config is not None else get_config(site=site)
url = config.get('url', DEFAULT_UR... | [
"def",
"get_server_api",
"(",
"token",
"=",
"None",
",",
"site",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"config",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"cls",
":",
"from",
"binstar_client",
"import",
"Binstar",
"cls",
"=",
... | Get the anaconda server api class | [
"Get",
"the",
"anaconda",
"server",
"api",
"class"
] | python | train |
markovmodel/msmtools | msmtools/analysis/dense/decomposition.py | https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/dense/decomposition.py#L476-L519 | def timescales(T, tau=1, k=None, reversible=False, mu=None):
r"""Compute implied time scales of given transition matrix
Parameters
----------
T : (M, M) ndarray
Transition matrix
tau : int, optional
lag time
k : int, optional
Number of time scales
reversible : bool, ... | [
"def",
"timescales",
"(",
"T",
",",
"tau",
"=",
"1",
",",
"k",
"=",
"None",
",",
"reversible",
"=",
"False",
",",
"mu",
"=",
"None",
")",
":",
"values",
"=",
"eigenvalues",
"(",
"T",
",",
"reversible",
"=",
"reversible",
",",
"mu",
"=",
"mu",
")"... | r"""Compute implied time scales of given transition matrix
Parameters
----------
T : (M, M) ndarray
Transition matrix
tau : int, optional
lag time
k : int, optional
Number of time scales
reversible : bool, optional
Indicate that transition matirx is reversible
... | [
"r",
"Compute",
"implied",
"time",
"scales",
"of",
"given",
"transition",
"matrix"
] | python | train |
jaredLunde/redis_structures | redis_structures/__init__.py | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L407-L410 | def decr(self, key, by=1):
""" Decrements @key by @by
-> #int the value of @key after the decrement """
return self._client.decr(self.get_key(key), by) | [
"def",
"decr",
"(",
"self",
",",
"key",
",",
"by",
"=",
"1",
")",
":",
"return",
"self",
".",
"_client",
".",
"decr",
"(",
"self",
".",
"get_key",
"(",
"key",
")",
",",
"by",
")"
] | Decrements @key by @by
-> #int the value of @key after the decrement | [
"Decrements"
] | python | train |
hvac/hvac | hvac/api/auth_methods/github.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/auth_methods/github.py#L191-L216 | def login(self, token, use_token=True, mount_point=DEFAULT_MOUNT_POINT):
"""Login using GitHub access token.
Supported methods:
POST: /auth/{mount_point}/login. Produces: 200 application/json
:param token: GitHub personal API token.
:type token: str | unicode
:para... | [
"def",
"login",
"(",
"self",
",",
"token",
",",
"use_token",
"=",
"True",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"token",
",",
"}",
"api_path",
"=",
"'/v1/auth/{mount_point}/login'",
".",
"format",
"(",
... | Login using GitHub access token.
Supported methods:
POST: /auth/{mount_point}/login. Produces: 200 application/json
:param token: GitHub personal API token.
:type token: str | unicode
:param use_token: if True, uses the token in the response received from the auth request ... | [
"Login",
"using",
"GitHub",
"access",
"token",
"."
] | python | train |
bububa/pyTOP | pyTOP/fenxiao.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/fenxiao.py#L93-L102 | def get(self, session, **kwargs):
'''taobao.fenxiao.cooperation.get 获取供应商的合作关系信息
获取供应商的合作关系信息'''
request = TOPRequest('taobao.fenxiao.cooperation.get')
for k, v in kwargs.iteritems():
if k not in ('status', 'start_date', 'end_date', 'trade_type', 'page_no', 'page_siz... | [
"def",
"get",
"(",
"self",
",",
"session",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.fenxiao.cooperation.get'",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"if",
"k",
"not",
"in",
"... | taobao.fenxiao.cooperation.get 获取供应商的合作关系信息
获取供应商的合作关系信息 | [
"taobao",
".",
"fenxiao",
".",
"cooperation",
".",
"get",
"获取供应商的合作关系信息",
"获取供应商的合作关系信息"
] | python | train |
erdewit/ib_insync | ib_insync/ib.py | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/ib.py#L1172-L1191 | def reqTickByTickData(
self, contract: Contract, tickType: str,
numberOfTicks: int = 0, ignoreSize: bool = False) -> Ticker:
"""
Subscribe to tick-by-tick data and return the Ticker that
holds the ticks in ticker.tickByTicks.
https://interactivebrokers.github.io/... | [
"def",
"reqTickByTickData",
"(",
"self",
",",
"contract",
":",
"Contract",
",",
"tickType",
":",
"str",
",",
"numberOfTicks",
":",
"int",
"=",
"0",
",",
"ignoreSize",
":",
"bool",
"=",
"False",
")",
"->",
"Ticker",
":",
"reqId",
"=",
"self",
".",
"clie... | Subscribe to tick-by-tick data and return the Ticker that
holds the ticks in ticker.tickByTicks.
https://interactivebrokers.github.io/tws-api/tick_data.html
Args:
contract: Contract of interest.
tickType: One of 'Last', 'AllLast', 'BidAsk' or 'MidPoint'.
nu... | [
"Subscribe",
"to",
"tick",
"-",
"by",
"-",
"tick",
"data",
"and",
"return",
"the",
"Ticker",
"that",
"holds",
"the",
"ticks",
"in",
"ticker",
".",
"tickByTicks",
"."
] | python | train |
matthewdeanmartin/jiggle_version | build_utils.py | https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/build_utils.py#L143-L170 | def execute_get_text(command): # type: (str) ->str
"""
Execute shell command and return stdout txt
:param command:
:return:
"""
try:
_ = subprocess.run
try:
completed = subprocess.run(
command,
check=True,
shell=True,
... | [
"def",
"execute_get_text",
"(",
"command",
")",
":",
"# type: (str) ->str",
"try",
":",
"_",
"=",
"subprocess",
".",
"run",
"try",
":",
"completed",
"=",
"subprocess",
".",
"run",
"(",
"command",
",",
"check",
"=",
"True",
",",
"shell",
"=",
"True",
",",... | Execute shell command and return stdout txt
:param command:
:return: | [
"Execute",
"shell",
"command",
"and",
"return",
"stdout",
"txt",
":",
"param",
"command",
":",
":",
"return",
":"
] | python | train |
ucsb-cs/submit | submit/models.py | https://github.com/ucsb-cs/submit/blob/92810c81255a4fc6bbebac1ac8aae856fd576ffe/submit/models.py#L625-L627 | def can_view(self, user):
"""Return whether or not `user` can view the submission."""
return user in self.group.users or self.project.can_view(user) | [
"def",
"can_view",
"(",
"self",
",",
"user",
")",
":",
"return",
"user",
"in",
"self",
".",
"group",
".",
"users",
"or",
"self",
".",
"project",
".",
"can_view",
"(",
"user",
")"
] | Return whether or not `user` can view the submission. | [
"Return",
"whether",
"or",
"not",
"user",
"can",
"view",
"the",
"submission",
"."
] | python | train |
xym-tool/xym | xym/xym.py | https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L237-L253 | def add_line_references(self, input_model):
"""
This function is a part of the model post-processing pipeline. For
each line in the module, it adds a reference to the line number in
the original draft/RFC from where the module line was extracted.
:param input_model: The YANG mode... | [
"def",
"add_line_references",
"(",
"self",
",",
"input_model",
")",
":",
"output_model",
"=",
"[",
"]",
"for",
"ln",
"in",
"input_model",
":",
"line_len",
"=",
"len",
"(",
"ln",
"[",
"0",
"]",
")",
"line_ref",
"=",
"(",
"'// %4d'",
"%",
"ln",
"[",
"1... | This function is a part of the model post-processing pipeline. For
each line in the module, it adds a reference to the line number in
the original draft/RFC from where the module line was extracted.
:param input_model: The YANG model to be processed
:return: Modified YANG model, where li... | [
"This",
"function",
"is",
"a",
"part",
"of",
"the",
"model",
"post",
"-",
"processing",
"pipeline",
".",
"For",
"each",
"line",
"in",
"the",
"module",
"it",
"adds",
"a",
"reference",
"to",
"the",
"line",
"number",
"in",
"the",
"original",
"draft",
"/",
... | python | train |
bhmm/bhmm | bhmm/hidden/api.py | https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L44-L62 | def set_implementation(impl):
"""
Sets the implementation of this module
Parameters
----------
impl : str
One of ["python", "c"]
"""
global __impl__
if impl.lower() == 'python':
__impl__ = __IMPL_PYTHON__
elif impl.lower() == 'c':
__impl__ = __IMPL_C__
e... | [
"def",
"set_implementation",
"(",
"impl",
")",
":",
"global",
"__impl__",
"if",
"impl",
".",
"lower",
"(",
")",
"==",
"'python'",
":",
"__impl__",
"=",
"__IMPL_PYTHON__",
"elif",
"impl",
".",
"lower",
"(",
")",
"==",
"'c'",
":",
"__impl__",
"=",
"__IMPL_... | Sets the implementation of this module
Parameters
----------
impl : str
One of ["python", "c"] | [
"Sets",
"the",
"implementation",
"of",
"this",
"module"
] | python | train |
nvbn/thefuck | thefuck/conf.py | https://github.com/nvbn/thefuck/blob/40ab4eb62db57627bff10cf029d29c94704086a2/thefuck/conf.py#L82-L89 | def _priority_from_env(self, val):
"""Gets priority pairs from env."""
for part in val.split(':'):
try:
rule, priority = part.split('=')
yield rule, int(priority)
except ValueError:
continue | [
"def",
"_priority_from_env",
"(",
"self",
",",
"val",
")",
":",
"for",
"part",
"in",
"val",
".",
"split",
"(",
"':'",
")",
":",
"try",
":",
"rule",
",",
"priority",
"=",
"part",
".",
"split",
"(",
"'='",
")",
"yield",
"rule",
",",
"int",
"(",
"pr... | Gets priority pairs from env. | [
"Gets",
"priority",
"pairs",
"from",
"env",
"."
] | python | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAData/data_resample.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/data_resample.py#L30-L201 | def QA_data_tick_resample_1min(tick, type_='1min', if_drop=True):
"""
tick 采样为 分钟数据
1. 仅使用将 tick 采样为 1 分钟数据
2. 仅测试过,与通达信 1 分钟数据达成一致
3. 经测试,可以匹配 QA.QA_fetch_get_stock_transaction 得到的数据,其他类型数据未测试
demo:
df = QA.QA_fetch_get_stock_transaction(package='tdx', code='000001',
... | [
"def",
"QA_data_tick_resample_1min",
"(",
"tick",
",",
"type_",
"=",
"'1min'",
",",
"if_drop",
"=",
"True",
")",
":",
"tick",
"=",
"tick",
".",
"assign",
"(",
"amount",
"=",
"tick",
".",
"price",
"*",
"tick",
".",
"vol",
")",
"resx",
"=",
"pd",
".",
... | tick 采样为 分钟数据
1. 仅使用将 tick 采样为 1 分钟数据
2. 仅测试过,与通达信 1 分钟数据达成一致
3. 经测试,可以匹配 QA.QA_fetch_get_stock_transaction 得到的数据,其他类型数据未测试
demo:
df = QA.QA_fetch_get_stock_transaction(package='tdx', code='000001',
start='2018-08-01 09:25:00',
... | [
"tick",
"采样为",
"分钟数据",
"1",
".",
"仅使用将",
"tick",
"采样为",
"1",
"分钟数据",
"2",
".",
"仅测试过,与通达信",
"1",
"分钟数据达成一致",
"3",
".",
"经测试,可以匹配",
"QA",
".",
"QA_fetch_get_stock_transaction",
"得到的数据,其他类型数据未测试",
"demo",
":",
"df",
"=",
"QA",
".",
"QA_fetch_get_stock_transactio... | python | train |
SHTOOLS/SHTOOLS | pyshtools/shclasses/shwindow.py | https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L653-L712 | def coupling_matrix(self, lmax, nwin=None, weights=None, mode='full'):
"""
Return the coupling matrix of the first nwin tapers. This matrix
relates the global power spectrum to the expectation of the localized
multitaper spectrum.
Usage
-----
Mmt = x.coupling_mat... | [
"def",
"coupling_matrix",
"(",
"self",
",",
"lmax",
",",
"nwin",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"mode",
"=",
"'full'",
")",
":",
"if",
"weights",
"is",
"not",
"None",
":",
"if",
"nwin",
"is",
"not",
"None",
":",
"if",
"len",
"(",
... | Return the coupling matrix of the first nwin tapers. This matrix
relates the global power spectrum to the expectation of the localized
multitaper spectrum.
Usage
-----
Mmt = x.coupling_matrix(lmax, [nwin, weights, mode])
Returns
-------
Mmt : ndarray, sh... | [
"Return",
"the",
"coupling",
"matrix",
"of",
"the",
"first",
"nwin",
"tapers",
".",
"This",
"matrix",
"relates",
"the",
"global",
"power",
"spectrum",
"to",
"the",
"expectation",
"of",
"the",
"localized",
"multitaper",
"spectrum",
"."
] | python | train |
adamchainz/django-mysql | django_mysql/models/handler.py | https://github.com/adamchainz/django-mysql/blob/967daa4245cf55c9bc5dc018e560f417c528916a/django_mysql/models/handler.py#L218-L231 | def _is_simple_query(cls, query):
"""
Inspect the internals of the Query and say if we think its WHERE clause
can be used in a HANDLER statement
"""
return (
not query.low_mark
and not query.high_mark
and not query.select
and not qu... | [
"def",
"_is_simple_query",
"(",
"cls",
",",
"query",
")",
":",
"return",
"(",
"not",
"query",
".",
"low_mark",
"and",
"not",
"query",
".",
"high_mark",
"and",
"not",
"query",
".",
"select",
"and",
"not",
"query",
".",
"group_by",
"and",
"not",
"query",
... | Inspect the internals of the Query and say if we think its WHERE clause
can be used in a HANDLER statement | [
"Inspect",
"the",
"internals",
"of",
"the",
"Query",
"and",
"say",
"if",
"we",
"think",
"its",
"WHERE",
"clause",
"can",
"be",
"used",
"in",
"a",
"HANDLER",
"statement"
] | python | train |
Jaymon/prom | prom/model.py | https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L182-L192 | def create(cls, fields=None, **fields_kwargs):
"""
create an instance of cls with the passed in fields and set it into the db
fields -- dict -- field_name keys, with their respective values
**fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also
... | [
"def",
"create",
"(",
"cls",
",",
"fields",
"=",
"None",
",",
"*",
"*",
"fields_kwargs",
")",
":",
"# NOTE -- you cannot use hydrate/populate here because populate alters modified fields",
"instance",
"=",
"cls",
"(",
"fields",
",",
"*",
"*",
"fields_kwargs",
")",
"... | create an instance of cls with the passed in fields and set it into the db
fields -- dict -- field_name keys, with their respective values
**fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also | [
"create",
"an",
"instance",
"of",
"cls",
"with",
"the",
"passed",
"in",
"fields",
"and",
"set",
"it",
"into",
"the",
"db"
] | python | train |
Esri/ArcREST | src/arcrest/common/geometry.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/geometry.py#L137-L148 | def asDictionary(self):
""" returns the object as a python dictionary """
#
template = {"x" : self._x,
"y" : self._y,
"spatialReference" : self.spatialReference
}
if not self._z is None:
template['z'] = self._z
... | [
"def",
"asDictionary",
"(",
"self",
")",
":",
"#",
"template",
"=",
"{",
"\"x\"",
":",
"self",
".",
"_x",
",",
"\"y\"",
":",
"self",
".",
"_y",
",",
"\"spatialReference\"",
":",
"self",
".",
"spatialReference",
"}",
"if",
"not",
"self",
".",
"_z",
"i... | returns the object as a python dictionary | [
"returns",
"the",
"object",
"as",
"a",
"python",
"dictionary"
] | python | train |
inspirehep/harvesting-kit | harvestingkit/ftp_utils.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L229-L253 | def rmdir(self, foldername):
""" Delete a folder from the server.
:param foldername: the folder to be deleted.
:type foldername: string
"""
current_folder = self._ftp.pwd()
try:
self.cd(foldername)
except error_perm:
print('550 Delete oper... | [
"def",
"rmdir",
"(",
"self",
",",
"foldername",
")",
":",
"current_folder",
"=",
"self",
".",
"_ftp",
".",
"pwd",
"(",
")",
"try",
":",
"self",
".",
"cd",
"(",
"foldername",
")",
"except",
"error_perm",
":",
"print",
"(",
"'550 Delete operation failed fold... | Delete a folder from the server.
:param foldername: the folder to be deleted.
:type foldername: string | [
"Delete",
"a",
"folder",
"from",
"the",
"server",
"."
] | python | valid |
ruipgil/TrackToTrip | tracktotrip/similarity.py | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L113-L136 | def closest_point(a, b, p):
"""Finds closest point in a line segment
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to find in the segment
Returns:
(float, float): x a... | [
"def",
"closest_point",
"(",
"a",
",",
"b",
",",
"p",
")",
":",
"ap",
"=",
"[",
"p",
"[",
"0",
"]",
"-",
"a",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
"-",
"a",
"[",
"1",
"]",
"]",
"ab",
"=",
"[",
"b",
"[",
"0",
"]",
"-",
"a",
"[",
... | Finds closest point in a line segment
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to find in the segment
Returns:
(float, float): x and y coordinates of the closest poi... | [
"Finds",
"closest",
"point",
"in",
"a",
"line",
"segment"
] | python | train |
HewlettPackard/python-hpOneView | hpOneView/resources/servers/server_hardware.py | https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/servers/server_hardware.py#L147-L164 | def get_ilo_sso_url(self, ip=None):
"""
Retrieves the URL to launch a Single Sign-On (SSO) session for the iLO web interface. If the server hardware is
unsupported, the resulting URL will not use SSO and the iLO web interface will prompt for credentials.
This is not supported on G7/iLO3 ... | [
"def",
"get_ilo_sso_url",
"(",
"self",
",",
"ip",
"=",
"None",
")",
":",
"uri",
"=",
"\"{}/iloSsoUrl\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"\"uri\"",
"]",
")",
"if",
"ip",
":",
"uri",
"=",
"\"{}?ip={}\"",
".",
"format",
"(",
"uri",
",",
... | Retrieves the URL to launch a Single Sign-On (SSO) session for the iLO web interface. If the server hardware is
unsupported, the resulting URL will not use SSO and the iLO web interface will prompt for credentials.
This is not supported on G7/iLO3 or earlier servers.
Args:
ip: IP ad... | [
"Retrieves",
"the",
"URL",
"to",
"launch",
"a",
"Single",
"Sign",
"-",
"On",
"(",
"SSO",
")",
"session",
"for",
"the",
"iLO",
"web",
"interface",
".",
"If",
"the",
"server",
"hardware",
"is",
"unsupported",
"the",
"resulting",
"URL",
"will",
"not",
"use"... | python | train |
saltstack/salt | salt/modules/win_service.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L320-L340 | def get_enabled():
'''
Return a list of enabled services. Enabled is defined as a service that is
marked to Auto Start.
Returns:
list: A list of enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
raw_services = _get_services()
serv... | [
"def",
"get_enabled",
"(",
")",
":",
"raw_services",
"=",
"_get_services",
"(",
")",
"services",
"=",
"set",
"(",
")",
"for",
"service",
"in",
"raw_services",
":",
"if",
"info",
"(",
"service",
"[",
"'ServiceName'",
"]",
")",
"[",
"'StartType'",
"]",
"in... | Return a list of enabled services. Enabled is defined as a service that is
marked to Auto Start.
Returns:
list: A list of enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled | [
"Return",
"a",
"list",
"of",
"enabled",
"services",
".",
"Enabled",
"is",
"defined",
"as",
"a",
"service",
"that",
"is",
"marked",
"to",
"Auto",
"Start",
"."
] | python | train |
spacetelescope/drizzlepac | drizzlepac/hlautils/astrometric_utils.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L807-L855 | def build_self_reference(filename, clean_wcs=False):
""" This function creates a reference, undistorted WCS that can be used to
apply a correction to the WCS of the input file.
Parameters
----------
filename : str
Filename of image which will be corrected, and which will form the basis
... | [
"def",
"build_self_reference",
"(",
"filename",
",",
"clean_wcs",
"=",
"False",
")",
":",
"if",
"'sipwcs'",
"in",
"filename",
":",
"sciname",
"=",
"'sipwcs'",
"else",
":",
"sciname",
"=",
"'sci'",
"wcslin",
"=",
"build_reference_wcs",
"(",
"[",
"filename",
"... | This function creates a reference, undistorted WCS that can be used to
apply a correction to the WCS of the input file.
Parameters
----------
filename : str
Filename of image which will be corrected, and which will form the basis
of the undistorted WCS.
clean_wcs : bool
Spe... | [
"This",
"function",
"creates",
"a",
"reference",
"undistorted",
"WCS",
"that",
"can",
"be",
"used",
"to",
"apply",
"a",
"correction",
"to",
"the",
"WCS",
"of",
"the",
"input",
"file",
"."
] | python | train |
tylertreat/BigQuery-Python | bigquery/client.py | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1417-L1438 | def get_all_tables(self, dataset_id, project_id=None):
"""Retrieve a list of tables for the dataset.
Parameters
----------
dataset_id : str
The dataset to retrieve table data for.
project_id: str
Unique ``str`` identifying the BigQuery project contains th... | [
"def",
"get_all_tables",
"(",
"self",
",",
"dataset_id",
",",
"project_id",
"=",
"None",
")",
":",
"tables_data",
"=",
"self",
".",
"_get_all_tables_for_dataset",
"(",
"dataset_id",
",",
"project_id",
")",
"tables",
"=",
"[",
"]",
"for",
"table",
"in",
"tabl... | Retrieve a list of tables for the dataset.
Parameters
----------
dataset_id : str
The dataset to retrieve table data for.
project_id: str
Unique ``str`` identifying the BigQuery project contains the dataset
Returns
-------
A ``list`` with... | [
"Retrieve",
"a",
"list",
"of",
"tables",
"for",
"the",
"dataset",
"."
] | python | train |
taskcluster/taskcluster-client.py | taskcluster/utils.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/utils.py#L123-L136 | def dumpJson(obj, **kwargs):
""" Match JS's JSON.stringify. When using the default seperators,
base64 encoding JSON results in \n sequences in the output. Hawk
barfs in your face if you have that in the text"""
def handleDateAndBinaryForJs(x):
if six.PY3 and isinstance(x, six.binary_type):
... | [
"def",
"dumpJson",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"handleDateAndBinaryForJs",
"(",
"x",
")",
":",
"if",
"six",
".",
"PY3",
"and",
"isinstance",
"(",
"x",
",",
"six",
".",
"binary_type",
")",
":",
"x",
"=",
"x",
".",
"decode",... | Match JS's JSON.stringify. When using the default seperators,
base64 encoding JSON results in \n sequences in the output. Hawk
barfs in your face if you have that in the text | [
"Match",
"JS",
"s",
"JSON",
".",
"stringify",
".",
"When",
"using",
"the",
"default",
"seperators",
"base64",
"encoding",
"JSON",
"results",
"in",
"\\",
"n",
"sequences",
"in",
"the",
"output",
".",
"Hawk",
"barfs",
"in",
"your",
"face",
"if",
"you",
"ha... | python | train |
log2timeline/plaso | plaso/engine/zeromq_queue.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/engine/zeromq_queue.py#L334-L371 | def PopItem(self):
"""Pops an item off the queue.
If no ZeroMQ socket has been created, one will be created the first
time this method is called.
Returns:
object: item from the queue.
Raises:
KeyboardInterrupt: if the process is sent a KeyboardInterrupt while
popping an item... | [
"def",
"PopItem",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_zmq_socket",
":",
"self",
".",
"_CreateZMQSocket",
"(",
")",
"if",
"not",
"self",
".",
"_closed_event",
"or",
"not",
"self",
".",
"_terminate_event",
":",
"raise",
"RuntimeError",
"(",
... | Pops an item off the queue.
If no ZeroMQ socket has been created, one will be created the first
time this method is called.
Returns:
object: item from the queue.
Raises:
KeyboardInterrupt: if the process is sent a KeyboardInterrupt while
popping an item.
QueueEmpty: if the... | [
"Pops",
"an",
"item",
"off",
"the",
"queue",
"."
] | python | train |
twilio/twilio-python | twilio/rest/authy/v1/service/entity/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/authy/v1/service/entity/__init__.py#L327-L341 | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: EntityContext for this EntityInstance
:rtype: twilio.rest.authy.v1.service.entity.EntityContext
... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"EntityContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"i... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: EntityContext for this EntityInstance
:rtype: twilio.rest.authy.v1.service.entity.EntityContext | [
"Generate",
"an",
"instance",
"context",
"for",
"the",
"instance",
"the",
"context",
"is",
"capable",
"of",
"performing",
"various",
"actions",
".",
"All",
"instance",
"actions",
"are",
"proxied",
"to",
"the",
"context"
] | python | train |
LuqueDaniel/pybooru | pybooru/api_moebooru.py | https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/api_moebooru.py#L370-L378 | def wiki_revert(self, title, version):
"""Function to revert a specific wiki page (Requires login) (UNTESTED).
Parameters:
title (str): The title of the wiki page to update.
version (int): The version to revert to.
"""
params = {'title': title, 'version': version... | [
"def",
"wiki_revert",
"(",
"self",
",",
"title",
",",
"version",
")",
":",
"params",
"=",
"{",
"'title'",
":",
"title",
",",
"'version'",
":",
"version",
"}",
"return",
"self",
".",
"_get",
"(",
"'wiki/revert'",
",",
"params",
",",
"method",
"=",
"'PUT... | Function to revert a specific wiki page (Requires login) (UNTESTED).
Parameters:
title (str): The title of the wiki page to update.
version (int): The version to revert to. | [
"Function",
"to",
"revert",
"a",
"specific",
"wiki",
"page",
"(",
"Requires",
"login",
")",
"(",
"UNTESTED",
")",
"."
] | python | train |
PyGithub/PyGithub | github/Repository.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/Repository.py#L2154-L2163 | def get_languages(self):
"""
:calls: `GET /repos/:owner/:repo/languages <http://developer.github.com/v3/repos>`_
:rtype: dict of string to integer
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/languages"
)
ret... | [
"def",
"get_languages",
"(",
"self",
")",
":",
"headers",
",",
"data",
"=",
"self",
".",
"_requester",
".",
"requestJsonAndCheck",
"(",
"\"GET\"",
",",
"self",
".",
"url",
"+",
"\"/languages\"",
")",
"return",
"data"
] | :calls: `GET /repos/:owner/:repo/languages <http://developer.github.com/v3/repos>`_
:rtype: dict of string to integer | [
":",
"calls",
":",
"GET",
"/",
"repos",
"/",
":",
"owner",
"/",
":",
"repo",
"/",
"languages",
"<http",
":",
"//",
"developer",
".",
"github",
".",
"com",
"/",
"v3",
"/",
"repos",
">",
"_",
":",
"rtype",
":",
"dict",
"of",
"string",
"to",
"intege... | python | train |
knipknap/SpiffWorkflow | SpiffWorkflow/specs/Trigger.py | https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/Trigger.py#L97-L103 | def deserialize(cls, serializer, wf_spec, s_state, **kwargs):
"""
Deserializes the trigger using the provided serializer.
"""
return serializer.deserialize_trigger(wf_spec,
s_state,
**kwargs) | [
"def",
"deserialize",
"(",
"cls",
",",
"serializer",
",",
"wf_spec",
",",
"s_state",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"serializer",
".",
"deserialize_trigger",
"(",
"wf_spec",
",",
"s_state",
",",
"*",
"*",
"kwargs",
")"
] | Deserializes the trigger using the provided serializer. | [
"Deserializes",
"the",
"trigger",
"using",
"the",
"provided",
"serializer",
"."
] | python | valid |
esheldon/fitsio | fitsio/header.py | https://github.com/esheldon/fitsio/blob/a6f07919f457a282fe240adad9d2c30906b71a15/fitsio/header.py#L372-L438 | def _record2card(self, record):
"""
when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
KEYSNC = 'hello ... | [
"def",
"_record2card",
"(",
"self",
",",
"record",
")",
":",
"name",
"=",
"record",
"[",
"'name'",
"]",
"value",
"=",
"record",
"[",
"'value'",
"]",
"v_isstring",
"=",
"isstring",
"(",
"value",
")",
"if",
"name",
"==",
"'COMMENT'",
":",
"# card = 'COMMEN... | when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
KEYSNC = 'hello '
KEYSC = 'hello ' / a c... | [
"when",
"we",
"add",
"new",
"records",
"they",
"don",
"t",
"have",
"a",
"card",
"this",
"sort",
"of",
"fakes",
"it",
"up",
"similar",
"to",
"what",
"cfitsio",
"does",
"just",
"for",
"display",
"purposes",
".",
"e",
".",
"g",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/qos_mpls/map_/inexp_outexp/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/qos_mpls/map_/inexp_outexp/__init__.py#L131-L152 | def _set_in_exp(self, v, load=False):
"""
Setter method for in_exp, mapped from YANG variable /qos_mpls/map/inexp_outexp/in_exp (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_in_exp is considered as a private
method. Backends looking to populate this variable... | [
"def",
"_set_in_exp",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | Setter method for in_exp, mapped from YANG variable /qos_mpls/map/inexp_outexp/in_exp (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_in_exp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_in_exp(... | [
"Setter",
"method",
"for",
"in_exp",
"mapped",
"from",
"YANG",
"variable",
"/",
"qos_mpls",
"/",
"map",
"/",
"inexp_outexp",
"/",
"in_exp",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"... | python | train |
dailymuse/oz | oz/redis/__init__.py | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/redis/__init__.py#L12-L37 | def create_connection():
"""Sets up a redis configuration"""
global _cached_connection
settings = oz.settings
if settings["redis_cache_connections"] and _cached_connection != None:
return _cached_connection
else:
conn = redis.StrictRedis(
host=settings["redis_host"],
... | [
"def",
"create_connection",
"(",
")",
":",
"global",
"_cached_connection",
"settings",
"=",
"oz",
".",
"settings",
"if",
"settings",
"[",
"\"redis_cache_connections\"",
"]",
"and",
"_cached_connection",
"!=",
"None",
":",
"return",
"_cached_connection",
"else",
":",... | Sets up a redis configuration | [
"Sets",
"up",
"a",
"redis",
"configuration"
] | python | train |
obriencj/python-javatools | javatools/opcodes.py | https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/opcodes.py#L231-L255 | def disassemble(bytecode):
"""
Generator. Disassembles Java bytecode into a sequence of (offset,
code, args) tuples
:type bytecode: bytes
"""
offset = 0
end = len(bytecode)
while offset < end:
orig_offset = offset
code = bytecode[offset]
if not isinstance(code,... | [
"def",
"disassemble",
"(",
"bytecode",
")",
":",
"offset",
"=",
"0",
"end",
"=",
"len",
"(",
"bytecode",
")",
"while",
"offset",
"<",
"end",
":",
"orig_offset",
"=",
"offset",
"code",
"=",
"bytecode",
"[",
"offset",
"]",
"if",
"not",
"isinstance",
"(",... | Generator. Disassembles Java bytecode into a sequence of (offset,
code, args) tuples
:type bytecode: bytes | [
"Generator",
".",
"Disassembles",
"Java",
"bytecode",
"into",
"a",
"sequence",
"of",
"(",
"offset",
"code",
"args",
")",
"tuples",
":",
"type",
"bytecode",
":",
"bytes"
] | python | train |
numenta/nupic | src/nupic/algorithms/backtracking_tm.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L1927-L1973 | def _inferPhase1(self, activeColumns, useStartCells):
"""
Update the inference active state from the last set of predictions
and the current bottom-up.
This looks at:
- ``infPredictedState['t-1']``
This modifies:
- ``infActiveState['t']``
:param activeColumns: (list) active bot... | [
"def",
"_inferPhase1",
"(",
"self",
",",
"activeColumns",
",",
"useStartCells",
")",
":",
"# Init to zeros to start",
"self",
".",
"infActiveState",
"[",
"'t'",
"]",
".",
"fill",
"(",
"0",
")",
"# Phase 1 - turn on predicted cells in each column receiving bottom-up",
"#... | Update the inference active state from the last set of predictions
and the current bottom-up.
This looks at:
- ``infPredictedState['t-1']``
This modifies:
- ``infActiveState['t']``
:param activeColumns: (list) active bottom-ups
:param useStartCells: (bool) If true, ignore previous ... | [
"Update",
"the",
"inference",
"active",
"state",
"from",
"the",
"last",
"set",
"of",
"predictions",
"and",
"the",
"current",
"bottom",
"-",
"up",
"."
] | python | valid |
mnooner256/pyqrcode | pyqrcode/builder.py | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L1107-L1241 | def _svg(code, version, file, scale=1, module_color='#000', background=None,
quiet_zone=4, xmldecl=True, svgns=True, title=None, svgclass='pyqrcode',
lineclass='pyqrline', omithw=False, debug=False):
"""This function writes the QR code out as an SVG document. The
code is drawn by drawing only ... | [
"def",
"_svg",
"(",
"code",
",",
"version",
",",
"file",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"'#000'",
",",
"background",
"=",
"None",
",",
"quiet_zone",
"=",
"4",
",",
"xmldecl",
"=",
"True",
",",
"svgns",
"=",
"True",
",",
"title",
... | This function writes the QR code out as an SVG document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line. The file parameter is used to
specify where to write the document to. It can eithe... | [
"This",
"function",
"writes",
"the",
"QR",
"code",
"out",
"as",
"an",
"SVG",
"document",
".",
"The",
"code",
"is",
"drawn",
"by",
"drawing",
"only",
"the",
"modules",
"corresponding",
"to",
"a",
"1",
".",
"They",
"are",
"drawn",
"using",
"a",
"line",
"... | python | train |
resync/resync | resync/client.py | https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/client.py#L799-L830 | def log_status(self, in_sync=True, incremental=False, audit=False,
same=None, created=0, updated=0, deleted=0, to_delete=0):
"""Write log message regarding status in standard form.
Split this off so all messages from baseline/audit/incremental
are written in a consistent form... | [
"def",
"log_status",
"(",
"self",
",",
"in_sync",
"=",
"True",
",",
"incremental",
"=",
"False",
",",
"audit",
"=",
"False",
",",
"same",
"=",
"None",
",",
"created",
"=",
"0",
",",
"updated",
"=",
"0",
",",
"deleted",
"=",
"0",
",",
"to_delete",
"... | Write log message regarding status in standard form.
Split this off so all messages from baseline/audit/incremental
are written in a consistent form. | [
"Write",
"log",
"message",
"regarding",
"status",
"in",
"standard",
"form",
"."
] | python | train |
sci-bots/svg-model | svg_model/data_frame.py | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/data_frame.py#L11-L44 | def get_shape_areas(df_shapes, shape_i_columns, signed=False):
'''
Return a `pandas.Series` indexed by `shape_i_columns` (i.e., each entry
corresponds to a single shape/polygon), containing the following columns
the area of each shape.
If `signed=True`, a positive area value corresponds to a clockw... | [
"def",
"get_shape_areas",
"(",
"df_shapes",
",",
"shape_i_columns",
",",
"signed",
"=",
"False",
")",
":",
"# Make a copy of the SVG data frame since we need to add columns to it.",
"df_i",
"=",
"df_shapes",
".",
"copy",
"(",
")",
"df_i",
"[",
"'vertex_count'",
"]",
"... | Return a `pandas.Series` indexed by `shape_i_columns` (i.e., each entry
corresponds to a single shape/polygon), containing the following columns
the area of each shape.
If `signed=True`, a positive area value corresponds to a clockwise loop,
whereas a negative area value corresponds to a counter-clockw... | [
"Return",
"a",
"pandas",
".",
"Series",
"indexed",
"by",
"shape_i_columns",
"(",
"i",
".",
"e",
".",
"each",
"entry",
"corresponds",
"to",
"a",
"single",
"shape",
"/",
"polygon",
")",
"containing",
"the",
"following",
"columns",
"the",
"area",
"of",
"each"... | python | train |
tompollard/tableone | tableone.py | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L311-L332 | def _tukey(self,x,threshold):
"""
Count outliers according to Tukey's rule.
Where Q1 is the lower quartile and Q3 is the upper quartile,
an outlier is an observation outside of the range:
[Q1 - k(Q3 - Q1), Q3 + k(Q3 - Q1)]
k = 1.5 indicates an outlier
k = 3.0 i... | [
"def",
"_tukey",
"(",
"self",
",",
"x",
",",
"threshold",
")",
":",
"vals",
"=",
"x",
".",
"values",
"[",
"~",
"np",
".",
"isnan",
"(",
"x",
".",
"values",
")",
"]",
"try",
":",
"q1",
",",
"q3",
"=",
"np",
".",
"percentile",
"(",
"vals",
",",... | Count outliers according to Tukey's rule.
Where Q1 is the lower quartile and Q3 is the upper quartile,
an outlier is an observation outside of the range:
[Q1 - k(Q3 - Q1), Q3 + k(Q3 - Q1)]
k = 1.5 indicates an outlier
k = 3.0 indicates an outlier that is "far out" | [
"Count",
"outliers",
"according",
"to",
"Tukey",
"s",
"rule",
"."
] | python | train |
Workiva/furious | furious/async.py | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L263-L268 | def set_execution_context(self, execution_context):
"""Set the ExecutionContext this async is executing under."""
if self._execution_context:
raise errors.AlreadyInContextError
self._execution_context = execution_context | [
"def",
"set_execution_context",
"(",
"self",
",",
"execution_context",
")",
":",
"if",
"self",
".",
"_execution_context",
":",
"raise",
"errors",
".",
"AlreadyInContextError",
"self",
".",
"_execution_context",
"=",
"execution_context"
] | Set the ExecutionContext this async is executing under. | [
"Set",
"the",
"ExecutionContext",
"this",
"async",
"is",
"executing",
"under",
"."
] | python | train |
salu133445/pypianoroll | pypianoroll/multitrack.py | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L830-L884 | def save(self, filename, compressed=True):
"""
Save the multitrack pianoroll to a (compressed) npz file, which can be
later loaded by :meth:`pypianoroll.Multitrack.load`.
Notes
-----
To reduce the file size, the pianorolls are first converted to instances
of scip... | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"compressed",
"=",
"True",
")",
":",
"def",
"update_sparse",
"(",
"target_dict",
",",
"sparse_matrix",
",",
"name",
")",
":",
"\"\"\"Turn `sparse_matrix` into a scipy.sparse.csc_matrix and update\n its component... | Save the multitrack pianoroll to a (compressed) npz file, which can be
later loaded by :meth:`pypianoroll.Multitrack.load`.
Notes
-----
To reduce the file size, the pianorolls are first converted to instances
of scipy.sparse.csc_matrix, whose component arrays are then collected
... | [
"Save",
"the",
"multitrack",
"pianoroll",
"to",
"a",
"(",
"compressed",
")",
"npz",
"file",
"which",
"can",
"be",
"later",
"loaded",
"by",
":",
"meth",
":",
"pypianoroll",
".",
"Multitrack",
".",
"load",
"."
] | python | train |
awslabs/serverless-application-model | samtranslator/plugins/policies/policy_templates_plugin.py | https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/policies/policy_templates_plugin.py#L31-L78 | def on_before_transform_resource(self, logical_id, resource_type, resource_properties):
"""
Hook method that gets called before "each" SAM resource gets processed
:param string logical_id: Logical ID of the resource being processed
:param string resource_type: Type of the resource being... | [
"def",
"on_before_transform_resource",
"(",
"self",
",",
"logical_id",
",",
"resource_type",
",",
"resource_properties",
")",
":",
"if",
"not",
"self",
".",
"_is_supported",
"(",
"resource_type",
")",
":",
"return",
"function_policies",
"=",
"FunctionPolicies",
"(",... | Hook method that gets called before "each" SAM resource gets processed
:param string logical_id: Logical ID of the resource being processed
:param string resource_type: Type of the resource being processed
:param dict resource_properties: Properties of the resource
:return: Nothing | [
"Hook",
"method",
"that",
"gets",
"called",
"before",
"each",
"SAM",
"resource",
"gets",
"processed"
] | python | train |
Nic30/hwtGraph | hwtGraph/elk/fromHwt/flattenPorts.py | https://github.com/Nic30/hwtGraph/blob/6b7d4fdd759f263a0fdd2736f02f123e44e4354f/hwtGraph/elk/fromHwt/flattenPorts.py#L18-L26 | def _flattenPortsSide(side: List[LNode]) -> List[LNode]:
"""
Flatten hierarchical ports on node side
"""
new_side = []
for i in side:
for new_p in flattenPort(i):
new_side.append(new_p)
return new_side | [
"def",
"_flattenPortsSide",
"(",
"side",
":",
"List",
"[",
"LNode",
"]",
")",
"->",
"List",
"[",
"LNode",
"]",
":",
"new_side",
"=",
"[",
"]",
"for",
"i",
"in",
"side",
":",
"for",
"new_p",
"in",
"flattenPort",
"(",
"i",
")",
":",
"new_side",
".",
... | Flatten hierarchical ports on node side | [
"Flatten",
"hierarchical",
"ports",
"on",
"node",
"side"
] | python | train |
jstitch/MambuPy | MambuPy/rest/mambuclient.py | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuclient.py#L41-L109 | def preprocess(self):
"""Preprocessing.
Flattens the object. Important data comes on the 'client'
dictionary inside of the response. Instead, every element of the
'client' dictionary is taken out to the main attrs dictionary.
Removes repeated chars from firstName, middleName an... | [
"def",
"preprocess",
"(",
"self",
")",
":",
"super",
"(",
"MambuClient",
",",
"self",
")",
".",
"preprocess",
"(",
")",
"try",
":",
"for",
"k",
",",
"v",
"in",
"self",
"[",
"'client'",
"]",
".",
"items",
"(",
")",
":",
"self",
"[",
"k",
"]",
"=... | Preprocessing.
Flattens the object. Important data comes on the 'client'
dictionary inside of the response. Instead, every element of the
'client' dictionary is taken out to the main attrs dictionary.
Removes repeated chars from firstName, middleName and lastName
fields. Adds a... | [
"Preprocessing",
"."
] | python | train |
saltstack/salt | salt/modules/boto_vpc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2116-L2181 | def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None,
gateway_id=None, instance_id=None, interface_id=None, tags=None,
region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None):
'''
Checks if a route exists.
.. versiona... | [
"def",
"route_exists",
"(",
"destination_cidr_block",
",",
"route_table_name",
"=",
"None",
",",
"route_table_id",
"=",
"None",
",",
"gateway_id",
"=",
"None",
",",
"instance_id",
"=",
"None",
",",
"interface_id",
"=",
"None",
",",
"tags",
"=",
"None",
",",
... | Checks if a route exists.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' | [
"Checks",
"if",
"a",
"route",
"exists",
"."
] | python | train |
manns/pyspread | pyspread/src/lib/vlc.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L4756-L4765 | def libvlc_media_list_event_manager(p_ml):
'''Get libvlc_event_manager from this media list instance.
The p_event_manager is immutable, so you don't have to hold the lock.
@param p_ml: a media list instance.
@return: libvlc_event_manager.
'''
f = _Cfunctions.get('libvlc_media_list_event_manager'... | [
"def",
"libvlc_media_list_event_manager",
"(",
"p_ml",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_list_event_manager'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_list_event_manager'",
",",
"(",
"(",
"1",
",",
")",
",",
")"... | Get libvlc_event_manager from this media list instance.
The p_event_manager is immutable, so you don't have to hold the lock.
@param p_ml: a media list instance.
@return: libvlc_event_manager. | [
"Get",
"libvlc_event_manager",
"from",
"this",
"media",
"list",
"instance",
".",
"The",
"p_event_manager",
"is",
"immutable",
"so",
"you",
"don",
"t",
"have",
"to",
"hold",
"the",
"lock",
"."
] | python | train |
chrisrink10/basilisp | src/basilisp/lang/multifn.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/multifn.py#L46-L54 | def get_method(self, key: T) -> Optional[Method]:
"""Return the method which would handle this dispatch key or
None if no method defined for this key and no default."""
method_cache = self.methods
# The 'type: ignore' comment below silences a spurious MyPy error
# about having a ... | [
"def",
"get_method",
"(",
"self",
",",
"key",
":",
"T",
")",
"->",
"Optional",
"[",
"Method",
"]",
":",
"method_cache",
"=",
"self",
".",
"methods",
"# The 'type: ignore' comment below silences a spurious MyPy error",
"# about having a return statement in a method which doe... | Return the method which would handle this dispatch key or
None if no method defined for this key and no default. | [
"Return",
"the",
"method",
"which",
"would",
"handle",
"this",
"dispatch",
"key",
"or",
"None",
"if",
"no",
"method",
"defined",
"for",
"this",
"key",
"and",
"no",
"default",
"."
] | python | test |
project-ncl/pnc-cli | pnc_cli/products.py | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/products.py#L116-L122 | def list_products(page_size=200, page_index=0, sort="", q=""):
"""
List all Products
"""
content = list_products_raw(page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | [
"def",
"list_products",
"(",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"content",
"=",
"list_products_raw",
"(",
"page_size",
",",
"page_index",
",",
"sort",
",",
"q",
")",
"if",
... | List all Products | [
"List",
"all",
"Products"
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py#L362-L378 | def get_interface_switchport_output_switchport_acceptable_frame_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_in... | [
"def",
"get_interface_switchport_output_switchport_acceptable_frame_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_interface_switchport",
"=",
"ET",
".",
"Element",
"(",
"\"get_interface_switchp... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
Alignak-monitoring/alignak | alignak/objects/satellitelink.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/satellitelink.py#L770-L777 | def wait_new_conf(self):
"""Send a HTTP request to the satellite (GET /wait_new_conf)
:return: True if wait new conf, otherwise False
:rtype: bool
"""
logger.debug("Wait new configuration for %s, %s %s", self.name, self.alive, self.reachable)
return self.con.get('_wait_n... | [
"def",
"wait_new_conf",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Wait new configuration for %s, %s %s\"",
",",
"self",
".",
"name",
",",
"self",
".",
"alive",
",",
"self",
".",
"reachable",
")",
"return",
"self",
".",
"con",
".",
"get",
"(",
... | Send a HTTP request to the satellite (GET /wait_new_conf)
:return: True if wait new conf, otherwise False
:rtype: bool | [
"Send",
"a",
"HTTP",
"request",
"to",
"the",
"satellite",
"(",
"GET",
"/",
"wait_new_conf",
")"
] | python | train |
numenta/nupic | src/nupic/algorithms/fdrutilities.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L278-L315 | def generateSequences(nPatterns=10, patternLen=500, patternActivity=50,
hubs=[2,6], seqLength=[5,6,7],
nSimpleSequences=50, nHubSequences=50):
"""
Generate a set of simple and hub sequences. A simple sequence contains
a randomly chosen set of elements from 0 to 'nCoinc-1'... | [
"def",
"generateSequences",
"(",
"nPatterns",
"=",
"10",
",",
"patternLen",
"=",
"500",
",",
"patternActivity",
"=",
"50",
",",
"hubs",
"=",
"[",
"2",
",",
"6",
"]",
",",
"seqLength",
"=",
"[",
"5",
",",
"6",
",",
"7",
"]",
",",
"nSimpleSequences",
... | Generate a set of simple and hub sequences. A simple sequence contains
a randomly chosen set of elements from 0 to 'nCoinc-1'. A hub sequence
always contains a hub element in the middle of it.
Parameters:
-----------------------------------------------
nPatterns: the number of patterns to use in the s... | [
"Generate",
"a",
"set",
"of",
"simple",
"and",
"hub",
"sequences",
".",
"A",
"simple",
"sequence",
"contains",
"a",
"randomly",
"chosen",
"set",
"of",
"elements",
"from",
"0",
"to",
"nCoinc",
"-",
"1",
".",
"A",
"hub",
"sequence",
"always",
"contains",
"... | python | valid |
googledatalab/pydatalab | google/datalab/ml/_tensorboard.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_tensorboard.py#L82-L93 | def stop(pid):
"""Shut down a specific process.
Args:
pid: the pid of the process to shutdown.
"""
if psutil.pid_exists(pid):
try:
p = psutil.Process(pid)
p.kill()
except Exception:
pass | [
"def",
"stop",
"(",
"pid",
")",
":",
"if",
"psutil",
".",
"pid_exists",
"(",
"pid",
")",
":",
"try",
":",
"p",
"=",
"psutil",
".",
"Process",
"(",
"pid",
")",
"p",
".",
"kill",
"(",
")",
"except",
"Exception",
":",
"pass"
] | Shut down a specific process.
Args:
pid: the pid of the process to shutdown. | [
"Shut",
"down",
"a",
"specific",
"process",
"."
] | python | train |
pygobject/pgi | pgi/overrides/GObject.py | https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/GObject.py#L458-L476 | def signal_handler_block(obj, handler_id):
"""Blocks the signal handler from being invoked until
handler_unblock() is called.
:param GObject.Object obj:
Object instance to block handlers for.
:param int handler_id:
Id of signal to block.
:returns:
A context manager which opt... | [
"def",
"signal_handler_block",
"(",
"obj",
",",
"handler_id",
")",
":",
"GObjectModule",
".",
"signal_handler_block",
"(",
"obj",
",",
"handler_id",
")",
"return",
"_HandlerBlockManager",
"(",
"obj",
",",
"handler_id",
")"
] | Blocks the signal handler from being invoked until
handler_unblock() is called.
:param GObject.Object obj:
Object instance to block handlers for.
:param int handler_id:
Id of signal to block.
:returns:
A context manager which optionally can be used to
automatically unblo... | [
"Blocks",
"the",
"signal",
"handler",
"from",
"being",
"invoked",
"until",
"handler_unblock",
"()",
"is",
"called",
"."
] | python | train |
ubernostrum/django-soapbox | soapbox/models.py | https://github.com/ubernostrum/django-soapbox/blob/f9189e1ddf47175f2392b92c7a0a902817ee1e93/soapbox/models.py#L36-L45 | def match(self, url):
"""
Return a list of all active Messages which match the given
URL.
"""
return list({
message for message in self.active() if
message.is_global or message.match(url)
}) | [
"def",
"match",
"(",
"self",
",",
"url",
")",
":",
"return",
"list",
"(",
"{",
"message",
"for",
"message",
"in",
"self",
".",
"active",
"(",
")",
"if",
"message",
".",
"is_global",
"or",
"message",
".",
"match",
"(",
"url",
")",
"}",
")"
] | Return a list of all active Messages which match the given
URL. | [
"Return",
"a",
"list",
"of",
"all",
"active",
"Messages",
"which",
"match",
"the",
"given",
"URL",
"."
] | python | train |
googledatalab/pydatalab | google/datalab/storage/commands/_storage.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L34-L51 | def _extract_gcs_api_response_error(message):
""" A helper function to extract user-friendly error messages from service exceptions.
Args:
message: An error message from an exception. If this is from our HTTP client code, it
will actually be a tuple.
Returns:
A modified version of the message th... | [
"def",
"_extract_gcs_api_response_error",
"(",
"message",
")",
":",
"try",
":",
"if",
"len",
"(",
"message",
")",
"==",
"3",
":",
"# Try treat the last part as JSON",
"data",
"=",
"json",
".",
"loads",
"(",
"message",
"[",
"2",
"]",
")",
"return",
"data",
... | A helper function to extract user-friendly error messages from service exceptions.
Args:
message: An error message from an exception. If this is from our HTTP client code, it
will actually be a tuple.
Returns:
A modified version of the message that is less cryptic. | [
"A",
"helper",
"function",
"to",
"extract",
"user",
"-",
"friendly",
"error",
"messages",
"from",
"service",
"exceptions",
"."
] | python | train |
AtteqCom/zsl | src/zsl/utils/nginx_push_helper.py | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/nginx_push_helper.py#L43-L50 | def push(self, channel_id, data):
"""Push message with POST ``data`` for ``channel_id``
"""
channel_path = self.channel_path(channel_id)
response = requests.post(channel_path, data)
return response.json() | [
"def",
"push",
"(",
"self",
",",
"channel_id",
",",
"data",
")",
":",
"channel_path",
"=",
"self",
".",
"channel_path",
"(",
"channel_id",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"channel_path",
",",
"data",
")",
"return",
"response",
".",
"j... | Push message with POST ``data`` for ``channel_id`` | [
"Push",
"message",
"with",
"POST",
"data",
"for",
"channel_id"
] | python | train |
StackStorm/pybind | pybind/slxos/v17r_1_01a/system_monitor/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/system_monitor/__init__.py#L275-L296 | def _set_MM(self, v, load=False):
"""
Setter method for MM, mapped from YANG variable /system_monitor/MM (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_MM is considered as a private
method. Backends looking to populate this variable should
do so via ... | [
"def",
"_set_MM",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
"=... | Setter method for MM, mapped from YANG variable /system_monitor/MM (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_MM is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_MM() directly. | [
"Setter",
"method",
"for",
"MM",
"mapped",
"from",
"YANG",
"variable",
"/",
"system_monitor",
"/",
"MM",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
... | python | train |
kibitzr/kibitzr | kibitzr/cli.py | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/cli.py#L61-L65 | def once(ctx, name):
"""Run kibitzr checks once and exit"""
from kibitzr.app import Application
app = Application()
sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) | [
"def",
"once",
"(",
"ctx",
",",
"name",
")",
":",
"from",
"kibitzr",
".",
"app",
"import",
"Application",
"app",
"=",
"Application",
"(",
")",
"sys",
".",
"exit",
"(",
"app",
".",
"run",
"(",
"once",
"=",
"True",
",",
"log_level",
"=",
"ctx",
".",
... | Run kibitzr checks once and exit | [
"Run",
"kibitzr",
"checks",
"once",
"and",
"exit"
] | python | train |
jobovy/galpy | galpy/potential/SpiralArmsPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/SpiralArmsPotential.py#L585-L590 | def _dD_dR(self, R):
"""Return numpy array of dD/dR from D1 up to and including Dn."""
HNn_R_sina = self._HNn / R / self._sin_alpha
return HNn_R_sina * (0.3 * (HNn_R_sina + 0.3 * HNn_R_sina**2. + 1) / R / (0.3 * HNn_R_sina + 1)**2
- (1/R * (1 + 0.6 * HNn_R_sina) / (... | [
"def",
"_dD_dR",
"(",
"self",
",",
"R",
")",
":",
"HNn_R_sina",
"=",
"self",
".",
"_HNn",
"/",
"R",
"/",
"self",
".",
"_sin_alpha",
"return",
"HNn_R_sina",
"*",
"(",
"0.3",
"*",
"(",
"HNn_R_sina",
"+",
"0.3",
"*",
"HNn_R_sina",
"**",
"2.",
"+",
"1"... | Return numpy array of dD/dR from D1 up to and including Dn. | [
"Return",
"numpy",
"array",
"of",
"dD",
"/",
"dR",
"from",
"D1",
"up",
"to",
"and",
"including",
"Dn",
"."
] | python | train |
rndusr/torf | torf/_torrent.py | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L707-L718 | def convert(self):
"""
Return :attr:`metainfo` with all keys encoded to :class:`bytes` and all
values encoded to :class:`bytes`, :class:`int`, :class:`list` or
:class:`OrderedDict`
:raises MetainfoError: on values that cannot be converted properly
"""
try:
... | [
"def",
"convert",
"(",
"self",
")",
":",
"try",
":",
"return",
"utils",
".",
"encode_dict",
"(",
"self",
".",
"metainfo",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"error",
".",
"MetainfoError",
"(",
"str",
"(",
"e",
")",
")"
] | Return :attr:`metainfo` with all keys encoded to :class:`bytes` and all
values encoded to :class:`bytes`, :class:`int`, :class:`list` or
:class:`OrderedDict`
:raises MetainfoError: on values that cannot be converted properly | [
"Return",
":",
"attr",
":",
"metainfo",
"with",
"all",
"keys",
"encoded",
"to",
":",
"class",
":",
"bytes",
"and",
"all",
"values",
"encoded",
"to",
":",
"class",
":",
"bytes",
":",
"class",
":",
"int",
":",
"class",
":",
"list",
"or",
":",
"class",
... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.