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 |
|---|---|---|---|---|---|---|---|---|
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1977-L1983 | def clear_threads(self):
"""
Clears the threads snapshot.
"""
for aThread in compat.itervalues(self.__threadDict):
aThread.clear()
self.__threadDict = dict() | [
"def",
"clear_threads",
"(",
"self",
")",
":",
"for",
"aThread",
"in",
"compat",
".",
"itervalues",
"(",
"self",
".",
"__threadDict",
")",
":",
"aThread",
".",
"clear",
"(",
")",
"self",
".",
"__threadDict",
"=",
"dict",
"(",
")"
] | Clears the threads snapshot. | [
"Clears",
"the",
"threads",
"snapshot",
"."
] | python | train |
Avsecz/kopt | kopt/hyopt.py | https://github.com/Avsecz/kopt/blob/fe4f929c8938590845306a759547daa5ba8bd7a9/kopt/hyopt.py#L129-L143 | def best_trial_tid(self, rank=0):
"""Get tid of the best trial
rank=0 means the best model
rank=1 means second best
...
"""
candidates = [t for t in self.trials
if t['result']['status'] == STATUS_OK]
if len(candidates) == 0:
retu... | [
"def",
"best_trial_tid",
"(",
"self",
",",
"rank",
"=",
"0",
")",
":",
"candidates",
"=",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"trials",
"if",
"t",
"[",
"'result'",
"]",
"[",
"'status'",
"]",
"==",
"STATUS_OK",
"]",
"if",
"len",
"(",
"candidate... | Get tid of the best trial
rank=0 means the best model
rank=1 means second best
... | [
"Get",
"tid",
"of",
"the",
"best",
"trial"
] | python | train |
sci-bots/mpm | mpm/api.py | https://github.com/sci-bots/mpm/blob/a69651cda4b37ee6b17df4fe0809249e7f4dc536/mpm/api.py#L57-L91 | def _save_action(extra_context=None):
'''
Save list of revisions revisions for active Conda environment.
.. versionchanged:: 0.18
Compress action revision files using ``bz2`` to save disk space.
Parameters
----------
extra_context : dict, optional
Extra content to store in stor... | [
"def",
"_save_action",
"(",
"extra_context",
"=",
"None",
")",
":",
"# Get list of revisions to Conda environment since creation.",
"revisions_js",
"=",
"ch",
".",
"conda_exec",
"(",
"'list'",
",",
"'--revisions'",
",",
"'--json'",
",",
"verbose",
"=",
"False",
")",
... | Save list of revisions revisions for active Conda environment.
.. versionchanged:: 0.18
Compress action revision files using ``bz2`` to save disk space.
Parameters
----------
extra_context : dict, optional
Extra content to store in stored action revision.
Returns
-------
p... | [
"Save",
"list",
"of",
"revisions",
"revisions",
"for",
"active",
"Conda",
"environment",
"."
] | python | train |
Opentrons/opentrons | api/src/opentrons/protocol_api/contexts.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/contexts.py#L650-L683 | def mix(self,
repetitions: int = 1,
volume: float = None,
location: Union[types.Location, Well] = None,
rate: float = 1.0) -> 'InstrumentContext':
"""
Mix a volume of liquid (uL) using this pipette.
If no location is specified, the pipette will mix... | [
"def",
"mix",
"(",
"self",
",",
"repetitions",
":",
"int",
"=",
"1",
",",
"volume",
":",
"float",
"=",
"None",
",",
"location",
":",
"Union",
"[",
"types",
".",
"Location",
",",
"Well",
"]",
"=",
"None",
",",
"rate",
":",
"float",
"=",
"1.0",
")"... | Mix a volume of liquid (uL) using this pipette.
If no location is specified, the pipette will mix from its current
position. If no Volume is passed, 'mix' will default to its max_volume.
:param repetitions: how many times the pipette should mix (default: 1)
:param volume: number of micr... | [
"Mix",
"a",
"volume",
"of",
"liquid",
"(",
"uL",
")",
"using",
"this",
"pipette",
".",
"If",
"no",
"location",
"is",
"specified",
"the",
"pipette",
"will",
"mix",
"from",
"its",
"current",
"position",
".",
"If",
"no",
"Volume",
"is",
"passed",
"mix",
"... | python | train |
pydata/xarray | xarray/core/computation.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/computation.py#L663-L680 | def apply_array_ufunc(func, *args, dask='forbidden'):
"""Apply a ndarray level function over ndarray objects."""
if any(isinstance(arg, dask_array_type) for arg in args):
if dask == 'forbidden':
raise ValueError('apply_ufunc encountered a dask array on an '
'argu... | [
"def",
"apply_array_ufunc",
"(",
"func",
",",
"*",
"args",
",",
"dask",
"=",
"'forbidden'",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"arg",
",",
"dask_array_type",
")",
"for",
"arg",
"in",
"args",
")",
":",
"if",
"dask",
"==",
"'forbidden'",
":",... | Apply a ndarray level function over ndarray objects. | [
"Apply",
"a",
"ndarray",
"level",
"function",
"over",
"ndarray",
"objects",
"."
] | python | train |
allelos/vectors | vectors/vectors.py | https://github.com/allelos/vectors/blob/55db2a7e489ae5f4380e70b3c5b7a6ce39de5cee/vectors/vectors.py#L130-L134 | def sum(self, vector):
"""Return a Vector instance as the vector sum of two vectors."""
return self.from_list(
[x + vector.vector[i] for i, x in self.to_list()]
) | [
"def",
"sum",
"(",
"self",
",",
"vector",
")",
":",
"return",
"self",
".",
"from_list",
"(",
"[",
"x",
"+",
"vector",
".",
"vector",
"[",
"i",
"]",
"for",
"i",
",",
"x",
"in",
"self",
".",
"to_list",
"(",
")",
"]",
")"
] | Return a Vector instance as the vector sum of two vectors. | [
"Return",
"a",
"Vector",
"instance",
"as",
"the",
"vector",
"sum",
"of",
"two",
"vectors",
"."
] | python | train |
timothydmorton/isochrones | isochrones/starmodel_old.py | https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L1668-L1711 | def maxlike(self,nseeds=50):
"""Returns the best-fit parameters, choosing the best of multiple starting guesses
:param nseeds: (optional)
Number of starting guesses, uniformly distributed throughout
allowed ranges. Default=50.
:return:
list of best-fit para... | [
"def",
"maxlike",
"(",
"self",
",",
"nseeds",
"=",
"50",
")",
":",
"mA_0",
",",
"age0",
",",
"feh0",
"=",
"self",
".",
"ic",
".",
"random_points",
"(",
"nseeds",
")",
"mB_0",
",",
"foo1",
",",
"foo2",
"=",
"self",
".",
"ic",
".",
"random_points",
... | Returns the best-fit parameters, choosing the best of multiple starting guesses
:param nseeds: (optional)
Number of starting guesses, uniformly distributed throughout
allowed ranges. Default=50.
:return:
list of best-fit parameters: ``[mA,mB,age,feh,[distance,A_V]]... | [
"Returns",
"the",
"best",
"-",
"fit",
"parameters",
"choosing",
"the",
"best",
"of",
"multiple",
"starting",
"guesses"
] | python | train |
bjmorgan/lattice_mc | lattice_mc/simulation.py | https://github.com/bjmorgan/lattice_mc/blob/7fa7be85f2f23a2d8dfd0830ecdb89d0dbf2bfd5/lattice_mc/simulation.py#L135-L150 | def is_initialised( self ):
"""
Check whether the simulation has been initialised.
Args:
None
Returns:
None
"""
if not self.lattice:
raise AttributeError('Running a simulation needs the lattice to be initialised')
if not self.... | [
"def",
"is_initialised",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"lattice",
":",
"raise",
"AttributeError",
"(",
"'Running a simulation needs the lattice to be initialised'",
")",
"if",
"not",
"self",
".",
"atoms",
":",
"raise",
"AttributeError",
"(",
"'R... | Check whether the simulation has been initialised.
Args:
None
Returns:
None | [
"Check",
"whether",
"the",
"simulation",
"has",
"been",
"initialised",
"."
] | python | train |
tdryer/hangups | hangups/conversation_event.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation_event.py#L168-L171 | def segments(self):
"""List of :class:`ChatMessageSegment` in message (:class:`list`)."""
seg_list = self._event.chat_message.message_content.segment
return [ChatMessageSegment.deserialize(seg) for seg in seg_list] | [
"def",
"segments",
"(",
"self",
")",
":",
"seg_list",
"=",
"self",
".",
"_event",
".",
"chat_message",
".",
"message_content",
".",
"segment",
"return",
"[",
"ChatMessageSegment",
".",
"deserialize",
"(",
"seg",
")",
"for",
"seg",
"in",
"seg_list",
"]"
] | List of :class:`ChatMessageSegment` in message (:class:`list`). | [
"List",
"of",
":",
"class",
":",
"ChatMessageSegment",
"in",
"message",
"(",
":",
"class",
":",
"list",
")",
"."
] | python | valid |
trp07/messages | messages/telegram.py | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/telegram.py#L146-L161 | def _send_content(self, method="/sendMessage"):
"""send via HTTP Post."""
url = self.base_url + method
try:
resp = requests.post(url, json=self.message)
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
raise MessageSendError(e)
... | [
"def",
"_send_content",
"(",
"self",
",",
"method",
"=",
"\"/sendMessage\"",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"method",
"try",
":",
"resp",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"json",
"=",
"self",
".",
"message",
")",
"r... | send via HTTP Post. | [
"send",
"via",
"HTTP",
"Post",
"."
] | python | test |
Clinical-Genomics/scout | scout/parse/omim.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/parse/omim.py#L321-L364 | def get_mim_phenotypes(genemap_lines):
"""Get a dictionary with phenotypes
Use the mim numbers for phenotypes as keys and phenotype information as
values.
Args:
genemap_lines(iterable(str))
Returns:
phenotypes_found(dict): A dictionary with mim_numbers as keys and
... | [
"def",
"get_mim_phenotypes",
"(",
"genemap_lines",
")",
":",
"# Set with all omim numbers that are phenotypes",
"# Parsed from mim2gene.txt",
"phenotype_mims",
"=",
"set",
"(",
")",
"phenotypes_found",
"=",
"{",
"}",
"# Genemap is a file with one entry per gene.",
"# Each line ho... | Get a dictionary with phenotypes
Use the mim numbers for phenotypes as keys and phenotype information as
values.
Args:
genemap_lines(iterable(str))
Returns:
phenotypes_found(dict): A dictionary with mim_numbers as keys and
dictionaries with phenotype information as v... | [
"Get",
"a",
"dictionary",
"with",
"phenotypes",
"Use",
"the",
"mim",
"numbers",
"for",
"phenotypes",
"as",
"keys",
"and",
"phenotype",
"information",
"as",
"values",
"."
] | python | test |
blockstack/blockstack-core | blockstack/blockstackd.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L95-L133 | def get_bitcoind( new_bitcoind_opts=None, reset=False, new=False ):
"""
Get or instantiate our bitcoind client.
Optionally re-set the bitcoind options.
"""
global bitcoind
if reset:
bitcoind = None
elif not new and bitcoind is not None:
return bitcoind
if new or bitcoind is None:... | [
"def",
"get_bitcoind",
"(",
"new_bitcoind_opts",
"=",
"None",
",",
"reset",
"=",
"False",
",",
"new",
"=",
"False",
")",
":",
"global",
"bitcoind",
"if",
"reset",
":",
"bitcoind",
"=",
"None",
"elif",
"not",
"new",
"and",
"bitcoind",
"is",
"not",
"None",... | Get or instantiate our bitcoind client.
Optionally re-set the bitcoind options. | [
"Get",
"or",
"instantiate",
"our",
"bitcoind",
"client",
".",
"Optionally",
"re",
"-",
"set",
"the",
"bitcoind",
"options",
"."
] | python | train |
saltstack/salt | salt/modules/boto_elb.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L332-L354 | def delete_listeners(name, ports, region=None, key=None, keyid=None,
profile=None):
'''
Delete listeners on an ELB.
CLI example:
.. code-block:: bash
salt myminion boto_elb.delete_listeners myelb '[80,443]'
'''
conn = _get_conn(region=region, key=key, keyid=keyid,... | [
"def",
"delete_listeners",
"(",
"name",
",",
"ports",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"k... | Delete listeners on an ELB.
CLI example:
.. code-block:: bash
salt myminion boto_elb.delete_listeners myelb '[80,443]' | [
"Delete",
"listeners",
"on",
"an",
"ELB",
"."
] | python | train |
brbsix/subnuker | subnuker.py | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L99-L117 | def open(self):
"""Open the subtitle file into an Aeidon project."""
try:
self.project.open_main(self.filename)
except UnicodeDecodeError:
with open(self.filename, 'rb') as openfile:
encoding = get_encoding(openfile.read())
try:
... | [
"def",
"open",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"project",
".",
"open_main",
"(",
"self",
".",
"filename",
")",
"except",
"UnicodeDecodeError",
":",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'rb'",
")",
"as",
"openfile",
":",
... | Open the subtitle file into an Aeidon project. | [
"Open",
"the",
"subtitle",
"file",
"into",
"an",
"Aeidon",
"project",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_vswitch.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_vswitch.py#L323-L334 | def get_vnetwork_vms_output_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_vms = ET.Element("get_vnetwork_vms")
config = get_vnetwork_vms
output = ET.SubElement(get_vnetwork_vms, "output")
instance_id = ET.SubEle... | [
"def",
"get_vnetwork_vms_output_instance_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_vms",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_vms\"",
")",
"config",
"=",
"get_vnet... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
Azure/azure-sdk-for-python | azure-servicemanagement-legacy/azure/servicemanagement/servicemanagementservice.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/servicemanagementservice.py#L2290-L2340 | def update_os_image_from_image_reference(self, image_name, os_image):
'''
Updates metadata elements from a given OS image reference.
image_name:
The name of the image to update.
os_image:
An instance of OSImage class.
os_image.label: Optional. Specifies a... | [
"def",
"update_os_image_from_image_reference",
"(",
"self",
",",
"image_name",
",",
"os_image",
")",
":",
"_validate_not_none",
"(",
"'image_name'",
",",
"image_name",
")",
"_validate_not_none",
"(",
"'os_image'",
",",
"os_image",
")",
"return",
"self",
".",
"_perfo... | Updates metadata elements from a given OS image reference.
image_name:
The name of the image to update.
os_image:
An instance of OSImage class.
os_image.label: Optional. Specifies an identifier for the image.
os_image.description: Optional. Specifies the descript... | [
"Updates",
"metadata",
"elements",
"from",
"a",
"given",
"OS",
"image",
"reference",
"."
] | python | test |
fabioz/PyDev.Debugger | third_party/isort_container/isort/isort.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/isort_container/isort/isort.py#L322-L327 | def _add_comments(self, comments, original_string=""):
"""
Returns a string with comments added
"""
return comments and "{0} # {1}".format(self._strip_comments(original_string)[0],
"; ".join(comments)) or original_string | [
"def",
"_add_comments",
"(",
"self",
",",
"comments",
",",
"original_string",
"=",
"\"\"",
")",
":",
"return",
"comments",
"and",
"\"{0} # {1}\"",
".",
"format",
"(",
"self",
".",
"_strip_comments",
"(",
"original_string",
")",
"[",
"0",
"]",
",",
"\"; \"",... | Returns a string with comments added | [
"Returns",
"a",
"string",
"with",
"comments",
"added"
] | python | train |
thespacedoctor/rockAtlas | rockAtlas/positions/pyephemPositions.py | https://github.com/thespacedoctor/rockAtlas/blob/062ecaa95ab547efda535aa33165944f13c621de/rockAtlas/positions/pyephemPositions.py#L93-L141 | def get(self, singleSnapshot=False):
"""
*geneate the pyephem positions*
**Key Arguments:**
- ``singleSnapshot`` -- just extract positions for a single pyephem snapshot (used for unit testing)
**Return:**
- ``None``
"""
self.log.info('starting t... | [
"def",
"get",
"(",
"self",
",",
"singleSnapshot",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``get`` method'",
")",
"global",
"xephemOE",
"global",
"tileSide",
"global",
"magLimit",
"# GRAB PARAMETERS FROM SETTINGS FILE",
"tileSide"... | *geneate the pyephem positions*
**Key Arguments:**
- ``singleSnapshot`` -- just extract positions for a single pyephem snapshot (used for unit testing)
**Return:**
- ``None`` | [
"*",
"geneate",
"the",
"pyephem",
"positions",
"*"
] | python | train |
opendatateam/udata | udata/models/owned.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/owned.py#L41-L68 | def owned_pre_save(sender, document, **kwargs):
'''
Owned mongoengine.pre_save signal handler
Need to fetch original owner before the new one erase it.
'''
if not isinstance(document, Owned):
return
changed_fields = getattr(document, '_changed_fields', [])
if 'organization' in change... | [
"def",
"owned_pre_save",
"(",
"sender",
",",
"document",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"document",
",",
"Owned",
")",
":",
"return",
"changed_fields",
"=",
"getattr",
"(",
"document",
",",
"'_changed_fields'",
",",
"[",... | Owned mongoengine.pre_save signal handler
Need to fetch original owner before the new one erase it. | [
"Owned",
"mongoengine",
".",
"pre_save",
"signal",
"handler",
"Need",
"to",
"fetch",
"original",
"owner",
"before",
"the",
"new",
"one",
"erase",
"it",
"."
] | python | train |
hazelcast/hazelcast-python-client | hazelcast/proxy/multi_map.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/multi_map.py#L298-L320 | def try_lock(self, key, lease_time=-1, timeout=-1):
"""
Tries to acquire the lock for the specified key. When the lock is not available,
* If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately.
* If a timeout is provided, the current threa... | [
"def",
"try_lock",
"(",
"self",
",",
"key",
",",
"lease_time",
"=",
"-",
"1",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"check_not_none",
"(",
"key",
",",
"\"key can't be None\"",
")",
"key_data",
"=",
"self",
".",
"_to_data",
"(",
"key",
")",
"return",... | Tries to acquire the lock for the specified key. When the lock is not available,
* If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately.
* If a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies
... | [
"Tries",
"to",
"acquire",
"the",
"lock",
"for",
"the",
"specified",
"key",
".",
"When",
"the",
"lock",
"is",
"not",
"available"
] | python | train |
kragniz/python-etcd3 | etcd3/client.py | https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L620-L624 | def watch_prefix(self, key_prefix, **kwargs):
"""Watches a range of keys with a prefix."""
kwargs['range_end'] = \
utils.increment_last_byte(utils.to_bytes(key_prefix))
return self.watch(key_prefix, **kwargs) | [
"def",
"watch_prefix",
"(",
"self",
",",
"key_prefix",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'range_end'",
"]",
"=",
"utils",
".",
"increment_last_byte",
"(",
"utils",
".",
"to_bytes",
"(",
"key_prefix",
")",
")",
"return",
"self",
".",
"wat... | Watches a range of keys with a prefix. | [
"Watches",
"a",
"range",
"of",
"keys",
"with",
"a",
"prefix",
"."
] | python | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/msgprop.py | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/msgprop.py#L248-L299 | def _make_model_class(message_type, indexed_fields, **props):
"""Construct a Model subclass corresponding to a Message subclass.
Args:
message_type: A Message subclass.
indexed_fields: A list of dotted and undotted field names.
**props: Additional properties with which to seed the class.
Returns:
... | [
"def",
"_make_model_class",
"(",
"message_type",
",",
"indexed_fields",
",",
"*",
"*",
"props",
")",
":",
"analyzed",
"=",
"_analyze_indexed_fields",
"(",
"indexed_fields",
")",
"for",
"field_name",
",",
"sub_fields",
"in",
"analyzed",
".",
"iteritems",
"(",
")"... | Construct a Model subclass corresponding to a Message subclass.
Args:
message_type: A Message subclass.
indexed_fields: A list of dotted and undotted field names.
**props: Additional properties with which to seed the class.
Returns:
A Model subclass whose properties correspond to those fields of
... | [
"Construct",
"a",
"Model",
"subclass",
"corresponding",
"to",
"a",
"Message",
"subclass",
"."
] | python | train |
summa-tx/riemann | riemann/simple.py | https://github.com/summa-tx/riemann/blob/04ae336dfd4007ceaed748daadc91cc32fa278ec/riemann/simple.py#L104-L116 | def unsigned_input(outpoint, redeem_script=None, sequence=None):
'''
Outpoint, byte-like, int -> TxIn
'''
if redeem_script is not None and sequence is None:
sequence = guess_sequence(redeem_script)
if sequence is None:
sequence = 0xFFFFFFFE
return tb.make_legacy_input(
ou... | [
"def",
"unsigned_input",
"(",
"outpoint",
",",
"redeem_script",
"=",
"None",
",",
"sequence",
"=",
"None",
")",
":",
"if",
"redeem_script",
"is",
"not",
"None",
"and",
"sequence",
"is",
"None",
":",
"sequence",
"=",
"guess_sequence",
"(",
"redeem_script",
")... | Outpoint, byte-like, int -> TxIn | [
"Outpoint",
"byte",
"-",
"like",
"int",
"-",
">",
"TxIn"
] | python | train |
pgmpy/pgmpy | pgmpy/models/MarkovModel.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/models/MarkovModel.py#L623-L677 | def to_bayesian_model(self):
"""
Creates a Bayesian Model which is a minimum I-Map for this markov model.
The ordering of parents may not remain constant. It would depend on the
ordering of variable in the junction tree (which is not constant) all the
time.
Examples
... | [
"def",
"to_bayesian_model",
"(",
"self",
")",
":",
"from",
"pgmpy",
".",
"models",
"import",
"BayesianModel",
"bm",
"=",
"BayesianModel",
"(",
")",
"var_clique_dict",
"=",
"defaultdict",
"(",
"tuple",
")",
"var_order",
"=",
"[",
"]",
"# Create a junction tree fr... | Creates a Bayesian Model which is a minimum I-Map for this markov model.
The ordering of parents may not remain constant. It would depend on the
ordering of variable in the junction tree (which is not constant) all the
time.
Examples
--------
>>> from pgmpy.models impor... | [
"Creates",
"a",
"Bayesian",
"Model",
"which",
"is",
"a",
"minimum",
"I",
"-",
"Map",
"for",
"this",
"markov",
"model",
"."
] | python | train |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L4858-L4863 | def schemaValidateDoc(self, ctxt):
"""Validate a document tree in memory. """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.xmlSchemaValidateDoc(ctxt__o, self._o)
return ret | [
"def",
"schemaValidateDoc",
"(",
"self",
",",
"ctxt",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlSchemaValidateDoc",
"(",
"ctxt__o",
",",
"self",
... | Validate a document tree in memory. | [
"Validate",
"a",
"document",
"tree",
"in",
"memory",
"."
] | python | train |
kivy/python-for-android | pythonforandroid/recipe.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/recipe.py#L255-L264 | def get_build_container_dir(self, arch):
'''Given the arch name, returns the directory where it will be
built.
This returns a different directory depending on what
alternative or optional dependencies are being built.
'''
dir_name = self.get_dir_name()
return joi... | [
"def",
"get_build_container_dir",
"(",
"self",
",",
"arch",
")",
":",
"dir_name",
"=",
"self",
".",
"get_dir_name",
"(",
")",
"return",
"join",
"(",
"self",
".",
"ctx",
".",
"build_dir",
",",
"'other_builds'",
",",
"dir_name",
",",
"'{}__ndk_target_{}'",
"."... | Given the arch name, returns the directory where it will be
built.
This returns a different directory depending on what
alternative or optional dependencies are being built. | [
"Given",
"the",
"arch",
"name",
"returns",
"the",
"directory",
"where",
"it",
"will",
"be",
"built",
"."
] | python | train |
wesyoung/pyzyre | czmq/_czmq_ctypes.py | https://github.com/wesyoung/pyzyre/blob/22d4c757acefcfdb700d3802adaf30b402bb9eea/czmq/_czmq_ctypes.py#L4931-L4936 | def set_argsx(self, arguments, *args):
"""
Setup the command line arguments, the first item must be an (absolute) filename
to run. Variadic function, must be NULL terminated.
"""
return lib.zproc_set_argsx(self._as_parameter_, arguments, *args) | [
"def",
"set_argsx",
"(",
"self",
",",
"arguments",
",",
"*",
"args",
")",
":",
"return",
"lib",
".",
"zproc_set_argsx",
"(",
"self",
".",
"_as_parameter_",
",",
"arguments",
",",
"*",
"args",
")"
] | Setup the command line arguments, the first item must be an (absolute) filename
to run. Variadic function, must be NULL terminated. | [
"Setup",
"the",
"command",
"line",
"arguments",
"the",
"first",
"item",
"must",
"be",
"an",
"(",
"absolute",
")",
"filename",
"to",
"run",
".",
"Variadic",
"function",
"must",
"be",
"NULL",
"terminated",
"."
] | python | train |
thautwarm/Redy | Redy/Collections/Traversal.py | https://github.com/thautwarm/Redy/blob/8beee5c5f752edfd2754bb1e6b5f4acb016a7770/Redy/Collections/Traversal.py#L81-L94 | def each_do(action: Callable[[T], None]):
"""
>>> from Redy.Collections import Traversal, Flow
>>> lst: Iterable[int] = [1, 2, 3]
>>> def action(x: int) -> None: print(x)
>>> x = Flow(lst)[Traversal.each_do(action)]
>>> assert x.unbox is None
"""
def inner(collection: ActualIterable[T])... | [
"def",
"each_do",
"(",
"action",
":",
"Callable",
"[",
"[",
"T",
"]",
",",
"None",
"]",
")",
":",
"def",
"inner",
"(",
"collection",
":",
"ActualIterable",
"[",
"T",
"]",
")",
":",
"for",
"each",
"in",
"collection",
":",
"action",
"(",
"each",
")",... | >>> from Redy.Collections import Traversal, Flow
>>> lst: Iterable[int] = [1, 2, 3]
>>> def action(x: int) -> None: print(x)
>>> x = Flow(lst)[Traversal.each_do(action)]
>>> assert x.unbox is None | [
">>>",
"from",
"Redy",
".",
"Collections",
"import",
"Traversal",
"Flow",
">>>",
"lst",
":",
"Iterable",
"[",
"int",
"]",
"=",
"[",
"1",
"2",
"3",
"]",
">>>",
"def",
"action",
"(",
"x",
":",
"int",
")",
"-",
">",
"None",
":",
"print",
"(",
"x",
... | python | train |
eumis/pyviews | pyviews/core/xml.py | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/xml.py#L111-L123 | def parse(self, xml_file, view_name=None) -> XmlNode:
"""Parses xml file with xml_path and returns XmlNode"""
self._setup_parser()
try:
self._view_name = view_name
self._parser.ParseFile(xml_file)
except ExpatError as error:
# pylint: disable=E1101
... | [
"def",
"parse",
"(",
"self",
",",
"xml_file",
",",
"view_name",
"=",
"None",
")",
"->",
"XmlNode",
":",
"self",
".",
"_setup_parser",
"(",
")",
"try",
":",
"self",
".",
"_view_name",
"=",
"view_name",
"self",
".",
"_parser",
".",
"ParseFile",
"(",
"xml... | Parses xml file with xml_path and returns XmlNode | [
"Parses",
"xml",
"file",
"with",
"xml_path",
"and",
"returns",
"XmlNode"
] | python | train |
PyCQA/astroid | astroid/scoped_nodes.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1719-L1750 | def _is_metaclass(klass, seen=None):
""" Return if the given class can be
used as a metaclass.
"""
if klass.name == "type":
return True
if seen is None:
seen = set()
for base in klass.bases:
try:
for baseobj in base.infer():
baseobj_name = base... | [
"def",
"_is_metaclass",
"(",
"klass",
",",
"seen",
"=",
"None",
")",
":",
"if",
"klass",
".",
"name",
"==",
"\"type\"",
":",
"return",
"True",
"if",
"seen",
"is",
"None",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"base",
"in",
"klass",
".",
"bases"... | Return if the given class can be
used as a metaclass. | [
"Return",
"if",
"the",
"given",
"class",
"can",
"be",
"used",
"as",
"a",
"metaclass",
"."
] | python | train |
ejeschke/ginga | ginga/web/pgw/ipg.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/pgw/ipg.py#L107-L114 | def load_hdu(self, hdu):
"""
Load an HDU into the viewer.
"""
image = AstroImage.AstroImage(logger=self.logger)
image.load_hdu(hdu)
self.set_image(image) | [
"def",
"load_hdu",
"(",
"self",
",",
"hdu",
")",
":",
"image",
"=",
"AstroImage",
".",
"AstroImage",
"(",
"logger",
"=",
"self",
".",
"logger",
")",
"image",
".",
"load_hdu",
"(",
"hdu",
")",
"self",
".",
"set_image",
"(",
"image",
")"
] | Load an HDU into the viewer. | [
"Load",
"an",
"HDU",
"into",
"the",
"viewer",
"."
] | python | train |
sentinel-hub/eo-learn | ml_tools/eolearn/ml_tools/classifier.py | https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/ml_tools/eolearn/ml_tools/classifier.py#L72-L91 | def _check_image(self, X):
"""
Checks the image size and its compatibility with classifier's receptive field.
At this moment it is required that image size = K * receptive_field. This will
be relaxed in future with the introduction of padding.
"""
if (len(X.shap... | [
"def",
"_check_image",
"(",
"self",
",",
"X",
")",
":",
"if",
"(",
"len",
"(",
"X",
".",
"shape",
")",
"<",
"3",
")",
"or",
"(",
"len",
"(",
"X",
".",
"shape",
")",
">",
"4",
")",
":",
"raise",
"ValueError",
"(",
"'Input has to have shape [n_sample... | Checks the image size and its compatibility with classifier's receptive field.
At this moment it is required that image size = K * receptive_field. This will
be relaxed in future with the introduction of padding. | [
"Checks",
"the",
"image",
"size",
"and",
"its",
"compatibility",
"with",
"classifier",
"s",
"receptive",
"field",
".",
"At",
"this",
"moment",
"it",
"is",
"required",
"that",
"image",
"size",
"=",
"K",
"*",
"receptive_field",
".",
"This",
"will",
"be",
"re... | python | train |
UCSBarchlab/PyRTL | pyrtl/helperfuncs.py | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L200-L223 | def val_to_signed_integer(value, bitwidth):
""" Return value as intrepreted as a signed integer under twos complement.
:param value: a python integer holding the value to convert
:param bitwidth: the length of the integer in bits to assume for conversion
Given an unsigned integer (not a wirevector!) c... | [
"def",
"val_to_signed_integer",
"(",
"value",
",",
"bitwidth",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"WireVector",
")",
"or",
"isinstance",
"(",
"bitwidth",
",",
"WireVector",
")",
":",
"raise",
"PyrtlError",
"(",
"'inputs must not be wirevectors'",
"... | Return value as intrepreted as a signed integer under twos complement.
:param value: a python integer holding the value to convert
:param bitwidth: the length of the integer in bits to assume for conversion
Given an unsigned integer (not a wirevector!) covert that to a signed
integer. This is useful ... | [
"Return",
"value",
"as",
"intrepreted",
"as",
"a",
"signed",
"integer",
"under",
"twos",
"complement",
"."
] | python | train |
rsgalloway/grit | grit/repo/version.py | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/version.py#L51-L60 | def iteritems(self):
"""Generator that yields Items"""
if self.type in ['blob']:
raise StopIteration
for path, mode, sha in self.tree.iteritems():
item = Item(self, sha, path, mode)
yield item
for i in item.iteritems():
yield i | [
"def",
"iteritems",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"in",
"[",
"'blob'",
"]",
":",
"raise",
"StopIteration",
"for",
"path",
",",
"mode",
",",
"sha",
"in",
"self",
".",
"tree",
".",
"iteritems",
"(",
")",
":",
"item",
"=",
"Item",
... | Generator that yields Items | [
"Generator",
"that",
"yields",
"Items"
] | python | train |
lablup/backend.ai-client-py | src/ai/backend/client/kernel.py | https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L307-L361 | async def upload(self, files: Sequence[Union[str, Path]],
basedir: Union[str, Path] = None,
show_progress: bool = False):
'''
Uploads the given list of files to the compute session.
You may refer them in the batch-mode execution or from the code
... | [
"async",
"def",
"upload",
"(",
"self",
",",
"files",
":",
"Sequence",
"[",
"Union",
"[",
"str",
",",
"Path",
"]",
"]",
",",
"basedir",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
"=",
"None",
",",
"show_progress",
":",
"bool",
"=",
"False",
")",
... | Uploads the given list of files to the compute session.
You may refer them in the batch-mode execution or from the code
executed in the server afterwards.
:param files: The list of file paths in the client-side.
If the paths include directories, the location of them in the compute
... | [
"Uploads",
"the",
"given",
"list",
"of",
"files",
"to",
"the",
"compute",
"session",
".",
"You",
"may",
"refer",
"them",
"in",
"the",
"batch",
"-",
"mode",
"execution",
"or",
"from",
"the",
"code",
"executed",
"in",
"the",
"server",
"afterwards",
"."
] | python | train |
10gen/mongo-orchestration | mongo_orchestration/process.py | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/process.py#L81-L92 | def __check_port(self, port):
"""check port status
return True if port is free, False else
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((_host(), port))
return True
except socket.error:
return False
fina... | [
"def",
"__check_port",
"(",
"self",
",",
"port",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"try",
":",
"s",
".",
"bind",
"(",
"(",
"_host",
"(",
")",
",",
"port",
")",
")",... | check port status
return True if port is free, False else | [
"check",
"port",
"status",
"return",
"True",
"if",
"port",
"is",
"free",
"False",
"else"
] | python | train |
yougov/mongo-connector | mongo_connector/oplog_manager.py | https://github.com/yougov/mongo-connector/blob/557cafd4b54c848cd54ef28a258391a154650cb4/mongo_connector/oplog_manager.py#L736-L754 | def _get_oplog_timestamp(self, newest_entry):
"""Return the timestamp of the latest or earliest entry in the oplog.
"""
sort_order = pymongo.DESCENDING if newest_entry else pymongo.ASCENDING
curr = (
self.oplog.find({"op": {"$ne": "n"}}).sort("$natural", sort_order).limit(-1)... | [
"def",
"_get_oplog_timestamp",
"(",
"self",
",",
"newest_entry",
")",
":",
"sort_order",
"=",
"pymongo",
".",
"DESCENDING",
"if",
"newest_entry",
"else",
"pymongo",
".",
"ASCENDING",
"curr",
"=",
"(",
"self",
".",
"oplog",
".",
"find",
"(",
"{",
"\"op\"",
... | Return the timestamp of the latest or earliest entry in the oplog. | [
"Return",
"the",
"timestamp",
"of",
"the",
"latest",
"or",
"earliest",
"entry",
"in",
"the",
"oplog",
"."
] | python | train |
shoebot/shoebot | shoebot/core/cairo_sink.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/cairo_sink.py#L64-L78 | def _output_file(self, frame):
"""
If filename was used output a filename, along with multifile
numbered filenames will be used.
If buff was specified it is returned.
:return: Output buff or filename.
"""
if self.buff:
return self.buff
elif s... | [
"def",
"_output_file",
"(",
"self",
",",
"frame",
")",
":",
"if",
"self",
".",
"buff",
":",
"return",
"self",
".",
"buff",
"elif",
"self",
".",
"multifile",
":",
"return",
"self",
".",
"file_root",
"+",
"\"_%03d\"",
"%",
"frame",
"+",
"self",
".",
"f... | If filename was used output a filename, along with multifile
numbered filenames will be used.
If buff was specified it is returned.
:return: Output buff or filename. | [
"If",
"filename",
"was",
"used",
"output",
"a",
"filename",
"along",
"with",
"multifile",
"numbered",
"filenames",
"will",
"be",
"used",
"."
] | python | valid |
armet/python-armet | armet/query/parser.py | https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/query/parser.py#L284-L292 | def parse_directive(key):
"""
Takes a key of type (foo:bar) and returns either the key and the
directive, or the key and None (for no directive.)
"""
if constants.DIRECTIVE in key:
return key.split(constants.DIRECTIVE, 1)
else:
return key, None | [
"def",
"parse_directive",
"(",
"key",
")",
":",
"if",
"constants",
".",
"DIRECTIVE",
"in",
"key",
":",
"return",
"key",
".",
"split",
"(",
"constants",
".",
"DIRECTIVE",
",",
"1",
")",
"else",
":",
"return",
"key",
",",
"None"
] | Takes a key of type (foo:bar) and returns either the key and the
directive, or the key and None (for no directive.) | [
"Takes",
"a",
"key",
"of",
"type",
"(",
"foo",
":",
"bar",
")",
"and",
"returns",
"either",
"the",
"key",
"and",
"the",
"directive",
"or",
"the",
"key",
"and",
"None",
"(",
"for",
"no",
"directive",
".",
")"
] | python | valid |
GNS3/gns3-server | gns3server/compute/base_node.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L303-L327 | def close(self):
"""
Close the node process.
"""
if self._closed:
return False
log.info("{module}: '{name}' [{id}]: is closing".format(module=self.manager.module_name,
name=self.name,
... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"False",
"log",
".",
"info",
"(",
"\"{module}: '{name}' [{id}]: is closing\"",
".",
"format",
"(",
"module",
"=",
"self",
".",
"manager",
".",
"module_name",
",",
"name",
"... | Close the node process. | [
"Close",
"the",
"node",
"process",
"."
] | python | train |
nicholasbishop/shaderdef | tools/version_util.py | https://github.com/nicholasbishop/shaderdef/blob/b68a9faf4c7cfa61e32a2e49eb2cae2f2e2b1f78/tools/version_util.py#L19-L28 | def load_version_as_string():
"""Get the current version from version.py as a string."""
with open(VERSION_PATH, 'r') as rfile:
contents = rfile.read().strip()
_, version = contents.split('=')
version = version.strip()
# Remove quotes
return version.strip('"\'') | [
"def",
"load_version_as_string",
"(",
")",
":",
"with",
"open",
"(",
"VERSION_PATH",
",",
"'r'",
")",
"as",
"rfile",
":",
"contents",
"=",
"rfile",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"_",
",",
"version",
"=",
"contents",
".",
"split",
"("... | Get the current version from version.py as a string. | [
"Get",
"the",
"current",
"version",
"from",
"version",
".",
"py",
"as",
"a",
"string",
"."
] | python | train |
Kronuz/pyScss | scss/types.py | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L442-L483 | def _add_sub(self, other, op):
"""Implements both addition and subtraction."""
if not isinstance(other, Number):
return NotImplemented
# If either side is unitless, inherit the other side's units. Skip all
# the rest of the conversion math, too.
if self.is_unitless ... | [
"def",
"_add_sub",
"(",
"self",
",",
"other",
",",
"op",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Number",
")",
":",
"return",
"NotImplemented",
"# If either side is unitless, inherit the other side's units. Skip all",
"# the rest of the conversion math, ... | Implements both addition and subtraction. | [
"Implements",
"both",
"addition",
"and",
"subtraction",
"."
] | python | train |
sci-bots/mpm | mpm/api.py | https://github.com/sci-bots/mpm/blob/a69651cda4b37ee6b17df4fe0809249e7f4dc536/mpm/api.py#L578-L643 | def installed_plugins(only_conda=False):
'''
.. versionadded:: 0.20
Parameters
----------
only_conda : bool, optional
Only consider plugins that are installed **as Conda packages**.
.. versionadded:: 0.22
Returns
-------
list
List of properties corresponding to... | [
"def",
"installed_plugins",
"(",
"only_conda",
"=",
"False",
")",
":",
"available_path",
"=",
"MICRODROP_CONDA_SHARE",
".",
"joinpath",
"(",
"'plugins'",
",",
"'available'",
")",
"if",
"not",
"available_path",
".",
"isdir",
"(",
")",
":",
"return",
"[",
"]",
... | .. versionadded:: 0.20
Parameters
----------
only_conda : bool, optional
Only consider plugins that are installed **as Conda packages**.
.. versionadded:: 0.22
Returns
-------
list
List of properties corresponding to each available plugin that is
**installed**.... | [
"..",
"versionadded",
"::",
"0",
".",
"20"
] | python | train |
OCA/vertical-hotel | hotel_reservation/models/hotel_reservation.py | https://github.com/OCA/vertical-hotel/blob/a01442e92b5ea1fda7fb9e6180b3211e8749a35a/hotel_reservation/models/hotel_reservation.py#L314-L401 | def confirmed_reservation(self):
"""
This method create a new record set for hotel room reservation line
-------------------------------------------------------------------
@param self: The object pointer
@return: new record set for hotel room reservation line.
"""
... | [
"def",
"confirmed_reservation",
"(",
"self",
")",
":",
"reservation_line_obj",
"=",
"self",
".",
"env",
"[",
"'hotel.room.reservation.line'",
"]",
"vals",
"=",
"{",
"}",
"for",
"reservation",
"in",
"self",
":",
"reserv_checkin",
"=",
"datetime",
".",
"strptime",... | This method create a new record set for hotel room reservation line
-------------------------------------------------------------------
@param self: The object pointer
@return: new record set for hotel room reservation line. | [
"This",
"method",
"create",
"a",
"new",
"record",
"set",
"for",
"hotel",
"room",
"reservation",
"line",
"-------------------------------------------------------------------"
] | python | train |
greyli/flask-dropzone | flask_dropzone/__init__.py | https://github.com/greyli/flask-dropzone/blob/eb1d5ef16d8f83a12e6fed1bb9412a0c12c6d584/flask_dropzone/__init__.py#L325-L357 | def create(action='', csrf=False, action_view='', **kwargs):
"""Create a Dropzone form with given action.
.. versionchanged:: 1.4.2
Added ``csrf`` parameter to enable CSRF protect.
.. versionchanged:: 1.4.3
Added ``action`` parameter to replace ``action_view``, ``action... | [
"def",
"create",
"(",
"action",
"=",
"''",
",",
"csrf",
"=",
"False",
",",
"action_view",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"current_app",
".",
"config",
"[",
"'DROPZONE_IN_FORM'",
"]",
":",
"return",
"Markup",
"(",
"'<div class=\"dropz... | Create a Dropzone form with given action.
.. versionchanged:: 1.4.2
Added ``csrf`` parameter to enable CSRF protect.
.. versionchanged:: 1.4.3
Added ``action`` parameter to replace ``action_view``, ``action_view`` was deprecated now.
.. versionchanged:: 1.5.0
... | [
"Create",
"a",
"Dropzone",
"form",
"with",
"given",
"action",
"."
] | python | train |
tarbell-project/tarbell | tarbell/utils.py | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/utils.py#L34-L44 | def list_get(l, idx, default=None):
"""
Get from a list with an optional default value.
"""
try:
if l[idx]:
return l[idx]
else:
return default
except IndexError:
return default | [
"def",
"list_get",
"(",
"l",
",",
"idx",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"if",
"l",
"[",
"idx",
"]",
":",
"return",
"l",
"[",
"idx",
"]",
"else",
":",
"return",
"default",
"except",
"IndexError",
":",
"return",
"default"
] | Get from a list with an optional default value. | [
"Get",
"from",
"a",
"list",
"with",
"an",
"optional",
"default",
"value",
"."
] | python | train |
saltstack/salt | salt/cloud/clouds/vmware.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3524-L3610 | def list_hbas(kwargs=None, call=None):
'''
List all HBAs for each host system; or all HBAs for a specified host
system; or HBAs of specified type for each host system; or HBAs of
specified type for a specified host system in this VMware environment
.. note::
You can specify type as either ... | [
"def",
"list_hbas",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_hbas function must be called with '",
"'-f or --function.'",
")",
"ret",
"=",
"{",
"}",
"hb... | List all HBAs for each host system; or all HBAs for a specified host
system; or HBAs of specified type for each host system; or HBAs of
specified type for a specified host system in this VMware environment
.. note::
You can specify type as either ``parallel``, ``iscsi``, ``block``
or ``fib... | [
"List",
"all",
"HBAs",
"for",
"each",
"host",
"system",
";",
"or",
"all",
"HBAs",
"for",
"a",
"specified",
"host",
"system",
";",
"or",
"HBAs",
"of",
"specified",
"type",
"for",
"each",
"host",
"system",
";",
"or",
"HBAs",
"of",
"specified",
"type",
"f... | python | train |
pygobject/pgi | pgi/codegen/utils.py | https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/utils.py#L68-L76 | def request_name(self, name):
"""Request a name, might return the name or a similar one if already
used or reserved
"""
while name in self._blacklist:
name += "_"
self._blacklist.add(name)
return name | [
"def",
"request_name",
"(",
"self",
",",
"name",
")",
":",
"while",
"name",
"in",
"self",
".",
"_blacklist",
":",
"name",
"+=",
"\"_\"",
"self",
".",
"_blacklist",
".",
"add",
"(",
"name",
")",
"return",
"name"
] | Request a name, might return the name or a similar one if already
used or reserved | [
"Request",
"a",
"name",
"might",
"return",
"the",
"name",
"or",
"a",
"similar",
"one",
"if",
"already",
"used",
"or",
"reserved"
] | python | train |
PmagPy/PmagPy | programs/demag_gui.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L1835-L1873 | def plot_high_levels_data(self):
"""
Complicated function that draws the high level mean plot on canvas4,
draws all specimen, sample, or site interpretations according to the
UPPER_LEVEL_SHOW variable, draws the fisher mean or fisher mean by
polarity of all interpretations displa... | [
"def",
"plot_high_levels_data",
"(",
"self",
")",
":",
"# self.toolbar4.home()",
"high_level",
"=",
"self",
".",
"level_box",
".",
"GetValue",
"(",
")",
"self",
".",
"UPPER_LEVEL_NAME",
"=",
"self",
".",
"level_names",
".",
"GetValue",
"(",
")",
"self",
... | Complicated function that draws the high level mean plot on canvas4,
draws all specimen, sample, or site interpretations according to the
UPPER_LEVEL_SHOW variable, draws the fisher mean or fisher mean by
polarity of all interpretations displayed, draws sample orientation
check if on, an... | [
"Complicated",
"function",
"that",
"draws",
"the",
"high",
"level",
"mean",
"plot",
"on",
"canvas4",
"draws",
"all",
"specimen",
"sample",
"or",
"site",
"interpretations",
"according",
"to",
"the",
"UPPER_LEVEL_SHOW",
"variable",
"draws",
"the",
"fisher",
"mean",
... | python | train |
dslackw/slpkg | slpkg/main.py | https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/main.py#L166-L172 | def command_repo_remove(self):
"""Remove custom repositories
"""
if len(self.args) == 2 and self.args[0] == "repo-remove":
Repo().remove(self.args[1])
else:
usage("") | [
"def",
"command_repo_remove",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"args",
")",
"==",
"2",
"and",
"self",
".",
"args",
"[",
"0",
"]",
"==",
"\"repo-remove\"",
":",
"Repo",
"(",
")",
".",
"remove",
"(",
"self",
".",
"args",
"[",
"... | Remove custom repositories | [
"Remove",
"custom",
"repositories"
] | python | train |
ska-sa/montblanc | montblanc/examples/standalone.py | https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/examples/standalone.py#L52-L57 | def point_lm(self, context):
""" Supply point source lm coordinates to montblanc """
# Shape (npsrc, 2)
(ls, us), _ = context.array_extents(context.name)
return np.asarray(lm_coords[ls:us], dtype=context.dtype) | [
"def",
"point_lm",
"(",
"self",
",",
"context",
")",
":",
"# Shape (npsrc, 2)",
"(",
"ls",
",",
"us",
")",
",",
"_",
"=",
"context",
".",
"array_extents",
"(",
"context",
".",
"name",
")",
"return",
"np",
".",
"asarray",
"(",
"lm_coords",
"[",
"ls",
... | Supply point source lm coordinates to montblanc | [
"Supply",
"point",
"source",
"lm",
"coordinates",
"to",
"montblanc"
] | python | train |
Microsoft/knack | knack/commands.py | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/commands.py#L229-L255 | def create_command(self, name, operation, **kwargs):
""" Constructs the command object that can then be added to the command table """
if not isinstance(operation, six.string_types):
raise ValueError("Operation must be a string. Got '{}'".format(operation))
name = ' '.join(name.spli... | [
"def",
"create_command",
"(",
"self",
",",
"name",
",",
"operation",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"operation",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"\"Operation must be a string. Got '{}'\... | Constructs the command object that can then be added to the command table | [
"Constructs",
"the",
"command",
"object",
"that",
"can",
"then",
"be",
"added",
"to",
"the",
"command",
"table"
] | python | train |
smira/py-numa | numa.py | https://github.com/smira/py-numa/blob/eb38979c61028eb9422a4ad1eda0387cd93ea390/numa.py#L320-L331 | def get_membind():
"""
Returns the mask of nodes from which memory can currently be allocated.
@return: node mask
@rtype: C{set}
"""
bitmask = libnuma.numa_get_membind()
nodemask = nodemask_t()
libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask))
libnuma.numa_bitmask_free(bi... | [
"def",
"get_membind",
"(",
")",
":",
"bitmask",
"=",
"libnuma",
".",
"numa_get_membind",
"(",
")",
"nodemask",
"=",
"nodemask_t",
"(",
")",
"libnuma",
".",
"copy_bitmask_to_nodemask",
"(",
"bitmask",
",",
"byref",
"(",
"nodemask",
")",
")",
"libnuma",
".",
... | Returns the mask of nodes from which memory can currently be allocated.
@return: node mask
@rtype: C{set} | [
"Returns",
"the",
"mask",
"of",
"nodes",
"from",
"which",
"memory",
"can",
"currently",
"be",
"allocated",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/bgp.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/bgp.py#L154-L190 | def remove_bgp(self, **kwargs):
"""Remove BGP process completely.
Args:
vrf (str): The VRF for this BGP process.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
callback (function): A function executed u... | [
"def",
"remove_bgp",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"rbridge_id",
"=",
"kwargs",
".",
"pop",
"(",
"'rbridge_id'",
",",
"'1'",
")",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"'callback'",
",",
"self",
".",
"_callback",
")",
"disable_a... | Remove BGP process completely.
Args:
vrf (str): The VRF for this BGP process.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
callback (function): A function executed upon completion of the
metho... | [
"Remove",
"BGP",
"process",
"completely",
"."
] | python | train |
google-research/batch-ppo | agents/parts/normalize.py | https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/parts/normalize.py#L81-L108 | def update(self, value):
"""Update the mean and variance estimates.
Args:
value: Batch or single value tensor.
Returns:
Summary tensor.
"""
with tf.name_scope(self._name + '/update'):
if value.shape.ndims == self._mean.shape.ndims:
# Add a batch dimension if necessary.
... | [
"def",
"update",
"(",
"self",
",",
"value",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"self",
".",
"_name",
"+",
"'/update'",
")",
":",
"if",
"value",
".",
"shape",
".",
"ndims",
"==",
"self",
".",
"_mean",
".",
"shape",
".",
"ndims",
":",
... | Update the mean and variance estimates.
Args:
value: Batch or single value tensor.
Returns:
Summary tensor. | [
"Update",
"the",
"mean",
"and",
"variance",
"estimates",
"."
] | python | train |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L447-L477 | def _push_configs_to_nvram(self):
"""
Push the startup-config and private-config content to the NVRAM.
"""
startup_config_content = self.startup_config_content
if startup_config_content:
nvram_file = self._nvram_file()
try:
if not os.path.... | [
"def",
"_push_configs_to_nvram",
"(",
"self",
")",
":",
"startup_config_content",
"=",
"self",
".",
"startup_config_content",
"if",
"startup_config_content",
":",
"nvram_file",
"=",
"self",
".",
"_nvram_file",
"(",
")",
"try",
":",
"if",
"not",
"os",
".",
"path"... | Push the startup-config and private-config content to the NVRAM. | [
"Push",
"the",
"startup",
"-",
"config",
"and",
"private",
"-",
"config",
"content",
"to",
"the",
"NVRAM",
"."
] | python | train |
RyanBalfanz/django-smsish | smsish/sms/__init__.py | https://github.com/RyanBalfanz/django-smsish/blob/4d450e3d217cea9e373f16c5e4f0beb3218bd5c9/smsish/sms/__init__.py#L34-L50 | def send_sms(message, from_number, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None):
"""
Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipients in the 'To' field.
If auth_user is None, the EMAIL_HOST_US... | [
"def",
"send_sms",
"(",
"message",
",",
"from_number",
",",
"recipient_list",
",",
"fail_silently",
"=",
"False",
",",
"auth_user",
"=",
"None",
",",
"auth_password",
"=",
"None",
",",
"connection",
"=",
"None",
")",
":",
"connection",
"=",
"connection",
"or... | Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipients in the 'To' field.
If auth_user is None, the EMAIL_HOST_USER setting is used.
If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
Note: The API for this method is frozen. N... | [
"Easy",
"wrapper",
"for",
"sending",
"a",
"single",
"message",
"to",
"a",
"recipient",
"list",
".",
"All",
"members",
"of",
"the",
"recipient",
"list",
"will",
"see",
"the",
"other",
"recipients",
"in",
"the",
"To",
"field",
"."
] | python | train |
knipknap/exscript | Exscript/servers/httpd.py | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/servers/httpd.py#L90-L148 | def _require_authenticate(func):
'''A decorator to add digest authorization checks to HTTP Request Handlers'''
def wrapped(self):
if not hasattr(self, 'authenticated'):
self.authenticated = None
if self.authenticated:
return func(self)
auth = self.headers.get(u'... | [
"def",
"_require_authenticate",
"(",
"func",
")",
":",
"def",
"wrapped",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'authenticated'",
")",
":",
"self",
".",
"authenticated",
"=",
"None",
"if",
"self",
".",
"authenticated",
":",
"re... | A decorator to add digest authorization checks to HTTP Request Handlers | [
"A",
"decorator",
"to",
"add",
"digest",
"authorization",
"checks",
"to",
"HTTP",
"Request",
"Handlers"
] | python | train |
wummel/linkchecker | linkcheck/configuration/__init__.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/configuration/__init__.py#L563-L588 | def read_kioslaverc (kde_config_dir):
"""Read kioslaverc into data dictionary."""
data = {}
filename = os.path.join(kde_config_dir, "kioslaverc")
with open(filename) as fd:
# First read all lines into dictionary since they can occur
# in any order.
for line in fd:
li... | [
"def",
"read_kioslaverc",
"(",
"kde_config_dir",
")",
":",
"data",
"=",
"{",
"}",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"kde_config_dir",
",",
"\"kioslaverc\"",
")",
"with",
"open",
"(",
"filename",
")",
"as",
"fd",
":",
"# First read all l... | Read kioslaverc into data dictionary. | [
"Read",
"kioslaverc",
"into",
"data",
"dictionary",
"."
] | python | train |
SKA-ScienceDataProcessor/integration-prototype | sip/examples/flask_processing_controller/app/old.db/init.py | https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/examples/flask_processing_controller/app/old.db/init.py#L41-L53 | def _scheduling_block_config(num_blocks=5, start_sbi_id=0, start_pb_id=0,
project='sip'):
"""Return a Scheduling Block Configuration dictionary"""
pb_id = start_pb_id
for sb_id, sbi_id in _scheduling_block_ids(num_blocks, start_sbi_id,
... | [
"def",
"_scheduling_block_config",
"(",
"num_blocks",
"=",
"5",
",",
"start_sbi_id",
"=",
"0",
",",
"start_pb_id",
"=",
"0",
",",
"project",
"=",
"'sip'",
")",
":",
"pb_id",
"=",
"start_pb_id",
"for",
"sb_id",
",",
"sbi_id",
"in",
"_scheduling_block_ids",
"(... | Return a Scheduling Block Configuration dictionary | [
"Return",
"a",
"Scheduling",
"Block",
"Configuration",
"dictionary"
] | python | train |
liampauling/betfair | betfairlightweight/endpoints/historic.py | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/historic.py#L63-L89 | def get_data_size(self, sport, plan, from_day, from_month, from_year, to_day, to_month, to_year, event_id=None,
event_name=None, market_types_collection=None, countries_collection=None,
file_type_collection=None, session=None):
"""
Returns a dictionary of file... | [
"def",
"get_data_size",
"(",
"self",
",",
"sport",
",",
"plan",
",",
"from_day",
",",
"from_month",
",",
"from_year",
",",
"to_day",
",",
"to_month",
",",
"to_year",
",",
"event_id",
"=",
"None",
",",
"event_name",
"=",
"None",
",",
"market_types_collection"... | Returns a dictionary of file count and combines size files.
:param sport: sport to filter data for.
:param plan: plan type to filter for, Basic Plan, Advanced Plan or Pro Plan.
:param from_day: day of month to start data from.
:param from_month: month to start data from.
:param ... | [
"Returns",
"a",
"dictionary",
"of",
"file",
"count",
"and",
"combines",
"size",
"files",
"."
] | python | train |
aio-libs/aiodocker | aiodocker/tasks.py | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/tasks.py#L31-L43 | async def inspect(self, task_id: str) -> Mapping[str, Any]:
"""
Return info about a task
Args:
task_id: is ID of the task
"""
response = await self.docker._query_json(
"tasks/{task_id}".format(task_id=task_id), method="GET"
)
return resp... | [
"async",
"def",
"inspect",
"(",
"self",
",",
"task_id",
":",
"str",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"response",
"=",
"await",
"self",
".",
"docker",
".",
"_query_json",
"(",
"\"tasks/{task_id}\"",
".",
"format",
"(",
"task_id",
... | Return info about a task
Args:
task_id: is ID of the task | [
"Return",
"info",
"about",
"a",
"task"
] | python | train |
pyvisa/pyvisa | pyvisa/ctwrapper/functions.py | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/ctwrapper/functions.py#L1190-L1214 | def open(library, session, resource_name,
access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE):
"""Opens a session to the specified resource.
Corresponds to viOpen function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: ... | [
"def",
"open",
"(",
"library",
",",
"session",
",",
"resource_name",
",",
"access_mode",
"=",
"constants",
".",
"AccessModes",
".",
"no_lock",
",",
"open_timeout",
"=",
"constants",
".",
"VI_TMO_IMMEDIATE",
")",
":",
"try",
":",
"open_timeout",
"=",
"int",
"... | Opens a session to the specified resource.
Corresponds to viOpen function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Resource Manager session (should always be a session returned from open_default_resource_manager()).
:param resource_name: Unique symbolic ... | [
"Opens",
"a",
"session",
"to",
"the",
"specified",
"resource",
"."
] | python | train |
liampauling/betfair | betfairlightweight/endpoints/racecard.py | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/racecard.py#L41-L57 | def get_race_card(self, market_ids, data_entries=None, session=None, lightweight=None):
"""
Returns a list of race cards based on market ids provided.
:param list market_ids: The filter to select desired markets
:param str data_entries: Data to be returned
:param requests.sessio... | [
"def",
"get_race_card",
"(",
"self",
",",
"market_ids",
",",
"data_entries",
"=",
"None",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"app_key",
":",
"raise",
"RaceCardError",
"(",
"\"You need to login be... | Returns a list of race cards based on market ids provided.
:param list market_ids: The filter to select desired markets
:param str data_entries: Data to be returned
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
... | [
"Returns",
"a",
"list",
"of",
"race",
"cards",
"based",
"on",
"market",
"ids",
"provided",
"."
] | python | train |
aliyun/aliyun-odps-python-sdk | odps/df/backends/formatter.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/backends/formatter.py#L103-L177 | def pprint_thing(thing, _nest_lvl=0, escape_chars=None, default_escapes=False,
quote_strings=False, max_seq_items=None):
"""
This function is the sanctioned way of converting objects
to a unicode representation.
properly handles nested sequences containing unicode strings
(unicode(... | [
"def",
"pprint_thing",
"(",
"thing",
",",
"_nest_lvl",
"=",
"0",
",",
"escape_chars",
"=",
"None",
",",
"default_escapes",
"=",
"False",
",",
"quote_strings",
"=",
"False",
",",
"max_seq_items",
"=",
"None",
")",
":",
"def",
"as_escaped_unicode",
"(",
"thing... | This function is the sanctioned way of converting objects
to a unicode representation.
properly handles nested sequences containing unicode strings
(unicode(object) does not)
Parameters
----------
thing : anything to be formatted
_nest_lvl : internal use only. pprint_thing() is mutually-re... | [
"This",
"function",
"is",
"the",
"sanctioned",
"way",
"of",
"converting",
"objects",
"to",
"a",
"unicode",
"representation",
"."
] | python | train |
polyaxon/hestia | hestia/date_formatter.py | https://github.com/polyaxon/hestia/blob/382ed139cff8bf35c987cfc30a31b72c0d6b808e/hestia/date_formatter.py#L52-L65 | def extract_date(cls, date_str):
"""
Tries to extract a `datetime` object from the given string, expecting
date information only.
Raises `DateTimeFormatterException` if the extraction fails.
"""
if not date_str:
raise DateTimeFormatterException('date_str must... | [
"def",
"extract_date",
"(",
"cls",
",",
"date_str",
")",
":",
"if",
"not",
"date_str",
":",
"raise",
"DateTimeFormatterException",
"(",
"'date_str must a valid string {}.'",
".",
"format",
"(",
"date_str",
")",
")",
"try",
":",
"return",
"cls",
".",
"_extract_ti... | Tries to extract a `datetime` object from the given string, expecting
date information only.
Raises `DateTimeFormatterException` if the extraction fails. | [
"Tries",
"to",
"extract",
"a",
"datetime",
"object",
"from",
"the",
"given",
"string",
"expecting",
"date",
"information",
"only",
"."
] | python | train |
Stranger6667/pyoffers | pyoffers/models/raw_log.py | https://github.com/Stranger6667/pyoffers/blob/9575d6cdc878096242268311a22cc5fdd4f64b37/pyoffers/models/raw_log.py#L44-L52 | def content(self):
"""
Returns raw CSV content of the log file.
"""
raw_content = self._manager.api.session.get(self.download_link).content
data = BytesIO(raw_content)
archive = ZipFile(data)
filename = archive.filelist[0] # Always 1 file in the archive
r... | [
"def",
"content",
"(",
"self",
")",
":",
"raw_content",
"=",
"self",
".",
"_manager",
".",
"api",
".",
"session",
".",
"get",
"(",
"self",
".",
"download_link",
")",
".",
"content",
"data",
"=",
"BytesIO",
"(",
"raw_content",
")",
"archive",
"=",
"ZipF... | Returns raw CSV content of the log file. | [
"Returns",
"raw",
"CSV",
"content",
"of",
"the",
"log",
"file",
"."
] | python | train |
DreamLab/VmShepherd | src/vmshepherd/iaas/vm.py | https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/iaas/vm.py#L86-L91 | async def terminate(self):
""" Terminate vm.
"""
logging.debug('Terminate: %s', self)
self.state = VmState.TERMINATED
return await self.manager.terminate_vm(self.id) | [
"async",
"def",
"terminate",
"(",
"self",
")",
":",
"logging",
".",
"debug",
"(",
"'Terminate: %s'",
",",
"self",
")",
"self",
".",
"state",
"=",
"VmState",
".",
"TERMINATED",
"return",
"await",
"self",
".",
"manager",
".",
"terminate_vm",
"(",
"self",
"... | Terminate vm. | [
"Terminate",
"vm",
"."
] | python | train |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd5xx.py | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd5xx.py#L199-L205 | def funding_info(self, key, value):
"""Populate the ``funding_info`` key."""
return {
'agency': value.get('a'),
'grant_number': value.get('c'),
'project_number': value.get('f'),
} | [
"def",
"funding_info",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"return",
"{",
"'agency'",
":",
"value",
".",
"get",
"(",
"'a'",
")",
",",
"'grant_number'",
":",
"value",
".",
"get",
"(",
"'c'",
")",
",",
"'project_number'",
":",
"value",
"."... | Populate the ``funding_info`` key. | [
"Populate",
"the",
"funding_info",
"key",
"."
] | python | train |
tanghaibao/jcvi | jcvi/utils/orderedcollections.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/orderedcollections.py#L342-L347 | def insert(self, item):
'Insert a new item. If equal keys are found, add to the left'
k = self._key(item)
i = bisect_left(self._keys, k)
self._keys.insert(i, k)
self._items.insert(i, item) | [
"def",
"insert",
"(",
"self",
",",
"item",
")",
":",
"k",
"=",
"self",
".",
"_key",
"(",
"item",
")",
"i",
"=",
"bisect_left",
"(",
"self",
".",
"_keys",
",",
"k",
")",
"self",
".",
"_keys",
".",
"insert",
"(",
"i",
",",
"k",
")",
"self",
"."... | Insert a new item. If equal keys are found, add to the left | [
"Insert",
"a",
"new",
"item",
".",
"If",
"equal",
"keys",
"are",
"found",
"add",
"to",
"the",
"left"
] | python | train |
chaoss/grimoirelab-sigils | src/migration/to_kibana5.py | https://github.com/chaoss/grimoirelab-sigils/blob/33d395195acb316287143a535a2c6e4009bf0528/src/migration/to_kibana5.py#L86-L104 | def parse_args():
"""Parse arguments from the command line"""
parser = argparse.ArgumentParser(description=TO_KIBANA5_DESC_MSG)
parser.add_argument('-s', '--source', dest='src_path', \
required=True, help='source directory')
parser.add_argument('-d', '--dest', dest='dest_path', \
requi... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"TO_KIBANA5_DESC_MSG",
")",
"parser",
".",
"add_argument",
"(",
"'-s'",
",",
"'--source'",
",",
"dest",
"=",
"'src_path'",
",",
"required",
"=",
"T... | Parse arguments from the command line | [
"Parse",
"arguments",
"from",
"the",
"command",
"line"
] | python | train |
ArchiveTeam/wpull | wpull/string.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/string.py#L9-L24 | def to_bytes(instance, encoding='utf-8', error='strict'):
'''Convert an instance recursively to bytes.'''
if isinstance(instance, bytes):
return instance
elif hasattr(instance, 'encode'):
return instance.encode(encoding, error)
elif isinstance(instance, list):
return list([to_byt... | [
"def",
"to_bytes",
"(",
"instance",
",",
"encoding",
"=",
"'utf-8'",
",",
"error",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"instance",
",",
"bytes",
")",
":",
"return",
"instance",
"elif",
"hasattr",
"(",
"instance",
",",
"'encode'",
")",
":"... | Convert an instance recursively to bytes. | [
"Convert",
"an",
"instance",
"recursively",
"to",
"bytes",
"."
] | python | train |
greenbender/pynntp | nntp/date.py | https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L316-L374 | def timestamp(value, fmt=None):
"""Parse a datetime to a unix timestamp.
Uses fast custom parsing for common datetime formats or the slow dateutil
parser for other formats. This is a trade off between ease of use and speed
and is very useful for fast parsing of timestamp strings whose format may
st... | [
"def",
"timestamp",
"(",
"value",
",",
"fmt",
"=",
"None",
")",
":",
"if",
"fmt",
":",
"return",
"_timestamp_formats",
".",
"get",
"(",
"fmt",
",",
"lambda",
"v",
":",
"timestamp_fmt",
"(",
"v",
",",
"fmt",
")",
")",
"(",
"value",
")",
"l",
"=",
... | Parse a datetime to a unix timestamp.
Uses fast custom parsing for common datetime formats or the slow dateutil
parser for other formats. This is a trade off between ease of use and speed
and is very useful for fast parsing of timestamp strings whose format may
standard but varied or unknown prior to p... | [
"Parse",
"a",
"datetime",
"to",
"a",
"unix",
"timestamp",
"."
] | python | test |
MagicStack/asyncpg | asyncpg/connection.py | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connection.py#L381-L393 | def cursor(self, query, *args, prefetch=None, timeout=None):
"""Return a *cursor factory* for the specified query.
:param args: Query arguments.
:param int prefetch: The number of rows the *cursor iterator*
will prefetch (defaults to ``50``.)
:param float ti... | [
"def",
"cursor",
"(",
"self",
",",
"query",
",",
"*",
"args",
",",
"prefetch",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_check_open",
"(",
")",
"return",
"cursor",
".",
"CursorFactory",
"(",
"self",
",",
"query",
",",
"None",... | Return a *cursor factory* for the specified query.
:param args: Query arguments.
:param int prefetch: The number of rows the *cursor iterator*
will prefetch (defaults to ``50``.)
:param float timeout: Optional timeout in seconds.
:return: A :class:`~cursor.... | [
"Return",
"a",
"*",
"cursor",
"factory",
"*",
"for",
"the",
"specified",
"query",
"."
] | python | train |
freeman-lab/regional | regional/regional.py | https://github.com/freeman-lab/regional/blob/e3a29c58982e5cd3d5700131ac96e5e0b84fb981/regional/regional.py#L459-L477 | def getcolors(spec, n, cmap=None, value=None):
"""
Turn list of color specs into list of arrays.
"""
if cmap is not None and spec is not None:
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.cm import get_cmap
if isinstance(cmap, LinearSegmentedColormap):
... | [
"def",
"getcolors",
"(",
"spec",
",",
"n",
",",
"cmap",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"if",
"cmap",
"is",
"not",
"None",
"and",
"spec",
"is",
"not",
"None",
":",
"from",
"matplotlib",
".",
"colors",
"import",
"LinearSegmentedColorma... | Turn list of color specs into list of arrays. | [
"Turn",
"list",
"of",
"color",
"specs",
"into",
"list",
"of",
"arrays",
"."
] | python | train |
Chilipp/psyplot | psyplot/data.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4355-L4374 | def append(self, value, new_name=False):
"""
Append a new array to the list
Parameters
----------
value: InteractiveBase
The data object to append to this list
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.... | [
"def",
"append",
"(",
"self",
",",
"value",
",",
"new_name",
"=",
"False",
")",
":",
"arr",
",",
"renamed",
"=",
"self",
".",
"rename",
"(",
"value",
",",
"new_name",
")",
"if",
"renamed",
"is",
"not",
"None",
":",
"super",
"(",
"ArrayList",
",",
"... | Append a new array to the list
Parameters
----------
value: InteractiveBase
The data object to append to this list
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
--------
list.appe... | [
"Append",
"a",
"new",
"array",
"to",
"the",
"list"
] | python | train |
toumorokoshi/sprinter | sprinter/external/pippuppet.py | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/external/pippuppet.py#L50-L54 | def delete_all_eggs(self):
""" delete all the eggs in the directory specified """
path_to_delete = os.path.join(self.egg_directory, "lib", "python")
if os.path.exists(path_to_delete):
shutil.rmtree(path_to_delete) | [
"def",
"delete_all_eggs",
"(",
"self",
")",
":",
"path_to_delete",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"egg_directory",
",",
"\"lib\"",
",",
"\"python\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path_to_delete",
")",
":",
... | delete all the eggs in the directory specified | [
"delete",
"all",
"the",
"eggs",
"in",
"the",
"directory",
"specified"
] | python | train |
neurosynth/neurosynth | neurosynth/base/mask.py | https://github.com/neurosynth/neurosynth/blob/948ce7edce15d7df693446e76834e0c23bfe8f11/neurosynth/base/mask.py#L92-L136 | def get_image(self, image, output='vector'):
""" A flexible method for transforming between different
representations of image data.
Args:
image: The input image. Can be a string (filename of image),
NiBabel image, N-dimensional array (must have same shape as
... | [
"def",
"get_image",
"(",
"self",
",",
"image",
",",
"output",
"=",
"'vector'",
")",
":",
"if",
"isinstance",
"(",
"image",
",",
"string_types",
")",
":",
"image",
"=",
"nb",
".",
"load",
"(",
"image",
")",
"if",
"type",
"(",
"image",
")",
".",
"__m... | A flexible method for transforming between different
representations of image data.
Args:
image: The input image. Can be a string (filename of image),
NiBabel image, N-dimensional array (must have same shape as
self.volume), or vectorized image data (must have... | [
"A",
"flexible",
"method",
"for",
"transforming",
"between",
"different",
"representations",
"of",
"image",
"data",
".",
"Args",
":",
"image",
":",
"The",
"input",
"image",
".",
"Can",
"be",
"a",
"string",
"(",
"filename",
"of",
"image",
")",
"NiBabel",
"i... | python | test |
ContextLab/quail | quail/egg.py | https://github.com/ContextLab/quail/blob/71dd53c792dd915dc84879d8237e3582dd68b7a4/quail/egg.py#L257-L298 | def save(self, fname, compression='blosc'):
"""
Save method for the Egg object
The data will be saved as a 'egg' file, which is a dictionary containing
the elements of a Egg saved in the hd5 format using
`deepdish`.
Parameters
----------
fname : str
... | [
"def",
"save",
"(",
"self",
",",
"fname",
",",
"compression",
"=",
"'blosc'",
")",
":",
"# put egg vars into a dict",
"egg",
"=",
"{",
"'pres'",
":",
"df2list",
"(",
"self",
".",
"pres",
")",
",",
"'rec'",
":",
"df2list",
"(",
"self",
".",
"rec",
")",
... | Save method for the Egg object
The data will be saved as a 'egg' file, which is a dictionary containing
the elements of a Egg saved in the hd5 format using
`deepdish`.
Parameters
----------
fname : str
A name for the file. If the file extension (.egg) is n... | [
"Save",
"method",
"for",
"the",
"Egg",
"object"
] | python | train |
jplusplus/statscraper | statscraper/scrapers/uka_scraper.py | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/scrapers/uka_scraper.py#L24-L35 | def _fetch_dimensions(self, dataset):
""" Iterate through semesters, counties and municipalities.
"""
yield Dimension(u"school")
yield Dimension(u"year",
datatype="year")
yield Dimension(u"semester",
datatype="academic_term",
... | [
"def",
"_fetch_dimensions",
"(",
"self",
",",
"dataset",
")",
":",
"yield",
"Dimension",
"(",
"u\"school\"",
")",
"yield",
"Dimension",
"(",
"u\"year\"",
",",
"datatype",
"=",
"\"year\"",
")",
"yield",
"Dimension",
"(",
"u\"semester\"",
",",
"datatype",
"=",
... | Iterate through semesters, counties and municipalities. | [
"Iterate",
"through",
"semesters",
"counties",
"and",
"municipalities",
"."
] | python | train |
yamcs/yamcs-python | yamcs-client/yamcs/archive/client.py | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/archive/client.py#L96-L123 | def list_processed_parameter_group_histogram(self, group=None, start=None, stop=None, merge_time=20):
"""
Reads index records related to processed parameter groups between the
specified start and stop time.
Each iteration returns a chunk of chronologically-sorted records.
:para... | [
"def",
"list_processed_parameter_group_histogram",
"(",
"self",
",",
"group",
"=",
"None",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"merge_time",
"=",
"20",
")",
":",
"params",
"=",
"{",
"}",
"if",
"group",
"is",
"not",
"None",
":",
"p... | Reads index records related to processed parameter groups between the
specified start and stop time.
Each iteration returns a chunk of chronologically-sorted records.
:param float merge_time: Maximum gap in seconds before two consecutive index records are merged together.
:rtype: ~coll... | [
"Reads",
"index",
"records",
"related",
"to",
"processed",
"parameter",
"groups",
"between",
"the",
"specified",
"start",
"and",
"stop",
"time",
"."
] | python | train |
ronaldguillen/wave | wave/renderers.py | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/renderers.py#L503-L563 | def get_raw_data_form(self, data, view, method, request):
"""
Returns a form that allows for arbitrary content types to be tunneled
via standard HTML forms.
(Which are typically application/x-www-form-urlencoded)
"""
# See issue #2089 for refactoring this.
seriali... | [
"def",
"get_raw_data_form",
"(",
"self",
",",
"data",
",",
"view",
",",
"method",
",",
"request",
")",
":",
"# See issue #2089 for refactoring this.",
"serializer",
"=",
"getattr",
"(",
"data",
",",
"'serializer'",
",",
"None",
")",
"if",
"serializer",
"and",
... | Returns a form that allows for arbitrary content types to be tunneled
via standard HTML forms.
(Which are typically application/x-www-form-urlencoded) | [
"Returns",
"a",
"form",
"that",
"allows",
"for",
"arbitrary",
"content",
"types",
"to",
"be",
"tunneled",
"via",
"standard",
"HTML",
"forms",
".",
"(",
"Which",
"are",
"typically",
"application",
"/",
"x",
"-",
"www",
"-",
"form",
"-",
"urlencoded",
")"
] | python | train |
wrobstory/vincent | vincent/visualization.py | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L153-L161 | def marks(value):
"""list or KeyedList of ``Mark`` : Mark definitions
Marks are the visual objects (such as lines, bars, etc.) that
represent the data in the visualization space. See the :class:`Mark`
class for details.
"""
for i, entry in enumerate(value):
_... | [
"def",
"marks",
"(",
"value",
")",
":",
"for",
"i",
",",
"entry",
"in",
"enumerate",
"(",
"value",
")",
":",
"_assert_is_type",
"(",
"'marks[{0}]'",
".",
"format",
"(",
"i",
")",
",",
"entry",
",",
"Mark",
")"
] | list or KeyedList of ``Mark`` : Mark definitions
Marks are the visual objects (such as lines, bars, etc.) that
represent the data in the visualization space. See the :class:`Mark`
class for details. | [
"list",
"or",
"KeyedList",
"of",
"Mark",
":",
"Mark",
"definitions"
] | python | train |
v1k45/python-qBittorrent | qbittorrent/client.py | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L93-L113 | def login(self, username='admin', password='admin'):
"""
Method to authenticate the qBittorrent Client.
Declares a class attribute named ``session`` which
stores the authenticated session if the login is correct.
Else, shows the login error.
:param username: Username.
... | [
"def",
"login",
"(",
"self",
",",
"username",
"=",
"'admin'",
",",
"password",
"=",
"'admin'",
")",
":",
"self",
".",
"session",
"=",
"requests",
".",
"Session",
"(",
")",
"login",
"=",
"self",
".",
"session",
".",
"post",
"(",
"self",
".",
"url",
... | Method to authenticate the qBittorrent Client.
Declares a class attribute named ``session`` which
stores the authenticated session if the login is correct.
Else, shows the login error.
:param username: Username.
:param password: Password.
:return: Response to login req... | [
"Method",
"to",
"authenticate",
"the",
"qBittorrent",
"Client",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/transpiler/passes/mapping/dense_layout.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/dense_layout.py#L68-L121 | def _best_subset(self, n_qubits):
"""Computes the qubit mapping with the best connectivity.
Args:
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best connectivity mapping.
"""
if n_qubits == 1:
... | [
"def",
"_best_subset",
"(",
"self",
",",
"n_qubits",
")",
":",
"if",
"n_qubits",
"==",
"1",
":",
"return",
"np",
".",
"array",
"(",
"[",
"0",
"]",
")",
"device_qubits",
"=",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
"cmap",
"=",
"np",
"."... | Computes the qubit mapping with the best connectivity.
Args:
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best connectivity mapping. | [
"Computes",
"the",
"qubit",
"mapping",
"with",
"the",
"best",
"connectivity",
"."
] | python | test |
broadinstitute/fiss | firecloud/supervisor.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/supervisor.py#L148-L289 | def supervise_until_complete(monitor_data, dependencies, args, recovery_file):
""" Supervisor loop. Loop forever until all tasks are evaluated or completed """
project = args['project']
workspace = args['workspace']
namespace = args['namespace']
sample_sets = args['sample_sets']
recovery_data = ... | [
"def",
"supervise_until_complete",
"(",
"monitor_data",
",",
"dependencies",
",",
"args",
",",
"recovery_file",
")",
":",
"project",
"=",
"args",
"[",
"'project'",
"]",
"workspace",
"=",
"args",
"[",
"'workspace'",
"]",
"namespace",
"=",
"args",
"[",
"'namespa... | Supervisor loop. Loop forever until all tasks are evaluated or completed | [
"Supervisor",
"loop",
".",
"Loop",
"forever",
"until",
"all",
"tasks",
"are",
"evaluated",
"or",
"completed"
] | python | train |
google/dotty | efilter/protocols/repeated.py | https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/protocols/repeated.py#L55-L78 | def meld(*values):
"""Return the repeated value, or the first value if there's only one.
This is a convenience function, equivalent to calling
getvalue(repeated(x)) to get x.
This function skips over instances of None in values (None is not allowed
in repeated variables).
Examples:
me... | [
"def",
"meld",
"(",
"*",
"values",
")",
":",
"values",
"=",
"[",
"x",
"for",
"x",
"in",
"values",
"if",
"x",
"is",
"not",
"None",
"]",
"if",
"not",
"values",
":",
"return",
"None",
"result",
"=",
"repeated",
"(",
"*",
"values",
")",
"if",
"isrepe... | Return the repeated value, or the first value if there's only one.
This is a convenience function, equivalent to calling
getvalue(repeated(x)) to get x.
This function skips over instances of None in values (None is not allowed
in repeated variables).
Examples:
meld("foo", "bar") # => List... | [
"Return",
"the",
"repeated",
"value",
"or",
"the",
"first",
"value",
"if",
"there",
"s",
"only",
"one",
"."
] | python | train |
apache/airflow | airflow/www/api/experimental/endpoints.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/api/experimental/endpoints.py#L142-L150 | def get_dag_code(dag_id):
"""Return python code of a given dag_id."""
try:
return get_code(dag_id)
except AirflowException as err:
_log.info(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response | [
"def",
"get_dag_code",
"(",
"dag_id",
")",
":",
"try",
":",
"return",
"get_code",
"(",
"dag_id",
")",
"except",
"AirflowException",
"as",
"err",
":",
"_log",
".",
"info",
"(",
"err",
")",
"response",
"=",
"jsonify",
"(",
"error",
"=",
"\"{}\"",
".",
"f... | Return python code of a given dag_id. | [
"Return",
"python",
"code",
"of",
"a",
"given",
"dag_id",
"."
] | python | test |
google/grr | grr/server/grr_response_server/gui/api_plugins/vfs.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_plugins/vfs.py#L1279-L1288 | def _GetTimelineStatEntries(client_id, file_path, with_history=True):
"""Gets timeline entries from the appropriate data source (AFF4 or REL_DB)."""
if data_store.RelationalDBEnabled():
fn = _GetTimelineStatEntriesRelDB
else:
fn = _GetTimelineStatEntriesLegacy
for v in fn(client_id, file_path, with_hi... | [
"def",
"_GetTimelineStatEntries",
"(",
"client_id",
",",
"file_path",
",",
"with_history",
"=",
"True",
")",
":",
"if",
"data_store",
".",
"RelationalDBEnabled",
"(",
")",
":",
"fn",
"=",
"_GetTimelineStatEntriesRelDB",
"else",
":",
"fn",
"=",
"_GetTimelineStatEnt... | Gets timeline entries from the appropriate data source (AFF4 or REL_DB). | [
"Gets",
"timeline",
"entries",
"from",
"the",
"appropriate",
"data",
"source",
"(",
"AFF4",
"or",
"REL_DB",
")",
"."
] | python | train |
OpenKMIP/PyKMIP | kmip/services/server/engine.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/services/server/engine.py#L865-L917 | def is_allowed(
self,
policy_name,
session_user,
session_group,
object_owner,
object_type,
operation
):
"""
Determine if object access is allowed for the provided policy and
session settings.
"""
... | [
"def",
"is_allowed",
"(",
"self",
",",
"policy_name",
",",
"session_user",
",",
"session_group",
",",
"object_owner",
",",
"object_type",
",",
"operation",
")",
":",
"policy_section",
"=",
"self",
".",
"get_relevant_policy_section",
"(",
"policy_name",
",",
"sessi... | Determine if object access is allowed for the provided policy and
session settings. | [
"Determine",
"if",
"object",
"access",
"is",
"allowed",
"for",
"the",
"provided",
"policy",
"and",
"session",
"settings",
"."
] | python | test |
Yelp/threat_intel | threat_intel/opendns.py | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L324-L334 | def risk_score(self, domains):
"""Performs Umbrella risk score analysis on the input domains
Args:
domains: an enumerable of domains
Returns:
An enumerable of associated domain risk scores
"""
api_name = 'opendns-risk_score'
fmt_url_path = u'domai... | [
"def",
"risk_score",
"(",
"self",
",",
"domains",
")",
":",
"api_name",
"=",
"'opendns-risk_score'",
"fmt_url_path",
"=",
"u'domains/risk-score/{0}'",
"return",
"self",
".",
"_multi_get",
"(",
"api_name",
",",
"fmt_url_path",
",",
"domains",
")"
] | Performs Umbrella risk score analysis on the input domains
Args:
domains: an enumerable of domains
Returns:
An enumerable of associated domain risk scores | [
"Performs",
"Umbrella",
"risk",
"score",
"analysis",
"on",
"the",
"input",
"domains"
] | python | train |
jobovy/galpy | galpy/orbit/OrbitTop.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L543-L564 | def bb(self,*args,**kwargs):
"""
NAME:
bb
PURPOSE:
return Galactic latitude
INPUT:
t - (optional) time at which to get bb
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(default=Object-wide default)
... | [
"def",
"bb",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_check_roSet",
"(",
"self",
",",
"kwargs",
",",
"'bb'",
")",
"lbd",
"=",
"self",
".",
"_lbd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"lbd",
"[",
... | NAME:
bb
PURPOSE:
return Galactic latitude
INPUT:
t - (optional) time at which to get bb
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(default=Object-wide default)
OR Orbit object that corresponds to... | [
"NAME",
":",
"bb",
"PURPOSE",
":",
"return",
"Galactic",
"latitude",
"INPUT",
":",
"t",
"-",
"(",
"optional",
")",
"time",
"at",
"which",
"to",
"get",
"bb",
"obs",
"=",
"[",
"X",
"Y",
"Z",
"]",
"-",
"(",
"optional",
")",
"position",
"of",
"observer... | python | train |
cggh/scikit-allel | allel/model/ndarray.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/model/ndarray.py#L2971-L3027 | def map_alleles(self, mapping, max_allele=None):
"""Transform alleles via a mapping.
Parameters
----------
mapping : ndarray, int8, shape (n_variants, max_allele)
An array defining the allele mapping for each variant.
max_allele : int, optional
Highest al... | [
"def",
"map_alleles",
"(",
"self",
",",
"mapping",
",",
"max_allele",
"=",
"None",
")",
":",
"# ensure correct dimensionality and matching dtype",
"mapping",
"=",
"asarray_ndim",
"(",
"mapping",
",",
"2",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"check_dim0... | Transform alleles via a mapping.
Parameters
----------
mapping : ndarray, int8, shape (n_variants, max_allele)
An array defining the allele mapping for each variant.
max_allele : int, optional
Highest allele index expected in the output. If not provided
... | [
"Transform",
"alleles",
"via",
"a",
"mapping",
"."
] | python | train |
koenedaele/skosprovider | skosprovider/skos.py | https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/skos.py#L555-L571 | def filter_labels_by_language(labels, language, broader=False):
'''
Filter a list of labels, leaving only labels of a certain language.
:param list labels: A list of :class:`Label`.
:param str language: An IANA language string, eg. `nl` or `nl-BE`.
:param boolean broader: When true, will also match... | [
"def",
"filter_labels_by_language",
"(",
"labels",
",",
"language",
",",
"broader",
"=",
"False",
")",
":",
"if",
"language",
"==",
"'any'",
":",
"return",
"labels",
"if",
"broader",
":",
"language",
"=",
"tags",
".",
"tag",
"(",
"language",
")",
".",
"l... | Filter a list of labels, leaving only labels of a certain language.
:param list labels: A list of :class:`Label`.
:param str language: An IANA language string, eg. `nl` or `nl-BE`.
:param boolean broader: When true, will also match `nl-BE` when filtering
on `nl`. When false, only exact matches are ... | [
"Filter",
"a",
"list",
"of",
"labels",
"leaving",
"only",
"labels",
"of",
"a",
"certain",
"language",
"."
] | python | valid |
saltstack/salt | salt/utils/thin.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/thin.py#L155-L166 | def _add_dependency(container, obj):
'''
Add a dependency to the top list.
:param obj:
:param is_file:
:return:
'''
if os.path.basename(obj.__file__).split('.')[0] == '__init__':
container.append(os.path.dirname(obj.__file__))
else:
container.append(obj.__file__.replace(... | [
"def",
"_add_dependency",
"(",
"container",
",",
"obj",
")",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"obj",
".",
"__file__",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"==",
"'__init__'",
":",
"container",
".",
"append",
"(",
"o... | Add a dependency to the top list.
:param obj:
:param is_file:
:return: | [
"Add",
"a",
"dependency",
"to",
"the",
"top",
"list",
"."
] | python | train |
mpg-age-bioinformatics/AGEpy | AGEpy/fasta.py | https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/fasta.py#L54-L92 | def rewriteFasta(sequence, sequence_name, fasta_in, fasta_out):
"""
Rewrites a specific sequence in a multifasta file while keeping the sequence header.
:param sequence: a string with the sequence to be written
:param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome ch... | [
"def",
"rewriteFasta",
"(",
"sequence",
",",
"sequence_name",
",",
"fasta_in",
",",
"fasta_out",
")",
":",
"f",
"=",
"open",
"(",
"fasta_in",
",",
"'r+'",
")",
"f2",
"=",
"open",
"(",
"fasta_out",
",",
"'w'",
")",
"lines",
"=",
"f",
".",
"readlines",
... | Rewrites a specific sequence in a multifasta file while keeping the sequence header.
:param sequence: a string with the sequence to be written
:param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:182113224:1 REF' use: sequence_name=str(2)
:param fa... | [
"Rewrites",
"a",
"specific",
"sequence",
"in",
"a",
"multifasta",
"file",
"while",
"keeping",
"the",
"sequence",
"header",
"."
] | python | train |
xaptum/xtt-python | xtt/_utils.py | https://github.com/xaptum/xtt-python/blob/23ee469488d710d730314bec1136c4dd7ac2cd5c/xtt/_utils.py#L21-L31 | def to_bytes(s, encoding="utf-8"):
"""
Converts the string to a bytes type, if not already.
:s: the string to convert to bytes
:returns: `str` on Python2 and `bytes` on Python3.
"""
if isinstance(s, six.binary_type):
return s
else:
return six.text_type(s).encode(encoding) | [
"def",
"to_bytes",
"(",
"s",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"binary_type",
")",
":",
"return",
"s",
"else",
":",
"return",
"six",
".",
"text_type",
"(",
"s",
")",
".",
"encode",
"(",
"enc... | Converts the string to a bytes type, if not already.
:s: the string to convert to bytes
:returns: `str` on Python2 and `bytes` on Python3. | [
"Converts",
"the",
"string",
"to",
"a",
"bytes",
"type",
"if",
"not",
"already",
"."
] | python | train |
Titan-C/slaveparticles | slaveparticles/utils/plotter.py | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/utils/plotter.py#L11-L27 | def solve_loop(slsp, u_span, j_coup):
"""Calculates the quasiparticle for the input loop of:
@param slsp: Slave spin Object
@param Uspan: local Couloumb interation
@param J_coup: Fraction of Uspan of Hund coupling strength"""
zet, lam, eps, hlog, mean_f = [], [], [], [], [None]
for... | [
"def",
"solve_loop",
"(",
"slsp",
",",
"u_span",
",",
"j_coup",
")",
":",
"zet",
",",
"lam",
",",
"eps",
",",
"hlog",
",",
"mean_f",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"None",
"]",
"for",
"u",
"in",
"u_spa... | Calculates the quasiparticle for the input loop of:
@param slsp: Slave spin Object
@param Uspan: local Couloumb interation
@param J_coup: Fraction of Uspan of Hund coupling strength | [
"Calculates",
"the",
"quasiparticle",
"for",
"the",
"input",
"loop",
"of",
":"
] | python | train |
persephone-tools/persephone | persephone/corpus.py | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L368-L392 | def prepare_feats(self) -> None:
""" Prepares input features"""
logger.debug("Preparing input features")
self.feat_dir.mkdir(parents=True, exist_ok=True)
should_extract_feats = False
for path in self.wav_dir.iterdir():
if not path.suffix == ".wav":
l... | [
"def",
"prepare_feats",
"(",
"self",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"\"Preparing input features\"",
")",
"self",
".",
"feat_dir",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"should_extract_feats",
"=",... | Prepares input features | [
"Prepares",
"input",
"features"
] | python | train |
BoGoEngine/bogo-python | bogo/utils.py | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/utils.py#L51-L75 | def append_comps(comps, char):
"""
Append a character to `comps` following this rule: a vowel is added to the
vowel part if there is no last consonant, else to the last consonant part;
a consonant is added to the first consonant part if there is no vowel, and
to the last consonant part if the vowel ... | [
"def",
"append_comps",
"(",
"comps",
",",
"char",
")",
":",
"c",
"=",
"list",
"(",
"comps",
")",
"if",
"is_vowel",
"(",
"char",
")",
":",
"if",
"not",
"c",
"[",
"2",
"]",
":",
"pos",
"=",
"1",
"else",
":",
"pos",
"=",
"2",
"else",
":",
"if",
... | Append a character to `comps` following this rule: a vowel is added to the
vowel part if there is no last consonant, else to the last consonant part;
a consonant is added to the first consonant part if there is no vowel, and
to the last consonant part if the vowel part is not empty.
>>> transform(['', ... | [
"Append",
"a",
"character",
"to",
"comps",
"following",
"this",
"rule",
":",
"a",
"vowel",
"is",
"added",
"to",
"the",
"vowel",
"part",
"if",
"there",
"is",
"no",
"last",
"consonant",
"else",
"to",
"the",
"last",
"consonant",
"part",
";",
"a",
"consonant... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.