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 |
|---|---|---|---|---|---|---|---|---|---|
south-coast-science/scs_core | src/scs_core/position/nmea/gpdatetime.py | https://github.com/south-coast-science/scs_core/blob/a4152b0bbed6acbbf257e1bba6a912f6ebe578e5/src/scs_core/position/nmea/gpdatetime.py#L30-L38 | def as_iso8601(self):
"""
example: 2016-08-13T00:38:05.210+00:00
"""
if self.__date is None or self.__time is None:
return None
return "20%s-%s-%sT%s:%s:%s0Z" % \
(self.__date[4:], self.__date[2:4], self.__date[:2], self.__time[:2], self.__time[2:4], s... | [
"def",
"as_iso8601",
"(",
"self",
")",
":",
"if",
"self",
".",
"__date",
"is",
"None",
"or",
"self",
".",
"__time",
"is",
"None",
":",
"return",
"None",
"return",
"\"20%s-%s-%sT%s:%s:%s0Z\"",
"%",
"(",
"self",
".",
"__date",
"[",
"4",
":",
"]",
",",
... | example: 2016-08-13T00:38:05.210+00:00 | [
"example",
":",
"2016",
"-",
"08",
"-",
"13T00",
":",
"38",
":",
"05",
".",
"210",
"+",
"00",
":",
"00"
] | python | train | 36.333333 |
Azure/azure-event-hubs-python | azure/eventprocessorhost/eph.py | https://github.com/Azure/azure-event-hubs-python/blob/737c5f966557ada2cf10fa0d8f3c19671ae96348/azure/eventprocessorhost/eph.py#L49-L55 | async def open_async(self):
"""
Starts the host.
"""
if not self.loop:
self.loop = asyncio.get_event_loop()
await self.partition_manager.start_async() | [
"async",
"def",
"open_async",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"loop",
":",
"self",
".",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"await",
"self",
".",
"partition_manager",
".",
"start_async",
"(",
")"
] | Starts the host. | [
"Starts",
"the",
"host",
"."
] | python | train | 28 |
joke2k/faker | faker/providers/date_time/__init__.py | https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/date_time/__init__.py#L1589-L1602 | def future_datetime(self, end_date='+30d', tzinfo=None):
"""
Get a DateTime object based on a random date between 1 second form now
and a given date.
Accepts date strings that can be recognized by strtotime().
:param end_date Defaults to "+30d"
:param tzinfo: timezone, i... | [
"def",
"future_datetime",
"(",
"self",
",",
"end_date",
"=",
"'+30d'",
",",
"tzinfo",
"=",
"None",
")",
":",
"return",
"self",
".",
"date_time_between",
"(",
"start_date",
"=",
"'+1s'",
",",
"end_date",
"=",
"end_date",
",",
"tzinfo",
"=",
"tzinfo",
",",
... | Get a DateTime object based on a random date between 1 second form now
and a given date.
Accepts date strings that can be recognized by strtotime().
:param end_date Defaults to "+30d"
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('1999-02-02 11:... | [
"Get",
"a",
"DateTime",
"object",
"based",
"on",
"a",
"random",
"date",
"between",
"1",
"second",
"form",
"now",
"and",
"a",
"given",
"date",
".",
"Accepts",
"date",
"strings",
"that",
"can",
"be",
"recognized",
"by",
"strtotime",
"()",
"."
] | python | train | 38.642857 |
gagneurlab/concise | concise/legacy/kmer.py | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/kmer.py#L28-L102 | def best_kmers(dt, response, sequence, k=6, consider_shift=True, n_cores=1,
seq_align="start", trim_seq_len=None):
"""
Find best k-mers for CONCISE initialization.
Args:
dt (pd.DataFrame): Table containing response variable and sequence.
response (str): Name of the column use... | [
"def",
"best_kmers",
"(",
"dt",
",",
"response",
",",
"sequence",
",",
"k",
"=",
"6",
",",
"consider_shift",
"=",
"True",
",",
"n_cores",
"=",
"1",
",",
"seq_align",
"=",
"\"start\"",
",",
"trim_seq_len",
"=",
"None",
")",
":",
"y",
"=",
"dt",
"[",
... | Find best k-mers for CONCISE initialization.
Args:
dt (pd.DataFrame): Table containing response variable and sequence.
response (str): Name of the column used as the reponse variable.
sequence (str): Name of the column storing the DNA/RNA sequences.
k (int): Desired k-mer length.
... | [
"Find",
"best",
"k",
"-",
"mers",
"for",
"CONCISE",
"initialization",
"."
] | python | train | 43.693333 |
ncclient/ncclient | ncclient/transport/session.py | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/transport/session.py#L248-L264 | def build(capabilities, device_handler):
"Given a list of capability URI's returns <hello> message XML string"
if device_handler:
# This is used as kwargs dictionary for lxml's Element() function.
# Therefore the arg-name ("nsmap") is used as key here.
xml_namespace_k... | [
"def",
"build",
"(",
"capabilities",
",",
"device_handler",
")",
":",
"if",
"device_handler",
":",
"# This is used as kwargs dictionary for lxml's Element() function.",
"# Therefore the arg-name (\"nsmap\") is used as key here.",
"xml_namespace_kwargs",
"=",
"{",
"\"nsmap\"",
":",
... | Given a list of capability URI's returns <hello> message XML string | [
"Given",
"a",
"list",
"of",
"capability",
"URI",
"s",
"returns",
"<hello",
">",
"message",
"XML",
"string"
] | python | train | 44.705882 |
apache/incubator-heron | heron/common/src/python/utils/log.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/common/src/python/utils/log.py#L93-L104 | def set_logging_level(cl_args):
"""simply set verbose level based on command-line args
:param cl_args: CLI arguments
:type cl_args: dict
:return: None
:rtype: None
"""
if 'verbose' in cl_args and cl_args['verbose']:
configure(logging.DEBUG)
else:
configure(logging.INFO) | [
"def",
"set_logging_level",
"(",
"cl_args",
")",
":",
"if",
"'verbose'",
"in",
"cl_args",
"and",
"cl_args",
"[",
"'verbose'",
"]",
":",
"configure",
"(",
"logging",
".",
"DEBUG",
")",
"else",
":",
"configure",
"(",
"logging",
".",
"INFO",
")"
] | simply set verbose level based on command-line args
:param cl_args: CLI arguments
:type cl_args: dict
:return: None
:rtype: None | [
"simply",
"set",
"verbose",
"level",
"based",
"on",
"command",
"-",
"line",
"args"
] | python | valid | 23.666667 |
boriel/zxbasic | asm.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/asm.py#L115-L126 | def argval(self):
""" Returns the value of the arg (if any) or None.
If the arg. is not an integer, an error be triggered.
"""
if self.arg is None or any(x is None for x in self.arg):
return None
for x in self.arg:
if not isinstance(x, int):
... | [
"def",
"argval",
"(",
"self",
")",
":",
"if",
"self",
".",
"arg",
"is",
"None",
"or",
"any",
"(",
"x",
"is",
"None",
"for",
"x",
"in",
"self",
".",
"arg",
")",
":",
"return",
"None",
"for",
"x",
"in",
"self",
".",
"arg",
":",
"if",
"not",
"is... | Returns the value of the arg (if any) or None.
If the arg. is not an integer, an error be triggered. | [
"Returns",
"the",
"value",
"of",
"the",
"arg",
"(",
"if",
"any",
")",
"or",
"None",
".",
"If",
"the",
"arg",
".",
"is",
"not",
"an",
"integer",
"an",
"error",
"be",
"triggered",
"."
] | python | train | 30.666667 |
IdentityPython/SATOSA | src/satosa/state.py | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L235-L253 | def urlstate(self, encryption_key):
"""
Will return a url safe representation of the state.
:type encryption_key: Key used for encryption.
:rtype: str
:return: Url representation av of the state.
"""
lzma = LZMACompressor()
urlstate_data = json.dumps(sel... | [
"def",
"urlstate",
"(",
"self",
",",
"encryption_key",
")",
":",
"lzma",
"=",
"LZMACompressor",
"(",
")",
"urlstate_data",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"_state_dict",
")",
"urlstate_data",
"=",
"lzma",
".",
"compress",
"(",
"urlstate_data",
... | Will return a url safe representation of the state.
:type encryption_key: Key used for encryption.
:rtype: str
:return: Url representation av of the state. | [
"Will",
"return",
"a",
"url",
"safe",
"representation",
"of",
"the",
"state",
"."
] | python | train | 38.368421 |
Nukesor/pueue | pueue/daemon/daemon.py | https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/daemon.py#L319-L344 | def send_status(self, payload):
"""Send the daemon status and the current queue for displaying."""
answer = {}
data = []
# Get daemon status
if self.paused:
answer['status'] = 'paused'
else:
answer['status'] = 'running'
# Add current queue... | [
"def",
"send_status",
"(",
"self",
",",
"payload",
")",
":",
"answer",
"=",
"{",
"}",
"data",
"=",
"[",
"]",
"# Get daemon status",
"if",
"self",
".",
"paused",
":",
"answer",
"[",
"'status'",
"]",
"=",
"'paused'",
"else",
":",
"answer",
"[",
"'status'... | Send the daemon status and the current queue for displaying. | [
"Send",
"the",
"daemon",
"status",
"and",
"the",
"current",
"queue",
"for",
"displaying",
"."
] | python | train | 33.807692 |
ozgurgunes/django-manifest | manifest/accounts/models.py | https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/models.py#L273-L300 | def get_full_name_or_username(self):
"""
Returns the full name of the user, or if none is supplied will return
the username.
Also looks at ``ACCOUNTS_WITHOUT_USERNAMES`` settings to define if it
should return the username or email address when the full name is not
suppli... | [
"def",
"get_full_name_or_username",
"(",
"self",
")",
":",
"if",
"self",
".",
"first_name",
"or",
"self",
".",
"last_name",
":",
"# We will return this as translated string. Maybe there are some",
"# countries that first display the last name.",
"name",
"=",
"_",
"(",
"u\"%... | Returns the full name of the user, or if none is supplied will return
the username.
Also looks at ``ACCOUNTS_WITHOUT_USERNAMES`` settings to define if it
should return the username or email address when the full name is not
supplied.
:return:
``String`` containing t... | [
"Returns",
"the",
"full",
"name",
"of",
"the",
"user",
"or",
"if",
"none",
"is",
"supplied",
"will",
"return",
"the",
"username",
"."
] | python | train | 41.928571 |
spdx/tools-python | spdx/parsers/tagvaluebuilders.py | https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L788-L802 | def set_pkg_desc(self, doc, text):
"""Set's the package's description.
Raises SPDXValueError if text is not free form text.
Raises CardinalityError if description already set.
Raises OrderError if no package previously defined.
"""
self.assert_package_exists()
if ... | [
"def",
"set_pkg_desc",
"(",
"self",
",",
"doc",
",",
"text",
")",
":",
"self",
".",
"assert_package_exists",
"(",
")",
"if",
"not",
"self",
".",
"package_desc_set",
":",
"self",
".",
"package_desc_set",
"=",
"True",
"if",
"validations",
".",
"validate_pkg_de... | Set's the package's description.
Raises SPDXValueError if text is not free form text.
Raises CardinalityError if description already set.
Raises OrderError if no package previously defined. | [
"Set",
"s",
"the",
"package",
"s",
"description",
".",
"Raises",
"SPDXValueError",
"if",
"text",
"is",
"not",
"free",
"form",
"text",
".",
"Raises",
"CardinalityError",
"if",
"description",
"already",
"set",
".",
"Raises",
"OrderError",
"if",
"no",
"package",
... | python | valid | 42.6 |
saltstack/salt | salt/states/boto_ec2.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_ec2.py#L589-L988 | def instance_present(name, instance_name=None, instance_id=None, image_id=None,
image_name=None, tags=None, key_name=None,
security_groups=None, user_data=None, instance_type=None,
placement=None, kernel_id=None, ramdisk_id=None,
vpc_id... | [
"def",
"instance_present",
"(",
"name",
",",
"instance_name",
"=",
"None",
",",
"instance_id",
"=",
"None",
",",
"image_id",
"=",
"None",
",",
"image_name",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"key_name",
"=",
"None",
",",
"security_groups",
"=",
... | Ensure an EC2 instance is running with the given attributes and state.
name
(string) - The name of the state definition. Recommended that this
match the instance_name attribute (generally the FQDN of the instance).
instance_name
(string) - The name of the instance, generally its FQDN. ... | [
"Ensure",
"an",
"EC2",
"instance",
"is",
"running",
"with",
"the",
"given",
"attributes",
"and",
"state",
"."
] | python | train | 48.9675 |
bcbio/bcbio-nextgen | bcbio/variation/validateplot.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validateplot.py#L230-L244 | def _check_cats(cats, vtypes, df, prep, callers):
"""Only include categories in the final output if they have values.
"""
out = []
for cat in cats:
all_vals = []
for vtype in vtypes:
vals, labels, maxval = _get_chart_info(df, vtype, cat, prep, callers)
all_vals.ex... | [
"def",
"_check_cats",
"(",
"cats",
",",
"vtypes",
",",
"df",
",",
"prep",
",",
"callers",
")",
":",
"out",
"=",
"[",
"]",
"for",
"cat",
"in",
"cats",
":",
"all_vals",
"=",
"[",
"]",
"for",
"vtype",
"in",
"vtypes",
":",
"vals",
",",
"labels",
",",... | Only include categories in the final output if they have values. | [
"Only",
"include",
"categories",
"in",
"the",
"final",
"output",
"if",
"they",
"have",
"values",
"."
] | python | train | 31.2 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe_ext.py#L241-L255 | def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_wwn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "output")
... | [
"def",
"fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_wwn",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"fcoe_get_interface",
"=",
"ET",
".",
"Element",
"(",
"\"fcoe_get_interface\"",
")",
"conf... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 50.466667 |
cdeboever3/cdpybio | cdpybio/variants.py | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/variants.py#L32-L81 | def wasp_snp_directory(vcf, directory, sample_name=None):
"""
Convert VCF file into input for WASP. Only bi-allelic heterozygous sites are
used.
Parameters:
-----------
vcf : str
Path to VCF file.
directory : str
Output directory. This is the directory that will hold the fi... | [
"def",
"wasp_snp_directory",
"(",
"vcf",
",",
"directory",
",",
"sample_name",
"=",
"None",
")",
":",
"chrom",
"=",
"[",
"]",
"pos",
"=",
"[",
"]",
"ref",
"=",
"[",
"]",
"alt",
"=",
"[",
"]",
"vcf_reader",
"=",
"pyvcf",
".",
"Reader",
"(",
"open",
... | Convert VCF file into input for WASP. Only bi-allelic heterozygous sites are
used.
Parameters:
-----------
vcf : str
Path to VCF file.
directory : str
Output directory. This is the directory that will hold the files for
WASP.
sample_name : str
If provided, use ... | [
"Convert",
"VCF",
"file",
"into",
"input",
"for",
"WASP",
".",
"Only",
"bi",
"-",
"allelic",
"heterozygous",
"sites",
"are",
"used",
"."
] | python | train | 32.16 |
pyslackers/slack-sansio | slack/io/requests.py | https://github.com/pyslackers/slack-sansio/blob/068ddd6480c6d2f9bf14fa4db498c9fe1017f4ab/slack/io/requests.py#L159-L178 | def rtm( # type: ignore
self, url: Optional[str] = None, bot_id: Optional[str] = None
) -> Iterator[events.Event]:
"""
Iterate over event from the RTM API
Args:
url: Websocket connection url
bot_id: Connecting bot ID
Returns:
:class:`sla... | [
"def",
"rtm",
"(",
"# type: ignore",
"self",
",",
"url",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"bot_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Iterator",
"[",
"events",
".",
"Event",
"]",
":",
"while",
"True",
":"... | Iterate over event from the RTM API
Args:
url: Websocket connection url
bot_id: Connecting bot ID
Returns:
:class:`slack.events.Event` or :class:`slack.events.Message` | [
"Iterate",
"over",
"event",
"from",
"the",
"RTM",
"API"
] | python | train | 29.7 |
aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/connection.py#L295-L300 | def close(self):
"""Close socket connection"""
if self._writer:
self._writer.transport.close()
self._writer = None
self._reader = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_writer",
":",
"self",
".",
"_writer",
".",
"transport",
".",
"close",
"(",
")",
"self",
".",
"_writer",
"=",
"None",
"self",
".",
"_reader",
"=",
"None"
] | Close socket connection | [
"Close",
"socket",
"connection"
] | python | train | 28.833333 |
weld-project/weld | python/grizzly/grizzly/grizzly_impl.py | https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/grizzly_impl.py#L195-L247 | def pivot_filter(pivot_array, predicates, ty=None):
"""
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
... | [
"def",
"pivot_filter",
"(",
"pivot_array",
",",
"predicates",
",",
"ty",
"=",
"None",
")",
":",
"weld_obj",
"=",
"WeldObject",
"(",
"encoder_",
",",
"decoder_",
")",
"pivot_array_var",
"=",
"weld_obj",
".",
"update",
"(",
"pivot_array",
")",
"if",
"isinstanc... | Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
ty (WeldType): Type of each element in the input array
... | [
"Returns",
"a",
"new",
"array",
"with",
"each",
"element",
"in",
"the",
"original",
"array",
"satisfying",
"the",
"passed",
"-",
"in",
"predicate",
"set",
"to",
"new_value"
] | python | train | 28.396226 |
LonamiWebs/Telethon | telethon_examples/interactive_telegram_client.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_examples/interactive_telegram_client.py#L16-L23 | def sprint(string, *args, **kwargs):
"""Safe Print (handle UnicodeEncodeErrors on some terminals)"""
try:
print(string, *args, **kwargs)
except UnicodeEncodeError:
string = string.encode('utf-8', errors='ignore')\
.decode('ascii', errors='ignore')
print(string,... | [
"def",
"sprint",
"(",
"string",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"print",
"(",
"string",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"UnicodeEncodeError",
":",
"string",
"=",
"string",
".",
"encode",
"(... | Safe Print (handle UnicodeEncodeErrors on some terminals) | [
"Safe",
"Print",
"(",
"handle",
"UnicodeEncodeErrors",
"on",
"some",
"terminals",
")"
] | python | train | 41.25 |
spyder-ide/spyder | spyder/utils/qthelpers.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L44-L48 | def get_image_label(name, default="not_found.png"):
"""Return image inside a QLabel object"""
label = QLabel()
label.setPixmap(QPixmap(get_image_path(name, default)))
return label | [
"def",
"get_image_label",
"(",
"name",
",",
"default",
"=",
"\"not_found.png\"",
")",
":",
"label",
"=",
"QLabel",
"(",
")",
"label",
".",
"setPixmap",
"(",
"QPixmap",
"(",
"get_image_path",
"(",
"name",
",",
"default",
")",
")",
")",
"return",
"label"
] | Return image inside a QLabel object | [
"Return",
"image",
"inside",
"a",
"QLabel",
"object"
] | python | train | 39 |
SoCo/SoCo | soco/services.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/services.py#L786-L790 | def GetZoneGroupState(self, *args, **kwargs):
"""Overrides default handling to use the global shared zone group state
cache, unless another cache is specified."""
kwargs['cache'] = kwargs.get('cache', zone_group_state_shared_cache)
return self.send_command('GetZoneGroupState', *args, **k... | [
"def",
"GetZoneGroupState",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'cache'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'cache'",
",",
"zone_group_state_shared_cache",
")",
"return",
"self",
".",
"send_command",
"(",
... | Overrides default handling to use the global shared zone group state
cache, unless another cache is specified. | [
"Overrides",
"default",
"handling",
"to",
"use",
"the",
"global",
"shared",
"zone",
"group",
"state",
"cache",
"unless",
"another",
"cache",
"is",
"specified",
"."
] | python | train | 64.4 |
tomduck/pandoc-eqnos | pandoc_eqnos.py | https://github.com/tomduck/pandoc-eqnos/blob/a0e2b5684d2024ea96049ed2cff3acf4ab47c541/pandoc_eqnos.py#L158-L208 | def process_equations(key, value, fmt, meta):
"""Processes the attributed equations."""
if key == 'Math' and len(value) == 3:
# Process the equation
eq = _process_equation(value, fmt)
# Get the attributes and label
attrs = eq['attrs']
label = attrs[0]
if eq['is... | [
"def",
"process_equations",
"(",
"key",
",",
"value",
",",
"fmt",
",",
"meta",
")",
":",
"if",
"key",
"==",
"'Math'",
"and",
"len",
"(",
"value",
")",
"==",
"3",
":",
"# Process the equation",
"eq",
"=",
"_process_equation",
"(",
"value",
",",
"fmt",
"... | Processes the attributed equations. | [
"Processes",
"the",
"attributed",
"equations",
"."
] | python | train | 44.745098 |
assemblerflow/flowcraft | flowcraft/templates/assembly_report.py | https://github.com/assemblerflow/flowcraft/blob/fc3f4bddded1efc76006600016dc71a06dd908c0/flowcraft/templates/assembly_report.py#L143-L181 | def _parse_assembly(self, assembly_file):
"""Parse an assembly file in fasta format.
This is a Fasta parsing method that populates the
:py:attr:`Assembly.contigs` attribute with data for each contig in the
assembly.
Parameters
----------
assembly_file : str
... | [
"def",
"_parse_assembly",
"(",
"self",
",",
"assembly_file",
")",
":",
"with",
"open",
"(",
"assembly_file",
")",
"as",
"fh",
":",
"header",
"=",
"None",
"logger",
".",
"debug",
"(",
"\"Starting iteration of assembly file: {}\"",
".",
"format",
"(",
"assembly_fi... | Parse an assembly file in fasta format.
This is a Fasta parsing method that populates the
:py:attr:`Assembly.contigs` attribute with data for each contig in the
assembly.
Parameters
----------
assembly_file : str
Path to the assembly fasta file. | [
"Parse",
"an",
"assembly",
"file",
"in",
"fasta",
"format",
"."
] | python | test | 31.384615 |
androguard/androguard | androguard/core/bytecodes/dvm.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/dvm.py#L2294-L2303 | def get_class_name(self):
"""
Return the class name of the field
:rtype: string
"""
if self.class_idx_value is None:
self.class_idx_value = self.CM.get_type(self.class_idx)
return self.class_idx_value | [
"def",
"get_class_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"class_idx_value",
"is",
"None",
":",
"self",
".",
"class_idx_value",
"=",
"self",
".",
"CM",
".",
"get_type",
"(",
"self",
".",
"class_idx",
")",
"return",
"self",
".",
"class_idx_value"
] | Return the class name of the field
:rtype: string | [
"Return",
"the",
"class",
"name",
"of",
"the",
"field"
] | python | train | 25.3 |
RedHatInsights/insights-core | insights/client/mount.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/mount.py#L112-L118 | def _get_fs(thin_pathname):
"""
Returns the file system type (xfs, ext4) of a given device
"""
cmd = ['lsblk', '-o', 'FSTYPE', '-n', thin_pathname]
fs_return = util.subp(cmd)
return fs_return.stdout.strip() | [
"def",
"_get_fs",
"(",
"thin_pathname",
")",
":",
"cmd",
"=",
"[",
"'lsblk'",
",",
"'-o'",
",",
"'FSTYPE'",
",",
"'-n'",
",",
"thin_pathname",
"]",
"fs_return",
"=",
"util",
".",
"subp",
"(",
"cmd",
")",
"return",
"fs_return",
".",
"stdout",
".",
"stri... | Returns the file system type (xfs, ext4) of a given device | [
"Returns",
"the",
"file",
"system",
"type",
"(",
"xfs",
"ext4",
")",
"of",
"a",
"given",
"device"
] | python | train | 35.428571 |
hamelsmu/ktext | ktext/preprocess.py | https://github.com/hamelsmu/ktext/blob/221f09f5b1762705075fd1bd914881c0724d5e02/ktext/preprocess.py#L60-L78 | def apply_parallel(func: Callable,
data: List[Any],
cpu_cores: int = None) -> List[Any]:
"""
Apply function to list of elements.
Automatically determines the chunk size.
"""
if not cpu_cores:
cpu_cores = cpu_count()
try:
chunk_size = ceil(l... | [
"def",
"apply_parallel",
"(",
"func",
":",
"Callable",
",",
"data",
":",
"List",
"[",
"Any",
"]",
",",
"cpu_cores",
":",
"int",
"=",
"None",
")",
"->",
"List",
"[",
"Any",
"]",
":",
"if",
"not",
"cpu_cores",
":",
"cpu_cores",
"=",
"cpu_count",
"(",
... | Apply function to list of elements.
Automatically determines the chunk size. | [
"Apply",
"function",
"to",
"list",
"of",
"elements",
"."
] | python | test | 27.473684 |
shad7/tvrenamer | tasks.py | https://github.com/shad7/tvrenamer/blob/7fb59cb02669357e73b7acb92dcb6d74fdff4654/tasks.py#L220-L234 | def clean(all=False, docs=False, dist=False, extra=None):
"""Clean up build files"""
run('find . -type f -name "*.py[co]" -delete')
run('find . -type d -name "__pycache__" -delete')
patterns = ['build', '*.egg-info/']
if all or docs:
patterns.append('doc/build/*')
if all or dist:
... | [
"def",
"clean",
"(",
"all",
"=",
"False",
",",
"docs",
"=",
"False",
",",
"dist",
"=",
"False",
",",
"extra",
"=",
"None",
")",
":",
"run",
"(",
"'find . -type f -name \"*.py[co]\" -delete'",
")",
"run",
"(",
"'find . -type d -name \"__pycache__\" -delete'",
")"... | Clean up build files | [
"Clean",
"up",
"build",
"files"
] | python | train | 29.8 |
pybel/pybel | src/pybel/parser/parse_bel.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L720-L741 | def _add_qualified_edge(self, u, v, relation, annotations, subject_modifier, object_modifier) -> str:
"""Add an edge, then adds the opposite direction edge if it should."""
sha512 = self._add_qualified_edge_helper(
u,
v,
relation=relation,
annotations=anno... | [
"def",
"_add_qualified_edge",
"(",
"self",
",",
"u",
",",
"v",
",",
"relation",
",",
"annotations",
",",
"subject_modifier",
",",
"object_modifier",
")",
"->",
"str",
":",
"sha512",
"=",
"self",
".",
"_add_qualified_edge_helper",
"(",
"u",
",",
"v",
",",
"... | Add an edge, then adds the opposite direction edge if it should. | [
"Add",
"an",
"edge",
"then",
"adds",
"the",
"opposite",
"direction",
"edge",
"if",
"it",
"should",
"."
] | python | train | 34 |
genialis/resolwe | resolwe/flow/signals.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/signals.py#L48-L61 | def delete_relation(sender, instance, **kwargs):
"""Delete the Relation object when the last Entity is removed."""
def process_signal(relation_id):
"""Get the relation and delete it if it has no entities left."""
try:
relation = Relation.objects.get(pk=relation_id)
except Rel... | [
"def",
"delete_relation",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"process_signal",
"(",
"relation_id",
")",
":",
"\"\"\"Get the relation and delete it if it has no entities left.\"\"\"",
"try",
":",
"relation",
"=",
"Relation",
".",
... | Delete the Relation object when the last Entity is removed. | [
"Delete",
"the",
"Relation",
"object",
"when",
"the",
"last",
"Entity",
"is",
"removed",
"."
] | python | train | 38.214286 |
googleapis/google-cloud-python | oslogin/google/cloud/oslogin_v1/gapic/os_login_service_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/oslogin/google/cloud/oslogin_v1/gapic/os_login_service_client.py#L195-L248 | def delete_posix_account(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a POSIX account.
Example:
>>> from google.cloud import oslogin_v1
... | [
"def",
"delete_posix_account",
"(",
"self",
",",
"name",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"m... | Deletes a POSIX account.
Example:
>>> from google.cloud import oslogin_v1
>>>
>>> client = oslogin_v1.OsLoginServiceClient()
>>>
>>> name = client.project_path('[USER]', '[PROJECT]')
>>>
>>> client.delete_posix_account(name)
... | [
"Deletes",
"a",
"POSIX",
"account",
"."
] | python | train | 44.166667 |
franciscogarate/pyliferisk | pyliferisk/__init__.py | https://github.com/franciscogarate/pyliferisk/blob/8d906bed04df1ba00fa1cacc6f31030ce5ab6233/pyliferisk/__init__.py#L272-L279 | def Mx(mt, x):
""" Return the Mx """
n = len(mt.Cx)
sum1 = 0
for j in range(x, n):
k = mt.Cx[j]
sum1 += k
return sum1 | [
"def",
"Mx",
"(",
"mt",
",",
"x",
")",
":",
"n",
"=",
"len",
"(",
"mt",
".",
"Cx",
")",
"sum1",
"=",
"0",
"for",
"j",
"in",
"range",
"(",
"x",
",",
"n",
")",
":",
"k",
"=",
"mt",
".",
"Cx",
"[",
"j",
"]",
"sum1",
"+=",
"k",
"return",
... | Return the Mx | [
"Return",
"the",
"Mx"
] | python | train | 18.25 |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L604-L614 | def convert_relational(relational):
"""Convert all inequalities to >=0 form.
"""
rel = relational.rel_op
if rel in ['==', '>=', '>']:
return relational.lhs-relational.rhs
elif rel in ['<=', '<']:
return relational.rhs-relational.lhs
else:
raise Exception("The relational o... | [
"def",
"convert_relational",
"(",
"relational",
")",
":",
"rel",
"=",
"relational",
".",
"rel_op",
"if",
"rel",
"in",
"[",
"'=='",
",",
"'>='",
",",
"'>'",
"]",
":",
"return",
"relational",
".",
"lhs",
"-",
"relational",
".",
"rhs",
"elif",
"rel",
"in"... | Convert all inequalities to >=0 form. | [
"Convert",
"all",
"inequalities",
"to",
">",
"=",
"0",
"form",
"."
] | python | train | 34.454545 |
pandas-dev/pandas | pandas/core/frame.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L3659-L3708 | def lookup(self, row_labels, col_labels):
"""
Label-based "fancy indexing" function for DataFrame.
Given equal-length arrays of row and column labels, return an
array of the values corresponding to each (row, col) pair.
Parameters
----------
row_labels : sequenc... | [
"def",
"lookup",
"(",
"self",
",",
"row_labels",
",",
"col_labels",
")",
":",
"n",
"=",
"len",
"(",
"row_labels",
")",
"if",
"n",
"!=",
"len",
"(",
"col_labels",
")",
":",
"raise",
"ValueError",
"(",
"'Row labels must have same size as column labels'",
")",
... | Label-based "fancy indexing" function for DataFrame.
Given equal-length arrays of row and column labels, return an
array of the values corresponding to each (row, col) pair.
Parameters
----------
row_labels : sequence
The row labels to use for lookup
col_lab... | [
"Label",
"-",
"based",
"fancy",
"indexing",
"function",
"for",
"DataFrame",
"."
] | python | train | 32.44 |
tornadoweb/tornado | demos/blog/blog.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/demos/blog/blog.py#L99-L112 | async def query(self, stmt, *args):
"""Query for a list of results.
Typical usage::
results = await self.query(...)
Or::
for row in await self.query(...)
"""
with (await self.application.db.cursor()) as cur:
await cur.execute(stmt, args)
... | [
"async",
"def",
"query",
"(",
"self",
",",
"stmt",
",",
"*",
"args",
")",
":",
"with",
"(",
"await",
"self",
".",
"application",
".",
"db",
".",
"cursor",
"(",
")",
")",
"as",
"cur",
":",
"await",
"cur",
".",
"execute",
"(",
"stmt",
",",
"args",
... | Query for a list of results.
Typical usage::
results = await self.query(...)
Or::
for row in await self.query(...) | [
"Query",
"for",
"a",
"list",
"of",
"results",
"."
] | python | train | 27.357143 |
EwilDawe/typy | typy/keyboard.py | https://github.com/EwilDawe/typy/blob/0349e7176567a4dbef318e75d9b3d6868950a1a9/typy/keyboard.py#L11-L21 | def press(*keys):
"""
Simulates a key-press for all the keys passed to the function
:param keys: list of keys to be pressed
:return: None
"""
for key in keys:
win32api.keybd_event(codes[key], 0, 0, 0)
release(key) | [
"def",
"press",
"(",
"*",
"keys",
")",
":",
"for",
"key",
"in",
"keys",
":",
"win32api",
".",
"keybd_event",
"(",
"codes",
"[",
"key",
"]",
",",
"0",
",",
"0",
",",
"0",
")",
"release",
"(",
"key",
")"
] | Simulates a key-press for all the keys passed to the function
:param keys: list of keys to be pressed
:return: None | [
"Simulates",
"a",
"key",
"-",
"press",
"for",
"all",
"the",
"keys",
"passed",
"to",
"the",
"function"
] | python | train | 22.272727 |
DLR-RM/RAFCON | source/rafcon/gui/models/container_state.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/container_state.py#L100-L104 | def _load_transition_models(self):
""" Adds models for each transition of the state """
self.transitions = []
for transition in self.state.transitions.values():
self._add_model(self.transitions, transition, TransitionModel) | [
"def",
"_load_transition_models",
"(",
"self",
")",
":",
"self",
".",
"transitions",
"=",
"[",
"]",
"for",
"transition",
"in",
"self",
".",
"state",
".",
"transitions",
".",
"values",
"(",
")",
":",
"self",
".",
"_add_model",
"(",
"self",
".",
"transitio... | Adds models for each transition of the state | [
"Adds",
"models",
"for",
"each",
"transition",
"of",
"the",
"state"
] | python | train | 51 |
data61/clkhash | clkhash/cli.py | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/cli.py#L182-L202 | def create(server, name, project, apikey, output, threshold, verbose):
"""Create a new run on an entity matching server.
See entity matching service documentation for details on threshold.
Returns details for the created run.
"""
if verbose:
log("Entity Matching Server: {}".format(server))... | [
"def",
"create",
"(",
"server",
",",
"name",
",",
"project",
",",
"apikey",
",",
"output",
",",
"threshold",
",",
"verbose",
")",
":",
"if",
"verbose",
":",
"log",
"(",
"\"Entity Matching Server: {}\"",
".",
"format",
"(",
"server",
")",
")",
"if",
"thre... | Create a new run on an entity matching server.
See entity matching service documentation for details on threshold.
Returns details for the created run. | [
"Create",
"a",
"new",
"run",
"on",
"an",
"entity",
"matching",
"server",
"."
] | python | train | 31.190476 |
maxalbert/tohu | tohu/v2/custom_generator_NEW.py | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L129-L136 | def make_item_class_for_custom_generator_class(cls):
"""
cls:
The custom generator class for which to create an item-class
"""
clsname = cls.__tohu_items_name__
attr_names = cls.field_gens.keys()
return make_item_class(clsname, attr_names) | [
"def",
"make_item_class_for_custom_generator_class",
"(",
"cls",
")",
":",
"clsname",
"=",
"cls",
".",
"__tohu_items_name__",
"attr_names",
"=",
"cls",
".",
"field_gens",
".",
"keys",
"(",
")",
"return",
"make_item_class",
"(",
"clsname",
",",
"attr_names",
")"
] | cls:
The custom generator class for which to create an item-class | [
"cls",
":",
"The",
"custom",
"generator",
"class",
"for",
"which",
"to",
"create",
"an",
"item",
"-",
"class"
] | python | train | 33 |
neherlab/treetime | treetime/node_interpolator.py | https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/node_interpolator.py#L137-L155 | def _evaluate_convolution(t_val, f, g, n_integral = 100, inverse_time=None, return_log=False):
"""
Calculate convolution F(t) = int { f(tau)g(t-tau) } dtau
"""
FG = _convolution_integrand(t_val, f, g, inverse_time, return_log)
#integrate the interpolation object, return log, make neg_log
... | [
"def",
"_evaluate_convolution",
"(",
"t_val",
",",
"f",
",",
"g",
",",
"n_integral",
"=",
"100",
",",
"inverse_time",
"=",
"None",
",",
"return_log",
"=",
"False",
")",
":",
"FG",
"=",
"_convolution_integrand",
"(",
"t_val",
",",
"f",
",",
"g",
",",
"i... | Calculate convolution F(t) = int { f(tau)g(t-tau) } dtau | [
"Calculate",
"convolution",
"F",
"(",
"t",
")",
"=",
"int",
"{",
"f",
"(",
"tau",
")",
"g",
"(",
"t",
"-",
"tau",
")",
"}",
"dtau"
] | python | test | 37.842105 |
calmjs/calmjs | src/calmjs/toolchain.py | https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1225-L1244 | def compile_loaderplugin_entry(self, spec, entry):
"""
Generic loader plugin entry handler.
The default implementation assumes that everything up to the
first '!' symbol resolves to some known loader plugin within
the registry.
The registry instance responsible for the ... | [
"def",
"compile_loaderplugin_entry",
"(",
"self",
",",
"spec",
",",
"entry",
")",
":",
"modname",
",",
"source",
",",
"target",
",",
"modpath",
"=",
"entry",
"handler",
"=",
"spec",
"[",
"CALMJS_LOADERPLUGIN_REGISTRY",
"]",
".",
"get",
"(",
"modname",
")",
... | Generic loader plugin entry handler.
The default implementation assumes that everything up to the
first '!' symbol resolves to some known loader plugin within
the registry.
The registry instance responsible for the resolution of the
loader plugin handlers must be available in t... | [
"Generic",
"loader",
"plugin",
"entry",
"handler",
"."
] | python | train | 38.45 |
summa-tx/riemann | riemann/encoding/cashaddr.py | https://github.com/summa-tx/riemann/blob/04ae336dfd4007ceaed748daadc91cc32fa278ec/riemann/encoding/cashaddr.py#L48-L66 | def decode(data):
'''
str -> bytes
'''
if riemann.network.CASHADDR_PREFIX is None:
raise ValueError('Network {} does not support cashaddresses.'
.format(riemann.get_current_network_name()))
if data.find(riemann.network.CASHADDR_PREFIX) != 0:
raise ValueError(... | [
"def",
"decode",
"(",
"data",
")",
":",
"if",
"riemann",
".",
"network",
".",
"CASHADDR_PREFIX",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Network {} does not support cashaddresses.'",
".",
"format",
"(",
"riemann",
".",
"get_current_network_name",
"(",
")"... | str -> bytes | [
"str",
"-",
">",
"bytes"
] | python | train | 36.947368 |
sony/nnabla | python/src/nnabla/utils/learning_rate_scheduler.py | https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/learning_rate_scheduler.py#L118-L129 | def get_learning_rate(self, iter):
'''
Get learning rate with exponential decay based on current iteration.
Args:
iter (int): Current iteration (starting with 0).
Returns:
float: Learning rate
'''
return self.init_lr * (self.gamma ** (iter // se... | [
"def",
"get_learning_rate",
"(",
"self",
",",
"iter",
")",
":",
"return",
"self",
".",
"init_lr",
"*",
"(",
"self",
".",
"gamma",
"**",
"(",
"iter",
"//",
"self",
".",
"iter_interval",
")",
")"
] | Get learning rate with exponential decay based on current iteration.
Args:
iter (int): Current iteration (starting with 0).
Returns:
float: Learning rate | [
"Get",
"learning",
"rate",
"with",
"exponential",
"decay",
"based",
"on",
"current",
"iteration",
"."
] | python | train | 27.25 |
cimatosa/progression | progression/progress.py | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L608-L638 | def _show_stat_wrapper_multi_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat_function, len_,
add_args, lock, info_line, no_move_up=False):
"""
call the static method s... | [
"def",
"_show_stat_wrapper_multi_Progress",
"(",
"count",
",",
"last_count",
",",
"start_time",
",",
"max_count",
",",
"speed_calc_cycles",
",",
"width",
",",
"q",
",",
"last_speed",
",",
"prepend",
",",
"show_stat_function",
",",
"len_",
",",
"add_args",
",",
"... | call the static method show_stat_wrapper for each process | [
"call",
"the",
"static",
"method",
"show_stat_wrapper",
"for",
"each",
"process"
] | python | train | 44.548387 |
asweigart/pyautogui | pyautogui/__init__.py | https://github.com/asweigart/pyautogui/blob/77524bd47334a89024013fd48e05151c3ac9289a/pyautogui/__init__.py#L778-L827 | def dragRel(xOffset=0, yOffset=0, duration=0.0, tween=linear, button='left', pause=None, _pause=True, mouseDownUp=True):
"""Performs a mouse drag (mouse movement while a button is held down) to a
point on the screen, relative to its current position.
The x and y parameters detail where the mouse event happ... | [
"def",
"dragRel",
"(",
"xOffset",
"=",
"0",
",",
"yOffset",
"=",
"0",
",",
"duration",
"=",
"0.0",
",",
"tween",
"=",
"linear",
",",
"button",
"=",
"'left'",
",",
"pause",
"=",
"None",
",",
"_pause",
"=",
"True",
",",
"mouseDownUp",
"=",
"True",
")... | Performs a mouse drag (mouse movement while a button is held down) to a
point on the screen, relative to its current position.
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. If
outside the boundaries of the... | [
"Performs",
"a",
"mouse",
"drag",
"(",
"mouse",
"movement",
"while",
"a",
"button",
"is",
"held",
"down",
")",
"to",
"a",
"point",
"on",
"the",
"screen",
"relative",
"to",
"its",
"current",
"position",
"."
] | python | train | 42.18 |
dpkp/kafka-python | kafka/client_async.py | https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/client_async.py#L772-L827 | def _maybe_refresh_metadata(self, wakeup=False):
"""Send a metadata request if needed.
Returns:
int: milliseconds until next refresh
"""
ttl = self.cluster.ttl()
wait_for_in_progress_ms = self.config['request_timeout_ms'] if self._metadata_refresh_in_progress else 0
... | [
"def",
"_maybe_refresh_metadata",
"(",
"self",
",",
"wakeup",
"=",
"False",
")",
":",
"ttl",
"=",
"self",
".",
"cluster",
".",
"ttl",
"(",
")",
"wait_for_in_progress_ms",
"=",
"self",
".",
"config",
"[",
"'request_timeout_ms'",
"]",
"if",
"self",
".",
"_me... | Send a metadata request if needed.
Returns:
int: milliseconds until next refresh | [
"Send",
"a",
"metadata",
"request",
"if",
"needed",
"."
] | python | train | 46.410714 |
knipknap/SpiffWorkflow | SpiffWorkflow/serializer/xml.py | https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/xml.py#L211-L224 | def serialize_operator_not_equal(self, op):
"""
Serializer for :meth:`SpiffWorkflow.operators.NotEqual`.
Example::
<not-equals>
<value>text</value>
<value><attribute>foobar</attribute></value>
<value><path>foobar</path></value>
... | [
"def",
"serialize_operator_not_equal",
"(",
"self",
",",
"op",
")",
":",
"elem",
"=",
"etree",
".",
"Element",
"(",
"'not-equals'",
")",
"return",
"self",
".",
"serialize_value_list",
"(",
"elem",
",",
"op",
".",
"args",
")"
] | Serializer for :meth:`SpiffWorkflow.operators.NotEqual`.
Example::
<not-equals>
<value>text</value>
<value><attribute>foobar</attribute></value>
<value><path>foobar</path></value>
</not-equals> | [
"Serializer",
"for",
":",
"meth",
":",
"SpiffWorkflow",
".",
"operators",
".",
"NotEqual",
"."
] | python | valid | 31.214286 |
edoburu/sphinxcontrib-django | sphinxcontrib_django/docstrings.py | https://github.com/edoburu/sphinxcontrib-django/blob/5116ac7f1510a76b1ff58cf7f8d2fab7d8bbe2a9/sphinxcontrib_django/docstrings.py#L113-L118 | def _improve_class_docs(app, cls, lines):
"""Improve the documentation of a class."""
if issubclass(cls, models.Model):
_add_model_fields_as_params(app, cls, lines)
elif issubclass(cls, forms.Form):
_add_form_fields(cls, lines) | [
"def",
"_improve_class_docs",
"(",
"app",
",",
"cls",
",",
"lines",
")",
":",
"if",
"issubclass",
"(",
"cls",
",",
"models",
".",
"Model",
")",
":",
"_add_model_fields_as_params",
"(",
"app",
",",
"cls",
",",
"lines",
")",
"elif",
"issubclass",
"(",
"cls... | Improve the documentation of a class. | [
"Improve",
"the",
"documentation",
"of",
"a",
"class",
"."
] | python | train | 41.666667 |
timstaley/voevent-parse | src/voeventparse/voevent.py | https://github.com/timstaley/voevent-parse/blob/58fc1eb3af5eca23d9e819c727204950615402a7/src/voeventparse/voevent.py#L228-L252 | def set_author(voevent, title=None, shortName=None, logoURL=None,
contactName=None, contactEmail=None, contactPhone=None,
contributor=None):
"""For setting fields in the detailed author description.
This can optionally be neglected if a well defined AuthorIVORN is supplied.
.... | [
"def",
"set_author",
"(",
"voevent",
",",
"title",
"=",
"None",
",",
"shortName",
"=",
"None",
",",
"logoURL",
"=",
"None",
",",
"contactName",
"=",
"None",
",",
"contactEmail",
"=",
"None",
",",
"contactPhone",
"=",
"None",
",",
"contributor",
"=",
"Non... | For setting fields in the detailed author description.
This can optionally be neglected if a well defined AuthorIVORN is supplied.
.. note:: Unusually for this library,
the args here use CamelCase naming convention,
since there's a direct mapping to the ``Author.*``
attributes to which... | [
"For",
"setting",
"fields",
"in",
"the",
"detailed",
"author",
"description",
"."
] | python | train | 41.84 |
wummel/linkchecker | linkcheck/plugins/viruscheck.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/plugins/viruscheck.py#L86-L110 | def new_scansock (self):
"""Return a connected socket for sending scan data to it."""
port = None
try:
self.sock.sendall("STREAM")
port = None
for dummy in range(60):
data = self.sock.recv(self.sock_rcvbuf)
i = data.find("PORT")... | [
"def",
"new_scansock",
"(",
"self",
")",
":",
"port",
"=",
"None",
"try",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"\"STREAM\"",
")",
"port",
"=",
"None",
"for",
"dummy",
"in",
"range",
"(",
"60",
")",
":",
"data",
"=",
"self",
".",
"sock",
... | Return a connected socket for sending scan data to it. | [
"Return",
"a",
"connected",
"socket",
"for",
"sending",
"scan",
"data",
"to",
"it",
"."
] | python | train | 33.56 |
doakey3/DashTable | dashtable/html2data/restructify/process_tag.py | https://github.com/doakey3/DashTable/blob/744cfb6a717fa75a8092c83ebcd49b2668023681/dashtable/html2data/restructify/process_tag.py#L13-L36 | def process_tag(node):
"""
Recursively go through a tag's children, converting them, then
convert the tag itself.
"""
text = ''
exceptions = ['table']
for element in node.children:
if isinstance(element, NavigableString):
text += element
elif not node.name in e... | [
"def",
"process_tag",
"(",
"node",
")",
":",
"text",
"=",
"''",
"exceptions",
"=",
"[",
"'table'",
"]",
"for",
"element",
"in",
"node",
".",
"children",
":",
"if",
"isinstance",
"(",
"element",
",",
"NavigableString",
")",
":",
"text",
"+=",
"element",
... | Recursively go through a tag's children, converting them, then
convert the tag itself. | [
"Recursively",
"go",
"through",
"a",
"tag",
"s",
"children",
"converting",
"them",
"then",
"convert",
"the",
"tag",
"itself",
"."
] | python | train | 21.375 |
EmbodiedCognition/py-c3d | c3d.py | https://github.com/EmbodiedCognition/py-c3d/blob/391493d9cb4c6b4aaeee4de2930685e3a67f5845/c3d.py#L447-L465 | def write(self, group_id, handle):
'''Write this parameter group, with parameters, to a file handle.
Parameters
----------
group_id : int
The numerical ID of the group.
handle : file handle
An open, writable, binary file handle.
'''
name =... | [
"def",
"write",
"(",
"self",
",",
"group_id",
",",
"handle",
")",
":",
"name",
"=",
"self",
".",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
"desc",
"=",
"self",
".",
"desc",
".",
"encode",
"(",
"'utf-8'",
")",
"handle",
".",
"write",
"(",
"struct"... | Write this parameter group, with parameters, to a file handle.
Parameters
----------
group_id : int
The numerical ID of the group.
handle : file handle
An open, writable, binary file handle. | [
"Write",
"this",
"parameter",
"group",
"with",
"parameters",
"to",
"a",
"file",
"handle",
"."
] | python | train | 35.526316 |
coleifer/walrus | walrus/cache.py | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/cache.py#L82-L85 | def delete(self, key):
"""Remove the given key from the cache."""
if not self.debug:
self.database.delete(self.make_key(key)) | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"self",
".",
"debug",
":",
"self",
".",
"database",
".",
"delete",
"(",
"self",
".",
"make_key",
"(",
"key",
")",
")"
] | Remove the given key from the cache. | [
"Remove",
"the",
"given",
"key",
"from",
"the",
"cache",
"."
] | python | train | 37.5 |
msmbuilder/msmbuilder | msmbuilder/preprocessing/base.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/preprocessing/base.py#L146-L160 | def fit(self, X, y=None):
"""Fit Preprocessing to X.
Parameters
----------
sequence : array-like, [sequence_length, n_features]
A multivariate timeseries.
y : None
Ignored
Returns
-------
self
"""
return self.parti... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"return",
"self",
".",
"partial_fit",
"(",
"np",
".",
"concatenate",
"(",
"X",
",",
"axis",
"=",
"0",
")",
")"
] | Fit Preprocessing to X.
Parameters
----------
sequence : array-like, [sequence_length, n_features]
A multivariate timeseries.
y : None
Ignored
Returns
-------
self | [
"Fit",
"Preprocessing",
"to",
"X",
"."
] | python | train | 22.6 |
ANTsX/ANTsPy | ants/viz/plot.py | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/viz/plot.py#L127-L342 | def plot_grid(images, slices=None, axes=2,
# general figure arguments
figsize=1., rpad=0, cpad=0,
# title arguments
title=None, tfontsize=20, title_dx=0, title_dy=0,
# row arguments
rlabels=None, rfontsize=14, rfontcolor='white', rfacecolor='black',
# column arguments
clabels=None, cf... | [
"def",
"plot_grid",
"(",
"images",
",",
"slices",
"=",
"None",
",",
"axes",
"=",
"2",
",",
"# general figure arguments",
"figsize",
"=",
"1.",
",",
"rpad",
"=",
"0",
",",
"cpad",
"=",
"0",
",",
"# title arguments",
"title",
"=",
"None",
",",
"tfontsize",... | Plot a collection of images in an arbitrarily-defined grid
Matplotlib named colors: https://matplotlib.org/examples/color/named_colors.html
Arguments
---------
images : list of ANTsImage types
image(s) to plot.
if one image, this image will be used for all grid locations.
i... | [
"Plot",
"a",
"collection",
"of",
"images",
"in",
"an",
"arbitrarily",
"-",
"defined",
"grid",
"Matplotlib",
"named",
"colors",
":",
"https",
":",
"//",
"matplotlib",
".",
"org",
"/",
"examples",
"/",
"color",
"/",
"named_colors",
".",
"html"
] | python | train | 37.74537 |
ahmontero/dop | dop/client.py | https://github.com/ahmontero/dop/blob/40354ac6feefe92a7555fe2d1834138c9a03e518/dop/client.py#L630-L636 | def destroy_ssh_key(self, ssh_key_id):
"""
This method will delete the SSH key from your account.
"""
json = self.request('/ssh_keys/%s/destroy' % ssh_key_id, method='GET')
status = json.get('status')
return status | [
"def",
"destroy_ssh_key",
"(",
"self",
",",
"ssh_key_id",
")",
":",
"json",
"=",
"self",
".",
"request",
"(",
"'/ssh_keys/%s/destroy'",
"%",
"ssh_key_id",
",",
"method",
"=",
"'GET'",
")",
"status",
"=",
"json",
".",
"get",
"(",
"'status'",
")",
"return",
... | This method will delete the SSH key from your account. | [
"This",
"method",
"will",
"delete",
"the",
"SSH",
"key",
"from",
"your",
"account",
"."
] | python | train | 36.571429 |
pwaller/pyprof2calltree | pyprof2calltree.py | https://github.com/pwaller/pyprof2calltree/blob/62b99c7b366ad317d3d5e21fb73466c8baea670e/pyprof2calltree.py#L204-L211 | def output(self, out_file):
"""Write the converted entries to out_file"""
self.out_file = out_file
out_file.write('event: ns : Nanoseconds\n')
out_file.write('events: ns\n')
self._output_summary()
for entry in sorted(self.entries, key=_entry_sort_key):
self._o... | [
"def",
"output",
"(",
"self",
",",
"out_file",
")",
":",
"self",
".",
"out_file",
"=",
"out_file",
"out_file",
".",
"write",
"(",
"'event: ns : Nanoseconds\\n'",
")",
"out_file",
".",
"write",
"(",
"'events: ns\\n'",
")",
"self",
".",
"_output_summary",
"(",
... | Write the converted entries to out_file | [
"Write",
"the",
"converted",
"entries",
"to",
"out_file"
] | python | train | 41.375 |
mozilla/crontabber | crontabber/app.py | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L264-L286 | def items(self):
"""return all the app_names and their values as tuples"""
sql = """
SELECT
app_name,
next_run,
first_run,
last_run,
last_success,
depends_on,
error_count,
... | [
"def",
"items",
"(",
"self",
")",
":",
"sql",
"=",
"\"\"\"\n SELECT\n app_name,\n next_run,\n first_run,\n last_run,\n last_success,\n depends_on,\n error_count,\n last_... | return all the app_names and their values as tuples | [
"return",
"all",
"the",
"app_names",
"and",
"their",
"values",
"as",
"tuples"
] | python | train | 32 |
f3at/feat | src/feat/agents/base/agent.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/agents/base/agent.py#L363-L380 | def substitute_partner(self, state, partners_recp, recp, alloc_id):
'''
Establish the partnership to recp and, when it is successfull
remove partner with recipient partners_recp.
Use with caution: The partner which we are removing is not notified
in any way, so he still keeps li... | [
"def",
"substitute_partner",
"(",
"self",
",",
"state",
",",
"partners_recp",
",",
"recp",
",",
"alloc_id",
")",
":",
"partner",
"=",
"state",
".",
"partners",
".",
"find",
"(",
"recipient",
".",
"IRecipient",
"(",
"partners_recp",
")",
")",
"if",
"not",
... | Establish the partnership to recp and, when it is successfull
remove partner with recipient partners_recp.
Use with caution: The partner which we are removing is not notified
in any way, so he still keeps link in his description. The correct
usage of this method requires calling it from... | [
"Establish",
"the",
"partnership",
"to",
"recp",
"and",
"when",
"it",
"is",
"successfull",
"remove",
"partner",
"with",
"recipient",
"partners_recp",
"."
] | python | train | 48.777778 |
cloudmesh-cmd3/cmd3 | cmd3/plugins/info.py | https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/info.py#L22-L42 | def do_info(self, arg, arguments):
"""
::
Usage:
info [--all]
Options:
--all -a more extensive information
Prints some internal information about the shell
"""
if arguments["--all"]:
Console.ok(... | [
"def",
"do_info",
"(",
"self",
",",
"arg",
",",
"arguments",
")",
":",
"if",
"arguments",
"[",
"\"--all\"",
"]",
":",
"Console",
".",
"ok",
"(",
"70",
"*",
"\"-\"",
")",
"Console",
".",
"ok",
"(",
"'DIR'",
")",
"Console",
".",
"ok",
"(",
"70",
"*... | ::
Usage:
info [--all]
Options:
--all -a more extensive information
Prints some internal information about the shell | [
"::"
] | python | train | 24.285714 |
mfcloud/python-zvm-sdk | zvmsdk/smtclient.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L346-L355 | def get_power_state(self, userid):
"""Get power status of a z/VM instance."""
LOG.debug('Querying power stat of %s' % userid)
requestData = "PowerVM " + userid + " status"
action = "query power state of '%s'" % userid
with zvmutils.log_and_reraise_smt_request_failed(action):
... | [
"def",
"get_power_state",
"(",
"self",
",",
"userid",
")",
":",
"LOG",
".",
"debug",
"(",
"'Querying power stat of %s'",
"%",
"userid",
")",
"requestData",
"=",
"\"PowerVM \"",
"+",
"userid",
"+",
"\" status\"",
"action",
"=",
"\"query power state of '%s'\"",
"%",... | Get power status of a z/VM instance. | [
"Get",
"power",
"status",
"of",
"a",
"z",
"/",
"VM",
"instance",
"."
] | python | train | 49.7 |
santoshphilip/eppy | eppy/hvacbuilder.py | https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/hvacbuilder.py#L72-L78 | def makepipecomponent(idf, pname):
"""make a pipe component
generate inlet outlet names"""
apipe = idf.newidfobject("Pipe:Adiabatic".upper(), Name=pname)
apipe.Inlet_Node_Name = "%s_inlet" % (pname,)
apipe.Outlet_Node_Name = "%s_outlet" % (pname,)
return apipe | [
"def",
"makepipecomponent",
"(",
"idf",
",",
"pname",
")",
":",
"apipe",
"=",
"idf",
".",
"newidfobject",
"(",
"\"Pipe:Adiabatic\"",
".",
"upper",
"(",
")",
",",
"Name",
"=",
"pname",
")",
"apipe",
".",
"Inlet_Node_Name",
"=",
"\"%s_inlet\"",
"%",
"(",
"... | make a pipe component
generate inlet outlet names | [
"make",
"a",
"pipe",
"component",
"generate",
"inlet",
"outlet",
"names"
] | python | train | 39.714286 |
python-wink/python-wink | src/pywink/devices/cloud_clock.py | https://github.com/python-wink/python-wink/blob/cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da/src/pywink/devices/cloud_clock.py#L183-L187 | def update_state(self):
""" Update state with latest info from Wink API. """
response = self.api_interface.get_device_state(self, id_override=self.parent_id(),
type_override=self.parent_object_type())
self._update_state_from_response(res... | [
"def",
"update_state",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"api_interface",
".",
"get_device_state",
"(",
"self",
",",
"id_override",
"=",
"self",
".",
"parent_id",
"(",
")",
",",
"type_override",
"=",
"self",
".",
"parent_object_type",
"(",... | Update state with latest info from Wink API. | [
"Update",
"state",
"with",
"latest",
"info",
"from",
"Wink",
"API",
"."
] | python | train | 64.4 |
saltstack/salt | salt/modules/postfix.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postfix.py#L284-L308 | def set_main(key, value, path=MAIN_CF):
'''
Set a single config value in the main.cf file. If the value does not already
exist, it will be appended to the end.
CLI Example:
salt <minion> postfix.set_main mailq_path /usr/bin/mailq
'''
pairs, conf_list = _parse_main(path)
new_conf =... | [
"def",
"set_main",
"(",
"key",
",",
"value",
",",
"path",
"=",
"MAIN_CF",
")",
":",
"pairs",
",",
"conf_list",
"=",
"_parse_main",
"(",
"path",
")",
"new_conf",
"=",
"[",
"]",
"key_line_match",
"=",
"re",
".",
"compile",
"(",
"\"^{0}([\\\\s=]|$)\"",
".",... | Set a single config value in the main.cf file. If the value does not already
exist, it will be appended to the end.
CLI Example:
salt <minion> postfix.set_main mailq_path /usr/bin/mailq | [
"Set",
"a",
"single",
"config",
"value",
"in",
"the",
"main",
".",
"cf",
"file",
".",
"If",
"the",
"value",
"does",
"not",
"already",
"exist",
"it",
"will",
"be",
"appended",
"to",
"the",
"end",
"."
] | python | train | 29.6 |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/process.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/process.py#L118-L152 | def update(self):
"""
Get virtual size of current process by reading the process' stat file.
This should work for Linux.
"""
try:
stat = open('/proc/self/stat')
status = open('/proc/self/status')
except IOError: # pragma: no cover
retur... | [
"def",
"update",
"(",
"self",
")",
":",
"try",
":",
"stat",
"=",
"open",
"(",
"'/proc/self/stat'",
")",
"status",
"=",
"open",
"(",
"'/proc/self/status'",
")",
"except",
"IOError",
":",
"# pragma: no cover",
"return",
"False",
"else",
":",
"stats",
"=",
"s... | Get virtual size of current process by reading the process' stat file.
This should work for Linux. | [
"Get",
"virtual",
"size",
"of",
"current",
"process",
"by",
"reading",
"the",
"process",
"stat",
"file",
".",
"This",
"should",
"work",
"for",
"Linux",
"."
] | python | train | 35.857143 |
razor-x/scipy-data_fitting | scipy_data_fitting/figure/plot.py | https://github.com/razor-x/scipy-data_fitting/blob/c756a645da8629699b3f22244bfb7d5d4d88b179/scipy_data_fitting/figure/plot.py#L88-L92 | def plot_fit(self):
"""
Add the fit to the plot.
"""
self.plt.plot(*self.fit.fit, **self.options['fit']) | [
"def",
"plot_fit",
"(",
"self",
")",
":",
"self",
".",
"plt",
".",
"plot",
"(",
"*",
"self",
".",
"fit",
".",
"fit",
",",
"*",
"*",
"self",
".",
"options",
"[",
"'fit'",
"]",
")"
] | Add the fit to the plot. | [
"Add",
"the",
"fit",
"to",
"the",
"plot",
"."
] | python | train | 26.4 |
ereOn/azmq | azmq/multiplexer.py | https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/multiplexer.py#L41-L72 | async def recv_multipart(self):
"""
Read from all the associated sockets.
:returns: A list of tuples (socket, frames) for each socket that
returned a result.
"""
if not self._sockets:
return []
results = []
async def recv_and_store(socke... | [
"async",
"def",
"recv_multipart",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_sockets",
":",
"return",
"[",
"]",
"results",
"=",
"[",
"]",
"async",
"def",
"recv_and_store",
"(",
"socket",
")",
":",
"frames",
"=",
"await",
"socket",
".",
"recv_mu... | Read from all the associated sockets.
:returns: A list of tuples (socket, frames) for each socket that
returned a result. | [
"Read",
"from",
"all",
"the",
"associated",
"sockets",
"."
] | python | train | 25.03125 |
Qiskit/qiskit-terra | qiskit/quantum_info/operators/channel/transformations.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/transformations.py#L61-L72 | def _to_kraus(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Kraus representation."""
if rep == 'Kraus':
return data
if rep == 'Stinespring':
return _stinespring_to_kraus(data, input_dim, output_dim)
if rep == 'Operator':
return _from_operator('Kraus', da... | [
"def",
"_to_kraus",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"if",
"rep",
"==",
"'Kraus'",
":",
"return",
"data",
"if",
"rep",
"==",
"'Stinespring'",
":",
"return",
"_stinespring_to_kraus",
"(",
"data",
",",
"input_dim",
",",... | Transform a QuantumChannel to the Kraus representation. | [
"Transform",
"a",
"QuantumChannel",
"to",
"the",
"Kraus",
"representation",
"."
] | python | test | 41.916667 |
limpyd/redis-limpyd | limpyd/model.py | https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/model.py#L278-L289 | def get_class_field(cls, field_name):
"""
Return the field object with the given name (for the class, the fields
are in the "_redis_attr_%s" form)
"""
if not cls.has_field(field_name):
raise AttributeError('"%s" is not a field for the model "%s"' %
... | [
"def",
"get_class_field",
"(",
"cls",
",",
"field_name",
")",
":",
"if",
"not",
"cls",
".",
"has_field",
"(",
"field_name",
")",
":",
"raise",
"AttributeError",
"(",
"'\"%s\" is not a field for the model \"%s\"'",
"%",
"(",
"field_name",
",",
"cls",
".",
"__name... | Return the field object with the given name (for the class, the fields
are in the "_redis_attr_%s" form) | [
"Return",
"the",
"field",
"object",
"with",
"the",
"given",
"name",
"(",
"for",
"the",
"class",
"the",
"fields",
"are",
"in",
"the",
"_redis_attr_%s",
"form",
")"
] | python | train | 36.083333 |
inspirehep/refextract | refextract/references/text.py | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/text.py#L91-L142 | def get_reference_lines(docbody,
ref_sect_start_line,
ref_sect_end_line,
ref_sect_title,
ref_line_marker_ptn,
title_marker_same_line):
"""After the reference section of a document has been identif... | [
"def",
"get_reference_lines",
"(",
"docbody",
",",
"ref_sect_start_line",
",",
"ref_sect_end_line",
",",
"ref_sect_title",
",",
"ref_line_marker_ptn",
",",
"title_marker_same_line",
")",
":",
"start_idx",
"=",
"ref_sect_start_line",
"if",
"title_marker_same_line",
":",
"#... | After the reference section of a document has been identified, and the
first and last lines of the reference section have been recorded, this
function is called to take the reference lines out of the document body.
The document's reference lines are returned in a list of strings whereby
each... | [
"After",
"the",
"reference",
"section",
"of",
"a",
"document",
"has",
"been",
"identified",
"and",
"the",
"first",
"and",
"last",
"lines",
"of",
"the",
"reference",
"section",
"have",
"been",
"recorded",
"this",
"function",
"is",
"called",
"to",
"take",
"the... | python | train | 49.519231 |
StackStorm/pybind | pybind/slxos/v17s_1_02/routing_system/interface/ve/ipv6/ipv6_nd_ra/ipv6_intf_cmds/nd/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/routing_system/interface/ve/ipv6/ipv6_nd_ra/ipv6_intf_cmds/nd/__init__.py#L583-L604 | def _set_ra_dns_server(self, v, load=False):
"""
Setter method for ra_dns_server, mapped from YANG variable /routing_system/interface/ve/ipv6/ipv6_nd_ra/ipv6_intf_cmds/nd/ra_dns_server (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ra_dns_server is considered as ... | [
"def",
"_set_ra_dns_server",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | Setter method for ra_dns_server, mapped from YANG variable /routing_system/interface/ve/ipv6/ipv6_nd_ra/ipv6_intf_cmds/nd/ra_dns_server (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ra_dns_server is considered as a private
method. Backends looking to populate this v... | [
"Setter",
"method",
"for",
"ra_dns_server",
"mapped",
"from",
"YANG",
"variable",
"/",
"routing_system",
"/",
"interface",
"/",
"ve",
"/",
"ipv6",
"/",
"ipv6_nd_ra",
"/",
"ipv6_intf_cmds",
"/",
"nd",
"/",
"ra_dns_server",
"(",
"list",
")",
"If",
"this",
"var... | python | train | 124.818182 |
althonos/pronto | pronto/ontology.py | https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/ontology.py#L539-L558 | def obo(self):
"""str: the ontology serialized in obo format.
"""
meta = self._obo_meta()
meta = [meta] if meta else []
newline = "\n\n" if six.PY3 else "\n\n".encode('utf-8')
try: # if 'namespace' in self.meta:
return newline.join( meta + [
r... | [
"def",
"obo",
"(",
"self",
")",
":",
"meta",
"=",
"self",
".",
"_obo_meta",
"(",
")",
"meta",
"=",
"[",
"meta",
"]",
"if",
"meta",
"else",
"[",
"]",
"newline",
"=",
"\"\\n\\n\"",
"if",
"six",
".",
"PY3",
"else",
"\"\\n\\n\"",
".",
"encode",
"(",
... | str: the ontology serialized in obo format. | [
"str",
":",
"the",
"ontology",
"serialized",
"in",
"obo",
"format",
"."
] | python | train | 32.2 |
axialmarket/fsq | fsq/const.py | https://github.com/axialmarket/fsq/blob/43b84c292cb8a187599d86753b947cf73248f989/fsq/const.py#L31-L60 | def set_const(const, val):
'''Convenience wrapper to reliably set the value of a constant from
outside of package scope'''
try:
cur = getattr(_c, const)
except AttributeError:
raise FSQEnvError(errno.ENOENT, u'no such constant:'\
u' {0}'.format(const))
ex... | [
"def",
"set_const",
"(",
"const",
",",
"val",
")",
":",
"try",
":",
"cur",
"=",
"getattr",
"(",
"_c",
",",
"const",
")",
"except",
"AttributeError",
":",
"raise",
"FSQEnvError",
"(",
"errno",
".",
"ENOENT",
",",
"u'no such constant:'",
"u' {0}'",
".",
"f... | Convenience wrapper to reliably set the value of a constant from
outside of package scope | [
"Convenience",
"wrapper",
"to",
"reliably",
"set",
"the",
"value",
"of",
"a",
"constant",
"from",
"outside",
"of",
"package",
"scope"
] | python | train | 41.866667 |
hugapi/hug | hug/decorators.py | https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/decorators.py#L86-L95 | def context_factory(apply_globally=False, api=None):
"""A decorator that registers a single hug context factory"""
def decorator(context_factory_):
if apply_globally:
hug.defaults.context_factory = context_factory_
else:
apply_to_api = hug.API(api) if api else hug.api.fro... | [
"def",
"context_factory",
"(",
"apply_globally",
"=",
"False",
",",
"api",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"context_factory_",
")",
":",
"if",
"apply_globally",
":",
"hug",
".",
"defaults",
".",
"context_factory",
"=",
"context_factory_",
"else... | A decorator that registers a single hug context factory | [
"A",
"decorator",
"that",
"registers",
"a",
"single",
"hug",
"context",
"factory"
] | python | train | 45 |
cocaine/cocaine-framework-python | cocaine/detail/secadaptor.py | https://github.com/cocaine/cocaine-framework-python/blob/d8a30074b6338bac4389eb996e00d404338115e4/cocaine/detail/secadaptor.py#L54-L65 | def fetch_token(self):
"""Gains token from secure backend service.
:return: Token formatted for Cocaine protocol header.
"""
grant_type = 'client_credentials'
channel = yield self._tvm.ticket_full(
self._client_id, self._client_secret, grant_type, {})
ticket... | [
"def",
"fetch_token",
"(",
"self",
")",
":",
"grant_type",
"=",
"'client_credentials'",
"channel",
"=",
"yield",
"self",
".",
"_tvm",
".",
"ticket_full",
"(",
"self",
".",
"_client_id",
",",
"self",
".",
"_client_secret",
",",
"grant_type",
",",
"{",
"}",
... | Gains token from secure backend service.
:return: Token formatted for Cocaine protocol header. | [
"Gains",
"token",
"from",
"secure",
"backend",
"service",
"."
] | python | train | 32.166667 |
project-rig/rig | rig/geometry.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/geometry.py#L331-L371 | def spinn5_local_eth_coord(x, y, w, h, root_x=0, root_y=0):
"""Get the coordinates of a chip's local ethernet connected chip.
Returns the coordinates of the ethernet connected chip on the same board as
the supplied chip.
.. note::
This function assumes the system is constructed from SpiNN-5 bo... | [
"def",
"spinn5_local_eth_coord",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"root_x",
"=",
"0",
",",
"root_y",
"=",
"0",
")",
":",
"dx",
",",
"dy",
"=",
"SPINN5_ETH_OFFSET",
"[",
"(",
"y",
"-",
"root_y",
")",
"%",
"12",
"]",
"[",
"(",
"x",
... | Get the coordinates of a chip's local ethernet connected chip.
Returns the coordinates of the ethernet connected chip on the same board as
the supplied chip.
.. note::
This function assumes the system is constructed from SpiNN-5 boards
.. warning::
In general, applications should int... | [
"Get",
"the",
"coordinates",
"of",
"a",
"chip",
"s",
"local",
"ethernet",
"connected",
"chip",
"."
] | python | train | 39.195122 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/generate/commands.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/generate/commands.py#L501-L535 | def _writepydoc(doc, *args):
"""create pydoc html pages
doc -- destination directory for documents
*args -- modules run thru pydoc
"""
ok = True
if not os.path.isdir(doc):
os.makedirs(doc)
if os.path.curdir not in sys.path:
sys.path.append(os.path.curdir)
for f in a... | [
"def",
"_writepydoc",
"(",
"doc",
",",
"*",
"args",
")",
":",
"ok",
"=",
"True",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"doc",
")",
":",
"os",
".",
"makedirs",
"(",
"doc",
")",
"if",
"os",
".",
"path",
".",
"curdir",
"not",
"in",
... | create pydoc html pages
doc -- destination directory for documents
*args -- modules run thru pydoc | [
"create",
"pydoc",
"html",
"pages",
"doc",
"--",
"destination",
"directory",
"for",
"documents",
"*",
"args",
"--",
"modules",
"run",
"thru",
"pydoc"
] | python | train | 25.457143 |
consbio/ncdjango | ncdjango/geoprocessing/tasks/raster.py | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/tasks/raster.py#L82-L96 | def get_context(self, arr, expr, context):
"""
Returns a context dictionary for use in evaluating the expression.
:param arr: The input array.
:param expr: The input expression.
:param context: Evaluation context.
"""
expression_names = [x for x in self.get_expr... | [
"def",
"get_context",
"(",
"self",
",",
"arr",
",",
"expr",
",",
"context",
")",
":",
"expression_names",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"get_expression_names",
"(",
"expr",
")",
"if",
"x",
"not",
"in",
"set",
"(",
"context",
".",
"key... | Returns a context dictionary for use in evaluating the expression.
:param arr: The input array.
:param expr: The input expression.
:param context: Evaluation context. | [
"Returns",
"a",
"context",
"dictionary",
"for",
"use",
"in",
"evaluating",
"the",
"expression",
"."
] | python | train | 35.466667 |
mojaie/chorus | chorus/descriptor.py | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/descriptor.py#L53-L96 | def assign_aromatic(mol):
"""Assign aromatic ring
sp2 atom:
pi=1 -> +1
N, O, S, C- -> +2
>C=O, B, C+ -> 0
sp3 atom -> not aromatic
sum of the score satisfies 4n+2 -> aromatic
"""
mol.require("Valence")
mol.require("MinifiedRing")
for ring in mol.rings:
pi_cnt = 0
... | [
"def",
"assign_aromatic",
"(",
"mol",
")",
":",
"mol",
".",
"require",
"(",
"\"Valence\"",
")",
"mol",
".",
"require",
"(",
"\"MinifiedRing\"",
")",
"for",
"ring",
"in",
"mol",
".",
"rings",
":",
"pi_cnt",
"=",
"0",
"for",
"r",
"in",
"ring",
":",
"if... | Assign aromatic ring
sp2 atom:
pi=1 -> +1
N, O, S, C- -> +2
>C=O, B, C+ -> 0
sp3 atom -> not aromatic
sum of the score satisfies 4n+2 -> aromatic | [
"Assign",
"aromatic",
"ring",
"sp2",
"atom",
":",
"pi",
"=",
"1",
"-",
">",
"+",
"1",
"N",
"O",
"S",
"C",
"-",
"-",
">",
"+",
"2",
">",
"C",
"=",
"O",
"B",
"C",
"+",
"-",
">",
"0",
"sp3",
"atom",
"-",
">",
"not",
"aromatic",
"sum",
"of",
... | python | train | 31.318182 |
carpedm20/ndrive | ndrive/models.py | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/ndrive/models.py#L185-L220 | def login(self, user_id, password, svctype = "Android NDrive App ver", auth = 0):
"""Log in Naver and get cookie
Agrs:
user_id: Naver account's login id
password: Naver account's login password
Returns:
True: Login success
False: Login failed
... | [
"def",
"login",
"(",
"self",
",",
"user_id",
",",
"password",
",",
"svctype",
"=",
"\"Android NDrive App ver\"",
",",
"auth",
"=",
"0",
")",
":",
"self",
".",
"user_id",
"=",
"user_id",
"self",
".",
"password",
"=",
"password",
"if",
"self",
".",
"user_i... | Log in Naver and get cookie
Agrs:
user_id: Naver account's login id
password: Naver account's login password
Returns:
True: Login success
False: Login failed
Remarks:
self.cookie is a dictionary with 5 keys: path, domain, NID_AUT, ni... | [
"Log",
"in",
"Naver",
"and",
"get",
"cookie"
] | python | train | 29.277778 |
yyuu/botornado | boto/ec2/connection.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/ec2/connection.py#L352-L373 | def get_image_attribute(self, image_id, attribute='launchPermission'):
"""
Gets an attribute from an image.
:type image_id: string
:param image_id: The Amazon image id for which you want info about
:type attribute: string
:param attribute: The attribute you need informa... | [
"def",
"get_image_attribute",
"(",
"self",
",",
"image_id",
",",
"attribute",
"=",
"'launchPermission'",
")",
":",
"params",
"=",
"{",
"'ImageId'",
":",
"image_id",
",",
"'Attribute'",
":",
"attribute",
"}",
"return",
"self",
".",
"get_object",
"(",
"'Describe... | Gets an attribute from an image.
:type image_id: string
:param image_id: The Amazon image id for which you want info about
:type attribute: string
:param attribute: The attribute you need information about.
Valid choices are:
* launch... | [
"Gets",
"an",
"attribute",
"from",
"an",
"image",
"."
] | python | train | 39.681818 |
senaite/senaite.core | bika/lims/browser/widgets/reflexrulewidget.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/widgets/reflexrulewidget.py#L219-L232 | def _get_sorted_cond_keys(self, keys_list):
"""
This function returns only the elements starting with
'analysisservice-' in 'keys_list'. The returned list is sorted by the
index appended to the end of each element
"""
# The names can be found in reflexrulewidget.pt inside... | [
"def",
"_get_sorted_cond_keys",
"(",
"self",
",",
"keys_list",
")",
":",
"# The names can be found in reflexrulewidget.pt inside the",
"# conditionscontainer div.",
"cond_list",
"=",
"[",
"]",
"for",
"key",
"in",
"keys_list",
":",
"if",
"key",
".",
"startswith",
"(",
... | This function returns only the elements starting with
'analysisservice-' in 'keys_list'. The returned list is sorted by the
index appended to the end of each element | [
"This",
"function",
"returns",
"only",
"the",
"elements",
"starting",
"with",
"analysisservice",
"-",
"in",
"keys_list",
".",
"The",
"returned",
"list",
"is",
"sorted",
"by",
"the",
"index",
"appended",
"to",
"the",
"end",
"of",
"each",
"element"
] | python | train | 38.428571 |
rsheftel/raccoon | raccoon/series.py | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L170-L195 | def get_slice(self, start_index=None, stop_index=None, as_list=False):
"""
For sorted Series will return either a Series or list of all of the rows where the index is greater than
or equal to the start_index if provided and less than or equal to the stop_index if provided. If either the
... | [
"def",
"get_slice",
"(",
"self",
",",
"start_index",
"=",
"None",
",",
"stop_index",
"=",
"None",
",",
"as_list",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_sort",
":",
"raise",
"RuntimeError",
"(",
"'Can only use get_slice on sorted Series'",
")",
... | For sorted Series will return either a Series or list of all of the rows where the index is greater than
or equal to the start_index if provided and less than or equal to the stop_index if provided. If either the
start or stop index is None then will include from the first or last element, similar to st... | [
"For",
"sorted",
"Series",
"will",
"return",
"either",
"a",
"Series",
"or",
"list",
"of",
"all",
"of",
"the",
"rows",
"where",
"the",
"index",
"is",
"greater",
"than",
"or",
"equal",
"to",
"the",
"start_index",
"if",
"provided",
"and",
"less",
"than",
"o... | python | train | 55.346154 |
apache/spark | python/pyspark/sql/column.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/column.py#L81-L87 | def _unary_op(name, doc="unary operator"):
""" Create a method for given unary operator """
def _(self):
jc = getattr(self._jc, name)()
return Column(jc)
_.__doc__ = doc
return _ | [
"def",
"_unary_op",
"(",
"name",
",",
"doc",
"=",
"\"unary operator\"",
")",
":",
"def",
"_",
"(",
"self",
")",
":",
"jc",
"=",
"getattr",
"(",
"self",
".",
"_jc",
",",
"name",
")",
"(",
")",
"return",
"Column",
"(",
"jc",
")",
"_",
".",
"__doc__... | Create a method for given unary operator | [
"Create",
"a",
"method",
"for",
"given",
"unary",
"operator"
] | python | train | 29.142857 |
lemieuxl/pyGenClean | pyGenClean/LaTeX/auto_report.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/LaTeX/auto_report.py#L27-L181 | def create_report(outdirname, report_filename, **kwargs):
"""Creates a LaTeX report.
:param report_filename: the name of the file.
:param outdirname: the name of the output directory.
:type report_filename: str
:type outdirname: str
"""
# Checking the required variables
if "steps" in ... | [
"def",
"create_report",
"(",
"outdirname",
",",
"report_filename",
",",
"*",
"*",
"kwargs",
")",
":",
"# Checking the required variables",
"if",
"\"steps\"",
"in",
"kwargs",
":",
"assert",
"\"descriptions\"",
"in",
"kwargs",
"assert",
"\"long_descriptions\"",
"in",
... | Creates a LaTeX report.
:param report_filename: the name of the file.
:param outdirname: the name of the output directory.
:type report_filename: str
:type outdirname: str | [
"Creates",
"a",
"LaTeX",
"report",
"."
] | python | train | 38.341935 |
blockstack/blockstack-core | blockstack/lib/nameset/db.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L840-L854 | def namedb_namespace_fields_check( namespace_rec ):
"""
Given a namespace record, make sure the following fields are present:
* namespace_id
* buckets
Makes the record suitable for insertion/update.
NOTE: MODIFIES namespace_rec
"""
assert namespace_rec.has_key('namespace_id'), "BUG: na... | [
"def",
"namedb_namespace_fields_check",
"(",
"namespace_rec",
")",
":",
"assert",
"namespace_rec",
".",
"has_key",
"(",
"'namespace_id'",
")",
",",
"\"BUG: namespace record has no ID\"",
"assert",
"namespace_rec",
".",
"has_key",
"(",
"'buckets'",
")",
",",
"'BUG: missi... | Given a namespace record, make sure the following fields are present:
* namespace_id
* buckets
Makes the record suitable for insertion/update.
NOTE: MODIFIES namespace_rec | [
"Given",
"a",
"namespace",
"record",
"make",
"sure",
"the",
"following",
"fields",
"are",
"present",
":",
"*",
"namespace_id",
"*",
"buckets"
] | python | train | 35.466667 |
clinicedc/edc-notification | edc_notification/notification/notification.py | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/notification/notification.py#L256-L274 | def sms_recipients(self):
"""Returns a list of recipients subscribed to receive SMS's
for this "notifications" class.
See also: edc_auth.UserProfile.
"""
sms_recipients = []
UserProfile = django_apps.get_model("edc_auth.UserProfile")
for user_profile in UserProfi... | [
"def",
"sms_recipients",
"(",
"self",
")",
":",
"sms_recipients",
"=",
"[",
"]",
"UserProfile",
"=",
"django_apps",
".",
"get_model",
"(",
"\"edc_auth.UserProfile\"",
")",
"for",
"user_profile",
"in",
"UserProfile",
".",
"objects",
".",
"filter",
"(",
"user__is_... | Returns a list of recipients subscribed to receive SMS's
for this "notifications" class.
See also: edc_auth.UserProfile. | [
"Returns",
"a",
"list",
"of",
"recipients",
"subscribed",
"to",
"receive",
"SMS",
"s",
"for",
"this",
"notifications",
"class",
"."
] | python | train | 35.789474 |
eavanvalkenburg/brunt-api | brunt/brunt.py | https://github.com/eavanvalkenburg/brunt-api/blob/c6bae43f56e0fd8f79b7af67d524611dd104dafa/brunt/brunt.py#L121-L127 | def _is_logged_in(self):
""" Check whether or not the user is logged in. """
# if the user has not logged in in 24 hours, relogin
if not self._http._has_session() or datetime.utcnow() >= self._lastlogin + timedelta(hours=24):
return self._login()
else:
return {} | [
"def",
"_is_logged_in",
"(",
"self",
")",
":",
"# if the user has not logged in in 24 hours, relogin",
"if",
"not",
"self",
".",
"_http",
".",
"_has_session",
"(",
")",
"or",
"datetime",
".",
"utcnow",
"(",
")",
">=",
"self",
".",
"_lastlogin",
"+",
"timedelta",... | Check whether or not the user is logged in. | [
"Check",
"whether",
"or",
"not",
"the",
"user",
"is",
"logged",
"in",
"."
] | python | train | 44.571429 |
ipython/ipynb | ipynb/utils.py | https://github.com/ipython/ipynb/blob/2f1526a447104d7d7b97e2a8ab66bee8d2da90ad/ipynb/utils.py#L43-L70 | def filter_ast(module_ast):
"""
Filters a given module ast, removing non-whitelisted nodes
It allows only the following top level items:
- imports
- function definitions
- class definitions
- top level assignments where all the targets on the LHS are all caps
"""
def node_predic... | [
"def",
"filter_ast",
"(",
"module_ast",
")",
":",
"def",
"node_predicate",
"(",
"node",
")",
":",
"\"\"\"\n Return true if given node is whitelisted\n \"\"\"",
"for",
"an",
"in",
"ALLOWED_NODES",
":",
"if",
"isinstance",
"(",
"node",
",",
"an",
")",
":... | Filters a given module ast, removing non-whitelisted nodes
It allows only the following top level items:
- imports
- function definitions
- class definitions
- top level assignments where all the targets on the LHS are all caps | [
"Filters",
"a",
"given",
"module",
"ast",
"removing",
"non",
"-",
"whitelisted",
"nodes"
] | python | train | 33.535714 |
python-rope/rope | rope/contrib/codeassist.py | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/codeassist.py#L43-L58 | def starting_offset(source_code, offset):
"""Return the offset in which the completion should be inserted
Usually code assist proposals should be inserted like::
completion = proposal.name
result = (source_code[:starting_offset] +
completion + source_code[offset:])
Where... | [
"def",
"starting_offset",
"(",
"source_code",
",",
"offset",
")",
":",
"word_finder",
"=",
"worder",
".",
"Worder",
"(",
"source_code",
",",
"True",
")",
"expression",
",",
"starting",
",",
"starting_offset",
"=",
"word_finder",
".",
"get_splitted_primary_before",... | Return the offset in which the completion should be inserted
Usually code assist proposals should be inserted like::
completion = proposal.name
result = (source_code[:starting_offset] +
completion + source_code[offset:])
Where starting_offset is the offset returned by this f... | [
"Return",
"the",
"offset",
"in",
"which",
"the",
"completion",
"should",
"be",
"inserted"
] | python | train | 34.4375 |
msuozzo/Aduro | aduro/manager.py | https://github.com/msuozzo/Aduro/blob/338eeb1deeff30c198e721b660ae4daca3660911/aduro/manager.py#L36-L70 | def detect_events(self, max_attempts=3):
"""Returns a list of `Event`s detected from differences in state
between the current snapshot and the Kindle Library.
`books` and `progress` attributes will be set with the latest API
results upon successful completion of the function.
R... | [
"def",
"detect_events",
"(",
"self",
",",
"max_attempts",
"=",
"3",
")",
":",
"# Attempt to retrieve current state from KindleAPI",
"for",
"_",
"in",
"xrange",
"(",
"max_attempts",
")",
":",
"try",
":",
"with",
"KindleCloudReaderAPI",
".",
"get_instance",
"(",
"se... | Returns a list of `Event`s detected from differences in state
between the current snapshot and the Kindle Library.
`books` and `progress` attributes will be set with the latest API
results upon successful completion of the function.
Returns:
If failed to retrieve progress, ... | [
"Returns",
"a",
"list",
"of",
"Event",
"s",
"detected",
"from",
"differences",
"in",
"state",
"between",
"the",
"current",
"snapshot",
"and",
"the",
"Kindle",
"Library",
"."
] | python | train | 37.742857 |
emirozer/fake2db | fake2db/sqlite_handler.py | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/sqlite_handler.py#L140-L161 | def data_filler_user_agent(self, number_of_rows, conn):
'''creates and fills the table with user agent data
'''
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE user_agent(id TEXT PRIMARY KEY,
ip TEXT, countrycode TEXT, useragent TEXT)
''')
conn.com... | [
"def",
"data_filler_user_agent",
"(",
"self",
",",
"number_of_rows",
",",
"conn",
")",
":",
"cursor",
"=",
"conn",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"'''\n CREATE TABLE user_agent(id TEXT PRIMARY KEY,\n ip TEXT, countrycode TEXT, useragen... | creates and fills the table with user agent data | [
"creates",
"and",
"fills",
"the",
"table",
"with",
"user",
"agent",
"data"
] | python | train | 38.772727 |
tensorflow/cleverhans | cleverhans/utils_tf.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L304-L324 | def model_argmax(sess, x, predictions, samples, feed=None):
"""
Helper function that computes the current class prediction
:param sess: TF session
:param x: the input placeholder
:param predictions: the model's symbolic output
:param samples: numpy array with input samples (dims must match x)
:param feed:... | [
"def",
"model_argmax",
"(",
"sess",
",",
"x",
",",
"predictions",
",",
"samples",
",",
"feed",
"=",
"None",
")",
":",
"feed_dict",
"=",
"{",
"x",
":",
"samples",
"}",
"if",
"feed",
"is",
"not",
"None",
":",
"feed_dict",
".",
"update",
"(",
"feed",
... | Helper function that computes the current class prediction
:param sess: TF session
:param x: the input placeholder
:param predictions: the model's symbolic output
:param samples: numpy array with input samples (dims must match x)
:param feed: An optional dictionary that is appended to the feeding
d... | [
"Helper",
"function",
"that",
"computes",
"the",
"current",
"class",
"prediction",
":",
"param",
"sess",
":",
"TF",
"session",
":",
"param",
"x",
":",
"the",
"input",
"placeholder",
":",
"param",
"predictions",
":",
"the",
"model",
"s",
"symbolic",
"output",... | python | train | 38.666667 |
CSchoel/nolds | nolds/measures.py | https://github.com/CSchoel/nolds/blob/8a5ecc472d67ac08b571bd68967287668ca9058e/nolds/measures.py#L839-L874 | def logmid_n(max_n, ratio=1/4.0, nsteps=15):
"""
Creates an array of integers that lie evenly spaced in the "middle" of the
logarithmic scale from 0 to log(max_n).
If max_n is very small and/or nsteps is very large, this may lead to
duplicate values which will be removed from the output.
This function has... | [
"def",
"logmid_n",
"(",
"max_n",
",",
"ratio",
"=",
"1",
"/",
"4.0",
",",
"nsteps",
"=",
"15",
")",
":",
"l",
"=",
"np",
".",
"log",
"(",
"max_n",
")",
"span",
"=",
"l",
"*",
"ratio",
"start",
"=",
"l",
"*",
"(",
"1",
"-",
"ratio",
")",
"*"... | Creates an array of integers that lie evenly spaced in the "middle" of the
logarithmic scale from 0 to log(max_n).
If max_n is very small and/or nsteps is very large, this may lead to
duplicate values which will be removed from the output.
This function has benefits in hurst_rs, because it cuts away both very... | [
"Creates",
"an",
"array",
"of",
"integers",
"that",
"lie",
"evenly",
"spaced",
"in",
"the",
"middle",
"of",
"the",
"logarithmic",
"scale",
"from",
"0",
"to",
"log",
"(",
"max_n",
")",
"."
] | python | train | 35.361111 |
kmmbvnr/django-any | django_any/models.py | https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L86-L98 | def any_positiveinteger_field(field, **kwargs):
"""
An positive integer
>>> result = any_field(models.PositiveIntegerField())
>>> type(result)
<type 'int'>
>>> result > 0
True
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 9999)
re... | [
"def",
"any_positiveinteger_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_value",
"=",
"kwargs",
".",
"get",
"(",
"'min_value'",
",",
"1",
")",
"max_value",
"=",
"kwargs",
".",
"get",
"(",
"'max_value'",
",",
"9999",
")",
"return",
"xunit... | An positive integer
>>> result = any_field(models.PositiveIntegerField())
>>> type(result)
<type 'int'>
>>> result > 0
True | [
"An",
"positive",
"integer",
">>>",
"result",
"=",
"any_field",
"(",
"models",
".",
"PositiveIntegerField",
"()",
")",
">>>",
"type",
"(",
"result",
")",
"<type",
"int",
">",
">>>",
"result",
">",
"0",
"True"
] | python | test | 28.307692 |
cmbruns/pyopenvr | src/openvr/__init__.py | https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L5780-L5794 | def takeStereoScreenshot(self, pchPreviewFilename, pchVRFilename):
"""
Tells the compositor to take an internal screenshot of
type VRScreenshotType_Stereo. It will take the current
submitted scene textures of the running application and
write them into the preview image and a ... | [
"def",
"takeStereoScreenshot",
"(",
"self",
",",
"pchPreviewFilename",
",",
"pchVRFilename",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"takeStereoScreenshot",
"pOutScreenshotHandle",
"=",
"ScreenshotHandle_t",
"(",
")",
"result",
"=",
"fn",
"(",
"by... | Tells the compositor to take an internal screenshot of
type VRScreenshotType_Stereo. It will take the current
submitted scene textures of the running application and
write them into the preview image and a side-by-side file
for the VR image.
This is similar to request screen... | [
"Tells",
"the",
"compositor",
"to",
"take",
"an",
"internal",
"screenshot",
"of",
"type",
"VRScreenshotType_Stereo",
".",
"It",
"will",
"take",
"the",
"current",
"submitted",
"scene",
"textures",
"of",
"the",
"running",
"application",
"and",
"write",
"them",
"in... | python | train | 48.6 |
angr/angr | angr/state_plugins/symbolic_memory.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/symbolic_memory.py#L412-L427 | def concretize_read_addr(self, addr, strategies=None):
"""
Concretizes an address meant for reading.
:param addr: An expression for the address.
:param strategies: A list of concretization strategies (to override the default).
:returns: ... | [
"def",
"concretize_read_addr",
"(",
"self",
",",
"addr",
",",
"strategies",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"addr",
",",
"int",
")",
":",
"return",
"[",
"addr",
"]",
"elif",
"not",
"self",
".",
"state",
".",
"solver",
".",
"symbolic",
... | Concretizes an address meant for reading.
:param addr: An expression for the address.
:param strategies: A list of concretization strategies (to override the default).
:returns: A list of concrete addresses. | [
"Concretizes",
"an",
"address",
"meant",
"for",
"reading",
"."
] | python | train | 42 |
tkf/python-epc | epc/core.py | https://github.com/tkf/python-epc/blob/f3673ae5c35f20a0f71546ab34c28e3dde3595c1/epc/core.py#L75-L86 | def get_method(self, name):
"""
Get registered method callend `name`.
"""
try:
return self.funcs[name]
except KeyError:
try:
return self.instance._get_method(name)
except AttributeError:
return SimpleXMLRPCServer... | [
"def",
"get_method",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"return",
"self",
".",
"funcs",
"[",
"name",
"]",
"except",
"KeyError",
":",
"try",
":",
"return",
"self",
".",
"instance",
".",
"_get_method",
"(",
"name",
")",
"except",
"AttributeE... | Get registered method callend `name`. | [
"Get",
"registered",
"method",
"callend",
"name",
"."
] | python | train | 33.416667 |
blockadeio/analyst_toolbench | blockade/common/utils.py | https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/common/utils.py#L101-L114 | def get_logger(name):
"""Get a logging instance we can use."""
import logging
import sys
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
shandler = logging.StreamHandler(sys.stdout)
fmt = ""
fmt += '\033[1;32m%(levelname)-5s %(module)s:%(funcName)s():'
fmt += '%(linen... | [
"def",
"get_logger",
"(",
"name",
")",
":",
"import",
"logging",
"import",
"sys",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"shandler",
"=",
"logging",
".",
"StreamHandler",
... | Get a logging instance we can use. | [
"Get",
"a",
"logging",
"instance",
"we",
"can",
"use",
"."
] | python | train | 32.785714 |
DataBiosphere/toil | src/toil/cwl/cwltoil.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/cwl/cwltoil.py#L345-L365 | def uploadFile(uploadfunc, fileindex, existing, uf, skip_broken=False):
"""Update a file object so that the location is a reference to the toil file
store, writing it to the file store if necessary.
"""
if uf["location"].startswith("toilfs:") or uf["location"].startswith("_:"):
return
if u... | [
"def",
"uploadFile",
"(",
"uploadfunc",
",",
"fileindex",
",",
"existing",
",",
"uf",
",",
"skip_broken",
"=",
"False",
")",
":",
"if",
"uf",
"[",
"\"location\"",
"]",
".",
"startswith",
"(",
"\"toilfs:\"",
")",
"or",
"uf",
"[",
"\"location\"",
"]",
".",... | Update a file object so that the location is a reference to the toil file
store, writing it to the file store if necessary. | [
"Update",
"a",
"file",
"object",
"so",
"that",
"the",
"location",
"is",
"a",
"reference",
"to",
"the",
"toil",
"file",
"store",
"writing",
"it",
"to",
"the",
"file",
"store",
"if",
"necessary",
"."
] | python | train | 40.47619 |
yyuu/botornado | boto/pyami/installers/__init__.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/pyami/installers/__init__.py#L30-L34 | def add_cron(self, name, minute, hour, mday, month, wday, who, command, env=None):
"""
Add an entry to the system crontab.
"""
raise NotImplementedError | [
"def",
"add_cron",
"(",
"self",
",",
"name",
",",
"minute",
",",
"hour",
",",
"mday",
",",
"month",
",",
"wday",
",",
"who",
",",
"command",
",",
"env",
"=",
"None",
")",
":",
"raise",
"NotImplementedError"
] | Add an entry to the system crontab. | [
"Add",
"an",
"entry",
"to",
"the",
"system",
"crontab",
"."
] | python | train | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.