repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
neon-jungle/wagtailmodelchooser | wagtailmodelchooser/utils.py | https://github.com/neon-jungle/wagtailmodelchooser/blob/8dd1e33dd61418a726ff3acf67a956626c8b7ba1/wagtailmodelchooser/utils.py#L5-L29 | def kwarg_decorator(func):
"""
Turns a function that accepts a single arg and some kwargs in to a
decorator that can optionally be called with kwargs:
.. code-block:: python
@kwarg_decorator
def my_decorator(func, bar=True, baz=None):
...
@my_decorator
def ... | [
"def",
"kwarg_decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"decorator",
"(",
"arg",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"arg",
"is",
"None",
":",
"return",
"lambda",
"arg",
":",
"decorator",
"(",
"arg"... | Turns a function that accepts a single arg and some kwargs in to a
decorator that can optionally be called with kwargs:
.. code-block:: python
@kwarg_decorator
def my_decorator(func, bar=True, baz=None):
...
@my_decorator
def my_func():
pass
@m... | [
"Turns",
"a",
"function",
"that",
"accepts",
"a",
"single",
"arg",
"and",
"some",
"kwargs",
"in",
"to",
"a",
"decorator",
"that",
"can",
"optionally",
"be",
"called",
"with",
"kwargs",
":"
] | python | valid | 24.12 |
tcalmant/python-javaobj | javaobj/core.py | https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1552-L1559 | def write_reference(self, ref_index):
"""
Writes a reference
:param ref_index: Local index (0-based) to the reference
"""
self._writeStruct(
">BL", 1, (self.TC_REFERENCE, ref_index + self.BASE_REFERENCE_IDX)
) | [
"def",
"write_reference",
"(",
"self",
",",
"ref_index",
")",
":",
"self",
".",
"_writeStruct",
"(",
"\">BL\"",
",",
"1",
",",
"(",
"self",
".",
"TC_REFERENCE",
",",
"ref_index",
"+",
"self",
".",
"BASE_REFERENCE_IDX",
")",
")"
] | Writes a reference
:param ref_index: Local index (0-based) to the reference | [
"Writes",
"a",
"reference",
":",
"param",
"ref_index",
":",
"Local",
"index",
"(",
"0",
"-",
"based",
")",
"to",
"the",
"reference"
] | python | train | 32.75 |
waqasbhatti/astrobase | astrobase/services/lccs.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/services/lccs.py#L1770-L1853 | def get_dataset(lcc_server,
dataset_id,
strformat=False,
page=1):
'''This downloads a JSON form of a dataset from the specified lcc_server.
If the dataset contains more than 1000 rows, it will be paginated, so you
must use the `page` kwarg to get the page you... | [
"def",
"get_dataset",
"(",
"lcc_server",
",",
"dataset_id",
",",
"strformat",
"=",
"False",
",",
"page",
"=",
"1",
")",
":",
"urlparams",
"=",
"{",
"'strformat'",
":",
"1",
"if",
"strformat",
"else",
"0",
",",
"'page'",
":",
"page",
",",
"'json'",
":",... | This downloads a JSON form of a dataset from the specified lcc_server.
If the dataset contains more than 1000 rows, it will be paginated, so you
must use the `page` kwarg to get the page you want. The dataset JSON will
contain the keys 'npages', 'currpage', and 'rows_per_page' to help with
this. The 'r... | [
"This",
"downloads",
"a",
"JSON",
"form",
"of",
"a",
"dataset",
"from",
"the",
"specified",
"lcc_server",
"."
] | python | valid | 34.916667 |
django-danceschool/django-danceschool | danceschool/core/models.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L952-L964 | def availableRoles(self):
'''
Returns the set of roles for this event. Since roles are not always custom specified for
event, this looks for the set of available roles in multiple places. If no roles are found,
then the method returns an empty list, in which case it can be assumed that... | [
"def",
"availableRoles",
"(",
"self",
")",
":",
"eventRoles",
"=",
"self",
".",
"eventrole_set",
".",
"filter",
"(",
"capacity__gt",
"=",
"0",
")",
"if",
"eventRoles",
".",
"count",
"(",
")",
">",
"0",
":",
"return",
"[",
"x",
".",
"role",
"for",
"x"... | Returns the set of roles for this event. Since roles are not always custom specified for
event, this looks for the set of available roles in multiple places. If no roles are found,
then the method returns an empty list, in which case it can be assumed that the event's registration
is not role-... | [
"Returns",
"the",
"set",
"of",
"roles",
"for",
"this",
"event",
".",
"Since",
"roles",
"are",
"not",
"always",
"custom",
"specified",
"for",
"event",
"this",
"looks",
"for",
"the",
"set",
"of",
"available",
"roles",
"in",
"multiple",
"places",
".",
"If",
... | python | train | 50.384615 |
google/grumpy | third_party/stdlib/difflib.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L521-L590 | def get_matching_blocks(self):
"""Return list of triples describing matching subsequences.
Each triple is of the form (i, j, n), and means that
a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
i and in j. New in Python 2.5, it's also guaranteed that if
(i, j, ... | [
"def",
"get_matching_blocks",
"(",
"self",
")",
":",
"if",
"self",
".",
"matching_blocks",
"is",
"not",
"None",
":",
"return",
"self",
".",
"matching_blocks",
"la",
",",
"lb",
"=",
"len",
"(",
"self",
".",
"a",
")",
",",
"len",
"(",
"self",
".",
"b",... | Return list of triples describing matching subsequences.
Each triple is of the form (i, j, n), and means that
a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
i and in j. New in Python 2.5, it's also guaranteed that if
(i, j, n) and (i', j', n') are adjacent triples i... | [
"Return",
"list",
"of",
"triples",
"describing",
"matching",
"subsequences",
"."
] | python | valid | 44.042857 |
tkf/rash | rash/database.py | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L68-L86 | def sql_program_name_func(command):
"""
Extract program name from `command`.
>>> sql_program_name_func('ls')
'ls'
>>> sql_program_name_func('git status')
'git'
>>> sql_program_name_func('EMACS=emacs make')
'make'
:type command: str
"""
args = command.split(' ')
for pro... | [
"def",
"sql_program_name_func",
"(",
"command",
")",
":",
"args",
"=",
"command",
".",
"split",
"(",
"' '",
")",
"for",
"prog",
"in",
"args",
":",
"if",
"'='",
"not",
"in",
"prog",
":",
"return",
"prog",
"return",
"args",
"[",
"0",
"]"
] | Extract program name from `command`.
>>> sql_program_name_func('ls')
'ls'
>>> sql_program_name_func('git status')
'git'
>>> sql_program_name_func('EMACS=emacs make')
'make'
:type command: str | [
"Extract",
"program",
"name",
"from",
"command",
"."
] | python | train | 20.157895 |
nigma/django-twilio-sms | src/utils.py | https://github.com/nigma/django-twilio-sms/blob/386999c3da545e001cb8977c78b67408e33aba11/src/utils.py#L45-L88 | def send_sms(request, to_number, body, callback_urlname="sms_status_callback"):
"""
Create :class:`OutgoingSMS` object and send SMS using Twilio.
"""
client = TwilioRestClient(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
from_number = settings.TWILIO_PHONE_NUMBER
message = OutgoingS... | [
"def",
"send_sms",
"(",
"request",
",",
"to_number",
",",
"body",
",",
"callback_urlname",
"=",
"\"sms_status_callback\"",
")",
":",
"client",
"=",
"TwilioRestClient",
"(",
"settings",
".",
"TWILIO_ACCOUNT_SID",
",",
"settings",
".",
"TWILIO_AUTH_TOKEN",
")",
"fro... | Create :class:`OutgoingSMS` object and send SMS using Twilio. | [
"Create",
":",
"class",
":",
"OutgoingSMS",
"object",
"and",
"send",
"SMS",
"using",
"Twilio",
"."
] | python | test | 34.659091 |
saltstack/salt | salt/cloud/clouds/gce.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/gce.py#L1883-L1949 | def create_snapshot(kwargs=None, call=None):
'''
Create a new disk snapshot. Must specify `name` and `disk_name`.
CLI Example:
.. code-block:: bash
salt-cloud -f create_snapshot gce name=snap1 disk_name=pd
'''
if call != 'function':
raise SaltCloudSystemExit(
'The... | [
"def",
"create_snapshot",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The create_snapshot function must be called with -f or --function.'",
")",
"if",
"not",
"kwargs",
... | Create a new disk snapshot. Must specify `name` and `disk_name`.
CLI Example:
.. code-block:: bash
salt-cloud -f create_snapshot gce name=snap1 disk_name=pd | [
"Create",
"a",
"new",
"disk",
"snapshot",
".",
"Must",
"specify",
"name",
"and",
"disk_name",
"."
] | python | train | 25.029851 |
log2timeline/plaso | plaso/storage/interface.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/storage/interface.py#L1653-L1681 | def PrepareMergeTaskStorage(self, task):
"""Prepares a task storage for merging.
Moves the task storage file from the processed directory to the merge
directory.
Args:
task (Task): task.
Raises:
IOError: if the storage type is not supported or
if the storage file cannot be r... | [
"def",
"PrepareMergeTaskStorage",
"(",
"self",
",",
"task",
")",
":",
"if",
"self",
".",
"_storage_type",
"!=",
"definitions",
".",
"STORAGE_TYPE_SESSION",
":",
"raise",
"IOError",
"(",
"'Unsupported storage type.'",
")",
"merge_storage_file_path",
"=",
"self",
".",... | Prepares a task storage for merging.
Moves the task storage file from the processed directory to the merge
directory.
Args:
task (Task): task.
Raises:
IOError: if the storage type is not supported or
if the storage file cannot be renamed.
OSError: if the storage type is no... | [
"Prepares",
"a",
"task",
"storage",
"for",
"merging",
"."
] | python | train | 34.896552 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L283-L306 | def check_is_uuid(self, uuid_str: str):
"""Check if it's an Isogeo UUID handling specific form.
:param str uuid_str: UUID string to check
"""
# check uuid type
if not isinstance(uuid_str, str):
raise TypeError("'uuid_str' expected a str value.")
else:
... | [
"def",
"check_is_uuid",
"(",
"self",
",",
"uuid_str",
":",
"str",
")",
":",
"# check uuid type",
"if",
"not",
"isinstance",
"(",
"uuid_str",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"'uuid_str' expected a str value.\"",
")",
"else",
":",
"pass",
"# h... | Check if it's an Isogeo UUID handling specific form.
:param str uuid_str: UUID string to check | [
"Check",
"if",
"it",
"s",
"an",
"Isogeo",
"UUID",
"handling",
"specific",
"form",
"."
] | python | train | 34.583333 |
ray-project/ray | python/ray/services.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L880-L918 | def start_reporter(redis_address,
stdout_file=None,
stderr_file=None,
redis_password=None):
"""Start a reporter process.
Args:
redis_address (str): The address of the Redis instance.
stdout_file: A file handle opened for writing to redire... | [
"def",
"start_reporter",
"(",
"redis_address",
",",
"stdout_file",
"=",
"None",
",",
"stderr_file",
"=",
"None",
",",
"redis_password",
"=",
"None",
")",
":",
"reporter_filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",... | Start a reporter process.
Args:
redis_address (str): The address of the Redis instance.
stdout_file: A file handle opened for writing to redirect stdout to. If
no redirection should happen, then this should be None.
stderr_file: A file handle opened for writing to redirect stder... | [
"Start",
"a",
"reporter",
"process",
"."
] | python | train | 35.051282 |
orb-framework/pyramid_orb | pyramid_orb/api.py | https://github.com/orb-framework/pyramid_orb/blob/e5c716fc75626e1cd966f7bd87b470a8b71126bf/pyramid_orb/api.py#L161-L175 | def register(self, service, name=''):
"""
Exposes a given service to this API.
"""
try:
is_model = issubclass(service, orb.Model)
except StandardError:
is_model = False
# expose an ORB table dynamically as a service
if is_model:
... | [
"def",
"register",
"(",
"self",
",",
"service",
",",
"name",
"=",
"''",
")",
":",
"try",
":",
"is_model",
"=",
"issubclass",
"(",
"service",
",",
"orb",
".",
"Model",
")",
"except",
"StandardError",
":",
"is_model",
"=",
"False",
"# expose an ORB table dyn... | Exposes a given service to this API. | [
"Exposes",
"a",
"given",
"service",
"to",
"this",
"API",
"."
] | python | valid | 30.466667 |
iwoca/django-deep-collector | deep_collector/core.py | https://github.com/iwoca/django-deep-collector/blob/1bd599d5362ade525cb51d6ee70713a3f58af219/deep_collector/core.py#L203-L219 | def _is_same_type_as_root(self, obj):
"""
Testing if we try to collect an object of the same type as root.
This is not really a good sign, because it means that we are going to collect a whole new tree, that will
maybe collect a new tree, that will...
"""
if not self.ALLO... | [
"def",
"_is_same_type_as_root",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"self",
".",
"ALLOWS_SAME_TYPE_AS_ROOT_COLLECT",
":",
"obj_model",
"=",
"get_model_from_instance",
"(",
"obj",
")",
"obj_key",
"=",
"get_key_from_instance",
"(",
"obj",
")",
"is_same_t... | Testing if we try to collect an object of the same type as root.
This is not really a good sign, because it means that we are going to collect a whole new tree, that will
maybe collect a new tree, that will... | [
"Testing",
"if",
"we",
"try",
"to",
"collect",
"an",
"object",
"of",
"the",
"same",
"type",
"as",
"root",
".",
"This",
"is",
"not",
"really",
"a",
"good",
"sign",
"because",
"it",
"means",
"that",
"we",
"are",
"going",
"to",
"collect",
"a",
"whole",
... | python | train | 42.411765 |
KrishnaswamyLab/graphtools | graphtools/base.py | https://github.com/KrishnaswamyLab/graphtools/blob/44685352be7df2005d44722903092207967457f2/graphtools/base.py#L214-L250 | def transform(self, Y):
"""Transform input data `Y` to reduced data space defined by `self.data`
Takes data in the same ambient space as `self.data` and transforms it
to be in the same reduced space as `self.data_nu`.
Parameters
----------
Y : array-like, shape=[n_sampl... | [
"def",
"transform",
"(",
"self",
",",
"Y",
")",
":",
"try",
":",
"# try PCA first",
"return",
"self",
".",
"data_pca",
".",
"transform",
"(",
"Y",
")",
"except",
"AttributeError",
":",
"# no pca, try to return data",
"try",
":",
"if",
"Y",
".",
"shape",
"[... | Transform input data `Y` to reduced data space defined by `self.data`
Takes data in the same ambient space as `self.data` and transforms it
to be in the same reduced space as `self.data_nu`.
Parameters
----------
Y : array-like, shape=[n_samples_y, n_features]
n_fea... | [
"Transform",
"input",
"data",
"Y",
"to",
"reduced",
"data",
"space",
"defined",
"by",
"self",
".",
"data"
] | python | train | 33.216216 |
inveniosoftware/invenio-oauth2server | invenio_oauth2server/provider.py | https://github.com/inveniosoftware/invenio-oauth2server/blob/7033d3495c1a2b830e101e43918e92a37bbb49f2/invenio_oauth2server/provider.py#L145-L152 | def login_oauth2_user(valid, oauth):
"""Log in a user after having been verified."""
if valid:
oauth.user.login_via_oauth2 = True
_request_ctx_stack.top.user = oauth.user
identity_changed.send(current_app._get_current_object(),
identity=Identity(oauth.user.i... | [
"def",
"login_oauth2_user",
"(",
"valid",
",",
"oauth",
")",
":",
"if",
"valid",
":",
"oauth",
".",
"user",
".",
"login_via_oauth2",
"=",
"True",
"_request_ctx_stack",
".",
"top",
".",
"user",
"=",
"oauth",
".",
"user",
"identity_changed",
".",
"send",
"("... | Log in a user after having been verified. | [
"Log",
"in",
"a",
"user",
"after",
"having",
"been",
"verified",
"."
] | python | train | 42.5 |
libtcod/python-tcod | build_libtcod.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/build_libtcod.py#L394-L458 | def write_library_constants():
"""Write libtcod constants into the tcod.constants module."""
from tcod._libtcod import lib, ffi
import tcod.color
with open("tcod/constants.py", "w") as f:
all_names = []
f.write(CONSTANT_MODULE_HEADER)
for name in dir(lib):
value = ge... | [
"def",
"write_library_constants",
"(",
")",
":",
"from",
"tcod",
".",
"_libtcod",
"import",
"lib",
",",
"ffi",
"import",
"tcod",
".",
"color",
"with",
"open",
"(",
"\"tcod/constants.py\"",
",",
"\"w\"",
")",
"as",
"f",
":",
"all_names",
"=",
"[",
"]",
"f... | Write libtcod constants into the tcod.constants module. | [
"Write",
"libtcod",
"constants",
"into",
"the",
"tcod",
".",
"constants",
"module",
"."
] | python | train | 36.415385 |
fiesta/fiesta-python | fiesta/fiesta.py | https://github.com/fiesta/fiesta-python/blob/cfcc11e4ae4c76b1007794604c33dde877f62cfb/fiesta/fiesta.py#L210-L215 | def send_message(self, subject=None, text=None, markdown=None, message_dict=None):
"""
Helper function to send a message to a group
"""
message = FiestaMessage(self.api, self, subject, text, markdown, message_dict)
return message.send() | [
"def",
"send_message",
"(",
"self",
",",
"subject",
"=",
"None",
",",
"text",
"=",
"None",
",",
"markdown",
"=",
"None",
",",
"message_dict",
"=",
"None",
")",
":",
"message",
"=",
"FiestaMessage",
"(",
"self",
".",
"api",
",",
"self",
",",
"subject",
... | Helper function to send a message to a group | [
"Helper",
"function",
"to",
"send",
"a",
"message",
"to",
"a",
"group"
] | python | train | 45.166667 |
spyder-ide/spyder | spyder/plugins/findinfiles/widgets.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/findinfiles/widgets.py#L288-L291 | def get_external_paths(self):
"""Returns a list of the external paths listed in the combobox."""
return [to_text_string(self.itemText(i))
for i in range(EXTERNAL_PATHS, self.count())] | [
"def",
"get_external_paths",
"(",
"self",
")",
":",
"return",
"[",
"to_text_string",
"(",
"self",
".",
"itemText",
"(",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"EXTERNAL_PATHS",
",",
"self",
".",
"count",
"(",
")",
")",
"]"
] | Returns a list of the external paths listed in the combobox. | [
"Returns",
"a",
"list",
"of",
"the",
"external",
"paths",
"listed",
"in",
"the",
"combobox",
"."
] | python | train | 53.75 |
kiwi0fruit/sugartex | sugartex/pre_sugartex.py | https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/pre_sugartex.py#L39-L67 | def main():
"""
Usage: pre-sugartex [OPTIONS]
Reads from stdin and writes to stdout.
When no options: only replace
U+02CE Modifier Letter Low Grave Accent
(that looks like low '`') with $
Options:
--all Full SugarTeX replace with regexp,
--kiwi Same as above but wi... | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"1",
":",
"arg1",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"if",
"arg1",
"==",
"'--all'",
"or",
"arg1",
"==",
"'--kiwi'",
":",
"if",
"arg1",
"==",
"'--kiwi'",
":",
"... | Usage: pre-sugartex [OPTIONS]
Reads from stdin and writes to stdout.
When no options: only replace
U+02CE Modifier Letter Low Grave Accent
(that looks like low '`') with $
Options:
--all Full SugarTeX replace with regexp,
--kiwi Same as above but with kiwi flavor,
--... | [
"Usage",
":",
"pre",
"-",
"sugartex",
"[",
"OPTIONS",
"]"
] | python | train | 35.482759 |
edx/i18n-tools | i18n/branch_cleanup.py | https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/branch_cleanup.py#L27-L30 | def clean_conf_folder(self, locale):
"""Remove the configuration directory for `locale`"""
dirname = self.configuration.get_messages_dir(locale)
dirname.removedirs_p() | [
"def",
"clean_conf_folder",
"(",
"self",
",",
"locale",
")",
":",
"dirname",
"=",
"self",
".",
"configuration",
".",
"get_messages_dir",
"(",
"locale",
")",
"dirname",
".",
"removedirs_p",
"(",
")"
] | Remove the configuration directory for `locale` | [
"Remove",
"the",
"configuration",
"directory",
"for",
"locale"
] | python | train | 47 |
howie6879/ruia | ruia/spider.py | https://github.com/howie6879/ruia/blob/2dc5262fc9c3e902a8faa7d5fa2f046f9d9ee1fa/ruia/spider.py#L446-L454 | async def stop(self, _signal):
"""
Finish all running tasks, cancel remaining tasks, then stop loop.
:param _signal:
:return:
"""
self.logger.info(f'Stopping spider: {self.name}')
await self._cancel_tasks()
self.loop.stop() | [
"async",
"def",
"stop",
"(",
"self",
",",
"_signal",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"f'Stopping spider: {self.name}'",
")",
"await",
"self",
".",
"_cancel_tasks",
"(",
")",
"self",
".",
"loop",
".",
"stop",
"(",
")"
] | Finish all running tasks, cancel remaining tasks, then stop loop.
:param _signal:
:return: | [
"Finish",
"all",
"running",
"tasks",
"cancel",
"remaining",
"tasks",
"then",
"stop",
"loop",
".",
":",
"param",
"_signal",
":",
":",
"return",
":"
] | python | test | 31 |
croscon/fleaker | fleaker/marshmallow/json_schema.py | https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/marshmallow/json_schema.py#L185-L213 | def _get_object_from_python_path(python_path):
"""Method that will fetch a Marshmallow schema from a path to it.
Args:
python_path (str): The string path to the Marshmallow schema.
Returns:
marshmallow.Schema: The schema matching the provided path.
Raises:
... | [
"def",
"_get_object_from_python_path",
"(",
"python_path",
")",
":",
"# Dissect the path",
"python_path",
"=",
"python_path",
".",
"split",
"(",
"'.'",
")",
"module_path",
"=",
"python_path",
"[",
":",
"-",
"1",
"]",
"object_class",
"=",
"python_path",
"[",
"-",... | Method that will fetch a Marshmallow schema from a path to it.
Args:
python_path (str): The string path to the Marshmallow schema.
Returns:
marshmallow.Schema: The schema matching the provided path.
Raises:
TypeError: This is raised if the specified object ... | [
"Method",
"that",
"will",
"fetch",
"a",
"Marshmallow",
"schema",
"from",
"a",
"path",
"to",
"it",
"."
] | python | train | 29.172414 |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/inventory/__init__.py | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L101-L124 | def get_hosts(self, pattern="all"):
"""
find all host names matching a pattern string, taking into account any inventory restrictions or
applied subsets.
"""
# process patterns
if isinstance(pattern, list):
pattern = ';'.join(pattern)
patterns = patt... | [
"def",
"get_hosts",
"(",
"self",
",",
"pattern",
"=",
"\"all\"",
")",
":",
"# process patterns",
"if",
"isinstance",
"(",
"pattern",
",",
"list",
")",
":",
"pattern",
"=",
"';'",
".",
"join",
"(",
"pattern",
")",
"patterns",
"=",
"pattern",
".",
"replace... | find all host names matching a pattern string, taking into account any inventory restrictions or
applied subsets. | [
"find",
"all",
"host",
"names",
"matching",
"a",
"pattern",
"string",
"taking",
"into",
"account",
"any",
"inventory",
"restrictions",
"or",
"applied",
"subsets",
"."
] | python | train | 37.833333 |
apache/airflow | airflow/contrib/operators/jenkins_job_trigger_operator.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/jenkins_job_trigger_operator.py#L34-L79 | def jenkins_request_with_headers(jenkins_server, req):
"""
We need to get the headers in addition to the body answer
to get the location from them
This function uses jenkins_request method from python-jenkins library
with just the return call changed
:param jenkins_server: The server to query
... | [
"def",
"jenkins_request_with_headers",
"(",
"jenkins_server",
",",
"req",
")",
":",
"try",
":",
"response",
"=",
"jenkins_server",
".",
"jenkins_request",
"(",
"req",
")",
"response_body",
"=",
"response",
".",
"content",
"response_headers",
"=",
"response",
".",
... | We need to get the headers in addition to the body answer
to get the location from them
This function uses jenkins_request method from python-jenkins library
with just the return call changed
:param jenkins_server: The server to query
:param req: The request to execute
:return: Dict containing ... | [
"We",
"need",
"to",
"get",
"the",
"headers",
"in",
"addition",
"to",
"the",
"body",
"answer",
"to",
"get",
"the",
"location",
"from",
"them",
"This",
"function",
"uses",
"jenkins_request",
"method",
"from",
"python",
"-",
"jenkins",
"library",
"with",
"just"... | python | test | 43.934783 |
ThreatConnect-Inc/tcex | tcex/tcex.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L231-L311 | def _resources(self, custom_indicators=False):
"""Initialize the resource module.
This method will make a request to the ThreatConnect API to dynamically
build classes to support custom Indicators. All other resources are available
via this class.
.. Note:: Resource Classes ca... | [
"def",
"_resources",
"(",
"self",
",",
"custom_indicators",
"=",
"False",
")",
":",
"from",
"importlib",
"import",
"import_module",
"# create resource object",
"self",
".",
"resources",
"=",
"import_module",
"(",
"'tcex.tcex_resources'",
")",
"if",
"custom_indicators"... | Initialize the resource module.
This method will make a request to the ThreatConnect API to dynamically
build classes to support custom Indicators. All other resources are available
via this class.
.. Note:: Resource Classes can be accessed using ``tcex.resources.<Class>`` or using
... | [
"Initialize",
"the",
"resource",
"module",
"."
] | python | train | 47.493827 |
ska-sa/katcp-python | katcp/server.py | https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1030-L1119 | def handle_request(self, connection, msg):
"""Dispatch a request message to the appropriate method.
Parameters
----------
connection : ClientConnection object
The client connection the message was from.
msg : Message object
The request message to process.... | [
"def",
"handle_request",
"(",
"self",
",",
"connection",
",",
"msg",
")",
":",
"send_reply",
"=",
"True",
"# TODO Should check presence of Message-ids against protocol flags and",
"# raise an error as needed.",
"if",
"msg",
".",
"name",
"in",
"self",
".",
"_request_handle... | Dispatch a request message to the appropriate method.
Parameters
----------
connection : ClientConnection object
The client connection the message was from.
msg : Message object
The request message to process.
Returns
-------
done_future ... | [
"Dispatch",
"a",
"request",
"message",
"to",
"the",
"appropriate",
"method",
"."
] | python | train | 48.533333 |
Trebek/pydealer | pydealer/tools.py | https://github.com/Trebek/pydealer/blob/2ac583dd8c55715658c740b614387775f4dda333/pydealer/tools.py#L435-L462 | def sort_cards(cards, ranks=None):
"""
Sorts a given list of cards, either by poker ranks, or big two ranks.
:arg cards:
The cards to sort.
:arg dict ranks:
The rank dict to reference for sorting. If ``None``, it will
default to ``DEFAULT_RANKS``.
:returns:
The sort... | [
"def",
"sort_cards",
"(",
"cards",
",",
"ranks",
"=",
"None",
")",
":",
"ranks",
"=",
"ranks",
"or",
"DEFAULT_RANKS",
"if",
"ranks",
".",
"get",
"(",
"\"suits\"",
")",
":",
"cards",
"=",
"sorted",
"(",
"cards",
",",
"key",
"=",
"lambda",
"x",
":",
... | Sorts a given list of cards, either by poker ranks, or big two ranks.
:arg cards:
The cards to sort.
:arg dict ranks:
The rank dict to reference for sorting. If ``None``, it will
default to ``DEFAULT_RANKS``.
:returns:
The sorted cards. | [
"Sorts",
"a",
"given",
"list",
"of",
"cards",
"either",
"by",
"poker",
"ranks",
"or",
"big",
"two",
"ranks",
"."
] | python | train | 23.25 |
heuer/segno | segno/encoder.py | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L418-L434 | def add_finder_patterns(matrix, is_micro):
"""\
Adds the finder pattern(s) to the matrix.
QR Codes get three finder patterns, Micro QR Codes have just one finder
pattern.
ISO/IEC 18004:2015(E) -- 6.3.3 Finder pattern (page 16)
ISO/IEC 18004:2015(E) -- 6.3.4 Separator (page 17)
:param matr... | [
"def",
"add_finder_patterns",
"(",
"matrix",
",",
"is_micro",
")",
":",
"add_finder_pattern",
"(",
"matrix",
",",
"0",
",",
"0",
")",
"# Upper left corner",
"if",
"not",
"is_micro",
":",
"add_finder_pattern",
"(",
"matrix",
",",
"0",
",",
"-",
"7",
")",
"#... | \
Adds the finder pattern(s) to the matrix.
QR Codes get three finder patterns, Micro QR Codes have just one finder
pattern.
ISO/IEC 18004:2015(E) -- 6.3.3 Finder pattern (page 16)
ISO/IEC 18004:2015(E) -- 6.3.4 Separator (page 17)
:param matrix: The matrix.
:param bool is_micro: Indicate... | [
"\\",
"Adds",
"the",
"finder",
"pattern",
"(",
"s",
")",
"to",
"the",
"matrix",
"."
] | python | train | 34.705882 |
mitsei/dlkit | dlkit/json_/grading/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/sessions.py#L2970-L2998 | def get_gradebook_columns_by_genus_type(self, gradebook_column_genus_type):
"""Gets a ``GradebookColumnList`` corresponding to the given gradebook column genus ``Type`` which does not include gradebook columns of genus types derived from the specified ``Type``.
In plenary mode, the returned list contai... | [
"def",
"get_gradebook_columns_by_genus_type",
"(",
"self",
",",
"gradebook_column_genus_type",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resources_by_genus_type",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
... | Gets a ``GradebookColumnList`` corresponding to the given gradebook column genus ``Type`` which does not include gradebook columns of genus types derived from the specified ``Type``.
In plenary mode, the returned list contains all known gradebook
columns or an error results. Otherwise, the returned lis... | [
"Gets",
"a",
"GradebookColumnList",
"corresponding",
"to",
"the",
"given",
"gradebook",
"column",
"genus",
"Type",
"which",
"does",
"not",
"include",
"gradebook",
"columns",
"of",
"genus",
"types",
"derived",
"from",
"the",
"specified",
"Type",
"."
] | python | train | 55.62069 |
google/grr | grr/server/grr_response_server/aff4_objects/aff4_grr.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/aff4_grr.py#L636-L642 | def Initialize(self):
"""Open the delegate object."""
if "r" in self.mode:
delegate = self.Get(self.Schema.DELEGATE)
if delegate:
self.delegate = aff4.FACTORY.Open(
delegate, mode=self.mode, token=self.token, age=self.age_policy) | [
"def",
"Initialize",
"(",
"self",
")",
":",
"if",
"\"r\"",
"in",
"self",
".",
"mode",
":",
"delegate",
"=",
"self",
".",
"Get",
"(",
"self",
".",
"Schema",
".",
"DELEGATE",
")",
"if",
"delegate",
":",
"self",
".",
"delegate",
"=",
"aff4",
".",
"FAC... | Open the delegate object. | [
"Open",
"the",
"delegate",
"object",
"."
] | python | train | 37.571429 |
awslabs/sockeye | sockeye/rnn_attention.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/rnn_attention.py#L202-L219 | def make_input(self,
seq_idx: int,
word_vec_prev: mx.sym.Symbol,
decoder_state: mx.sym.Symbol) -> AttentionInput:
"""
Returns AttentionInput to be fed into the attend callable returned by the on() method.
:param seq_idx: Decoder time step... | [
"def",
"make_input",
"(",
"self",
",",
"seq_idx",
":",
"int",
",",
"word_vec_prev",
":",
"mx",
".",
"sym",
".",
"Symbol",
",",
"decoder_state",
":",
"mx",
".",
"sym",
".",
"Symbol",
")",
"->",
"AttentionInput",
":",
"query",
"=",
"decoder_state",
"if",
... | Returns AttentionInput to be fed into the attend callable returned by the on() method.
:param seq_idx: Decoder time step.
:param word_vec_prev: Embedding of previously predicted ord
:param decoder_state: Current decoder state
:return: Attention input. | [
"Returns",
"AttentionInput",
"to",
"be",
"fed",
"into",
"the",
"attend",
"callable",
"returned",
"by",
"the",
"on",
"()",
"method",
"."
] | python | train | 45.555556 |
gabstopper/smc-python | smc/elements/service.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/service.py#L138-L156 | def create(cls, name, protocol_number, protocol_agent=None, comment=None):
"""
Create the IP Service
:param str name: name of ip-service
:param int protocol_number: ip proto number for this service
:param str,ProtocolAgent protocol_agent: optional protocol agent for
... | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"protocol_number",
",",
"protocol_agent",
"=",
"None",
",",
"comment",
"=",
"None",
")",
":",
"json",
"=",
"{",
"'name'",
":",
"name",
",",
"'protocol_number'",
":",
"protocol_number",
",",
"'protocol_agent_ref'... | Create the IP Service
:param str name: name of ip-service
:param int protocol_number: ip proto number for this service
:param str,ProtocolAgent protocol_agent: optional protocol agent for
this service
:param str comment: optional comment
:raises CreateElementFailed: ... | [
"Create",
"the",
"IP",
"Service"
] | python | train | 39.315789 |
kushaldas/retask | retask/queue.py | https://github.com/kushaldas/retask/blob/5c955b8386653d3f0591ca2f4b1a213ff4b5a018/retask/queue.py#L61-L76 | def names(self):
"""
Returns a list of queues available, ``None`` if no such
queues found. Remember this will only shows queues with
at least one item enqueued.
"""
data = None
if not self.connected:
raise ConnectionError('Queue is not connected')
... | [
"def",
"names",
"(",
"self",
")",
":",
"data",
"=",
"None",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"ConnectionError",
"(",
"'Queue is not connected'",
")",
"try",
":",
"data",
"=",
"self",
".",
"rdb",
".",
"keys",
"(",
"\"retaskqueue-*\"",
... | Returns a list of queues available, ``None`` if no such
queues found. Remember this will only shows queues with
at least one item enqueued. | [
"Returns",
"a",
"list",
"of",
"queues",
"available",
"None",
"if",
"no",
"such",
"queues",
"found",
".",
"Remember",
"this",
"will",
"only",
"shows",
"queues",
"with",
"at",
"least",
"one",
"item",
"enqueued",
"."
] | python | train | 31.8125 |
opendatateam/udata | tasks.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/tasks.py#L134-L197 | def i18n(ctx, update=False):
'''Extract translatable strings'''
header('Extract translatable strings')
info('Extract Python strings')
lrun('python setup.py extract_messages')
# Fix crowdin requiring Language with `2-digit` iso code in potfile
# to produce 2-digit iso code pofile
# Opening ... | [
"def",
"i18n",
"(",
"ctx",
",",
"update",
"=",
"False",
")",
":",
"header",
"(",
"'Extract translatable strings'",
")",
"info",
"(",
"'Extract Python strings'",
")",
"lrun",
"(",
"'python setup.py extract_messages'",
")",
"# Fix crowdin requiring Language with `2-digit` i... | Extract translatable strings | [
"Extract",
"translatable",
"strings"
] | python | train | 42.8125 |
azraq27/neural | neural/driver.py | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/driver.py#L23-L26 | def set_thresh(thresh,p=False,hostname=None):
'''Sets the level of the threshold slider.
If ``p==True`` will be interpreted as a _p_-value'''
driver_send("SET_THRESHNEW %s *%s" % (str(thresh),"p" if p else ""),hostname=hostname) | [
"def",
"set_thresh",
"(",
"thresh",
",",
"p",
"=",
"False",
",",
"hostname",
"=",
"None",
")",
":",
"driver_send",
"(",
"\"SET_THRESHNEW %s *%s\"",
"%",
"(",
"str",
"(",
"thresh",
")",
",",
"\"p\"",
"if",
"p",
"else",
"\"\"",
")",
",",
"hostname",
"=",... | Sets the level of the threshold slider.
If ``p==True`` will be interpreted as a _p_-value | [
"Sets",
"the",
"level",
"of",
"the",
"threshold",
"slider",
".",
"If",
"p",
"==",
"True",
"will",
"be",
"interpreted",
"as",
"a",
"_p_",
"-",
"value"
] | python | train | 59.25 |
programa-stic/barf-project | barf/analysis/codeanalyzer/codeanalyzer.py | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/codeanalyzer/codeanalyzer.py#L116-L120 | def add_instruction(self, reil_instruction):
"""Add an instruction for analysis.
"""
for expr in self._translator.translate(reil_instruction):
self._solver.add(expr) | [
"def",
"add_instruction",
"(",
"self",
",",
"reil_instruction",
")",
":",
"for",
"expr",
"in",
"self",
".",
"_translator",
".",
"translate",
"(",
"reil_instruction",
")",
":",
"self",
".",
"_solver",
".",
"add",
"(",
"expr",
")"
] | Add an instruction for analysis. | [
"Add",
"an",
"instruction",
"for",
"analysis",
"."
] | python | train | 39.4 |
toumorokoshi/sprinter | sprinter/core/directory.py | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/directory.py#L144-L152 | def add_to_rc(self, content):
"""
add content to the rc script.
"""
if not self.rewrite_config:
raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.")
if not self.rc_file:
self.rc_path, self.rc_file = self.__get_rc_handle(self.r... | [
"def",
"add_to_rc",
"(",
"self",
",",
"content",
")",
":",
"if",
"not",
"self",
".",
"rewrite_config",
":",
"raise",
"DirectoryException",
"(",
"\"Error! Directory was not intialized w/ rewrite_config.\"",
")",
"if",
"not",
"self",
".",
"rc_file",
":",
"self",
"."... | add content to the rc script. | [
"add",
"content",
"to",
"the",
"rc",
"script",
"."
] | python | train | 40.333333 |
tensorflow/probability | tensorflow_probability/python/distributions/hidden_markov_model.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/hidden_markov_model.py#L489-L517 | def _marginal_hidden_probs(self):
"""Compute marginal pdf for each individual observable."""
initial_log_probs = tf.broadcast_to(self._log_init,
tf.concat([self.batch_shape_tensor(),
[self._num_states]],
... | [
"def",
"_marginal_hidden_probs",
"(",
"self",
")",
":",
"initial_log_probs",
"=",
"tf",
".",
"broadcast_to",
"(",
"self",
".",
"_log_init",
",",
"tf",
".",
"concat",
"(",
"[",
"self",
".",
"batch_shape_tensor",
"(",
")",
",",
"[",
"self",
".",
"_num_states... | Compute marginal pdf for each individual observable. | [
"Compute",
"marginal",
"pdf",
"for",
"each",
"individual",
"observable",
"."
] | python | test | 38.034483 |
Ouranosinc/xclim | xclim/run_length.py | https://github.com/Ouranosinc/xclim/blob/2080d139188bd8de2aeca097a025c2d89d6e0e09/xclim/run_length.py#L88-L108 | def windowed_run_count(da, window, dim='time'):
"""Return the number of consecutive true values in array for runs at least as long as given duration.
Parameters
----------
da: N-dimensional Xarray data array (boolean)
Input data array
window : int
Minimum run le... | [
"def",
"windowed_run_count",
"(",
"da",
",",
"window",
",",
"dim",
"=",
"'time'",
")",
":",
"d",
"=",
"rle",
"(",
"da",
",",
"dim",
"=",
"dim",
")",
"out",
"=",
"d",
".",
"where",
"(",
"d",
">=",
"window",
",",
"0",
")",
".",
"sum",
"(",
"dim... | Return the number of consecutive true values in array for runs at least as long as given duration.
Parameters
----------
da: N-dimensional Xarray data array (boolean)
Input data array
window : int
Minimum run length.
dim : Xarray dimension (default = 'time')... | [
"Return",
"the",
"number",
"of",
"consecutive",
"true",
"values",
"in",
"array",
"for",
"runs",
"at",
"least",
"as",
"long",
"as",
"given",
"duration",
"."
] | python | train | 33 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L432-L450 | def open_dut(self, port=None):
"""
Open connection to dut.
:param port: com port to use.
:return:
"""
if port is not None:
self.comport = port
try:
self.open_connection()
except (DutConnectionError, ValueError) as err:
... | [
"def",
"open_dut",
"(",
"self",
",",
"port",
"=",
"None",
")",
":",
"if",
"port",
"is",
"not",
"None",
":",
"self",
".",
"comport",
"=",
"port",
"try",
":",
"self",
".",
"open_connection",
"(",
")",
"except",
"(",
"DutConnectionError",
",",
"ValueError... | Open connection to dut.
:param port: com port to use.
:return: | [
"Open",
"connection",
"to",
"dut",
"."
] | python | train | 27.210526 |
tensorflow/tensor2tensor | tensor2tensor/models/resnet.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L348-L424 | def block_layer(inputs,
filters,
block_fn,
blocks,
strides,
is_training,
name,
data_format="channels_first",
use_td=False,
targeting_rate=None,
keep_prob=None):... | [
"def",
"block_layer",
"(",
"inputs",
",",
"filters",
",",
"block_fn",
",",
"blocks",
",",
"strides",
",",
"is_training",
",",
"name",
",",
"data_format",
"=",
"\"channels_first\"",
",",
"use_td",
"=",
"False",
",",
"targeting_rate",
"=",
"None",
",",
"keep_p... | Creates one layer of blocks for the ResNet model.
Args:
inputs: `Tensor` of size `[batch, channels, height, width]`.
filters: `int` number of filters for the first convolution of the layer.
block_fn: `function` for the block to use within the model
blocks: `int` number of blocks contained in the laye... | [
"Creates",
"one",
"layer",
"of",
"blocks",
"for",
"the",
"ResNet",
"model",
"."
] | python | train | 32.545455 |
Crypto-toolbox/btfxwss | btfxwss/connection.py | https://github.com/Crypto-toolbox/btfxwss/blob/16827fa6aacb2c0e289aa852bf61a18df6905835/btfxwss/connection.py#L374-L404 | def _system_handler(self, data, ts):
"""Distributes system messages to the appropriate handler.
System messages include everything that arrives as a dict,
or a list containing a heartbeat.
:param data:
:param ts:
:return:
"""
self.log.debug("_system_hand... | [
"def",
"_system_handler",
"(",
"self",
",",
"data",
",",
"ts",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"_system_handler(): Received a system message: %s\"",
",",
"data",
")",
"# Unpack the data",
"event",
"=",
"data",
".",
"pop",
"(",
"'event'",
")"... | Distributes system messages to the appropriate handler.
System messages include everything that arrives as a dict,
or a list containing a heartbeat.
:param data:
:param ts:
:return: | [
"Distributes",
"system",
"messages",
"to",
"the",
"appropriate",
"handler",
"."
] | python | test | 41 |
Vauxoo/cfdilib | cfdilib/tools.py | https://github.com/Vauxoo/cfdilib/blob/acd73d159f62119f3100d963a061820bbe3f93ea/cfdilib/tools.py#L171-L232 | def cache_s3(self, url, named): # pragma: no cover
"""Basically this is not to deploy automatically this is to be run once
all is properly defined to catch the xsd in your own S3 instance and
avoid third party (like government servers) failure, trying to manage
the cache transparently t... | [
"def",
"cache_s3",
"(",
"self",
",",
"url",
",",
"named",
")",
":",
"# pragma: no cover",
"# **Technical Notes:**",
"#",
"# Even if the tries are looking nested, this is perfect valid for",
"# this case:",
"# https://docs.python.org/3/glossary.html#term-eafp.",
"#",
"# The Coverage... | Basically this is not to deploy automatically this is to be run once
all is properly defined to catch the xsd in your own S3 instance and
avoid third party (like government servers) failure, trying to manage
the cache transparently to the user.
This method was created due to SAT is too ... | [
"Basically",
"this",
"is",
"not",
"to",
"deploy",
"automatically",
"this",
"is",
"to",
"be",
"run",
"once",
"all",
"is",
"properly",
"defined",
"to",
"catch",
"the",
"xsd",
"in",
"your",
"own",
"S3",
"instance",
"and",
"avoid",
"third",
"party",
"(",
"li... | python | train | 40.048387 |
MacHu-GWU/windtalker-project | windtalker/fingerprint.py | https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/fingerprint.py#L124-L133 | def of_pyobj(self, pyobj):
"""Use default hash method to return hash value of a piece of Python
picklable object.
"""
m = self.hash_algo()
m.update(pickle.dumps(pyobj, protocol=self.pk_protocol))
if self.return_int:
return int(m.hexdigest(), 16)
else:
... | [
"def",
"of_pyobj",
"(",
"self",
",",
"pyobj",
")",
":",
"m",
"=",
"self",
".",
"hash_algo",
"(",
")",
"m",
".",
"update",
"(",
"pickle",
".",
"dumps",
"(",
"pyobj",
",",
"protocol",
"=",
"self",
".",
"pk_protocol",
")",
")",
"if",
"self",
".",
"r... | Use default hash method to return hash value of a piece of Python
picklable object. | [
"Use",
"default",
"hash",
"method",
"to",
"return",
"hash",
"value",
"of",
"a",
"piece",
"of",
"Python",
"picklable",
"object",
"."
] | python | train | 34.3 |
BernardFW/bernard | src/bernard/platforms/facebook/platform.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L749-L783 | async def _send_text(self, request: Request, stack: Stack):
"""
Send text layers to the user. Each layer will go in its own bubble.
Also, Facebook limits messages to 320 chars, so if any message is
longer than that it will be split into as many messages as needed to
be accepted ... | [
"async",
"def",
"_send_text",
"(",
"self",
",",
"request",
":",
"Request",
",",
"stack",
":",
"Stack",
")",
":",
"parts",
"=",
"[",
"]",
"for",
"layer",
"in",
"stack",
".",
"layers",
":",
"if",
"isinstance",
"(",
"layer",
",",
"lyr",
".",
"MultiText"... | Send text layers to the user. Each layer will go in its own bubble.
Also, Facebook limits messages to 320 chars, so if any message is
longer than that it will be split into as many messages as needed to
be accepted by Facebook. | [
"Send",
"text",
"layers",
"to",
"the",
"user",
".",
"Each",
"layer",
"will",
"go",
"in",
"its",
"own",
"bubble",
"."
] | python | train | 31.942857 |
Lagg/steamodd | steam/user.py | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/user.py#L208-L226 | def level(self):
"""
Returns the the user's profile level, note that this runs a separate
request because the profile level data isn't in the standard player summary
output even though it should be. Which is also why it's not implemented
as a separate class. You won't need this o... | [
"def",
"level",
"(",
"self",
")",
":",
"level_key",
"=",
"\"player_level\"",
"if",
"level_key",
"in",
"self",
".",
"_api",
"[",
"\"response\"",
"]",
":",
"return",
"self",
".",
"_api",
"[",
"\"response\"",
"]",
"[",
"level_key",
"]",
"try",
":",
"lvl",
... | Returns the the user's profile level, note that this runs a separate
request because the profile level data isn't in the standard player summary
output even though it should be. Which is also why it's not implemented
as a separate class. You won't need this output and not the profile output | [
"Returns",
"the",
"the",
"user",
"s",
"profile",
"level",
"note",
"that",
"this",
"runs",
"a",
"separate",
"request",
"because",
"the",
"profile",
"level",
"data",
"isn",
"t",
"in",
"the",
"standard",
"player",
"summary",
"output",
"even",
"though",
"it",
... | python | train | 37.578947 |
senaite/senaite.core | bika/lims/browser/__init__.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/__init__.py#L38-L83 | def get_date(context, value):
"""Tries to return a DateTime.DateTime object
"""
if not value:
return None
if isinstance(value, DateTime):
return value
if isinstance(value, datetime):
return dt2DT(value)
if not isinstance(value, basestring):
return None
def tr... | [
"def",
"get_date",
"(",
"context",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"DateTime",
")",
":",
"return",
"value",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
")",
":",
"return... | Tries to return a DateTime.DateTime object | [
"Tries",
"to",
"return",
"a",
"DateTime",
".",
"DateTime",
"object"
] | python | train | 33.23913 |
rfk/django-supervisor | djsupervisor/management/commands/supervisor.py | https://github.com/rfk/django-supervisor/blob/545a379d4a73ed2ae21c4aee6b8009ded8aeedc6/djsupervisor/management/commands/supervisor.py#L222-L289 | def _handle_autoreload(self,cfg_file,*args,**options):
"""Command 'supervisor autoreload' watches for code changes.
This command provides a simulation of the Django dev server's
auto-reloading mechanism that will restart all supervised processes.
It's not quite as accurate as Django's ... | [
"def",
"_handle_autoreload",
"(",
"self",
",",
"cfg_file",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"if",
"args",
":",
"raise",
"CommandError",
"(",
"\"supervisor autoreload takes no arguments\"",
")",
"live_dirs",
"=",
"self",
".",
"_find_live_code... | Command 'supervisor autoreload' watches for code changes.
This command provides a simulation of the Django dev server's
auto-reloading mechanism that will restart all supervised processes.
It's not quite as accurate as Django's autoreloader because it runs
in a separate process, so it ... | [
"Command",
"supervisor",
"autoreload",
"watches",
"for",
"code",
"changes",
"."
] | python | train | 42.441176 |
RedHatInsights/insights-core | insights/contrib/magic.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/magic.py#L132-L141 | def buffer(self, buf):
"""
Returns a textual description of the contents of the argument passed
as a buffer or None if an error occurred and the MAGIC_ERROR flag
is set. A call to errno() will return the numeric error code.
"""
try: # attempt python3 approach first
... | [
"def",
"buffer",
"(",
"self",
",",
"buf",
")",
":",
"try",
":",
"# attempt python3 approach first",
"return",
"str",
"(",
"_buffer",
"(",
"self",
".",
"_magic_t",
",",
"buf",
",",
"len",
"(",
"buf",
")",
")",
",",
"'utf-8'",
")",
"except",
":",
"return... | Returns a textual description of the contents of the argument passed
as a buffer or None if an error occurred and the MAGIC_ERROR flag
is set. A call to errno() will return the numeric error code. | [
"Returns",
"a",
"textual",
"description",
"of",
"the",
"contents",
"of",
"the",
"argument",
"passed",
"as",
"a",
"buffer",
"or",
"None",
"if",
"an",
"error",
"occurred",
"and",
"the",
"MAGIC_ERROR",
"flag",
"is",
"set",
".",
"A",
"call",
"to",
"errno",
"... | python | train | 44.9 |
DataBiosphere/toil | src/toil/provisioners/clusterScaler.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/provisioners/clusterScaler.py#L473-L533 | def getEstimatedNodeCounts(self, queuedJobShapes, currentNodeCounts):
"""
Given the resource requirements of queued jobs and the current size of the cluster, returns
a dict mapping from nodeShape to the number of nodes we want in the cluster right now.
"""
nodesToRunQueuedJobs = ... | [
"def",
"getEstimatedNodeCounts",
"(",
"self",
",",
"queuedJobShapes",
",",
"currentNodeCounts",
")",
":",
"nodesToRunQueuedJobs",
"=",
"binPacking",
"(",
"jobShapes",
"=",
"queuedJobShapes",
",",
"nodeShapes",
"=",
"self",
".",
"nodeShapes",
",",
"goalTime",
"=",
... | Given the resource requirements of queued jobs and the current size of the cluster, returns
a dict mapping from nodeShape to the number of nodes we want in the cluster right now. | [
"Given",
"the",
"resource",
"requirements",
"of",
"queued",
"jobs",
"and",
"the",
"current",
"size",
"of",
"the",
"cluster",
"returns",
"a",
"dict",
"mapping",
"from",
"nodeShape",
"to",
"the",
"number",
"of",
"nodes",
"we",
"want",
"in",
"the",
"cluster",
... | python | train | 61.344262 |
jxtech/wechatpy | wechatpy/client/api/invoice.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/invoice.py#L385-L401 | def get_select_title_url(self, attach=None):
"""
获取商户专属开票链接
商户调用接口,获取链接。用户扫码,可以选择抬头发给商户。可以将链接转成二维码,立在收银台。
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1496554912_vfWU0
:param attach: 附加字段,用户提交发票时会发送给商户
:return: 商户专属开票链接
"""
return self._post(
... | [
"def",
"get_select_title_url",
"(",
"self",
",",
"attach",
"=",
"None",
")",
":",
"return",
"self",
".",
"_post",
"(",
"'biz/getselecttitleurl'",
",",
"data",
"=",
"{",
"'attach'",
":",
"attach",
",",
"}",
",",
"result_processor",
"=",
"lambda",
"x",
":",
... | 获取商户专属开票链接
商户调用接口,获取链接。用户扫码,可以选择抬头发给商户。可以将链接转成二维码,立在收银台。
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1496554912_vfWU0
:param attach: 附加字段,用户提交发票时会发送给商户
:return: 商户专属开票链接 | [
"获取商户专属开票链接",
"商户调用接口,获取链接。用户扫码,可以选择抬头发给商户。可以将链接转成二维码,立在收银台。",
"详情请参考",
"https",
":",
"//",
"mp",
".",
"weixin",
".",
"qq",
".",
"com",
"/",
"wiki?id",
"=",
"mp1496554912_vfWU0"
] | python | train | 27 |
aouyar/PyMunin | pymunin/__init__.py | https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pymunin/__init__.py#L317-L332 | def envGet(self, name, default=None, conv=None):
"""Return value for environment variable or None.
@param name: Name of environment variable.
@param default: Default value if variable is undefined.
@param conv: Function for converting value to desired type.
@retu... | [
"def",
"envGet",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"conv",
"=",
"None",
")",
":",
"if",
"self",
".",
"_env",
".",
"has_key",
"(",
"name",
")",
":",
"if",
"conv",
"is",
"not",
"None",
":",
"return",
"conv",
"(",
"self",
... | Return value for environment variable or None.
@param name: Name of environment variable.
@param default: Default value if variable is undefined.
@param conv: Function for converting value to desired type.
@return: Value of environment variable. | [
"Return",
"value",
"for",
"environment",
"variable",
"or",
"None",
"."
] | python | train | 36.6875 |
onyxfish/clan | clan/utils.py | https://github.com/onyxfish/clan/blob/415ddd027ea81013f2d62d75aec6da70703df49c/clan/utils.py#L53-L65 | def format_duration(secs):
"""
Format a duration in seconds as minutes and seconds.
"""
secs = int(secs)
if abs(secs) > 60:
mins = abs(secs) / 60
secs = abs(secs) - (mins * 60)
return '%s%im %02is' % ('-' if secs < 0 else '', mins, secs)
return '%is' % secs | [
"def",
"format_duration",
"(",
"secs",
")",
":",
"secs",
"=",
"int",
"(",
"secs",
")",
"if",
"abs",
"(",
"secs",
")",
">",
"60",
":",
"mins",
"=",
"abs",
"(",
"secs",
")",
"/",
"60",
"secs",
"=",
"abs",
"(",
"secs",
")",
"-",
"(",
"mins",
"*"... | Format a duration in seconds as minutes and seconds. | [
"Format",
"a",
"duration",
"in",
"seconds",
"as",
"minutes",
"and",
"seconds",
"."
] | python | train | 22.769231 |
resync/resync | resync/url_authority.py | https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/url_authority.py#L50-L55 | def set_master(self, url):
"""Set the master url that this object works with."""
m = urlparse(url)
self.master_scheme = m.scheme
self.master_netloc = m.netloc
self.master_path = os.path.dirname(m.path) | [
"def",
"set_master",
"(",
"self",
",",
"url",
")",
":",
"m",
"=",
"urlparse",
"(",
"url",
")",
"self",
".",
"master_scheme",
"=",
"m",
".",
"scheme",
"self",
".",
"master_netloc",
"=",
"m",
".",
"netloc",
"self",
".",
"master_path",
"=",
"os",
".",
... | Set the master url that this object works with. | [
"Set",
"the",
"master",
"url",
"that",
"this",
"object",
"works",
"with",
"."
] | python | train | 39.333333 |
bububa/pyTOP | pyTOP/packages/requests/auth.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/packages/requests/auth.py#L19-L30 | def http_basic(r, username, password):
"""Attaches HTTP Basic Authentication to the given Request object.
Arguments should be considered non-positional.
"""
username = str(username)
password = str(password)
auth_s = b64encode('%s:%s' % (username, password))
r.headers['Authorization'] = ('B... | [
"def",
"http_basic",
"(",
"r",
",",
"username",
",",
"password",
")",
":",
"username",
"=",
"str",
"(",
"username",
")",
"password",
"=",
"str",
"(",
"password",
")",
"auth_s",
"=",
"b64encode",
"(",
"'%s:%s'",
"%",
"(",
"username",
",",
"password",
")... | Attaches HTTP Basic Authentication to the given Request object.
Arguments should be considered non-positional. | [
"Attaches",
"HTTP",
"Basic",
"Authentication",
"to",
"the",
"given",
"Request",
"object",
".",
"Arguments",
"should",
"be",
"considered",
"non",
"-",
"positional",
"."
] | python | train | 28.416667 |
codeinn/vcs | vcs/backends/base.py | https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/backends/base.py#L831-L837 | def get_ipaths(self):
"""
Returns generator of paths from nodes marked as added, changed or
removed.
"""
for node in itertools.chain(self.added, self.changed, self.removed):
yield node.path | [
"def",
"get_ipaths",
"(",
"self",
")",
":",
"for",
"node",
"in",
"itertools",
".",
"chain",
"(",
"self",
".",
"added",
",",
"self",
".",
"changed",
",",
"self",
".",
"removed",
")",
":",
"yield",
"node",
".",
"path"
] | Returns generator of paths from nodes marked as added, changed or
removed. | [
"Returns",
"generator",
"of",
"paths",
"from",
"nodes",
"marked",
"as",
"added",
"changed",
"or",
"removed",
"."
] | python | train | 33.571429 |
boto/s3transfer | s3transfer/download.py | https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/download.py#L680-L712 | def request_writes(self, offset, data):
"""Request any available writes given new incoming data.
You call this method by providing new data along with the
offset associated with the data. If that new data unlocks
any contiguous writes that can now be submitted, this
method will... | [
"def",
"request_writes",
"(",
"self",
",",
"offset",
",",
"data",
")",
":",
"if",
"offset",
"<",
"self",
".",
"_next_offset",
":",
"# This is a request for a write that we've already",
"# seen. This can happen in the event of a retry",
"# where if we retry at at offset N/2, we... | Request any available writes given new incoming data.
You call this method by providing new data along with the
offset associated with the data. If that new data unlocks
any contiguous writes that can now be submitted, this
method will return all applicable writes.
This is don... | [
"Request",
"any",
"available",
"writes",
"given",
"new",
"incoming",
"data",
"."
] | python | test | 44.454545 |
nhfruchter/pgh-bustime | pghbustime/datatypes.py | https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/datatypes.py#L81-L86 | def next_stop(self):
"""Return the next stop for this bus."""
p = self.api.predictions(vid=self.vid)['prd']
pobj = Prediction.fromapi(self.api, p[0])
pobj._busobj = self
return pobj | [
"def",
"next_stop",
"(",
"self",
")",
":",
"p",
"=",
"self",
".",
"api",
".",
"predictions",
"(",
"vid",
"=",
"self",
".",
"vid",
")",
"[",
"'prd'",
"]",
"pobj",
"=",
"Prediction",
".",
"fromapi",
"(",
"self",
".",
"api",
",",
"p",
"[",
"0",
"]... | Return the next stop for this bus. | [
"Return",
"the",
"next",
"stop",
"for",
"this",
"bus",
"."
] | python | train | 36 |
QunarOPS/qg.core | qg/core/timeutils.py | https://github.com/QunarOPS/qg.core/blob/d5d7e36ea140cfe73e1b1850e8c96960b02a1ed3/qg/core/timeutils.py#L56-L60 | def strtime(at=None, fmt=PERFECT_TIME_FORMAT):
"""Returns formatted utcnow."""
if not at:
at = utcnow()
return at.strftime(fmt) | [
"def",
"strtime",
"(",
"at",
"=",
"None",
",",
"fmt",
"=",
"PERFECT_TIME_FORMAT",
")",
":",
"if",
"not",
"at",
":",
"at",
"=",
"utcnow",
"(",
")",
"return",
"at",
".",
"strftime",
"(",
"fmt",
")"
] | Returns formatted utcnow. | [
"Returns",
"formatted",
"utcnow",
"."
] | python | train | 28.6 |
Othernet-Project/conz | conz/console.py | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L241-L261 | def readpipe(self, chunk=None):
""" Return iterator that iterates over STDIN line by line
If ``chunk`` is set to a positive non-zero integer value, then the
reads are performed in chunks of that many lines, and returned as a
list. Otherwise the lines are returned one by one.
"""... | [
"def",
"readpipe",
"(",
"self",
",",
"chunk",
"=",
"None",
")",
":",
"read",
"=",
"[",
"]",
"while",
"True",
":",
"l",
"=",
"sys",
".",
"stdin",
".",
"readline",
"(",
")",
"if",
"not",
"l",
":",
"if",
"read",
":",
"yield",
"read",
"return",
"re... | Return iterator that iterates over STDIN line by line
If ``chunk`` is set to a positive non-zero integer value, then the
reads are performed in chunks of that many lines, and returned as a
list. Otherwise the lines are returned one by one. | [
"Return",
"iterator",
"that",
"iterates",
"over",
"STDIN",
"line",
"by",
"line"
] | python | train | 32 |
Qiskit/qiskit-terra | qiskit/tools/jupyter/backend_monitor.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/jupyter/backend_monitor.py#L497-L573 | def plot_job_history(jobs, interval='year'):
"""Plots the job history of the user from the given list of jobs.
Args:
jobs (list): A list of jobs with type IBMQjob.
interval (str): Interval over which to examine.
Returns:
fig: A Matplotlib figure instance.
"""
def get_date(j... | [
"def",
"plot_job_history",
"(",
"jobs",
",",
"interval",
"=",
"'year'",
")",
":",
"def",
"get_date",
"(",
"job",
")",
":",
"\"\"\"Returns a datetime object from a IBMQJob instance.\n\n Args:\n job (IBMQJob): A job.\n\n Returns:\n dt: A datetime obj... | Plots the job history of the user from the given list of jobs.
Args:
jobs (list): A list of jobs with type IBMQjob.
interval (str): Interval over which to examine.
Returns:
fig: A Matplotlib figure instance. | [
"Plots",
"the",
"job",
"history",
"of",
"the",
"user",
"from",
"the",
"given",
"list",
"of",
"jobs",
"."
] | python | test | 32.506494 |
programa-stic/barf-project | barf/core/reil/emulator/memory.py | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/memory.py#L59-L67 | def read(self, address, size):
"""Read arbitrary size content from memory.
"""
value = 0x0
for i in range(0, size):
value |= self._read_byte(address + i) << (i * 8)
return value | [
"def",
"read",
"(",
"self",
",",
"address",
",",
"size",
")",
":",
"value",
"=",
"0x0",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"size",
")",
":",
"value",
"|=",
"self",
".",
"_read_byte",
"(",
"address",
"+",
"i",
")",
"<<",
"(",
"i",
"*",
... | Read arbitrary size content from memory. | [
"Read",
"arbitrary",
"size",
"content",
"from",
"memory",
"."
] | python | train | 24.777778 |
IrvKalb/pygwidgets | pygwidgets/pygwidgets.py | https://github.com/IrvKalb/pygwidgets/blob/a830d8885d4d209e471cb53816277d30db56273c/pygwidgets/pygwidgets.py#L2471-L2490 | def play(self):
"""Starts an animation playing."""
if self.state == PygAnimation.PLAYING:
pass # nothing to do
elif self.state == PygAnimation.STOPPED: # restart from beginning of animation
self.index = 0 # first image in list
self.elapsed = 0
... | [
"def",
"play",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"PygAnimation",
".",
"PLAYING",
":",
"pass",
"# nothing to do\r",
"elif",
"self",
".",
"state",
"==",
"PygAnimation",
".",
"STOPPED",
":",
"# restart from beginning of animation\r",
"self",
... | Starts an animation playing. | [
"Starts",
"an",
"animation",
"playing",
"."
] | python | train | 49.65 |
globality-corp/microcosm-flask | microcosm_flask/conventions/crud_adapter.py | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud_adapter.py#L54-L81 | def update_batch(self, **kwargs):
"""
Simplistic batch update operation implemented in terms of `replace()`.
Assumes that:
- Request and response schemas contains lists of items.
- Request items define a primary key identifier
- The entire batch succeeds or fails tog... | [
"def",
"update_batch",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"items",
"=",
"kwargs",
".",
"pop",
"(",
"\"items\"",
")",
"def",
"transform",
"(",
"item",
")",
":",
"\"\"\"\n Transform the dictionary expected for replace (which uses the URI path's i... | Simplistic batch update operation implemented in terms of `replace()`.
Assumes that:
- Request and response schemas contains lists of items.
- Request items define a primary key identifier
- The entire batch succeeds or fails together. | [
"Simplistic",
"batch",
"update",
"operation",
"implemented",
"in",
"terms",
"of",
"replace",
"()",
"."
] | python | train | 29.142857 |
CalebBell/thermo | thermo/chemical.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/chemical.py#L1655-L1673 | def Cpg(self):
r'''Gas-phase heat capacity of the chemical at its current temperature,
in units of [J/kg/K]. For calculation of this property at other
temperatures, or specifying manually the method used to calculate it,
and more - see the object oriented interface
:obj:`thermo.h... | [
"def",
"Cpg",
"(",
"self",
")",
":",
"Cpgm",
"=",
"self",
".",
"HeatCapacityGas",
"(",
"self",
".",
"T",
")",
"if",
"Cpgm",
":",
"return",
"property_molar_to_mass",
"(",
"Cpgm",
",",
"self",
".",
"MW",
")",
"return",
"None"
] | r'''Gas-phase heat capacity of the chemical at its current temperature,
in units of [J/kg/K]. For calculation of this property at other
temperatures, or specifying manually the method used to calculate it,
and more - see the object oriented interface
:obj:`thermo.heat_capacity.HeatCapaci... | [
"r",
"Gas",
"-",
"phase",
"heat",
"capacity",
"of",
"the",
"chemical",
"at",
"its",
"current",
"temperature",
"in",
"units",
"of",
"[",
"J",
"/",
"kg",
"/",
"K",
"]",
".",
"For",
"calculation",
"of",
"this",
"property",
"at",
"other",
"temperatures",
"... | python | valid | 39.421053 |
acorg/dark-matter | dark/diamond/conversion.py | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/diamond/conversion.py#L302-L345 | def _dictToAlignments(self, diamondDict, read):
"""
Take a dict (made by DiamondTabularFormatReader.records)
and convert it to a list of alignments.
@param diamondDict: A C{dict}, from records().
@param read: A C{Read} instance, containing the read that DIAMOND used
... | [
"def",
"_dictToAlignments",
"(",
"self",
",",
"diamondDict",
",",
"read",
")",
":",
"alignments",
"=",
"[",
"]",
"getScore",
"=",
"itemgetter",
"(",
"'bits'",
"if",
"self",
".",
"_hspClass",
"is",
"HSP",
"else",
"'expect'",
")",
"for",
"diamondAlignment",
... | Take a dict (made by DiamondTabularFormatReader.records)
and convert it to a list of alignments.
@param diamondDict: A C{dict}, from records().
@param read: A C{Read} instance, containing the read that DIAMOND used
to create this record.
@return: A C{list} of L{dark.alignmen... | [
"Take",
"a",
"dict",
"(",
"made",
"by",
"DiamondTabularFormatReader",
".",
"records",
")",
"and",
"convert",
"it",
"to",
"a",
"list",
"of",
"alignments",
"."
] | python | train | 49.068182 |
ilgarm/pyzimbra | pyzimbra/z/client.py | https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/z/client.py#L72-L90 | def get_account_info(self):
"""
Gets account info.
@return: AccountInfo
"""
attrs = {sconstant.A_BY: sconstant.V_NAME}
account = SOAPpy.Types.stringType(data=self.auth_token.account_name,
attrs=attrs)
params = {sconstant.... | [
"def",
"get_account_info",
"(",
"self",
")",
":",
"attrs",
"=",
"{",
"sconstant",
".",
"A_BY",
":",
"sconstant",
".",
"V_NAME",
"}",
"account",
"=",
"SOAPpy",
".",
"Types",
".",
"stringType",
"(",
"data",
"=",
"self",
".",
"auth_token",
".",
"account_nam... | Gets account info.
@return: AccountInfo | [
"Gets",
"account",
"info",
"."
] | python | train | 28.684211 |
sorgerlab/indra | indra/mechlinker/__init__.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L540-L557 | def get_create_base_agent(self, agent):
"""Return BaseAgent from an Agent, creating it if needed.
Parameters
----------
agent : indra.statements.Agent
Returns
-------
base_agent : indra.mechlinker.BaseAgent
"""
try:
base_agent = self.... | [
"def",
"get_create_base_agent",
"(",
"self",
",",
"agent",
")",
":",
"try",
":",
"base_agent",
"=",
"self",
".",
"agents",
"[",
"agent",
".",
"name",
"]",
"except",
"KeyError",
":",
"base_agent",
"=",
"BaseAgent",
"(",
"agent",
".",
"name",
")",
"self",
... | Return BaseAgent from an Agent, creating it if needed.
Parameters
----------
agent : indra.statements.Agent
Returns
-------
base_agent : indra.mechlinker.BaseAgent | [
"Return",
"BaseAgent",
"from",
"an",
"Agent",
"creating",
"it",
"if",
"needed",
"."
] | python | train | 26.055556 |
gwastro/pycbc | pycbc/waveform/pycbc_phenomC_tmplt.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/pycbc_phenomC_tmplt.py#L158-L393 | def imrphenomc_tmplt(**kwds):
""" Return an IMRPhenomC waveform using CUDA to generate the phase and amplitude
Main Paper: arXiv:1005.3306
"""
# Pull out the input arguments
f_min = float128(kwds['f_lower'])
f_max = float128(kwds['f_final'])
delta_f = float128(kwds['delta_f'])
distance... | [
"def",
"imrphenomc_tmplt",
"(",
"*",
"*",
"kwds",
")",
":",
"# Pull out the input arguments",
"f_min",
"=",
"float128",
"(",
"kwds",
"[",
"'f_lower'",
"]",
")",
"f_max",
"=",
"float128",
"(",
"kwds",
"[",
"'f_final'",
"]",
")",
"delta_f",
"=",
"float128",
... | Return an IMRPhenomC waveform using CUDA to generate the phase and amplitude
Main Paper: arXiv:1005.3306 | [
"Return",
"an",
"IMRPhenomC",
"waveform",
"using",
"CUDA",
"to",
"generate",
"the",
"phase",
"and",
"amplitude",
"Main",
"Paper",
":",
"arXiv",
":",
"1005",
".",
"3306"
] | python | train | 34.995763 |
tariqdaouda/pyGeno | pyGeno/importation/Genomes.py | https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/importation/Genomes.py#L58-L97 | def deleteGenome(species, name) :
"""Removes a genome from the database"""
printf('deleting genome (%s, %s)...' % (species, name))
conf.db.beginTransaction()
objs = []
allGood = True
try :
genome = Genome_Raba(name = name, species = species.lower())
objs.append(genome)
... | [
"def",
"deleteGenome",
"(",
"species",
",",
"name",
")",
":",
"printf",
"(",
"'deleting genome (%s, %s)...'",
"%",
"(",
"species",
",",
"name",
")",
")",
"conf",
".",
"db",
".",
"beginTransaction",
"(",
")",
"objs",
"=",
"[",
"]",
"allGood",
"=",
"True",... | Removes a genome from the database | [
"Removes",
"a",
"genome",
"from",
"the",
"database"
] | python | train | 34.875 |
f3at/feat | src/feat/agents/common/host.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/agents/common/host.py#L116-L126 | def start_agent(agent, recp, desc, allocation_id=None, *args, **kwargs):
'''
Tells remote host agent to start agent identified by desc.
The result value of the fiber is IRecipient.
'''
f = fiber.Fiber()
f.add_callback(agent.initiate_protocol, IRecipient(recp), desc,
allocation... | [
"def",
"start_agent",
"(",
"agent",
",",
"recp",
",",
"desc",
",",
"allocation_id",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"=",
"fiber",
".",
"Fiber",
"(",
")",
"f",
".",
"add_callback",
"(",
"agent",
".",
"initiate_... | Tells remote host agent to start agent identified by desc.
The result value of the fiber is IRecipient. | [
"Tells",
"remote",
"host",
"agent",
"to",
"start",
"agent",
"identified",
"by",
"desc",
".",
"The",
"result",
"value",
"of",
"the",
"fiber",
"is",
"IRecipient",
"."
] | python | train | 39.363636 |
tcalmant/ipopo | pelix/shell/beans.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/beans.py#L220-L232 | def _write_str(self, data):
"""
Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()``
"""
with self.__lock:
self.output.write(
to_str(data, self.encoding)
.encode(... | [
"def",
"_write_str",
"(",
"self",
",",
"data",
")",
":",
"with",
"self",
".",
"__lock",
":",
"self",
".",
"output",
".",
"write",
"(",
"to_str",
"(",
"data",
",",
"self",
".",
"encoding",
")",
".",
"encode",
"(",
")",
".",
"decode",
"(",
"self",
... | Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()`` | [
"Converts",
"the",
"given",
"data",
"then",
"writes",
"it"
] | python | train | 29.538462 |
ska-sa/katversion | katversion/version.py | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L384-L388 | def build_info(name, path=None, module=None):
"""Return the build info tuple."""
verlist = get_version_list(path, module)
verlist[0] = name
return tuple(verlist) | [
"def",
"build_info",
"(",
"name",
",",
"path",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"verlist",
"=",
"get_version_list",
"(",
"path",
",",
"module",
")",
"verlist",
"[",
"0",
"]",
"=",
"name",
"return",
"tuple",
"(",
"verlist",
")"
] | Return the build info tuple. | [
"Return",
"the",
"build",
"info",
"tuple",
"."
] | python | train | 34.6 |
caffeinehit/django-oauth2-provider | provider/oauth2/forms.py | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/oauth2/forms.py#L138-L157 | def clean_response_type(self):
"""
:rfc:`3.1.1` Lists of values are space delimited.
"""
response_type = self.cleaned_data.get('response_type')
if not response_type:
raise OAuthValidationError({'error': 'invalid_request',
'error_description': "No 'res... | [
"def",
"clean_response_type",
"(",
"self",
")",
":",
"response_type",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'response_type'",
")",
"if",
"not",
"response_type",
":",
"raise",
"OAuthValidationError",
"(",
"{",
"'error'",
":",
"'invalid_request'",
",... | :rfc:`3.1.1` Lists of values are space delimited. | [
":",
"rfc",
":",
"3",
".",
"1",
".",
"1",
"Lists",
"of",
"values",
"are",
"space",
"delimited",
"."
] | python | train | 34.85 |
NoviceLive/intellicoder | intellicoder/msbuild/locators.py | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/msbuild/locators.py#L276-L285 | def get_vc_dir_from_vs_dir(self):
"""
Get Visual C++ directory from Visual Studio directory.
"""
vc_dir = os.path.join(self.vs_dir, 'vc')
if os.path.isdir(vc_dir):
logging.info(_('using vc: %s'), vc_dir)
return vc_dir
logging.debug(_('vc not found:... | [
"def",
"get_vc_dir_from_vs_dir",
"(",
"self",
")",
":",
"vc_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"vs_dir",
",",
"'vc'",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"vc_dir",
")",
":",
"logging",
".",
"info",
"(",
"_",
... | Get Visual C++ directory from Visual Studio directory. | [
"Get",
"Visual",
"C",
"++",
"directory",
"from",
"Visual",
"Studio",
"directory",
"."
] | python | train | 34.3 |
MagicStack/asyncpg | asyncpg/cluster.py | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/cluster.py#L323-L337 | def reset_hba(self):
"""Remove all records from pg_hba.conf."""
status = self.get_status()
if status == 'not-initialized':
raise ClusterError(
'cannot modify HBA records: cluster is not initialized')
pg_hba = os.path.join(self._data_dir, 'pg_hba.conf')
... | [
"def",
"reset_hba",
"(",
"self",
")",
":",
"status",
"=",
"self",
".",
"get_status",
"(",
")",
"if",
"status",
"==",
"'not-initialized'",
":",
"raise",
"ClusterError",
"(",
"'cannot modify HBA records: cluster is not initialized'",
")",
"pg_hba",
"=",
"os",
".",
... | Remove all records from pg_hba.conf. | [
"Remove",
"all",
"records",
"from",
"pg_hba",
".",
"conf",
"."
] | python | train | 33.133333 |
foxx/python-helpful | helpful.py | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L55-L61 | def unique_iter(seq):
"""
See http://www.peterbe.com/plog/uniqifiers-benchmark
Originally f8 written by Dave Kirby
"""
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)] | [
"def",
"unique_iter",
"(",
"seq",
")",
":",
"seen",
"=",
"set",
"(",
")",
"return",
"[",
"x",
"for",
"x",
"in",
"seq",
"if",
"x",
"not",
"in",
"seen",
"and",
"not",
"seen",
".",
"add",
"(",
"x",
")",
"]"
] | See http://www.peterbe.com/plog/uniqifiers-benchmark
Originally f8 written by Dave Kirby | [
"See",
"http",
":",
"//",
"www",
".",
"peterbe",
".",
"com",
"/",
"plog",
"/",
"uniqifiers",
"-",
"benchmark",
"Originally",
"f8",
"written",
"by",
"Dave",
"Kirby"
] | python | train | 30 |
deepmind/pysc2 | pysc2/lib/features.py | https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L768-L772 | def _update_camera(self, camera_center):
"""Update the camera transform based on the new camera center."""
self._world_tl_to_world_camera_rel.offset = (
-self._world_to_world_tl.fwd_pt(camera_center) *
self._world_tl_to_world_camera_rel.scale) | [
"def",
"_update_camera",
"(",
"self",
",",
"camera_center",
")",
":",
"self",
".",
"_world_tl_to_world_camera_rel",
".",
"offset",
"=",
"(",
"-",
"self",
".",
"_world_to_world_tl",
".",
"fwd_pt",
"(",
"camera_center",
")",
"*",
"self",
".",
"_world_tl_to_world_c... | Update the camera transform based on the new camera center. | [
"Update",
"the",
"camera",
"transform",
"based",
"on",
"the",
"new",
"camera",
"center",
"."
] | python | train | 52.6 |
datasift/datasift-python | datasift/limit.py | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/limit.py#L61-L79 | def update(self, identity_id, service, total_allowance=None, analyze_queries=None):
""" Update the limit
:param identity_id: The ID of the identity to retrieve
:param service: The service that the token is linked to
:param total_allowance: The total allowance for this token'... | [
"def",
"update",
"(",
"self",
",",
"identity_id",
",",
"service",
",",
"total_allowance",
"=",
"None",
",",
"analyze_queries",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'service'",
":",
"service",
"}",
"if",
"total_allowance",
"is",
"not",
"None",
":",
... | Update the limit
:param identity_id: The ID of the identity to retrieve
:param service: The service that the token is linked to
:param total_allowance: The total allowance for this token's limit
:param analyze_queries: The number of analyze calls
:return: dic... | [
"Update",
"the",
"limit"
] | python | train | 50.052632 |
dagwieers/vmguestlib | vmguestlib.py | https://github.com/dagwieers/vmguestlib/blob/2ba9333a745628cf9e6b4c767427a5bd997a71ad/vmguestlib.py#L269-L274 | def GetHostMemSwappedMB(self):
'''Undocumented.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetHostMemSwappedMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
return counter.value | [
"def",
"GetHostMemSwappedMB",
"(",
"self",
")",
":",
"counter",
"=",
"c_uint",
"(",
")",
"ret",
"=",
"vmGuestLib",
".",
"VMGuestLib_GetHostMemSwappedMB",
"(",
"self",
".",
"handle",
".",
"value",
",",
"byref",
"(",
"counter",
")",
")",
"if",
"ret",
"!=",
... | Undocumented. | [
"Undocumented",
"."
] | python | train | 45.833333 |
SheffieldML/GPy | GPy/util/multioutput.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/util/multioutput.py#L82-L100 | def Private(input_dim, num_outputs, kernel, output, kappa=None,name='X'):
"""
Builds a kernel for an Intrinsic Coregionalization Model
:input_dim: Input dimensionality
:num_outputs: Number of outputs
:param kernel: kernel that will be multiplied by the coregionalize kernel (matrix B).
:type ker... | [
"def",
"Private",
"(",
"input_dim",
",",
"num_outputs",
",",
"kernel",
",",
"output",
",",
"kappa",
"=",
"None",
",",
"name",
"=",
"'X'",
")",
":",
"K",
"=",
"ICM",
"(",
"input_dim",
",",
"num_outputs",
",",
"kernel",
",",
"W_rank",
"=",
"1",
",",
... | Builds a kernel for an Intrinsic Coregionalization Model
:input_dim: Input dimensionality
:num_outputs: Number of outputs
:param kernel: kernel that will be multiplied by the coregionalize kernel (matrix B).
:type kernel: a GPy kernel
:param W_rank: number tuples of the corregionalization parameter... | [
"Builds",
"a",
"kernel",
"for",
"an",
"Intrinsic",
"Coregionalization",
"Model"
] | python | train | 34.631579 |
merll/docker-map | dockermap/client/docker_util.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/client/docker_util.py#L57-L77 | def primary_container_name(names, default=None, strip_trailing_slash=True):
"""
From the list of names, finds the primary name of the container. Returns the defined default value (e.g. the
container id or ``None``) in case it cannot find any.
:param names: List with name and aliases of the container.
... | [
"def",
"primary_container_name",
"(",
"names",
",",
"default",
"=",
"None",
",",
"strip_trailing_slash",
"=",
"True",
")",
":",
"if",
"strip_trailing_slash",
":",
"ex_names",
"=",
"[",
"name",
"[",
"1",
":",
"]",
"for",
"name",
"in",
"names",
"if",
"name",... | From the list of names, finds the primary name of the container. Returns the defined default value (e.g. the
container id or ``None``) in case it cannot find any.
:param names: List with name and aliases of the container.
:type names: list[unicode | str]
:param default: Default value.
:param strip_... | [
"From",
"the",
"list",
"of",
"names",
"finds",
"the",
"primary",
"name",
"of",
"the",
"container",
".",
"Returns",
"the",
"defined",
"default",
"value",
"(",
"e",
".",
"g",
".",
"the",
"container",
"id",
"or",
"None",
")",
"in",
"case",
"it",
"cannot",... | python | train | 43.285714 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsPrefShockModel.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsPrefShockModel.py#L93-L112 | def getShocks(self):
'''
Gets permanent and transitory income shocks for this period as well as preference shocks.
Parameters
----------
None
Returns
-------
None
'''
IndShockConsumerType.getShocks(self) # Get permanent and transitory inc... | [
"def",
"getShocks",
"(",
"self",
")",
":",
"IndShockConsumerType",
".",
"getShocks",
"(",
"self",
")",
"# Get permanent and transitory income shocks",
"PrefShkNow",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"AgentCount",
")",
"# Initialize shock array",
"for",
"t",... | Gets permanent and transitory income shocks for this period as well as preference shocks.
Parameters
----------
None
Returns
-------
None | [
"Gets",
"permanent",
"and",
"transitory",
"income",
"shocks",
"for",
"this",
"period",
"as",
"well",
"as",
"preference",
"shocks",
"."
] | python | train | 33 |
django-salesforce/django-salesforce | salesforce/dbapi/subselect.py | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/subselect.py#L151-L174 | def parse_rest_response(self, records, rowcount, row_type=list):
"""Parse the REST API response to DB API cursor flat response"""
if self.is_plain_count:
# result of "SELECT COUNT() FROM ... WHERE ..."
assert list(records) == []
yield rowcount # originally [resp.json... | [
"def",
"parse_rest_response",
"(",
"self",
",",
"records",
",",
"rowcount",
",",
"row_type",
"=",
"list",
")",
":",
"if",
"self",
".",
"is_plain_count",
":",
"# result of \"SELECT COUNT() FROM ... WHERE ...\"",
"assert",
"list",
"(",
"records",
")",
"==",
"[",
"... | Parse the REST API response to DB API cursor flat response | [
"Parse",
"the",
"REST",
"API",
"response",
"to",
"DB",
"API",
"cursor",
"flat",
"response"
] | python | train | 55.666667 |
trevisanj/a99 | a99/gui/parameter.py | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/gui/parameter.py#L123-L144 | def RenderWidget(self):
"""Returns a QWidget subclass instance. Exact class depends on self.type"""
t = self.type
if t == int:
ret = QSpinBox()
ret.setMaximum(999999999)
ret.setValue(self.value)
elif t == float:
ret = QLineEdit()
... | [
"def",
"RenderWidget",
"(",
"self",
")",
":",
"t",
"=",
"self",
".",
"type",
"if",
"t",
"==",
"int",
":",
"ret",
"=",
"QSpinBox",
"(",
")",
"ret",
".",
"setMaximum",
"(",
"999999999",
")",
"ret",
".",
"setValue",
"(",
"self",
".",
"value",
")",
"... | Returns a QWidget subclass instance. Exact class depends on self.type | [
"Returns",
"a",
"QWidget",
"subclass",
"instance",
".",
"Exact",
"class",
"depends",
"on",
"self",
".",
"type"
] | python | train | 30.5 |
bokeh/bokeh | bokeh/core/property/descriptors.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L281-L296 | def serializable_value(self, obj):
''' Produce the value as it should be serialized.
Sometimes it is desirable for the serialized value to differ from
the ``__get__`` in order for the ``__get__`` value to appear simpler
for user or developer convenience.
Args:
obj (... | [
"def",
"serializable_value",
"(",
"self",
",",
"obj",
")",
":",
"value",
"=",
"self",
".",
"__get__",
"(",
"obj",
",",
"obj",
".",
"__class__",
")",
"return",
"self",
".",
"property",
".",
"serialize_value",
"(",
"value",
")"
] | Produce the value as it should be serialized.
Sometimes it is desirable for the serialized value to differ from
the ``__get__`` in order for the ``__get__`` value to appear simpler
for user or developer convenience.
Args:
obj (HasProps) : the object to get the serialized at... | [
"Produce",
"the",
"value",
"as",
"it",
"should",
"be",
"serialized",
"."
] | python | train | 32.3125 |
rosshamish/hexgrid | hexgrid.py | https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L242-L257 | def edge_coord_in_direction(tile_id, direction):
"""
Returns the edge coordinate in the given direction at the given tile identifier.
:param tile_id: tile identifier, int
:param direction: direction, str
:return: edge coord, int
"""
tile_coord = tile_id_to_coord(tile_id)
for edge_coord ... | [
"def",
"edge_coord_in_direction",
"(",
"tile_id",
",",
"direction",
")",
":",
"tile_coord",
"=",
"tile_id_to_coord",
"(",
"tile_id",
")",
"for",
"edge_coord",
"in",
"edges_touching_tile",
"(",
"tile_id",
")",
":",
"if",
"tile_edge_offset_to_direction",
"(",
"edge_co... | Returns the edge coordinate in the given direction at the given tile identifier.
:param tile_id: tile identifier, int
:param direction: direction, str
:return: edge coord, int | [
"Returns",
"the",
"edge",
"coordinate",
"in",
"the",
"given",
"direction",
"at",
"the",
"given",
"tile",
"identifier",
"."
] | python | train | 35.25 |
FPGAwars/apio | apio/resources.py | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/resources.py#L138-L158 | def list_fpgas(self):
"""Return a list with all the supported FPGAs"""
# Print table
click.echo('\nSupported FPGAs:\n')
FPGALIST_TPL = ('{fpga:30} {type:<5} {size:<5} {pack:<10}')
terminal_width, _ = click.get_terminal_size()
click.echo('-' * terminal_width)
cl... | [
"def",
"list_fpgas",
"(",
"self",
")",
":",
"# Print table",
"click",
".",
"echo",
"(",
"'\\nSupported FPGAs:\\n'",
")",
"FPGALIST_TPL",
"=",
"(",
"'{fpga:30} {type:<5} {size:<5} {pack:<10}'",
")",
"terminal_width",
",",
"_",
"=",
"click",
".",
"get_terminal_size",
... | Return a list with all the supported FPGAs | [
"Return",
"a",
"list",
"with",
"all",
"the",
"supported",
"FPGAs"
] | python | train | 36.428571 |
saltstack/salt | salt/modules/azurearm_network.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L202-L237 | def default_security_rules_list(security_group, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List default security rules within a security group.
:param security_group: The network security group to query.
:param resource_group: The resource group name assigned to the
network... | [
"def",
"default_security_rules_list",
"(",
"security_group",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"secgroup",
"=",
"network_security_group_get",
"(",
"security_group",
"=",
"security_group",
",",
"resource_group",
"=",
... | .. versionadded:: 2019.2.0
List default security rules within a security group.
:param security_group: The network security group to query.
:param resource_group: The resource group name assigned to the
network security group.
CLI Example:
.. code-block:: bash
salt-call azurear... | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | python | train | 24.25 |
apache/incubator-heron | heron/tools/tracker/src/python/config.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/config.py#L61-L82 | def validated_formatter(self, url_format):
"""validate visualization url format"""
# We try to create a string by substituting all known
# parameters. If an unknown parameter is present, an error
# will be thrown
valid_parameters = {
"${CLUSTER}": "cluster",
"${ENVIRON}": "environ",
... | [
"def",
"validated_formatter",
"(",
"self",
",",
"url_format",
")",
":",
"# We try to create a string by substituting all known",
"# parameters. If an unknown parameter is present, an error",
"# will be thrown",
"valid_parameters",
"=",
"{",
"\"${CLUSTER}\"",
":",
"\"cluster\"",
","... | validate visualization url format | [
"validate",
"visualization",
"url",
"format"
] | python | valid | 34.727273 |
timothydmorton/VESPA | vespa/stars/populations.py | https://github.com/timothydmorton/VESPA/blob/0446b54d48009f3655cfd1a3957ceea21d3adcaa/vespa/stars/populations.py#L1558-L1562 | def dRV(self, dt, band='g'):
"""Returns dRV of star A, if A is brighter than B+C, or of star B if B+C is brighter
"""
return (self.orbpop.dRV_1(dt)*self.A_brighter(band) +
self.orbpop.dRV_2(dt)*self.BC_brighter(band)) | [
"def",
"dRV",
"(",
"self",
",",
"dt",
",",
"band",
"=",
"'g'",
")",
":",
"return",
"(",
"self",
".",
"orbpop",
".",
"dRV_1",
"(",
"dt",
")",
"*",
"self",
".",
"A_brighter",
"(",
"band",
")",
"+",
"self",
".",
"orbpop",
".",
"dRV_2",
"(",
"dt",
... | Returns dRV of star A, if A is brighter than B+C, or of star B if B+C is brighter | [
"Returns",
"dRV",
"of",
"star",
"A",
"if",
"A",
"is",
"brighter",
"than",
"B",
"+",
"C",
"or",
"of",
"star",
"B",
"if",
"B",
"+",
"C",
"is",
"brighter"
] | python | train | 50.6 |
yymao/easyquery | easyquery.py | https://github.com/yymao/easyquery/blob/cd94c100e26f59042cd9ffb26d0a7b61cdcd457d/easyquery.py#L201-L234 | def mask(self, table):
"""
Use the current Query object to count the number of entries in `table`
that satisfy `queries`.
Parameters
----------
table : NumPy structured array, astropy Table, etc.
Returns
-------
mask : numpy bool array
""... | [
"def",
"mask",
"(",
"self",
",",
"table",
")",
":",
"if",
"self",
".",
"_operator",
"is",
"None",
":",
"if",
"self",
".",
"_operands",
"is",
"None",
":",
"return",
"np",
".",
"ones",
"(",
"self",
".",
"_get_table_len",
"(",
"table",
")",
",",
"dtyp... | Use the current Query object to count the number of entries in `table`
that satisfy `queries`.
Parameters
----------
table : NumPy structured array, astropy Table, etc.
Returns
-------
mask : numpy bool array | [
"Use",
"the",
"current",
"Query",
"object",
"to",
"count",
"the",
"number",
"of",
"entries",
"in",
"table",
"that",
"satisfy",
"queries",
"."
] | python | train | 29.794118 |
pandas-dev/pandas | pandas/io/pytables.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L553-L624 | def open(self, mode='a', **kwargs):
"""
Open the file in the specified mode
Parameters
----------
mode : {'a', 'w', 'r', 'r+'}, default 'a'
See HDFStore docstring or tables.open_file for info about modes
"""
tables = _tables()
if self._mode !... | [
"def",
"open",
"(",
"self",
",",
"mode",
"=",
"'a'",
",",
"*",
"*",
"kwargs",
")",
":",
"tables",
"=",
"_tables",
"(",
")",
"if",
"self",
".",
"_mode",
"!=",
"mode",
":",
"# if we are changing a write mode to read, ok",
"if",
"self",
".",
"_mode",
"in",
... | Open the file in the specified mode
Parameters
----------
mode : {'a', 'w', 'r', 'r+'}, default 'a'
See HDFStore docstring or tables.open_file for info about modes | [
"Open",
"the",
"file",
"in",
"the",
"specified",
"mode"
] | python | train | 36.902778 |
quantopian/empyrical | empyrical/stats.py | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1732-L1754 | def roll_up_down_capture(returns, factor_returns, window=10, **kwargs):
"""
Computes the up/down capture measure over a rolling window.
see documentation for :func:`~empyrical.stats.up_down_capture`.
(pass all args, kwargs required)
Parameters
----------
returns : pd.Series or np.ndarray
... | [
"def",
"roll_up_down_capture",
"(",
"returns",
",",
"factor_returns",
",",
"window",
"=",
"10",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"roll",
"(",
"returns",
",",
"factor_returns",
",",
"window",
"=",
"window",
",",
"function",
"=",
"up_down_capture",... | Computes the up/down capture measure over a rolling window.
see documentation for :func:`~empyrical.stats.up_down_capture`.
(pass all args, kwargs required)
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation i... | [
"Computes",
"the",
"up",
"/",
"down",
"capture",
"measure",
"over",
"a",
"rolling",
"window",
".",
"see",
"documentation",
"for",
":",
"func",
":",
"~empyrical",
".",
"stats",
".",
"up_down_capture",
".",
"(",
"pass",
"all",
"args",
"kwargs",
"required",
"... | python | train | 40.608696 |
jedie/DragonPy | dragonpy/Dragon32/MC6821_PIA.py | https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L379-L389 | def read_PIA0_B_control(self, cpu_cycles, op_address, address):
"""
read from 0xff03 -> PIA 0 B side Control reg.
"""
value = self.pia_0_B_control.value
log.error(
"%04x| read $%04x (PIA 0 B side Control reg.) send $%02x (%s) back.\t|%s",
op_address, addre... | [
"def",
"read_PIA0_B_control",
"(",
"self",
",",
"cpu_cycles",
",",
"op_address",
",",
"address",
")",
":",
"value",
"=",
"self",
".",
"pia_0_B_control",
".",
"value",
"log",
".",
"error",
"(",
"\"%04x| read $%04x (PIA 0 B side Control reg.) send $%02x (%s) back.\\t|%s\"... | read from 0xff03 -> PIA 0 B side Control reg. | [
"read",
"from",
"0xff03",
"-",
">",
"PIA",
"0",
"B",
"side",
"Control",
"reg",
"."
] | python | train | 39.090909 |
rahul13ramesh/hidden_markov | hidden_markov/hmm_class.py | https://github.com/rahul13ramesh/hidden_markov/blob/6ba6012665f9e09c980ff70901604d051ba57dcc/hidden_markov/hmm_class.py#L281-L363 | def train_hmm(self,observation_list, iterations, quantities):
""" Runs the Baum Welch Algorithm and finds the new model parameters
**Arguments**:
:param observation_list: A nested list, or a list of lists
:type observation_list: Contains a list multiple observation sequences.
... | [
"def",
"train_hmm",
"(",
"self",
",",
"observation_list",
",",
"iterations",
",",
"quantities",
")",
":",
"obs_size",
"=",
"len",
"(",
"observation_list",
")",
"prob",
"=",
"float",
"(",
"'inf'",
")",
"q",
"=",
"quantities",
"# Train the model 'iteration' number... | Runs the Baum Welch Algorithm and finds the new model parameters
**Arguments**:
:param observation_list: A nested list, or a list of lists
:type observation_list: Contains a list multiple observation sequences.
:param iterations: Maximum number of iterations for the algorithm
... | [
"Runs",
"the",
"Baum",
"Welch",
"Algorithm",
"and",
"finds",
"the",
"new",
"model",
"parameters"
] | python | train | 39.783133 |
getfleety/coralillo | coralillo/core.py | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L460-L482 | def delete(self):
''' Deletes this model from the database, calling delete in each field
to properly delete special cases '''
redis = type(self).get_redis()
for fieldname, field in self.proxy:
field.delete(redis)
redis.delete(self.key())
redis.srem(type(self... | [
"def",
"delete",
"(",
"self",
")",
":",
"redis",
"=",
"type",
"(",
"self",
")",
".",
"get_redis",
"(",
")",
"for",
"fieldname",
",",
"field",
"in",
"self",
".",
"proxy",
":",
"field",
".",
"delete",
"(",
"redis",
")",
"redis",
".",
"delete",
"(",
... | Deletes this model from the database, calling delete in each field
to properly delete special cases | [
"Deletes",
"this",
"model",
"from",
"the",
"database",
"calling",
"delete",
"in",
"each",
"field",
"to",
"properly",
"delete",
"special",
"cases"
] | python | train | 29.565217 |
trailofbits/manticore | manticore/native/cpu/x86.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2916-L2941 | def XCHG(cpu, dest, src):
"""
Exchanges register/memory with register.
Exchanges the contents of the destination (first) and source (second)
operands. The operands can be two general-purpose registers or a register
and a memory location. If a memory operand is referenced, the pr... | [
"def",
"XCHG",
"(",
"cpu",
",",
"dest",
",",
"src",
")",
":",
"temp",
"=",
"dest",
".",
"read",
"(",
")",
"dest",
".",
"write",
"(",
"src",
".",
"read",
"(",
")",
")",
"src",
".",
"write",
"(",
"temp",
")"
] | Exchanges register/memory with register.
Exchanges the contents of the destination (first) and source (second)
operands. The operands can be two general-purpose registers or a register
and a memory location. If a memory operand is referenced, the processor's
locking protocol is automati... | [
"Exchanges",
"register",
"/",
"memory",
"with",
"register",
"."
] | python | valid | 39.807692 |
gem/oq-engine | openquake/hazardlib/gsim/idriss_2014.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/idriss_2014.py#L100-L108 | def _get_distance_scaling_term(self, C, mag, rrup):
"""
Returns the magnitude dependent distance scaling term
"""
if mag < 6.75:
mag_factor = -(C["b1_lo"] + C["b2_lo"] * mag)
else:
mag_factor = -(C["b1_hi"] + C["b2_hi"] * mag)
return mag_factor * n... | [
"def",
"_get_distance_scaling_term",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
")",
":",
"if",
"mag",
"<",
"6.75",
":",
"mag_factor",
"=",
"-",
"(",
"C",
"[",
"\"b1_lo\"",
"]",
"+",
"C",
"[",
"\"b2_lo\"",
"]",
"*",
"mag",
")",
"else",
":",
... | Returns the magnitude dependent distance scaling term | [
"Returns",
"the",
"magnitude",
"dependent",
"distance",
"scaling",
"term"
] | python | train | 39.111111 |
hanguokai/youku | youku/youku_searches.py | https://github.com/hanguokai/youku/blob/b2df060c7dccfad990bcfa289fff68bb77d1e69b/youku/youku_searches.py#L140-L163 | def search_show_top_unite(self, category, genre=None, area=None,
year=None, orderby=None, headnum=1,
tailnum=1, onesiteflag=None,
page=1, count=20):
"""doc: http://open.youku.com/docs/doc?id=86
"""
url = 'h... | [
"def",
"search_show_top_unite",
"(",
"self",
",",
"category",
",",
"genre",
"=",
"None",
",",
"area",
"=",
"None",
",",
"year",
"=",
"None",
",",
"orderby",
"=",
"None",
",",
"headnum",
"=",
"1",
",",
"tailnum",
"=",
"1",
",",
"onesiteflag",
"=",
"No... | doc: http://open.youku.com/docs/doc?id=86 | [
"doc",
":",
"http",
":",
"//",
"open",
".",
"youku",
".",
"com",
"/",
"docs",
"/",
"doc?id",
"=",
"86"
] | python | train | 35.916667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.