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 |
|---|---|---|---|---|---|---|---|---|
vicalloy/lbutils | lbutils/templatetags/lbutils.py | https://github.com/vicalloy/lbutils/blob/66ae7e73bc939f073cdc1b91602a95e67caf4ba6/lbutils/templatetags/lbutils.py#L12-L26 | def get_setting(context, key, default_val="", as_key=None):
"""
get val form settings and set to context
{% load lbutils %}
{% get_setting "key" default_val "as_key" %}
{{ as_key }}
if as_key is None, this tag will return val
"""
if ("%s" % default_val).startswith('$.'):
... | [
"def",
"get_setting",
"(",
"context",
",",
"key",
",",
"default_val",
"=",
"\"\"",
",",
"as_key",
"=",
"None",
")",
":",
"if",
"(",
"\"%s\"",
"%",
"default_val",
")",
".",
"startswith",
"(",
"'$.'",
")",
":",
"default_val",
"=",
"getattr",
"(",
"settin... | get val form settings and set to context
{% load lbutils %}
{% get_setting "key" default_val "as_key" %}
{{ as_key }}
if as_key is None, this tag will return val | [
"get",
"val",
"form",
"settings",
"and",
"set",
"to",
"context",
"{",
"%",
"load",
"lbutils",
"%",
"}",
"{",
"%",
"get_setting",
"key",
"default_val",
"as_key",
"%",
"}",
"{{",
"as_key",
"}}",
"if",
"as_key",
"is",
"None",
"this",
"tag",
"will",
"retur... | python | train |
Hackerfleet/hfos | hfos/tool/objects.py | https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/objects.py#L118-L150 | def delete(ctx, schema, uuid, object_filter, yes):
"""Delete stored objects (CAUTION!)"""
database = ctx.obj['db']
if schema is None:
log('No schema given. Read the help', lvl=warn)
return
model = database.objectmodels[schema]
if uuid:
count = model.count({'uuid': uuid})
... | [
"def",
"delete",
"(",
"ctx",
",",
"schema",
",",
"uuid",
",",
"object_filter",
",",
"yes",
")",
":",
"database",
"=",
"ctx",
".",
"obj",
"[",
"'db'",
"]",
"if",
"schema",
"is",
"None",
":",
"log",
"(",
"'No schema given. Read the help'",
",",
"lvl",
"=... | Delete stored objects (CAUTION!) | [
"Delete",
"stored",
"objects",
"(",
"CAUTION!",
")"
] | python | train |
willhardy/django-seo | rollyourown/seo/admin.py | https://github.com/willhardy/django-seo/blob/3089686a3c490091315860979ad15ef2527c3e3e/rollyourown/seo/admin.py#L187-L196 | def core_choice_fields(metadata_class):
""" If the 'optional' core fields (_site and _language) are required,
list them here.
"""
fields = []
if metadata_class._meta.use_sites:
fields.append('_site')
if metadata_class._meta.use_i18n:
fields.append('_language')
return fi... | [
"def",
"core_choice_fields",
"(",
"metadata_class",
")",
":",
"fields",
"=",
"[",
"]",
"if",
"metadata_class",
".",
"_meta",
".",
"use_sites",
":",
"fields",
".",
"append",
"(",
"'_site'",
")",
"if",
"metadata_class",
".",
"_meta",
".",
"use_i18n",
":",
"f... | If the 'optional' core fields (_site and _language) are required,
list them here. | [
"If",
"the",
"optional",
"core",
"fields",
"(",
"_site",
"and",
"_language",
")",
"are",
"required",
"list",
"them",
"here",
"."
] | python | train |
ohenrik/tabs | tabs/tables.py | https://github.com/ohenrik/tabs/blob/039ced6c5612ecdd551aeaac63789862aba05711/tabs/tables.py#L223-L235 | def fetch(self, rebuild=False, cache=True):
"""Fetches the table and applies all post processors.
Args:
rebuild (bool): Rebuild the table and ignore cache. Default: False
cache (bool): Cache the finished table for faster future loading.
Default: True
"""
... | [
"def",
"fetch",
"(",
"self",
",",
"rebuild",
"=",
"False",
",",
"cache",
"=",
"True",
")",
":",
"if",
"rebuild",
":",
"return",
"self",
".",
"_process_table",
"(",
"cache",
")",
"try",
":",
"return",
"self",
".",
"read_cache",
"(",
")",
"except",
"Fi... | Fetches the table and applies all post processors.
Args:
rebuild (bool): Rebuild the table and ignore cache. Default: False
cache (bool): Cache the finished table for faster future loading.
Default: True | [
"Fetches",
"the",
"table",
"and",
"applies",
"all",
"post",
"processors",
".",
"Args",
":",
"rebuild",
"(",
"bool",
")",
":",
"Rebuild",
"the",
"table",
"and",
"ignore",
"cache",
".",
"Default",
":",
"False",
"cache",
"(",
"bool",
")",
":",
"Cache",
"t... | python | train |
dpkp/kafka-python | kafka/conn.py | https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/conn.py#L733-L741 | def blacked_out(self):
"""
Return true if we are disconnected from the given node and can't
re-establish a connection yet
"""
if self.state is ConnectionStates.DISCONNECTED:
if time.time() < self.last_attempt + self._reconnect_backoff:
return True
... | [
"def",
"blacked_out",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"is",
"ConnectionStates",
".",
"DISCONNECTED",
":",
"if",
"time",
".",
"time",
"(",
")",
"<",
"self",
".",
"last_attempt",
"+",
"self",
".",
"_reconnect_backoff",
":",
"return",
"Tr... | Return true if we are disconnected from the given node and can't
re-establish a connection yet | [
"Return",
"true",
"if",
"we",
"are",
"disconnected",
"from",
"the",
"given",
"node",
"and",
"can",
"t",
"re",
"-",
"establish",
"a",
"connection",
"yet"
] | python | train |
romanz/trezor-agent | libagent/gpg/decode.py | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/decode.py#L193-L197 | def _parse_user_id(stream, packet_type='user_id'):
"""See https://tools.ietf.org/html/rfc4880#section-5.11 for details."""
value = stream.read()
to_hash = b'\xb4' + util.prefix_len('>L', value)
return {'type': packet_type, 'value': value, '_to_hash': to_hash} | [
"def",
"_parse_user_id",
"(",
"stream",
",",
"packet_type",
"=",
"'user_id'",
")",
":",
"value",
"=",
"stream",
".",
"read",
"(",
")",
"to_hash",
"=",
"b'\\xb4'",
"+",
"util",
".",
"prefix_len",
"(",
"'>L'",
",",
"value",
")",
"return",
"{",
"'type'",
... | See https://tools.ietf.org/html/rfc4880#section-5.11 for details. | [
"See",
"https",
":",
"//",
"tools",
".",
"ietf",
".",
"org",
"/",
"html",
"/",
"rfc4880#section",
"-",
"5",
".",
"11",
"for",
"details",
"."
] | python | train |
orb-framework/orb | orb/core/database.py | https://github.com/orb-framework/orb/blob/575be2689cb269e65a0a2678232ff940acc19e5a/orb/core/database.py#L66-L75 | def activate(self, manager=None):
"""
Activates this database within the given orb instance. This will
register the database to orb and then set it as the active one.
:param manager | <orb.Manager>
"""
manager = manager or orb.system
manager.activat... | [
"def",
"activate",
"(",
"self",
",",
"manager",
"=",
"None",
")",
":",
"manager",
"=",
"manager",
"or",
"orb",
".",
"system",
"manager",
".",
"activate",
"(",
"self",
")",
"return",
"True"
] | Activates this database within the given orb instance. This will
register the database to orb and then set it as the active one.
:param manager | <orb.Manager> | [
"Activates",
"this",
"database",
"within",
"the",
"given",
"orb",
"instance",
".",
"This",
"will",
"register",
"the",
"database",
"to",
"orb",
"and",
"then",
"set",
"it",
"as",
"the",
"active",
"one",
".",
":",
"param",
"manager",
"|",
"<orb",
".",
"Mana... | python | train |
LISE-B26/pylabcontrol | pylabcontrol/scripts/select_points.py | https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/pylabcontrol/scripts/select_points.py#L120-L253 | def toggle_NV(self, pt):
'''
If there is not currently a selected NV within self.settings[patch_size] of pt, adds it to the selected list. If
there is, removes that point from the selected list.
Args:
pt: the point to add or remove from the selected list
Poststate: up... | [
"def",
"toggle_NV",
"(",
"self",
",",
"pt",
")",
":",
"if",
"not",
"self",
".",
"data",
"[",
"'nv_locations'",
"]",
":",
"#if self.data is empty so this is the first point",
"self",
".",
"data",
"[",
"'nv_locations'",
"]",
".",
"append",
"(",
"pt",
")",
"sel... | If there is not currently a selected NV within self.settings[patch_size] of pt, adds it to the selected list. If
there is, removes that point from the selected list.
Args:
pt: the point to add or remove from the selected list
Poststate: updates selected list | [
"If",
"there",
"is",
"not",
"currently",
"a",
"selected",
"NV",
"within",
"self",
".",
"settings",
"[",
"patch_size",
"]",
"of",
"pt",
"adds",
"it",
"to",
"the",
"selected",
"list",
".",
"If",
"there",
"is",
"removes",
"that",
"point",
"from",
"the",
"... | python | train |
klen/pylama | pylama/config.py | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/config.py#L242-L258 | def get_config(ini_path=None, rootdir=None):
""" Load configuration from INI.
:return Namespace:
"""
config = Namespace()
config.default_section = 'pylama'
if not ini_path:
path = get_default_config_file(rootdir)
if path:
config.read(path)
else:
config.... | [
"def",
"get_config",
"(",
"ini_path",
"=",
"None",
",",
"rootdir",
"=",
"None",
")",
":",
"config",
"=",
"Namespace",
"(",
")",
"config",
".",
"default_section",
"=",
"'pylama'",
"if",
"not",
"ini_path",
":",
"path",
"=",
"get_default_config_file",
"(",
"r... | Load configuration from INI.
:return Namespace: | [
"Load",
"configuration",
"from",
"INI",
"."
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/msi.py#L225-L265 | def create_default_directory_layout(root, NAME, VERSION, VENDOR, filename_set):
""" Create the wix default target directory layout and return the innermost
directory.
We assume that the XML tree delivered in the root argument already contains
the Product tag.
Everything is put under the PFiles dir... | [
"def",
"create_default_directory_layout",
"(",
"root",
",",
"NAME",
",",
"VERSION",
",",
"VENDOR",
",",
"filename_set",
")",
":",
"doc",
"=",
"Document",
"(",
")",
"d1",
"=",
"doc",
".",
"createElement",
"(",
"'Directory'",
")",
"d1",
".",
"attributes",
"[... | Create the wix default target directory layout and return the innermost
directory.
We assume that the XML tree delivered in the root argument already contains
the Product tag.
Everything is put under the PFiles directory property defined by WiX.
After that a directory with the 'VENDOR' tag is pla... | [
"Create",
"the",
"wix",
"default",
"target",
"directory",
"layout",
"and",
"return",
"the",
"innermost",
"directory",
"."
] | python | train |
prompt-toolkit/ptpython | ptpython/eventloop.py | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/eventloop.py#L18-L64 | def _inputhook_tk(inputhook_context):
"""
Inputhook for Tk.
Run the Tk eventloop until prompt-toolkit needs to process the next input.
"""
# Get the current TK application.
import _tkinter # Keep this imports inline!
from six.moves import tkinter
root = tkinter._default_root
def wa... | [
"def",
"_inputhook_tk",
"(",
"inputhook_context",
")",
":",
"# Get the current TK application.",
"import",
"_tkinter",
"# Keep this imports inline!",
"from",
"six",
".",
"moves",
"import",
"tkinter",
"root",
"=",
"tkinter",
".",
"_default_root",
"def",
"wait_using_filehan... | Inputhook for Tk.
Run the Tk eventloop until prompt-toolkit needs to process the next input. | [
"Inputhook",
"for",
"Tk",
".",
"Run",
"the",
"Tk",
"eventloop",
"until",
"prompt",
"-",
"toolkit",
"needs",
"to",
"process",
"the",
"next",
"input",
"."
] | python | train |
knipknap/SpiffWorkflow | SpiffWorkflow/bpmn/workflow.py | https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/workflow.py#L90-L95 | def get_ready_user_tasks(self):
"""
Returns a list of User Tasks that are READY for user action
"""
return [t for t in self.get_tasks(Task.READY)
if not self._is_engine_task(t.task_spec)] | [
"def",
"get_ready_user_tasks",
"(",
"self",
")",
":",
"return",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"get_tasks",
"(",
"Task",
".",
"READY",
")",
"if",
"not",
"self",
".",
"_is_engine_task",
"(",
"t",
".",
"task_spec",
")",
"]"
] | Returns a list of User Tasks that are READY for user action | [
"Returns",
"a",
"list",
"of",
"User",
"Tasks",
"that",
"are",
"READY",
"for",
"user",
"action"
] | python | valid |
carpedm20/ndrive | ndrive/models.py | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/ndrive/models.py#L368-L398 | def put(self, file_path, upload_path = ''):
"""PUT
Args:
file_path: Full path for a file you want to upload
upload_path: Ndrive path where you want to upload file
ex) /Picture/
Returns:
True: Upload success
False: Upload failed
... | [
"def",
"put",
"(",
"self",
",",
"file_path",
",",
"upload_path",
"=",
"''",
")",
":",
"f",
"=",
"open",
"(",
"file_path",
",",
"\"r\"",
")",
"c",
"=",
"f",
".",
"read",
"(",
")",
"file_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file_pa... | PUT
Args:
file_path: Full path for a file you want to upload
upload_path: Ndrive path where you want to upload file
ex) /Picture/
Returns:
True: Upload success
False: Upload failed | [
"PUT"
] | python | train |
saltstack/salt | salt/cloud/clouds/softlayer_hw.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer_hw.py#L619-L643 | def show_all_prices(call=None, kwargs=None):
'''
Return a dict of all prices on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_prices function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
conn... | [
"def",
"show_all_prices",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The show_all_prices function must be called with -f or --function.'",
")",
"if",
"kwargs",
"is",
"No... | Return a dict of all prices on the cloud provider. | [
"Return",
"a",
"dict",
"of",
"all",
"prices",
"on",
"the",
"cloud",
"provider",
"."
] | python | train |
NiklasRosenstein-Python/nr-deprecated | nr/concurrency.py | https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L841-L892 | def submit(self, target=None, task=None, args=(), kwargs=None, front=False,
dispose_inputs=None):
"""
Submit a new #Job to the ThreadPool.
# Arguments
task (function, Job): Either a function that accepts a #Job, *args* and
*kwargs* or a #Job object that is in #~Job.PENDING state.
... | [
"def",
"submit",
"(",
"self",
",",
"target",
"=",
"None",
",",
"task",
"=",
"None",
",",
"args",
"=",
"(",
")",
",",
"kwargs",
"=",
"None",
",",
"front",
"=",
"False",
",",
"dispose_inputs",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"__run... | Submit a new #Job to the ThreadPool.
# Arguments
task (function, Job): Either a function that accepts a #Job, *args* and
*kwargs* or a #Job object that is in #~Job.PENDING state.
target (function): A function object that accepts *args* and *kwargs*.
Only if *task* is not specified.
args (li... | [
"Submit",
"a",
"new",
"#Job",
"to",
"the",
"ThreadPool",
"."
] | python | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/universal.py | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/universal.py#L877-L946 | def com_google_fonts_check_ttx_roundtrip(font):
"""Checking with fontTools.ttx"""
from fontTools import ttx
import sys
ttFont = ttx.TTFont(font)
failed = False
class TTXLogger:
msgs = []
def __init__(self):
self.original_stderr = sys.stderr
self.original_stdout = sys.stdout
sys.s... | [
"def",
"com_google_fonts_check_ttx_roundtrip",
"(",
"font",
")",
":",
"from",
"fontTools",
"import",
"ttx",
"import",
"sys",
"ttFont",
"=",
"ttx",
".",
"TTFont",
"(",
"font",
")",
"failed",
"=",
"False",
"class",
"TTXLogger",
":",
"msgs",
"=",
"[",
"]",
"d... | Checking with fontTools.ttx | [
"Checking",
"with",
"fontTools",
".",
"ttx"
] | python | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_model.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_model.py#L669-L729 | def calc_wada_waes_v1(self):
"""Calculate the actual water release from the snow cover.
Required control parameters:
|NHRU|
|Lnk|
|PWMax|
Required flux sequences:
|NBes|
Calculated flux sequence:
|WaDa|
Updated state sequence:
|WAeS|
Basic equations:
... | [
"def",
"calc_wada_waes_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"sta",
"=",
"self",
".",
"sequences",
".",
"states",
".",... | Calculate the actual water release from the snow cover.
Required control parameters:
|NHRU|
|Lnk|
|PWMax|
Required flux sequences:
|NBes|
Calculated flux sequence:
|WaDa|
Updated state sequence:
|WAeS|
Basic equations:
:math:`\\frac{dWAeS}{dt} = NBes - ... | [
"Calculate",
"the",
"actual",
"water",
"release",
"from",
"the",
"snow",
"cover",
"."
] | python | train |
ndokter/dsmr_parser | dsmr_parser/__main__.py | https://github.com/ndokter/dsmr_parser/blob/c04b0a5add58ce70153eede1a87ca171876b61c7/dsmr_parser/__main__.py#L9-L65 | def console():
"""Output DSMR data to console."""
parser = argparse.ArgumentParser(description=console.__doc__)
parser.add_argument('--device', default='/dev/ttyUSB0',
help='port to read DSMR data from')
parser.add_argument('--host', default=None,
help='a... | [
"def",
"console",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"console",
".",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'--device'",
",",
"default",
"=",
"'/dev/ttyUSB0'",
",",
"help",
"=",
"'port to r... | Output DSMR data to console. | [
"Output",
"DSMR",
"data",
"to",
"console",
"."
] | python | test |
facelessuser/soupsieve | soupsieve/css_match.py | https://github.com/facelessuser/soupsieve/blob/24859cc3e756ebf46b75547d49c6b4a7bf35ee82/soupsieve/css_match.py#L348-L354 | def validate_week(year, week):
"""Validate week."""
max_week = datetime.strptime("{}-{}-{}".format(12, 31, year), "%m-%d-%Y").isocalendar()[1]
if max_week == 1:
max_week = 53
return 1 <= week <= max_week | [
"def",
"validate_week",
"(",
"year",
",",
"week",
")",
":",
"max_week",
"=",
"datetime",
".",
"strptime",
"(",
"\"{}-{}-{}\"",
".",
"format",
"(",
"12",
",",
"31",
",",
"year",
")",
",",
"\"%m-%d-%Y\"",
")",
".",
"isocalendar",
"(",
")",
"[",
"1",
"]... | Validate week. | [
"Validate",
"week",
"."
] | python | train |
jedie/DragonPy | PyDC/PyDC/utils.py | https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L185-L208 | def count_continuous_pattern(bitstream, pattern):
"""
>>> pattern = list(bytes2bit_strings("A"))
>>> bitstream = bytes2bit_strings("AAAXXX")
>>> count_continuous_pattern(bitstream, pattern)
3
>>> pattern = list(bytes2bit_strings("X"))
>>> bitstream = bytes2bit_strings("AAAXXX")
>>> coun... | [
"def",
"count_continuous_pattern",
"(",
"bitstream",
",",
"pattern",
")",
":",
"assert",
"isinstance",
"(",
"bitstream",
",",
"(",
"collections",
".",
"Iterable",
",",
"types",
".",
"GeneratorType",
")",
")",
"assert",
"isinstance",
"(",
"pattern",
",",
"(",
... | >>> pattern = list(bytes2bit_strings("A"))
>>> bitstream = bytes2bit_strings("AAAXXX")
>>> count_continuous_pattern(bitstream, pattern)
3
>>> pattern = list(bytes2bit_strings("X"))
>>> bitstream = bytes2bit_strings("AAAXXX")
>>> count_continuous_pattern(bitstream, pattern)
0 | [
">>>",
"pattern",
"=",
"list",
"(",
"bytes2bit_strings",
"(",
"A",
"))",
">>>",
"bitstream",
"=",
"bytes2bit_strings",
"(",
"AAAXXX",
")",
">>>",
"count_continuous_pattern",
"(",
"bitstream",
"pattern",
")",
"3"
] | python | train |
jantman/awslimitchecker | awslimitchecker/services/ses.py | https://github.com/jantman/awslimitchecker/blob/e50197f70f3d0abcc5cfc7fde6336f548b790e34/awslimitchecker/services/ses.py#L104-L120 | def _update_limits_from_api(self):
"""
Call the service's API action to retrieve limit/quota information, and
update AwsLimit objects in ``self.limits`` with this information.
"""
try:
self.connect()
resp = self.conn.get_send_quota()
except Endpoin... | [
"def",
"_update_limits_from_api",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"connect",
"(",
")",
"resp",
"=",
"self",
".",
"conn",
".",
"get_send_quota",
"(",
")",
"except",
"EndpointConnectionError",
"as",
"ex",
":",
"logger",
".",
"warning",
"(",
... | Call the service's API action to retrieve limit/quota information, and
update AwsLimit objects in ``self.limits`` with this information. | [
"Call",
"the",
"service",
"s",
"API",
"action",
"to",
"retrieve",
"limit",
"/",
"quota",
"information",
"and",
"update",
"AwsLimit",
"objects",
"in",
"self",
".",
"limits",
"with",
"this",
"information",
"."
] | python | train |
a1ezzz/wasp-general | wasp_general/uri.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L150-L168 | def parse(cls, uri):
""" Parse URI-string and return WURI object
:param uri: string to parse
:return: WURI
"""
uri_components = urlsplit(uri)
adapter_fn = lambda x: x if x is not None and (isinstance(x, str) is False or len(x)) > 0 else None
return cls(
scheme=adapter_fn(uri_components.scheme),
us... | [
"def",
"parse",
"(",
"cls",
",",
"uri",
")",
":",
"uri_components",
"=",
"urlsplit",
"(",
"uri",
")",
"adapter_fn",
"=",
"lambda",
"x",
":",
"x",
"if",
"x",
"is",
"not",
"None",
"and",
"(",
"isinstance",
"(",
"x",
",",
"str",
")",
"is",
"False",
... | Parse URI-string and return WURI object
:param uri: string to parse
:return: WURI | [
"Parse",
"URI",
"-",
"string",
"and",
"return",
"WURI",
"object"
] | python | train |
bcbio/bcbio-nextgen | bcbio/variation/cortex.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/cortex.py#L97-L120 | def _combine_variants(in_vcfs, out_file, ref_file, config):
"""Combine variant files, writing the header from the first non-empty input.
in_vcfs is a list with each item starting with the chromosome regions,
and ending with the input file.
We sort by these regions to ensure the output file is in the ex... | [
"def",
"_combine_variants",
"(",
"in_vcfs",
",",
"out_file",
",",
"ref_file",
",",
"config",
")",
":",
"in_vcfs",
".",
"sort",
"(",
")",
"wrote_header",
"=",
"False",
"with",
"open",
"(",
"out_file",
",",
"\"w\"",
")",
"as",
"out_handle",
":",
"for",
"in... | Combine variant files, writing the header from the first non-empty input.
in_vcfs is a list with each item starting with the chromosome regions,
and ending with the input file.
We sort by these regions to ensure the output file is in the expected order. | [
"Combine",
"variant",
"files",
"writing",
"the",
"header",
"from",
"the",
"first",
"non",
"-",
"empty",
"input",
"."
] | python | train |
radjkarl/imgProcessor | imgProcessor/simulate/navierStokes.py | https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/simulate/navierStokes.py#L52-L62 | def shiftImage(u, v, t, img, interpolation=cv2.INTER_LANCZOS4):
'''
remap an image using velocity field
'''
ny,nx = u.shape
sy, sx = np.mgrid[:float(ny):1,:float(nx):1]
sx += u*t
sy += v*t
return cv2.remap(img.astype(np.float32),
(sx).astype(np.float32),
... | [
"def",
"shiftImage",
"(",
"u",
",",
"v",
",",
"t",
",",
"img",
",",
"interpolation",
"=",
"cv2",
".",
"INTER_LANCZOS4",
")",
":",
"ny",
",",
"nx",
"=",
"u",
".",
"shape",
"sy",
",",
"sx",
"=",
"np",
".",
"mgrid",
"[",
":",
"float",
"(",
"ny",
... | remap an image using velocity field | [
"remap",
"an",
"image",
"using",
"velocity",
"field"
] | python | train |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/_backends/iam/apis/aggregator_account_admin_api.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/iam/apis/aggregator_account_admin_api.py#L151-L172 | def add_account_certificate(self, account_id, body, **kwargs): # noqa: E501
"""Upload new trusted certificate. # noqa: E501
An endpoint for uploading new trusted certificates. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/trusted-certificates -d {\"nam... | [
"def",
"add_account_certificate",
"(",
"self",
",",
"account_id",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"retur... | Upload new trusted certificate. # noqa: E501
An endpoint for uploading new trusted certificates. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/trusted-certificates -d {\"name\": \"myCert1\", \"description\": \"very important cert\", \"certificate\": \"certifica... | [
"Upload",
"new",
"trusted",
"certificate",
".",
"#",
"noqa",
":",
"E501"
] | python | train |
underscorephil/dayonelib | dayonelib/__init__.py | https://github.com/underscorephil/dayonelib/blob/4df134f601abcb033ec04cf7596f25ee25d44661/dayonelib/__init__.py#L41-L47 | def add_tag(self, _tags):
"""Add tag(s) to a DayOneEntry"""
if isinstance(_tags, list):
for t in _tags:
self.tags.append(t)
else:
self.tags.append(_tags) | [
"def",
"add_tag",
"(",
"self",
",",
"_tags",
")",
":",
"if",
"isinstance",
"(",
"_tags",
",",
"list",
")",
":",
"for",
"t",
"in",
"_tags",
":",
"self",
".",
"tags",
".",
"append",
"(",
"t",
")",
"else",
":",
"self",
".",
"tags",
".",
"append",
... | Add tag(s) to a DayOneEntry | [
"Add",
"tag",
"(",
"s",
")",
"to",
"a",
"DayOneEntry"
] | python | valid |
msmbuilder/msmbuilder | msmbuilder/utils/nearest.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/utils/nearest.py#L73-L125 | def query(self, x, k=1, p=2, distance_upper_bound=np.inf):
"""Query the kd-tree for nearest neighbors
Parameters
----------
x : array_like, last dimension self.m
An array of points to query.
k : int, optional
The number of nearest neighbors to return.
... | [
"def",
"query",
"(",
"self",
",",
"x",
",",
"k",
"=",
"1",
",",
"p",
"=",
"2",
",",
"distance_upper_bound",
"=",
"np",
".",
"inf",
")",
":",
"cdists",
",",
"cinds",
"=",
"self",
".",
"_kdtree",
".",
"query",
"(",
"x",
",",
"k",
",",
"p",
",",... | Query the kd-tree for nearest neighbors
Parameters
----------
x : array_like, last dimension self.m
An array of points to query.
k : int, optional
The number of nearest neighbors to return.
eps : nonnegative float, optional
Return approximate ... | [
"Query",
"the",
"kd",
"-",
"tree",
"for",
"nearest",
"neighbors"
] | python | train |
kubernetes-client/python | kubernetes/client/apis/core_v1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/core_v1_api.py#L13114-L13141 | def list_namespaced_service_account(self, namespace, **kwargs):
"""
list or watch objects of kind ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_service_acco... | [
"def",
"list_namespaced_service_account",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"list_na... | list or watch objects of kind ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_service_account(namespace, async_req=True)
>>> result = thread.get()
:param asy... | [
"list",
"or",
"watch",
"objects",
"of",
"kind",
"ServiceAccount",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
... | python | train |
ShadowBlip/Neteria | neteria/server.py | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/server.py#L432-L451 | def is_registered(self, cuuid, host):
"""This function will check to see if a given host with client uuid is
currently registered.
Args:
cuuid (string): The client uuid that wishes to register.
host (tuple): The (address, port) tuple of the client that is
registe... | [
"def",
"is_registered",
"(",
"self",
",",
"cuuid",
",",
"host",
")",
":",
"# Check to see if the host with the client uuid exists in the registry",
"# table.",
"if",
"(",
"cuuid",
"in",
"self",
".",
"registry",
")",
"and",
"(",
"self",
".",
"registry",
"[",
"cuuid... | This function will check to see if a given host with client uuid is
currently registered.
Args:
cuuid (string): The client uuid that wishes to register.
host (tuple): The (address, port) tuple of the client that is
registering.
Returns:
Will return Tru... | [
"This",
"function",
"will",
"check",
"to",
"see",
"if",
"a",
"given",
"host",
"with",
"client",
"uuid",
"is",
"currently",
"registered",
"."
] | python | train |
inspirehep/inspire-schemas | inspire_schemas/builders/authors.py | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L350-L378 | def add_advisor(self, name, ids=None, degree_type=None, record=None, curated=False):
"""Add an advisor.
Args:
:param name: full name of the advisor.
:type name: string
:param ids: list with the IDs of the advisor.
:type ids: list
:param degr... | [
"def",
"add_advisor",
"(",
"self",
",",
"name",
",",
"ids",
"=",
"None",
",",
"degree_type",
"=",
"None",
",",
"record",
"=",
"None",
",",
"curated",
"=",
"False",
")",
":",
"new_advisor",
"=",
"{",
"}",
"new_advisor",
"[",
"'name'",
"]",
"=",
"norma... | Add an advisor.
Args:
:param name: full name of the advisor.
:type name: string
:param ids: list with the IDs of the advisor.
:type ids: list
:param degree_type: one of the allowed types of degree the advisor helped with.
:type degree_ty... | [
"Add",
"an",
"advisor",
"."
] | python | train |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L764-L776 | def MakePmfFromDict(d, name=''):
"""Makes a PMF from a map from values to probabilities.
Args:
d: dictionary that maps values to probabilities
name: string name for this PMF
Returns:
Pmf object
"""
pmf = Pmf(d, name)
pmf.Normalize()
return pmf | [
"def",
"MakePmfFromDict",
"(",
"d",
",",
"name",
"=",
"''",
")",
":",
"pmf",
"=",
"Pmf",
"(",
"d",
",",
"name",
")",
"pmf",
".",
"Normalize",
"(",
")",
"return",
"pmf"
] | Makes a PMF from a map from values to probabilities.
Args:
d: dictionary that maps values to probabilities
name: string name for this PMF
Returns:
Pmf object | [
"Makes",
"a",
"PMF",
"from",
"a",
"map",
"from",
"values",
"to",
"probabilities",
"."
] | python | train |
chemlab/chemlab | chemlab/io/handlers/gamess.py | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/handlers/gamess.py#L67-L77 | def _parse_geometry(self, geom):
"""Parse a geometry string and return Molecule object from
it.
"""
atoms = []
for i, line in enumerate(geom.splitlines()):
sym, atno, x, y, z = line.split()
atoms.append(Atom(sym, [float(x), float(y), float(z)], id=i))
... | [
"def",
"_parse_geometry",
"(",
"self",
",",
"geom",
")",
":",
"atoms",
"=",
"[",
"]",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"geom",
".",
"splitlines",
"(",
")",
")",
":",
"sym",
",",
"atno",
",",
"x",
",",
"y",
",",
"z",
"=",
"line",... | Parse a geometry string and return Molecule object from
it. | [
"Parse",
"a",
"geometry",
"string",
"and",
"return",
"Molecule",
"object",
"from",
"it",
"."
] | python | train |
saltstack/salt | salt/pillar/mongo.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/mongo.py#L89-L165 | def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
collection='pillar',
id_field='_id',
re_pattern=None,
re_replace='',
fields=None):
'''
Connect to a mongo database and read per-node pillar information.
Param... | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"# pylint: disable=W0613",
"collection",
"=",
"'pillar'",
",",
"id_field",
"=",
"'_id'",
",",
"re_pattern",
"=",
"None",
",",
"re_replace",
"=",
"''",
",",
"fields",
"=",
"None",
")",
":",
"host",
... | Connect to a mongo database and read per-node pillar information.
Parameters:
* `collection`: The mongodb collection to read data from. Defaults to
``'pillar'``.
* `id_field`: The field in the collection that represents an individual
minion id. Defaults to ``'_id'``.
* `... | [
"Connect",
"to",
"a",
"mongo",
"database",
"and",
"read",
"per",
"-",
"node",
"pillar",
"information",
"."
] | python | train |
saltstack/salt | salt/modules/bigip.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L138-L159 | def _determine_toggles(payload, toggles):
'''
BigIP can't make up its mind if it likes yes / no or true or false.
Figure out what it likes to hear without confusing the user.
'''
for toggle, definition in six.iteritems(toggles):
#did the user specify anything?
if definition['value']... | [
"def",
"_determine_toggles",
"(",
"payload",
",",
"toggles",
")",
":",
"for",
"toggle",
",",
"definition",
"in",
"six",
".",
"iteritems",
"(",
"toggles",
")",
":",
"#did the user specify anything?",
"if",
"definition",
"[",
"'value'",
"]",
"is",
"not",
"None",... | BigIP can't make up its mind if it likes yes / no or true or false.
Figure out what it likes to hear without confusing the user. | [
"BigIP",
"can",
"t",
"make",
"up",
"its",
"mind",
"if",
"it",
"likes",
"yes",
"/",
"no",
"or",
"true",
"or",
"false",
".",
"Figure",
"out",
"what",
"it",
"likes",
"to",
"hear",
"without",
"confusing",
"the",
"user",
"."
] | python | train |
lowandrew/OLCTools | spadespipeline/skesa.py | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/skesa.py#L96-L156 | def merge(self, sample):
"""
Use bbmerge to merge paired FASTQ files for use in metagenomics pipelines. Create a report with the
total number of reads, and the number of reads that could be paired
:param sample: metadata sample object flagged as a metagenome
"""
# Set the... | [
"def",
"merge",
"(",
"self",
",",
"sample",
")",
":",
"# Set the assembly file to 'NA' as assembly is not desirable for metagenomes",
"sample",
".",
"general",
".",
"assemblyfile",
"=",
"'NA'",
"# Can only merge paired-end",
"if",
"len",
"(",
"sample",
".",
"general",
"... | Use bbmerge to merge paired FASTQ files for use in metagenomics pipelines. Create a report with the
total number of reads, and the number of reads that could be paired
:param sample: metadata sample object flagged as a metagenome | [
"Use",
"bbmerge",
"to",
"merge",
"paired",
"FASTQ",
"files",
"for",
"use",
"in",
"metagenomics",
"pipelines",
".",
"Create",
"a",
"report",
"with",
"the",
"total",
"number",
"of",
"reads",
"and",
"the",
"number",
"of",
"reads",
"that",
"could",
"be",
"pair... | python | train |
spacetelescope/drizzlepac | drizzlepac/util.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L51-L76 | def get_pool_size(usr_config_value, num_tasks):
""" Determine size of thread/process-pool for parallel processing.
This examines the cpu_count to decide and return the right pool
size to use. Also take into account the user's wishes via the config
object value, if specified. On top of that, don't allo... | [
"def",
"get_pool_size",
"(",
"usr_config_value",
",",
"num_tasks",
")",
":",
"if",
"not",
"can_parallel",
":",
"return",
"1",
"# Give priority to their specified cfg value, over the actual cpu count",
"if",
"usr_config_value",
"is",
"not",
"None",
":",
"if",
"num_tasks",
... | Determine size of thread/process-pool for parallel processing.
This examines the cpu_count to decide and return the right pool
size to use. Also take into account the user's wishes via the config
object value, if specified. On top of that, don't allow the pool size
returned to be any higher than the n... | [
"Determine",
"size",
"of",
"thread",
"/",
"process",
"-",
"pool",
"for",
"parallel",
"processing",
".",
"This",
"examines",
"the",
"cpu_count",
"to",
"decide",
"and",
"return",
"the",
"right",
"pool",
"size",
"to",
"use",
".",
"Also",
"take",
"into",
"acco... | python | train |
vanheeringen-lab/gimmemotifs | gimmemotifs/motif.py | https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/motif.py#L1149-L1178 | def parse_motifs(motifs):
"""Parse motifs in a variety of formats to return a list of motifs.
Parameters
----------
motifs : list or str
Filename of motif, list of motifs or single Motif instance.
Returns
-------
motifs : list
List of Motif instances.
"""
if isin... | [
"def",
"parse_motifs",
"(",
"motifs",
")",
":",
"if",
"isinstance",
"(",
"motifs",
",",
"six",
".",
"string_types",
")",
":",
"with",
"open",
"(",
"motifs",
")",
"as",
"f",
":",
"if",
"motifs",
".",
"endswith",
"(",
"\"pwm\"",
")",
"or",
"motifs",
".... | Parse motifs in a variety of formats to return a list of motifs.
Parameters
----------
motifs : list or str
Filename of motif, list of motifs or single Motif instance.
Returns
-------
motifs : list
List of Motif instances. | [
"Parse",
"motifs",
"in",
"a",
"variety",
"of",
"formats",
"to",
"return",
"a",
"list",
"of",
"motifs",
"."
] | python | train |
chaoss/grimoirelab-perceval-mozilla | perceval/backends/mozilla/crates.py | https://github.com/chaoss/grimoirelab-perceval-mozilla/blob/4514f8d3d609d3cb79d83c72d51fcc4b4a7daeb4/perceval/backends/mozilla/crates.py#L329-L334 | def fetch(self, url, payload=None):
"""Return the textual content associated to the Response object"""
response = super().fetch(url, payload=payload)
return response.text | [
"def",
"fetch",
"(",
"self",
",",
"url",
",",
"payload",
"=",
"None",
")",
":",
"response",
"=",
"super",
"(",
")",
".",
"fetch",
"(",
"url",
",",
"payload",
"=",
"payload",
")",
"return",
"response",
".",
"text"
] | Return the textual content associated to the Response object | [
"Return",
"the",
"textual",
"content",
"associated",
"to",
"the",
"Response",
"object"
] | python | test |
lago-project/lago | lago/virt.py | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/virt.py#L232-L293 | def generate_init(self, dst, out_format, vms_to_include, filters=None):
"""
Generate an init file which represents this env and can
be used with the images created by self.export_vms
Args:
dst (str): path and name of the new init file
out_format (plugins.output.Ou... | [
"def",
"generate_init",
"(",
"self",
",",
"dst",
",",
"out_format",
",",
"vms_to_include",
",",
"filters",
"=",
"None",
")",
":",
"# todo: move this logic to PrefixExportManager",
"with",
"LogTask",
"(",
"'Exporting init file to: {}'",
".",
"format",
"(",
"dst",
")"... | Generate an init file which represents this env and can
be used with the images created by self.export_vms
Args:
dst (str): path and name of the new init file
out_format (plugins.output.OutFormatPlugin):
formatter for the output (the default is yaml)
f... | [
"Generate",
"an",
"init",
"file",
"which",
"represents",
"this",
"env",
"and",
"can",
"be",
"used",
"with",
"the",
"images",
"created",
"by",
"self",
".",
"export_vms",
"Args",
":",
"dst",
"(",
"str",
")",
":",
"path",
"and",
"name",
"of",
"the",
"new"... | python | train |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L3406-L3409 | def ticket_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/tickets#create-ticket"
api_path = "/api/v2/tickets.json"
return self.call(api_path, method="POST", data=data, **kwargs) | [
"def",
"ticket_create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/tickets.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
"data",
"=",
"data",
",",
"*",
"*",
"... | https://developer.zendesk.com/rest_api/docs/core/tickets#create-ticket | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"tickets#create",
"-",
"ticket"
] | python | train |
Erotemic/utool | utool/util_arg.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_arg.py#L1068-L1127 | def get_argv_tail(scriptname, prefer_main=None, argv=None):
r"""
gets the rest of the arguments after a script has been invoked hack.
accounts for python -m scripts.
Args:
scriptname (str):
CommandLine:
python -m utool.util_arg --test-get_argv_tail
Example:
>>> # ENABL... | [
"def",
"get_argv_tail",
"(",
"scriptname",
",",
"prefer_main",
"=",
"None",
",",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"import",
"utool",
"as",
"ut",
"modname",
"=",
"ut",
".",
"get_argval",
... | r"""
gets the rest of the arguments after a script has been invoked hack.
accounts for python -m scripts.
Args:
scriptname (str):
CommandLine:
python -m utool.util_arg --test-get_argv_tail
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
... | [
"r",
"gets",
"the",
"rest",
"of",
"the",
"arguments",
"after",
"a",
"script",
"has",
"been",
"invoked",
"hack",
".",
"accounts",
"for",
"python",
"-",
"m",
"scripts",
"."
] | python | train |
gnarlychicken/aiohttp_auth | aiohttp_auth/auth/auth.py | https://github.com/gnarlychicken/aiohttp_auth/blob/3d55236889fb14b662279b050de18d43842bb886/aiohttp_auth/auth/auth.py#L10-L36 | def auth_middleware(policy):
"""Returns a aiohttp_auth middleware factory for use by the aiohttp
application object.
Args:
policy: A authentication policy with a base class of
AbstractAuthentication.
"""
assert isinstance(policy, AbstractAuthentication)
async def _auth_midd... | [
"def",
"auth_middleware",
"(",
"policy",
")",
":",
"assert",
"isinstance",
"(",
"policy",
",",
"AbstractAuthentication",
")",
"async",
"def",
"_auth_middleware_factory",
"(",
"app",
",",
"handler",
")",
":",
"async",
"def",
"_middleware_handler",
"(",
"request",
... | Returns a aiohttp_auth middleware factory for use by the aiohttp
application object.
Args:
policy: A authentication policy with a base class of
AbstractAuthentication. | [
"Returns",
"a",
"aiohttp_auth",
"middleware",
"factory",
"for",
"use",
"by",
"the",
"aiohttp",
"application",
"object",
"."
] | python | train |
awslabs/sockeye | sockeye/embeddings.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/embeddings.py#L57-L72 | def nearest_k(similarity_matrix: mx.nd.NDArray,
query_word_id: int,
k: int,
gamma: float = 1.0) -> Iterable[Tuple[int, float]]:
"""
Returns values and indices of k items with largest similarity.
:param similarity_matrix: Similarity matrix.
:param query_word_id:... | [
"def",
"nearest_k",
"(",
"similarity_matrix",
":",
"mx",
".",
"nd",
".",
"NDArray",
",",
"query_word_id",
":",
"int",
",",
"k",
":",
"int",
",",
"gamma",
":",
"float",
"=",
"1.0",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"int",
",",
"float",
"]",
... | Returns values and indices of k items with largest similarity.
:param similarity_matrix: Similarity matrix.
:param query_word_id: Query word id.
:param k: Number of closest items to retrieve.
:param gamma: Parameter to control distribution steepness.
:return: List of indices and values of k nearest... | [
"Returns",
"values",
"and",
"indices",
"of",
"k",
"items",
"with",
"largest",
"similarity",
"."
] | python | train |
dicaso/leopard | leopard/__init__.py | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L462-L502 | def getReportTable(reportzipfile,tablefilename,inReportsDir=True,verbose=False):
"""Get a pandas table from a previous report
Args:
reportzipfile (str): Zip folder location, '.zip' extension is optional.
tablefilename (str or list int): Table location within the zip folder.
... | [
"def",
"getReportTable",
"(",
"reportzipfile",
",",
"tablefilename",
",",
"inReportsDir",
"=",
"True",
",",
"verbose",
"=",
"False",
")",
":",
"import",
"zipfile",
",",
"io",
",",
"re",
"# zipfilename preparation",
"if",
"not",
"reportzipfile",
".",
"endswith",
... | Get a pandas table from a previous report
Args:
reportzipfile (str): Zip folder location, '.zip' extension is optional.
tablefilename (str or list int): Table location within the zip folder.
Can be provided as the filename within the zip folder, or a list of integers
... | [
"Get",
"a",
"pandas",
"table",
"from",
"a",
"previous",
"report"
] | python | train |
SheffieldML/GPy | GPy/kern/src/sde_matern.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/kern/src/sde_matern.py#L94-L137 | def sde(self):
"""
Return the state space representation of the covariance.
"""
variance = float(self.variance.values)
lengthscale = float(self.lengthscale.values)
lamda = np.sqrt(5.0)/lengthscale
kappa = 5.0/3.0*variance/lengthscale**2
... | [
"def",
"sde",
"(",
"self",
")",
":",
"variance",
"=",
"float",
"(",
"self",
".",
"variance",
".",
"values",
")",
"lengthscale",
"=",
"float",
"(",
"self",
".",
"lengthscale",
".",
"values",
")",
"lamda",
"=",
"np",
".",
"sqrt",
"(",
"5.0",
")",
"/"... | Return the state space representation of the covariance. | [
"Return",
"the",
"state",
"space",
"representation",
"of",
"the",
"covariance",
"."
] | python | train |
jobovy/galpy | galpy/potential/interpRZPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/interpRZPotential.py#L572-L599 | def calc_2dsplinecoeffs_c(array2d):
"""
NAME:
calc_2dsplinecoeffs_c
PURPOSE:
Use C to calculate spline coefficients for a 2D array
INPUT:
array2d
OUTPUT:
new array with spline coeffs
HISTORY:
2013-01-24 - Written - Bovy (IAS)
"""
#Set up result arrays
... | [
"def",
"calc_2dsplinecoeffs_c",
"(",
"array2d",
")",
":",
"#Set up result arrays",
"out",
"=",
"copy",
".",
"copy",
"(",
"array2d",
")",
"out",
"=",
"numpy",
".",
"require",
"(",
"out",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"requirements",
"=",
... | NAME:
calc_2dsplinecoeffs_c
PURPOSE:
Use C to calculate spline coefficients for a 2D array
INPUT:
array2d
OUTPUT:
new array with spline coeffs
HISTORY:
2013-01-24 - Written - Bovy (IAS) | [
"NAME",
":",
"calc_2dsplinecoeffs_c",
"PURPOSE",
":",
"Use",
"C",
"to",
"calculate",
"spline",
"coefficients",
"for",
"a",
"2D",
"array",
"INPUT",
":",
"array2d",
"OUTPUT",
":",
"new",
"array",
"with",
"spline",
"coeffs",
"HISTORY",
":",
"2013",
"-",
"01",
... | python | train |
michael-lazar/rtv | rtv/packages/praw/__init__.py | https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/__init__.py#L750-L766 | def set_oauth_app_info(self, client_id, client_secret, redirect_uri):
"""Set the app information to use with OAuth2.
This function need only be called if your praw.ini site configuration
does not already contain the necessary information.
Go to https://www.reddit.com/prefs/apps/ to dis... | [
"def",
"set_oauth_app_info",
"(",
"self",
",",
"client_id",
",",
"client_secret",
",",
"redirect_uri",
")",
":",
"self",
".",
"client_id",
"=",
"client_id",
"self",
".",
"client_secret",
"=",
"client_secret",
"self",
".",
"redirect_uri",
"=",
"redirect_uri"
] | Set the app information to use with OAuth2.
This function need only be called if your praw.ini site configuration
does not already contain the necessary information.
Go to https://www.reddit.com/prefs/apps/ to discover the appropriate
values for your application.
:param client... | [
"Set",
"the",
"app",
"information",
"to",
"use",
"with",
"OAuth2",
"."
] | python | train |
Nic30/hwt | hwt/synthesizer/rtlLevel/rtlSignal.py | https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/rtlLevel/rtlSignal.py#L106-L117 | def singleDriver(self):
"""
Returns a first driver if signal has only one driver.
"""
# [TODO] no driver exception
drv_cnt = len(self.drivers)
if not drv_cnt:
raise NoDriverErr(self)
elif drv_cnt != 1:
raise MultipleDriversErr(self)
... | [
"def",
"singleDriver",
"(",
"self",
")",
":",
"# [TODO] no driver exception",
"drv_cnt",
"=",
"len",
"(",
"self",
".",
"drivers",
")",
"if",
"not",
"drv_cnt",
":",
"raise",
"NoDriverErr",
"(",
"self",
")",
"elif",
"drv_cnt",
"!=",
"1",
":",
"raise",
"Multi... | Returns a first driver if signal has only one driver. | [
"Returns",
"a",
"first",
"driver",
"if",
"signal",
"has",
"only",
"one",
"driver",
"."
] | python | test |
saltstack/salt | salt/modules/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L4336-L4563 | def extract_hash(hash_fn,
hash_type='sha256',
file_name='',
source='',
source_hash_name=None):
'''
.. versionchanged:: 2016.3.5
Prior to this version, only the ``file_name`` argument was considered
for filename matches in the ha... | [
"def",
"extract_hash",
"(",
"hash_fn",
",",
"hash_type",
"=",
"'sha256'",
",",
"file_name",
"=",
"''",
",",
"source",
"=",
"''",
",",
"source_hash_name",
"=",
"None",
")",
":",
"hash_len",
"=",
"HASHES",
".",
"get",
"(",
"hash_type",
")",
"if",
"hash_len... | .. versionchanged:: 2016.3.5
Prior to this version, only the ``file_name`` argument was considered
for filename matches in the hash file. This would be problematic for
cases in which the user was relying on a remote checksum file that they
do not control, and they wished to use a differe... | [
"..",
"versionchanged",
"::",
"2016",
".",
"3",
".",
"5",
"Prior",
"to",
"this",
"version",
"only",
"the",
"file_name",
"argument",
"was",
"considered",
"for",
"filename",
"matches",
"in",
"the",
"hash",
"file",
".",
"This",
"would",
"be",
"problematic",
"... | python | train |
jwodder/doapi | doapi/droplet.py | https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/droplet.py#L424-L438 | def change_kernel(self, kernel):
"""
Change the droplet's kernel
:param kernel: a kernel ID or `Kernel` object representing the new
kernel
:type kernel: integer or `Kernel`
:return: an `Action` representing the in-progress operation on the
droplet
... | [
"def",
"change_kernel",
"(",
"self",
",",
"kernel",
")",
":",
"if",
"isinstance",
"(",
"kernel",
",",
"Kernel",
")",
":",
"kernel",
"=",
"kernel",
".",
"id",
"return",
"self",
".",
"act",
"(",
"type",
"=",
"'change_kernel'",
",",
"kernel",
"=",
"kernel... | Change the droplet's kernel
:param kernel: a kernel ID or `Kernel` object representing the new
kernel
:type kernel: integer or `Kernel`
:return: an `Action` representing the in-progress operation on the
droplet
:rtype: Action
:raises DOAPIError: if the AP... | [
"Change",
"the",
"droplet",
"s",
"kernel"
] | python | train |
odlgroup/odl | odl/contrib/solvers/spdhg/stochastic_primal_dual_hybrid_gradient.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/solvers/spdhg/stochastic_primal_dual_hybrid_gradient.py#L241-L407 | def spdhg_generic(x, f, g, A, tau, sigma, niter, **kwargs):
r"""Computes a saddle point with a stochastic PDHG.
This means, a solution (x*, y*), y* = (y*_1, ..., y*_n) such that
(x*, y*) in arg min_x max_y sum_i=1^n <y_i, A_i> - f*[i](y_i) + g(x)
where g : X -> IR_infty and f[i] : Y[i] -> IR_infty ar... | [
"def",
"spdhg_generic",
"(",
"x",
",",
"f",
",",
"g",
",",
"A",
",",
"tau",
",",
"sigma",
",",
"niter",
",",
"*",
"*",
"kwargs",
")",
":",
"# Callback object",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"'callback'",
",",
"None",
")",
"if",
"callb... | r"""Computes a saddle point with a stochastic PDHG.
This means, a solution (x*, y*), y* = (y*_1, ..., y*_n) such that
(x*, y*) in arg min_x max_y sum_i=1^n <y_i, A_i> - f*[i](y_i) + g(x)
where g : X -> IR_infty and f[i] : Y[i] -> IR_infty are convex, l.s.c. and
proper functionals. For this algorithm,... | [
"r",
"Computes",
"a",
"saddle",
"point",
"with",
"a",
"stochastic",
"PDHG",
"."
] | python | train |
BlueBrain/NeuroM | examples/end_to_end_distance.py | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/end_to_end_distance.py#L60-L71 | def calculate_and_plot_end_to_end_distance(neurite):
'''Calculate and plot the end-to-end distance vs the number of segments for
an increasingly larger part of a given neurite.
Note that the plots are not very meaningful for bifurcating trees.'''
def _dist(seg):
'''Distance between segmenr end ... | [
"def",
"calculate_and_plot_end_to_end_distance",
"(",
"neurite",
")",
":",
"def",
"_dist",
"(",
"seg",
")",
":",
"'''Distance between segmenr end and trunk'''",
"return",
"morphmath",
".",
"point_dist",
"(",
"seg",
"[",
"1",
"]",
",",
"neurite",
".",
"root_node",
... | Calculate and plot the end-to-end distance vs the number of segments for
an increasingly larger part of a given neurite.
Note that the plots are not very meaningful for bifurcating trees. | [
"Calculate",
"and",
"plot",
"the",
"end",
"-",
"to",
"-",
"end",
"distance",
"vs",
"the",
"number",
"of",
"segments",
"for",
"an",
"increasingly",
"larger",
"part",
"of",
"a",
"given",
"neurite",
"."
] | python | train |
wbond/oscrypto | oscrypto/_openssl/symmetric.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/symmetric.py#L772-L823 | def _setup_evp_encrypt_decrypt(cipher, data):
"""
Creates an EVP_CIPHER pointer object and determines the buffer size
necessary for the parameter specified.
:param evp_cipher_ctx:
An EVP_CIPHER_CTX pointer
:param cipher:
A unicode string of "aes128", "aes192", "aes256", "des",
... | [
"def",
"_setup_evp_encrypt_decrypt",
"(",
"cipher",
",",
"data",
")",
":",
"evp_cipher",
"=",
"{",
"'aes128'",
":",
"libcrypto",
".",
"EVP_aes_128_cbc",
",",
"'aes192'",
":",
"libcrypto",
".",
"EVP_aes_192_cbc",
",",
"'aes256'",
":",
"libcrypto",
".",
"EVP_aes_2... | Creates an EVP_CIPHER pointer object and determines the buffer size
necessary for the parameter specified.
:param evp_cipher_ctx:
An EVP_CIPHER_CTX pointer
:param cipher:
A unicode string of "aes128", "aes192", "aes256", "des",
"tripledes_2key", "tripledes_3key", "rc2", "rc4"
... | [
"Creates",
"an",
"EVP_CIPHER",
"pointer",
"object",
"and",
"determines",
"the",
"buffer",
"size",
"necessary",
"for",
"the",
"parameter",
"specified",
"."
] | python | valid |
mrsarm/mongotail | mongotail/out.py | https://github.com/mrsarm/mongotail/blob/82ba74e32eff92faa320833a8d19c58555f9cd49/mongotail/out.py#L35-L196 | def print_obj(obj, verbose, metadata, mongo_version):
"""
Print the dict returned by a MongoDB Query in the standard output.
"""
if verbose:
sys.stdout.write(json_encoder.encode(obj) + '\n')
sys.stdout.flush()
else:
try:
ts_time = obj['ts']
operation =... | [
"def",
"print_obj",
"(",
"obj",
",",
"verbose",
",",
"metadata",
",",
"mongo_version",
")",
":",
"if",
"verbose",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"json_encoder",
".",
"encode",
"(",
"obj",
")",
"+",
"'\\n'",
")",
"sys",
".",
"stdout",
"... | Print the dict returned by a MongoDB Query in the standard output. | [
"Print",
"the",
"dict",
"returned",
"by",
"a",
"MongoDB",
"Query",
"in",
"the",
"standard",
"output",
"."
] | python | test |
ActivisionGameScience/assertpy | assertpy/assertpy.py | https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L677-L685 | def is_alpha(self):
"""Asserts that val is non-empty string and all characters are alphabetic."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if len(self.val) == 0:
raise ValueError('val is empty')
if not self.val.isalpha():
... | [
"def",
"is_alpha",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"val",
",",
"str_types",
")",
":",
"raise",
"TypeError",
"(",
"'val is not a string'",
")",
"if",
"len",
"(",
"self",
".",
"val",
")",
"==",
"0",
":",
"raise",
"Va... | Asserts that val is non-empty string and all characters are alphabetic. | [
"Asserts",
"that",
"val",
"is",
"non",
"-",
"empty",
"string",
"and",
"all",
"characters",
"are",
"alphabetic",
"."
] | python | valid |
sorgerlab/indra | indra/preassembler/hierarchy_manager.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/hierarchy_manager.py#L128-L140 | def build_transitive_closures(self):
"""Build the transitive closures of the hierarchy.
This method constructs dictionaries which contain terms in the
hierarchy as keys and either all the "isa+" or "partof+" related terms
as values.
"""
self.component_counter = 0
... | [
"def",
"build_transitive_closures",
"(",
"self",
")",
":",
"self",
".",
"component_counter",
"=",
"0",
"for",
"rel",
",",
"tc_dict",
"in",
"(",
"(",
"self",
".",
"isa_objects",
",",
"self",
".",
"isa_closure",
")",
",",
"(",
"self",
".",
"partof_objects",
... | Build the transitive closures of the hierarchy.
This method constructs dictionaries which contain terms in the
hierarchy as keys and either all the "isa+" or "partof+" related terms
as values. | [
"Build",
"the",
"transitive",
"closures",
"of",
"the",
"hierarchy",
"."
] | python | train |
chrislit/abydos | setup.py | https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/setup.py#L41-L56 | def readfile(fn):
"""Read fn and return the contents.
Parameters
----------
fn : str
A filename
Returns
-------
str
The content of the file
"""
with open(path.join(HERE, fn), 'r', encoding='utf-8') as f:
return f.read() | [
"def",
"readfile",
"(",
"fn",
")",
":",
"with",
"open",
"(",
"path",
".",
"join",
"(",
"HERE",
",",
"fn",
")",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")"
] | Read fn and return the contents.
Parameters
----------
fn : str
A filename
Returns
-------
str
The content of the file | [
"Read",
"fn",
"and",
"return",
"the",
"contents",
"."
] | python | valid |
Telefonica/toolium | toolium/driver_wrappers_pool.py | https://github.com/Telefonica/toolium/blob/56847c243b3a98876df74c184b75e43f8810e475/toolium/driver_wrappers_pool.py#L155-L170 | def stop_drivers(cls, maintain_default=False):
"""Stop all drivers except default if it should be reused
:param maintain_default: True if the default driver should not be closed
"""
# Exclude first wrapper if the driver must be reused
driver_wrappers = cls.driver_wrappers[1:] if... | [
"def",
"stop_drivers",
"(",
"cls",
",",
"maintain_default",
"=",
"False",
")",
":",
"# Exclude first wrapper if the driver must be reused",
"driver_wrappers",
"=",
"cls",
".",
"driver_wrappers",
"[",
"1",
":",
"]",
"if",
"maintain_default",
"else",
"cls",
".",
"driv... | Stop all drivers except default if it should be reused
:param maintain_default: True if the default driver should not be closed | [
"Stop",
"all",
"drivers",
"except",
"default",
"if",
"it",
"should",
"be",
"reused"
] | python | train |
serkanyersen/underscore.py | src/underscore.py | https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L961-L971 | def invert(self):
"""
Invert the keys and values of an object.
The values must be serializable.
"""
keys = self._clean.keys()
inverted = {}
for key in keys:
inverted[self.obj[key]] = key
return self._wrap(inverted) | [
"def",
"invert",
"(",
"self",
")",
":",
"keys",
"=",
"self",
".",
"_clean",
".",
"keys",
"(",
")",
"inverted",
"=",
"{",
"}",
"for",
"key",
"in",
"keys",
":",
"inverted",
"[",
"self",
".",
"obj",
"[",
"key",
"]",
"]",
"=",
"key",
"return",
"sel... | Invert the keys and values of an object.
The values must be serializable. | [
"Invert",
"the",
"keys",
"and",
"values",
"of",
"an",
"object",
".",
"The",
"values",
"must",
"be",
"serializable",
"."
] | python | train |
HiPERCAM/hcam_widgets | hcam_widgets/widgets.py | https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L302-L327 | def _pollMouse(self):
"""
Polls @10Hz, with a slight delay at the
start.
"""
if self._mouseJustPressed:
delay = 300
self._mouseJustPressed = False
else:
delay = 100
if self._leftMousePressed:
self.add(1)
... | [
"def",
"_pollMouse",
"(",
"self",
")",
":",
"if",
"self",
".",
"_mouseJustPressed",
":",
"delay",
"=",
"300",
"self",
".",
"_mouseJustPressed",
"=",
"False",
"else",
":",
"delay",
"=",
"100",
"if",
"self",
".",
"_leftMousePressed",
":",
"self",
".",
"add... | Polls @10Hz, with a slight delay at the
start. | [
"Polls"
] | python | train |
bjodah/pyodesys | pyodesys/core.py | https://github.com/bjodah/pyodesys/blob/0034a6165b550d8d9808baef58678dca5a493ab7/pyodesys/core.py#L665-L691 | def _integrate_gsl(self, *args, **kwargs):
""" Do not use directly (use ``integrate(..., integrator='gsl')``).
Uses `GNU Scientific Library <http://www.gnu.org/software/gsl/>`_
(via `pygslodeiv2 <https://pypi.python.org/pypi/pygslodeiv2>`_)
to integrate the ODE system.
Paramete... | [
"def",
"_integrate_gsl",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"pygslodeiv2",
"# Python interface GSL's \"odeiv2\" integrators",
"kwargs",
"[",
"'with_jacobian'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'method'",
",",
"'bsimp... | Do not use directly (use ``integrate(..., integrator='gsl')``).
Uses `GNU Scientific Library <http://www.gnu.org/software/gsl/>`_
(via `pygslodeiv2 <https://pypi.python.org/pypi/pygslodeiv2>`_)
to integrate the ODE system.
Parameters
----------
\*args :
see ... | [
"Do",
"not",
"use",
"directly",
"(",
"use",
"integrate",
"(",
"...",
"integrator",
"=",
"gsl",
")",
")",
"."
] | python | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L909-L928 | def _SkipFieldValue(tokenizer):
"""Skips over a field value.
Args:
tokenizer: A tokenizer to parse the field name and values.
Raises:
ParseError: In case an invalid field value is found.
"""
# String/bytes tokens can come in multiple adjacent string literals.
# If we can consume one, consume as ma... | [
"def",
"_SkipFieldValue",
"(",
"tokenizer",
")",
":",
"# String/bytes tokens can come in multiple adjacent string literals.",
"# If we can consume one, consume as many as we can.",
"if",
"tokenizer",
".",
"TryConsumeByteString",
"(",
")",
":",
"while",
"tokenizer",
".",
"TryConsu... | Skips over a field value.
Args:
tokenizer: A tokenizer to parse the field name and values.
Raises:
ParseError: In case an invalid field value is found. | [
"Skips",
"over",
"a",
"field",
"value",
"."
] | python | train |
timothycrosley/deprecated.frosted | frosted/checker.py | https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/checker.py#L276-L289 | def check_plugins(self):
""" collect plugins from entry point 'frosted.plugins'
and run their check() method, passing the filename
"""
checkers = {}
for ep in pkg_resources.iter_entry_points(group='frosted.plugins'):
checkers.update({ep.name: ep.load()})
for... | [
"def",
"check_plugins",
"(",
"self",
")",
":",
"checkers",
"=",
"{",
"}",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"group",
"=",
"'frosted.plugins'",
")",
":",
"checkers",
".",
"update",
"(",
"{",
"ep",
".",
"name",
":",
"ep",
... | collect plugins from entry point 'frosted.plugins'
and run their check() method, passing the filename | [
"collect",
"plugins",
"from",
"entry",
"point",
"frosted",
".",
"plugins"
] | python | train |
ssato/python-anyconfig | src/anyconfig/template.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/template.py#L50-L62 | def copen(filepath, flag='r', encoding=None):
"""
FIXME: How to test this ?
>>> c = copen(__file__)
>>> c is not None
True
"""
if encoding is None:
encoding = locale.getdefaultlocale()[1]
return codecs.open(filepath, flag, encoding) | [
"def",
"copen",
"(",
"filepath",
",",
"flag",
"=",
"'r'",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"[",
"1",
"]",
"return",
"codecs",
".",
"open",
"(",
... | FIXME: How to test this ?
>>> c = copen(__file__)
>>> c is not None
True | [
"FIXME",
":",
"How",
"to",
"test",
"this",
"?"
] | python | train |
walter426/Python_GoogleMapsApi | GoogleMapsApi/GoogleMapsServiceParser.py | https://github.com/walter426/Python_GoogleMapsApi/blob/4832b293a0027446941a5f00ecc66256f92ddbce/GoogleMapsApi/GoogleMapsServiceParser.py#L112-L125 | def parse_json(self, page):
'''Returns json feed.'''
if not isinstance(page, basestring):
page = util.decode_page(page)
self.doc = json.loads(page)
results = self.doc.get(self.result_name, [])
if not results:
self.check_status(self.doc.ge... | [
"def",
"parse_json",
"(",
"self",
",",
"page",
")",
":",
"if",
"not",
"isinstance",
"(",
"page",
",",
"basestring",
")",
":",
"page",
"=",
"util",
".",
"decode_page",
"(",
"page",
")",
"self",
".",
"doc",
"=",
"json",
".",
"loads",
"(",
"page",
")"... | Returns json feed. | [
"Returns",
"json",
"feed",
"."
] | python | train |
saltstack/salt | salt/modules/netscaler.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L196-L211 | def servicegroup_exists(sg_name, sg_type=None, **connection_args):
'''
Checks if a service group exists
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_exists 'serviceGroupName'
'''
sg = _servicegroup_get(sg_name, **connection_args)
if sg is None:
return ... | [
"def",
"servicegroup_exists",
"(",
"sg_name",
",",
"sg_type",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"sg",
"=",
"_servicegroup_get",
"(",
"sg_name",
",",
"*",
"*",
"connection_args",
")",
"if",
"sg",
"is",
"None",
":",
"return",
"False",
... | Checks if a service group exists
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_exists 'serviceGroupName' | [
"Checks",
"if",
"a",
"service",
"group",
"exists"
] | python | train |
OSLL/jabba | jabba/analysis/parameters_present.py | https://github.com/OSLL/jabba/blob/71c1d008ab497020fba6ffa12a600721eb3f5ef7/jabba/analysis/parameters_present.py#L17-L42 | def parameters_present(options, **kwargs):
"""
Analysis function
Check whether all calls contain a given parameters or their synonyms
"""
synonyms = options['synonyms']
call_graph = options['call_graph']
result = _Result()
for node, edges in call_graph:
for edge in edges:
... | [
"def",
"parameters_present",
"(",
"options",
",",
"*",
"*",
"kwargs",
")",
":",
"synonyms",
"=",
"options",
"[",
"'synonyms'",
"]",
"call_graph",
"=",
"options",
"[",
"'call_graph'",
"]",
"result",
"=",
"_Result",
"(",
")",
"for",
"node",
",",
"edges",
"... | Analysis function
Check whether all calls contain a given parameters or their synonyms | [
"Analysis",
"function",
"Check",
"whether",
"all",
"calls",
"contain",
"a",
"given",
"parameters",
"or",
"their",
"synonyms"
] | python | train |
saltstack/salt | salt/modules/mac_shadow.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L78-L97 | def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or an... | [
"def",
"_set_account_policy",
"(",
"name",
",",
"policy",
")",
":",
"cmd",
"=",
"'pwpolicy -u {0} -setpolicy \"{1}\"'",
".",
"format",
"(",
"name",
",",
"policy",
")",
"try",
":",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
... | Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error | [
"Set",
"a",
"value",
"in",
"the",
"user",
"accountPolicy",
".",
"For",
"use",
"by",
"this",
"module",
"only"
] | python | train |
alorence/django-modern-rpc | modernrpc/system_methods.py | https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/system_methods.py#L55-L92 | def __system_multiCall(calls, **kwargs):
"""
Call multiple RPC methods at once.
:param calls: An array of struct like {"methodName": string, "params": array }
:param kwargs: Internal data
:type calls: list
:type kwargs: dict
:return:
"""
if not isinstance(calls, list):
raise... | [
"def",
"__system_multiCall",
"(",
"calls",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"calls",
",",
"list",
")",
":",
"raise",
"RPCInvalidParams",
"(",
"'system.multicall first argument should be a list, {} given.'",
".",
"format",
"(",
"ty... | Call multiple RPC methods at once.
:param calls: An array of struct like {"methodName": string, "params": array }
:param kwargs: Internal data
:type calls: list
:type kwargs: dict
:return: | [
"Call",
"multiple",
"RPC",
"methods",
"at",
"once",
"."
] | python | train |
justquick/python-varnish | varnish.py | https://github.com/justquick/python-varnish/blob/8f114c74898e6c5ade2ce49c8b595040bd150465/varnish.py#L198-L207 | def param_show(self, param, l=False):
"""
param.show [-l] [param]
Display a list if run-time parameters and their values.
If the -l option is specified, the list includes a brief explanation of each parameter.
If a param is specified, display only the value and ... | [
"def",
"param_show",
"(",
"self",
",",
"param",
",",
"l",
"=",
"False",
")",
":",
"cmd",
"=",
"'param.show '",
"if",
"l",
":",
"cmd",
"+=",
"'-l '",
"return",
"self",
".",
"fetch",
"(",
"cmd",
"+",
"param",
")"
] | param.show [-l] [param]
Display a list if run-time parameters and their values.
If the -l option is specified, the list includes a brief explanation of each parameter.
If a param is specified, display only the value and explanation for this parameter. | [
"param",
".",
"show",
"[",
"-",
"l",
"]",
"[",
"param",
"]",
"Display",
"a",
"list",
"if",
"run",
"-",
"time",
"parameters",
"and",
"their",
"values",
".",
"If",
"the",
"-",
"l",
"option",
"is",
"specified",
"the",
"list",
"includes",
"a",
"brief",
... | python | train |
MycroftAI/mycroft-precise | precise/model.py | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/model.py#L42-L48 | def load_precise_model(model_name: str) -> Any:
"""Loads a Keras model from file, handling custom loss function"""
if not model_name.endswith('.net'):
print('Warning: Unknown model type, ', model_name)
inject_params(model_name)
return load_keras().models.load_model(model_name) | [
"def",
"load_precise_model",
"(",
"model_name",
":",
"str",
")",
"->",
"Any",
":",
"if",
"not",
"model_name",
".",
"endswith",
"(",
"'.net'",
")",
":",
"print",
"(",
"'Warning: Unknown model type, '",
",",
"model_name",
")",
"inject_params",
"(",
"model_name",
... | Loads a Keras model from file, handling custom loss function | [
"Loads",
"a",
"Keras",
"model",
"from",
"file",
"handling",
"custom",
"loss",
"function"
] | python | train |
merll/docker-map | dockermap/client/base.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/client/base.py#L199-L212 | def push_container_logs(self, container):
"""
Reads the current container logs and passes them to :meth:`~push_log`. Removes a trailing empty line and
prefixes each log line with the container name.
:param container: Container name or id.
:type container: unicode | str
"... | [
"def",
"push_container_logs",
"(",
"self",
",",
"container",
")",
":",
"logs",
"=",
"self",
".",
"logs",
"(",
"container",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"log_lines",
"=",
"logs",
".",
"split",
"(",
"'\\n'",
")",
"if",
"log_lines",
"and",
"no... | Reads the current container logs and passes them to :meth:`~push_log`. Removes a trailing empty line and
prefixes each log line with the container name.
:param container: Container name or id.
:type container: unicode | str | [
"Reads",
"the",
"current",
"container",
"logs",
"and",
"passes",
"them",
"to",
":",
"meth",
":",
"~push_log",
".",
"Removes",
"a",
"trailing",
"empty",
"line",
"and",
"prefixes",
"each",
"log",
"line",
"with",
"the",
"container",
"name",
"."
] | python | train |
pantsbuild/pants | src/python/pants/subsystem/subsystem_client_mixin.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/subsystem/subsystem_client_mixin.py#L85-L110 | def subsystem_closure_iter(cls):
"""Iterate over the transitive closure of subsystem dependencies of this Optionable.
:rtype: :class:`collections.Iterator` of :class:`SubsystemDependency`
:raises: :class:`pants.subsystem.subsystem_client_mixin.SubsystemClientMixin.CycleException`
if a dependen... | [
"def",
"subsystem_closure_iter",
"(",
"cls",
")",
":",
"seen",
"=",
"set",
"(",
")",
"dep_path",
"=",
"OrderedSet",
"(",
")",
"def",
"iter_subsystem_closure",
"(",
"subsystem_cls",
")",
":",
"if",
"subsystem_cls",
"in",
"dep_path",
":",
"raise",
"cls",
".",
... | Iterate over the transitive closure of subsystem dependencies of this Optionable.
:rtype: :class:`collections.Iterator` of :class:`SubsystemDependency`
:raises: :class:`pants.subsystem.subsystem_client_mixin.SubsystemClientMixin.CycleException`
if a dependency cycle is detected. | [
"Iterate",
"over",
"the",
"transitive",
"closure",
"of",
"subsystem",
"dependencies",
"of",
"this",
"Optionable",
"."
] | python | train |
basho/riak-python-client | riak/table.py | https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/table.py#L51-L64 | def new(self, rows, columns=None):
"""
A shortcut for manually instantiating a new
:class:`~riak.ts_object.TsObject`
:param rows: An list of lists with timeseries data
:type rows: list
:param columns: An list of Column names and types. Optional.
:type columns: li... | [
"def",
"new",
"(",
"self",
",",
"rows",
",",
"columns",
"=",
"None",
")",
":",
"from",
"riak",
".",
"ts_object",
"import",
"TsObject",
"return",
"TsObject",
"(",
"self",
".",
"_client",
",",
"self",
",",
"rows",
",",
"columns",
")"
] | A shortcut for manually instantiating a new
:class:`~riak.ts_object.TsObject`
:param rows: An list of lists with timeseries data
:type rows: list
:param columns: An list of Column names and types. Optional.
:type columns: list
:rtype: :class:`~riak.ts_object.TsObject` | [
"A",
"shortcut",
"for",
"manually",
"instantiating",
"a",
"new",
":",
"class",
":",
"~riak",
".",
"ts_object",
".",
"TsObject"
] | python | train |
KelSolaar/Foundations | foundations/cache.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/cache.py#L51-L72 | def add_content(self, **content):
"""
Adds given content to the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache
{'Luke': 'Skywalker', 'John': 'Doe'}
:param \*\*content: Co... | [
"def",
"add_content",
"(",
"self",
",",
"*",
"*",
"content",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Adding '{0}' content to the cache.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"content",
")",
")",
"self",
".",
"update",
... | Adds given content to the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache
{'Luke': 'Skywalker', 'John': 'Doe'}
:param \*\*content: Content to add.
:type \*\*content: \*\*
... | [
"Adds",
"given",
"content",
"to",
"the",
"cache",
"."
] | python | train |
numenta/nupic | src/nupic/algorithms/spatial_pooler.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/spatial_pooler.py#L1083-L1099 | def _avgConnectedSpanForColumn1D(self, columnIndex):
"""
The range of connected synapses for column. This is used to
calculate the inhibition radius. This variation of the function only
supports a 1 dimensional column topology.
Parameters:
----------------------------
:param columnIndex: ... | [
"def",
"_avgConnectedSpanForColumn1D",
"(",
"self",
",",
"columnIndex",
")",
":",
"assert",
"(",
"self",
".",
"_inputDimensions",
".",
"size",
"==",
"1",
")",
"connected",
"=",
"self",
".",
"_connectedSynapses",
"[",
"columnIndex",
"]",
".",
"nonzero",
"(",
... | The range of connected synapses for column. This is used to
calculate the inhibition radius. This variation of the function only
supports a 1 dimensional column topology.
Parameters:
----------------------------
:param columnIndex: The index identifying a column in the permanence,
... | [
"The",
"range",
"of",
"connected",
"synapses",
"for",
"column",
".",
"This",
"is",
"used",
"to",
"calculate",
"the",
"inhibition",
"radius",
".",
"This",
"variation",
"of",
"the",
"function",
"only",
"supports",
"a",
"1",
"dimensional",
"column",
"topology",
... | python | valid |
gamechanger/confluent_schema_registry_client | confluent_schema_registry_client/__init__.py | https://github.com/gamechanger/confluent_schema_registry_client/blob/ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae/confluent_schema_registry_client/__init__.py#L170-L176 | def get_subject_compatibility_level(self, subject):
"""
Gets the compatibility level for the given subject.
"""
res = requests.get(self._url('/config/{}', subject), headers=HEADERS)
raise_if_failed(res)
return res.json()['compatibility'] | [
"def",
"get_subject_compatibility_level",
"(",
"self",
",",
"subject",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_url",
"(",
"'/config/{}'",
",",
"subject",
")",
",",
"headers",
"=",
"HEADERS",
")",
"raise_if_failed",
"(",
"res",
")"... | Gets the compatibility level for the given subject. | [
"Gets",
"the",
"compatibility",
"level",
"for",
"the",
"given",
"subject",
"."
] | python | train |
peerplays-network/python-peerplays | peerplays/cli/decorators.py | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/cli/decorators.py#L154-L164 | def configfile(f):
""" This decorator will parse a configuration file in YAML format
and store the dictionary in ``ctx.blockchain.config``
"""
@click.pass_context
def new_func(ctx, *args, **kwargs):
ctx.config = yaml.load(open(ctx.obj["configfile"]))
return ctx.invoke(f, *args, ... | [
"def",
"configfile",
"(",
"f",
")",
":",
"@",
"click",
".",
"pass_context",
"def",
"new_func",
"(",
"ctx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
".",
"config",
"=",
"yaml",
".",
"load",
"(",
"open",
"(",
"ctx",
".",
"obj",
... | This decorator will parse a configuration file in YAML format
and store the dictionary in ``ctx.blockchain.config`` | [
"This",
"decorator",
"will",
"parse",
"a",
"configuration",
"file",
"in",
"YAML",
"format",
"and",
"store",
"the",
"dictionary",
"in",
"ctx",
".",
"blockchain",
".",
"config"
] | python | train |
HazyResearch/fonduer | src/fonduer/utils/utils_udf.py | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/utils_udf.py#L342-L369 | def upsert_keys(session, key_table, keys):
"""Bulk add annotation keys to the specified table.
:param key_table: The sqlalchemy class to insert into.
:param keys: A map of {name: [candidate_classes]}.
"""
# Do nothing if empty
if not keys:
return
for key_batch in _batch_postgres_qu... | [
"def",
"upsert_keys",
"(",
"session",
",",
"key_table",
",",
"keys",
")",
":",
"# Do nothing if empty",
"if",
"not",
"keys",
":",
"return",
"for",
"key_batch",
"in",
"_batch_postgres_query",
"(",
"key_table",
",",
"[",
"{",
"\"name\"",
":",
"k",
"[",
"0",
... | Bulk add annotation keys to the specified table.
:param key_table: The sqlalchemy class to insert into.
:param keys: A map of {name: [candidate_classes]}. | [
"Bulk",
"add",
"annotation",
"keys",
"to",
"the",
"specified",
"table",
"."
] | python | train |
lwgray/pyEntrezId | PyEntrezId/Conversion.py | https://github.com/lwgray/pyEntrezId/blob/28286cf21b876dd4894bf21a222dfd1022441b75/PyEntrezId/Conversion.py#L82-L105 | def convert_uniprot_to_entrez(self, uniprot):
"""Convert Uniprot Id to Entrez Id"""
# Submit request to NCBI eutils/Gene Database
server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?" + self.options + "&db=gene&term={0}".format(
uniprot)
r = requests.get(serve... | [
"def",
"convert_uniprot_to_entrez",
"(",
"self",
",",
"uniprot",
")",
":",
"# Submit request to NCBI eutils/Gene Database",
"server",
"=",
"\"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?\"",
"+",
"self",
".",
"options",
"+",
"\"&db=gene&term={0}\"",
".",
"format",... | Convert Uniprot Id to Entrez Id | [
"Convert",
"Uniprot",
"Id",
"to",
"Entrez",
"Id"
] | python | train |
mabuchilab/QNET | src/qnet/algebra/core/abstract_quantum_algebra.py | https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/core/abstract_quantum_algebra.py#L515-L530 | def factor_for_space(self, spc):
"""Return a tuple of two products, where the first product contains the
given Hilbert space, and the second product is disjunct from it."""
if spc == TrivialSpace:
ops_on_spc = [
o for o in self.operands if o.space is TrivialSpace]
... | [
"def",
"factor_for_space",
"(",
"self",
",",
"spc",
")",
":",
"if",
"spc",
"==",
"TrivialSpace",
":",
"ops_on_spc",
"=",
"[",
"o",
"for",
"o",
"in",
"self",
".",
"operands",
"if",
"o",
".",
"space",
"is",
"TrivialSpace",
"]",
"ops_not_on_spc",
"=",
"["... | Return a tuple of two products, where the first product contains the
given Hilbert space, and the second product is disjunct from it. | [
"Return",
"a",
"tuple",
"of",
"two",
"products",
"where",
"the",
"first",
"product",
"contains",
"the",
"given",
"Hilbert",
"space",
"and",
"the",
"second",
"product",
"is",
"disjunct",
"from",
"it",
"."
] | python | train |
stsouko/CIMtools | CIMtools/model_selection/group_out.py | https://github.com/stsouko/CIMtools/blob/cbb46e68eaa1fe7e7b6cb311fc7063e97096bdf3/CIMtools/model_selection/group_out.py#L54-L92 | def split(self, X, y=None, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like, of length n_samples
Training data, includes reaction's containers
y : array-like, of length n_samples
The target va... | [
"def",
"split",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"groups",
"=",
"None",
")",
":",
"X",
",",
"y",
",",
"groups",
"=",
"indexable",
"(",
"X",
",",
"y",
",",
"groups",
")",
"cgrs",
"=",
"[",
"~",
"r",
"for",
"r",
"in",
"X",
... | Generate indices to split data into training and test set.
Parameters
----------
X : array-like, of length n_samples
Training data, includes reaction's containers
y : array-like, of length n_samples
The target variable for supervised learning problems.
gro... | [
"Generate",
"indices",
"to",
"split",
"data",
"into",
"training",
"and",
"test",
"set",
".",
"Parameters",
"----------",
"X",
":",
"array",
"-",
"like",
"of",
"length",
"n_samples",
"Training",
"data",
"includes",
"reaction",
"s",
"containers",
"y",
":",
"ar... | python | valid |
archman/beamline | beamline/mathutils.py | https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/mathutils.py#L179-L207 | def transQuad(length=0.0, k1=0.0, gamma=None):
""" Transport matrix of quadrupole
:param length: quad width in [m]
:param k1: quad k1 strength in [T/m]
:param gamma: electron energy, gamma value
:return: 6x6 numpy array
"""
m = np.eye(6, 6, dtype=np.float64)
if length == 0.0:
pr... | [
"def",
"transQuad",
"(",
"length",
"=",
"0.0",
",",
"k1",
"=",
"0.0",
",",
"gamma",
"=",
"None",
")",
":",
"m",
"=",
"np",
".",
"eye",
"(",
"6",
",",
"6",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"if",
"length",
"==",
"0.0",
":",
"print"... | Transport matrix of quadrupole
:param length: quad width in [m]
:param k1: quad k1 strength in [T/m]
:param gamma: electron energy, gamma value
:return: 6x6 numpy array | [
"Transport",
"matrix",
"of",
"quadrupole"
] | python | train |
shoebot/shoebot | lib/beziereditor/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/beziereditor/__init__.py#L197-L204 | def angle(self, x0, y0, x1, y1):
""" Calculates the angle between two points.
"""
a = degrees( atan((y1-y0) / (x1-x0+0.00001)) ) + 360
if x1-x0 < 0: a += 180
return a | [
"def",
"angle",
"(",
"self",
",",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
")",
":",
"a",
"=",
"degrees",
"(",
"atan",
"(",
"(",
"y1",
"-",
"y0",
")",
"/",
"(",
"x1",
"-",
"x0",
"+",
"0.00001",
")",
")",
")",
"+",
"360",
"if",
"x1",
"-",
... | Calculates the angle between two points. | [
"Calculates",
"the",
"angle",
"between",
"two",
"points",
"."
] | python | valid |
numba/llvmlite | llvmlite/ir/types.py | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/types.py#L50-L55 | def get_abi_size(self, target_data, context=None):
"""
Get the ABI size of this type according to data layout *target_data*.
"""
llty = self._get_ll_pointer_type(target_data, context)
return target_data.get_pointee_abi_size(llty) | [
"def",
"get_abi_size",
"(",
"self",
",",
"target_data",
",",
"context",
"=",
"None",
")",
":",
"llty",
"=",
"self",
".",
"_get_ll_pointer_type",
"(",
"target_data",
",",
"context",
")",
"return",
"target_data",
".",
"get_pointee_abi_size",
"(",
"llty",
")"
] | Get the ABI size of this type according to data layout *target_data*. | [
"Get",
"the",
"ABI",
"size",
"of",
"this",
"type",
"according",
"to",
"data",
"layout",
"*",
"target_data",
"*",
"."
] | python | train |
inveniosoftware/invenio-deposit | invenio_deposit/views/ui.py | https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/views/ui.py#L39-L90 | def create_blueprint(endpoints):
"""Create Invenio-Deposit-UI blueprint.
See: :data:`invenio_deposit.config.DEPOSIT_RECORDS_UI_ENDPOINTS`.
:param endpoints: List of endpoints configuration.
:returns: The configured blueprint.
"""
from invenio_records_ui.views import create_url_rule
bluepr... | [
"def",
"create_blueprint",
"(",
"endpoints",
")",
":",
"from",
"invenio_records_ui",
".",
"views",
"import",
"create_url_rule",
"blueprint",
"=",
"Blueprint",
"(",
"'invenio_deposit_ui'",
",",
"__name__",
",",
"static_folder",
"=",
"'../static'",
",",
"template_folder... | Create Invenio-Deposit-UI blueprint.
See: :data:`invenio_deposit.config.DEPOSIT_RECORDS_UI_ENDPOINTS`.
:param endpoints: List of endpoints configuration.
:returns: The configured blueprint. | [
"Create",
"Invenio",
"-",
"Deposit",
"-",
"UI",
"blueprint",
"."
] | python | valid |
mkouhei/tonicdnscli | src/tonicdnscli/processing.py | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/processing.py#L72-L87 | def delete_records(server, token, data):
"""Delete records of specific domain.
Arguments:
server: TonicDNS API server
token: TonicDNS API authentication token
data: Delete records
ContentType: application/json
x-authentication-token: token
"""
method = 'DELETE'
... | [
"def",
"delete_records",
"(",
"server",
",",
"token",
",",
"data",
")",
":",
"method",
"=",
"'DELETE'",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/zone'",
"for",
"i",
"in",
"data",
":",
"connect",
".",
"tonicdns_client",
"(",
"uri",
",",
"method",
... | Delete records of specific domain.
Arguments:
server: TonicDNS API server
token: TonicDNS API authentication token
data: Delete records
ContentType: application/json
x-authentication-token: token | [
"Delete",
"records",
"of",
"specific",
"domain",
"."
] | python | train |
pydata/xarray | xarray/conventions.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/conventions.py#L357-L416 | def decode_cf_variables(variables, attributes, concat_characters=True,
mask_and_scale=True, decode_times=True,
decode_coords=True, drop_variables=None,
use_cftime=None):
"""
Decode several CF encoded variables.
See: decode_cf_variable
... | [
"def",
"decode_cf_variables",
"(",
"variables",
",",
"attributes",
",",
"concat_characters",
"=",
"True",
",",
"mask_and_scale",
"=",
"True",
",",
"decode_times",
"=",
"True",
",",
"decode_coords",
"=",
"True",
",",
"drop_variables",
"=",
"None",
",",
"use_cftim... | Decode several CF encoded variables.
See: decode_cf_variable | [
"Decode",
"several",
"CF",
"encoded",
"variables",
"."
] | python | train |
siznax/wptools | wptools/page.py | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/page.py#L218-L238 | def _set_imageinfo_data(self):
"""
set image attributes from MediaWiki API:Imageinfo response
"""
data = self._load_response('imageinfo')
pages = data['query'].get('pages')
normalized = []
if 'normalized' in data['query']:
normalized = data['query']['... | [
"def",
"_set_imageinfo_data",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"_load_response",
"(",
"'imageinfo'",
")",
"pages",
"=",
"data",
"[",
"'query'",
"]",
".",
"get",
"(",
"'pages'",
")",
"normalized",
"=",
"[",
"]",
"if",
"'normalized'",
"in",... | set image attributes from MediaWiki API:Imageinfo response | [
"set",
"image",
"attributes",
"from",
"MediaWiki",
"API",
":",
"Imageinfo",
"response"
] | python | train |
agoragames/haigha | haigha/connections/rabbit_connection.py | https://github.com/agoragames/haigha/blob/7b004e1c0316ec14b94fec1c54554654c38b1a25/haigha/connections/rabbit_connection.py#L290-L316 | def _recv_cancel(self, method_frame):
'''Handle Basic.Cancel from broker
:param MethodFrame method_frame: Basic.Cancel method frame from broker
'''
self.logger.warning("consumer cancelled by broker: %r", method_frame)
consumer_tag = method_frame.args.read_shortstr()
# ... | [
"def",
"_recv_cancel",
"(",
"self",
",",
"method_frame",
")",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"consumer cancelled by broker: %r\"",
",",
"method_frame",
")",
"consumer_tag",
"=",
"method_frame",
".",
"args",
".",
"read_shortstr",
"(",
")",
"# ... | Handle Basic.Cancel from broker
:param MethodFrame method_frame: Basic.Cancel method frame from broker | [
"Handle",
"Basic",
".",
"Cancel",
"from",
"broker"
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ras_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ras_ext.py#L214-L225 | def show_support_save_status_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_support_save_status = ET.Element("show_support_save_status")
config = show_support_save_status
input = ET.SubElement(show_support_save_status, "inp... | [
"def",
"show_support_save_status_input_rbridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_support_save_status",
"=",
"ET",
".",
"Element",
"(",
"\"show_support_save_status\"",
")",
"confi... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
SeabornGames/Timestamp | seaborn_timestamp/timestamp.py | https://github.com/SeabornGames/Timestamp/blob/2b6902ddc2a009d6f3cb4dd0f6882bf4345f3871/seaborn_timestamp/timestamp.py#L68-L80 | def now(years=0, days=0, hours=0, minutes=0, seconds=0):
"""
:param years: int delta of years from now
:param days: int delta of days from now
:param hours: int delta of hours from now
:param minutes: int delta of minutes from now
:param seconds: float delta of seconds from now
:retur... | [
"def",
"now",
"(",
"years",
"=",
"0",
",",
"days",
"=",
"0",
",",
"hours",
"=",
"0",
",",
"minutes",
"=",
"0",
",",
"seconds",
"=",
"0",
")",
":",
"date_time",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"date_time",
"+=",
"timedelta",
"(",
"days",... | :param years: int delta of years from now
:param days: int delta of days from now
:param hours: int delta of hours from now
:param minutes: int delta of minutes from now
:param seconds: float delta of seconds from now
:return: str of the now timestamp | [
":",
"param",
"years",
":",
"int",
"delta",
"of",
"years",
"from",
"now",
":",
"param",
"days",
":",
"int",
"delta",
"of",
"days",
"from",
"now",
":",
"param",
"hours",
":",
"int",
"delta",
"of",
"hours",
"from",
"now",
":",
"param",
"minutes",
":",
... | python | train |
geophysics-ubonn/crtomo_tools | lib/crtomo/tdManager.py | https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/tdManager.py#L1716-L1748 | def add_homogeneous_model(self, magnitude, phase=0):
"""Add a homogeneous resistivity model to the tomodir. This is useful
for synthetic measurements.
Parameters
----------
magnitude : float
magnitude [Ohm m] value of the homogeneous model
phase : float, opti... | [
"def",
"add_homogeneous_model",
"(",
"self",
",",
"magnitude",
",",
"phase",
"=",
"0",
")",
":",
"if",
"self",
".",
"assignments",
"[",
"'forward_model'",
"]",
"is",
"not",
"None",
":",
"print",
"(",
"'model already set, will overwrite'",
")",
"# generate distri... | Add a homogeneous resistivity model to the tomodir. This is useful
for synthetic measurements.
Parameters
----------
magnitude : float
magnitude [Ohm m] value of the homogeneous model
phase : float, optional
phase [mrad] value of the homogeneous model
... | [
"Add",
"a",
"homogeneous",
"resistivity",
"model",
"to",
"the",
"tomodir",
".",
"This",
"is",
"useful",
"for",
"synthetic",
"measurements",
"."
] | python | train |
zsethna/OLGA | olga/generation_probability.py | https://github.com/zsethna/OLGA/blob/e825c333f0f9a4eb02132e0bcf86f0dca9123114/olga/generation_probability.py#L156-L213 | def compute_regex_CDR3_template_pgen(self, regex_seq, V_usage_mask_in = None, J_usage_mask_in = None, print_warnings = True, raise_overload_warning = True):
"""Compute Pgen for all seqs consistent with regular expression regex_seq.
Computes Pgen for a (limited vocabulary) regular expression of CDR3... | [
"def",
"compute_regex_CDR3_template_pgen",
"(",
"self",
",",
"regex_seq",
",",
"V_usage_mask_in",
"=",
"None",
",",
"J_usage_mask_in",
"=",
"None",
",",
"print_warnings",
"=",
"True",
",",
"raise_overload_warning",
"=",
"True",
")",
":",
"V_usage_mask",
",",
"J_us... | Compute Pgen for all seqs consistent with regular expression regex_seq.
Computes Pgen for a (limited vocabulary) regular expression of CDR3
amino acid sequences, conditioned on the V genes/alleles indicated in
V_usage_mask_in and the J genes/alleles in J_usage_mask_in. Please note
... | [
"Compute",
"Pgen",
"for",
"all",
"seqs",
"consistent",
"with",
"regular",
"expression",
"regex_seq",
".",
"Computes",
"Pgen",
"for",
"a",
"(",
"limited",
"vocabulary",
")",
"regular",
"expression",
"of",
"CDR3",
"amino",
"acid",
"sequences",
"conditioned",
"on",... | python | train |
zikzakmedia/python-mediawiki | mediawiki/wikimarkup/__init__.py | https://github.com/zikzakmedia/python-mediawiki/blob/7c26732efa520e16c35350815ce98cd7610a0bcb/mediawiki/wikimarkup/__init__.py#L558-L658 | def removeHtmlTags(self, text):
"""convert bad tags into HTML identities"""
sb = []
text = self.removeHtmlComments(text)
bits = text.split(u'<')
sb.append(bits.pop(0))
tagstack = []
tablestack = tagstack
for x in bits:
m = _tagPattern.match(x)
if not m:
continue
slash, t, params, brace, res... | [
"def",
"removeHtmlTags",
"(",
"self",
",",
"text",
")",
":",
"sb",
"=",
"[",
"]",
"text",
"=",
"self",
".",
"removeHtmlComments",
"(",
"text",
")",
"bits",
"=",
"text",
".",
"split",
"(",
"u'<'",
")",
"sb",
".",
"append",
"(",
"bits",
".",
"pop",
... | convert bad tags into HTML identities | [
"convert",
"bad",
"tags",
"into",
"HTML",
"identities"
] | python | train |
opencobra/memote | memote/suite/results/models.py | https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/suite/results/models.py#L84-L90 | def process_result_value(self, value, dialect):
"""Convert a JSON encoded string to a dictionary structure."""
if value is not None:
with BytesIO(value) as stream:
with GzipFile(fileobj=stream, mode="rb") as file_handle:
value = json.loads(file_handle.read... | [
"def",
"process_result_value",
"(",
"self",
",",
"value",
",",
"dialect",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"with",
"BytesIO",
"(",
"value",
")",
"as",
"stream",
":",
"with",
"GzipFile",
"(",
"fileobj",
"=",
"stream",
",",
"mode",
"=",... | Convert a JSON encoded string to a dictionary structure. | [
"Convert",
"a",
"JSON",
"encoded",
"string",
"to",
"a",
"dictionary",
"structure",
"."
] | python | train |
wheeler-microfluidics/dmf-control-board-firmware | dmf_control_board_firmware/__init__.py | https://github.com/wheeler-microfluidics/dmf-control-board-firmware/blob/1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c/dmf_control_board_firmware/__init__.py#L1027-L1061 | def _upgrade(self):
"""
Upgrade the serialized object if necessary.
Raises:
FutureVersionError: file was written by a future version of the
software.
"""
logging.debug("[FeedbackCalibration]._upgrade()")
version = Version.fromstring(self.versi... | [
"def",
"_upgrade",
"(",
"self",
")",
":",
"logging",
".",
"debug",
"(",
"\"[FeedbackCalibration]._upgrade()\"",
")",
"version",
"=",
"Version",
".",
"fromstring",
"(",
"self",
".",
"version",
")",
"logging",
".",
"debug",
"(",
"'[FeedbackCalibration] version=%s, c... | Upgrade the serialized object if necessary.
Raises:
FutureVersionError: file was written by a future version of the
software. | [
"Upgrade",
"the",
"serialized",
"object",
"if",
"necessary",
"."
] | python | train |
django-ldapdb/django-ldapdb | ldapdb/backends/ldap/base.py | https://github.com/django-ldapdb/django-ldapdb/blob/f3a35d3c8e42e7799d71e5d156ab97fb69e6b479/ldapdb/backends/ldap/base.py#L220-L236 | def get_connection_params(self):
"""Compute appropriate parameters for establishing a new connection.
Computed at system startup.
"""
return {
'uri': self.settings_dict['NAME'],
'tls': self.settings_dict.get('TLS', False),
'bind_dn': self.settings_dic... | [
"def",
"get_connection_params",
"(",
"self",
")",
":",
"return",
"{",
"'uri'",
":",
"self",
".",
"settings_dict",
"[",
"'NAME'",
"]",
",",
"'tls'",
":",
"self",
".",
"settings_dict",
".",
"get",
"(",
"'TLS'",
",",
"False",
")",
",",
"'bind_dn'",
":",
"... | Compute appropriate parameters for establishing a new connection.
Computed at system startup. | [
"Compute",
"appropriate",
"parameters",
"for",
"establishing",
"a",
"new",
"connection",
"."
] | python | train |
wangwenpei/cliez | cliez/mixins.py | https://github.com/wangwenpei/cliez/blob/d6fe775544cd380735c56c8a4a79bc2ad22cb6c4/cliez/mixins.py#L55-L86 | def parse_require(self, env, keys, defaults={}):
"""
check and get require config
:param dict env: user config node
:param list keys: check keys
.. note::
option and key name must be same.
:param dict defaults: default value for keys
:return:... | [
"def",
"parse_require",
"(",
"self",
",",
"env",
",",
"keys",
",",
"defaults",
"=",
"{",
"}",
")",
":",
"for",
"k",
"in",
"keys",
":",
"env",
"[",
"k",
"]",
"=",
"getattr",
"(",
"self",
".",
"options",
",",
"k",
")",
"or",
"env",
".",
"get",
... | check and get require config
:param dict env: user config node
:param list keys: check keys
.. note::
option and key name must be same.
:param dict defaults: default value for keys
:return: dict.env with verified.
.. exception::
will r... | [
"check",
"and",
"get",
"require",
"config",
":",
"param",
"dict",
"env",
":",
"user",
"config",
"node",
":",
"param",
"list",
"keys",
":",
"check",
"keys",
"..",
"note",
"::"
] | python | valid |
calmjs/calmjs | src/calmjs/loaderplugin.py | https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/loaderplugin.py#L236-L252 | def store_records_for_package(self, entry_point, records):
"""
Given that records are based on the parent, and the same entry
point(s) will reference those same records multiple times, the
actual stored records must be limited.
"""
pkg_records_entry = self._dist_to_packa... | [
"def",
"store_records_for_package",
"(",
"self",
",",
"entry_point",
",",
"records",
")",
":",
"pkg_records_entry",
"=",
"self",
".",
"_dist_to_package_module_map",
"(",
"entry_point",
")",
"pkg_records_entry",
".",
"extend",
"(",
"rec",
"for",
"rec",
"in",
"recor... | Given that records are based on the parent, and the same entry
point(s) will reference those same records multiple times, the
actual stored records must be limited. | [
"Given",
"that",
"records",
"are",
"based",
"on",
"the",
"parent",
"and",
"the",
"same",
"entry",
"point",
"(",
"s",
")",
"will",
"reference",
"those",
"same",
"records",
"multiple",
"times",
"the",
"actual",
"stored",
"records",
"must",
"be",
"limited",
"... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.