repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
soasme/rio | rio/blueprints/dashboard.py | https://github.com/soasme/rio/blob/f722eb0ff4b0382bceaff77737f0b87cb78429e7/rio/blueprints/dashboard.py#L62-L79 | def new_project():
"""New Project."""
form = NewProjectForm()
if not form.validate_on_submit():
return jsonify(errors=form.errors), 400
data = form.data
data['slug'] = slugify(data['name'])
data['owner_id'] = get_current_user_id()
id = add_instance('project', **data)
if not id... | [
"def",
"new_project",
"(",
")",
":",
"form",
"=",
"NewProjectForm",
"(",
")",
"if",
"not",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"return",
"jsonify",
"(",
"errors",
"=",
"form",
".",
"errors",
")",
",",
"400",
"data",
"=",
"form",
".",
"d... | New Project. | [
"New",
"Project",
"."
] | python | train |
yyuu/botornado | boto/ecs/__init__.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/ecs/__init__.py#L52-L75 | def get_response(self, action, params, page=0, itemSet=None):
"""
Utility method to handle calls to ECS and parsing of responses.
"""
params['Service'] = "AWSECommerceService"
params['Operation'] = action
if page:
params['ItemPage'] = page
response = s... | [
"def",
"get_response",
"(",
"self",
",",
"action",
",",
"params",
",",
"page",
"=",
"0",
",",
"itemSet",
"=",
"None",
")",
":",
"params",
"[",
"'Service'",
"]",
"=",
"\"AWSECommerceService\"",
"params",
"[",
"'Operation'",
"]",
"=",
"action",
"if",
"page... | Utility method to handle calls to ECS and parsing of responses. | [
"Utility",
"method",
"to",
"handle",
"calls",
"to",
"ECS",
"and",
"parsing",
"of",
"responses",
"."
] | python | train |
denisenkom/pytds | src/pytds/__init__.py | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/__init__.py#L1049-L1059 | def callproc(self, procname, parameters=()):
"""
Call a stored procedure with the given name.
:param procname: The name of the procedure to call
:type procname: str
:keyword parameters: The optional parameters for the procedure
:type parameters: sequence
"""
... | [
"def",
"callproc",
"(",
"self",
",",
"procname",
",",
"parameters",
"=",
"(",
")",
")",
":",
"self",
".",
"_assert_open",
"(",
")",
"return",
"self",
".",
"_callproc",
"(",
"procname",
",",
"parameters",
")"
] | Call a stored procedure with the given name.
:param procname: The name of the procedure to call
:type procname: str
:keyword parameters: The optional parameters for the procedure
:type parameters: sequence | [
"Call",
"a",
"stored",
"procedure",
"with",
"the",
"given",
"name",
"."
] | python | train |
swharden/SWHLab | swhlab/indexing/style.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/style.py#L68-L78 | def frames(fname=None,menuWidth=200,launch=False):
"""create and save a two column frames HTML file."""
html="""
<frameset cols="%dpx,*%%">
<frame name="menu" src="index_menu.html">
<frame name="content" src="index_splash.html">
</frameset>"""%(menuWidth)
with open(fname,'w') as f:
f... | [
"def",
"frames",
"(",
"fname",
"=",
"None",
",",
"menuWidth",
"=",
"200",
",",
"launch",
"=",
"False",
")",
":",
"html",
"=",
"\"\"\"\n <frameset cols=\"%dpx,*%%\">\n <frame name=\"menu\" src=\"index_menu.html\">\n <frame name=\"content\" src=\"index_splash.html\">\n ... | create and save a two column frames HTML file. | [
"create",
"and",
"save",
"a",
"two",
"column",
"frames",
"HTML",
"file",
"."
] | python | valid |
pilosus/ForgeryPy3 | forgery_py/forgery/russian_tax.py | https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/russian_tax.py#L81-L85 | def legal_ogrn():
"""Return a random government registration ID for a company."""
ogrn = "".join(map(str, [random.randint(1, 9) for _ in range(12)]))
ogrn += str((int(ogrn) % 11 % 10))
return ogrn | [
"def",
"legal_ogrn",
"(",
")",
":",
"ogrn",
"=",
"\"\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"[",
"random",
".",
"randint",
"(",
"1",
",",
"9",
")",
"for",
"_",
"in",
"range",
"(",
"12",
")",
"]",
")",
")",
"ogrn",
"+=",
"str",
"(",
"... | Return a random government registration ID for a company. | [
"Return",
"a",
"random",
"government",
"registration",
"ID",
"for",
"a",
"company",
"."
] | python | valid |
DBuildService/dockerfile-parse | dockerfile_parse/util.py | https://github.com/DBuildService/dockerfile-parse/blob/3d7b514d8b8eded1b33529cf0f6a0770a573aee0/dockerfile_parse/util.py#L107-L211 | def split(self, maxsplit=None, dequote=True):
"""
Generator for the words of the string
:param maxsplit: perform at most maxsplit splits;
if None, do not limit the number of splits
:param dequote: remove quotes and escape characters once consumed
"""
class W... | [
"def",
"split",
"(",
"self",
",",
"maxsplit",
"=",
"None",
",",
"dequote",
"=",
"True",
")",
":",
"class",
"Word",
"(",
"object",
")",
":",
"\"\"\"\n A None-or-str object which can always be appended to.\n Similar to a defaultdict but with only a single ... | Generator for the words of the string
:param maxsplit: perform at most maxsplit splits;
if None, do not limit the number of splits
:param dequote: remove quotes and escape characters once consumed | [
"Generator",
"for",
"the",
"words",
"of",
"the",
"string"
] | python | train |
hkff/FodtlMon | fodtlmon/tools/color.py | https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L237-L267 | def _parse_input(incoming):
"""Performs the actual conversion of tags to ANSI escaped codes.
Provides a version of the input without any colors for len() and other methods.
Positional arguments:
incoming -- the input unicode value.
Returns:
2-item tuple. First item is the parsed output. Secon... | [
"def",
"_parse_input",
"(",
"incoming",
")",
":",
"codes",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"_AutoCodes",
"(",
")",
".",
"items",
"(",
")",
"if",
"'{%s}'",
"%",
"k",
"in",
"incoming",
")",
"color_codes",
"=",... | Performs the actual conversion of tags to ANSI escaped codes.
Provides a version of the input without any colors for len() and other methods.
Positional arguments:
incoming -- the input unicode value.
Returns:
2-item tuple. First item is the parsed output. Second item is a version of the input wi... | [
"Performs",
"the",
"actual",
"conversion",
"of",
"tags",
"to",
"ANSI",
"escaped",
"codes",
"."
] | python | train |
davidcarboni/Flask-Sleuth | sleuth/__init__.py | https://github.com/davidcarboni/Flask-Sleuth/blob/2191aa2a929ec43c0176ec51c7abef924b12d015/sleuth/__init__.py#L71-L88 | def _tracing_information():
"""Gets B3 distributed tracing information, if available.
This is returned as a list, ready to be formatted into Spring Cloud Sleuth compatible format.
"""
# We'll collate trace information if the B3 headers have been collected:
values = b3.values()
if values[b3.b3... | [
"def",
"_tracing_information",
"(",
")",
":",
"# We'll collate trace information if the B3 headers have been collected:",
"values",
"=",
"b3",
".",
"values",
"(",
")",
"if",
"values",
"[",
"b3",
".",
"b3_trace_id",
"]",
":",
"# Trace information would normally be sent to Zi... | Gets B3 distributed tracing information, if available.
This is returned as a list, ready to be formatted into Spring Cloud Sleuth compatible format. | [
"Gets",
"B3",
"distributed",
"tracing",
"information",
"if",
"available",
".",
"This",
"is",
"returned",
"as",
"a",
"list",
"ready",
"to",
"be",
"formatted",
"into",
"Spring",
"Cloud",
"Sleuth",
"compatible",
"format",
"."
] | python | train |
bxlab/bx-python | lib/bx_extras/stats.py | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1762-L1816 | def outputpairedstats(fname,writemode,name1,n1,m1,se1,min1,max1,name2,n2,m2,se2,min2,max2,statname,stat,prob):
"""
Prints or write to a file stats for two groups, using the name, n,
mean, sterr, min and max for each group, as well as the statistic name,
its value, and the associated p-value.
Usage: outputpaireds... | [
"def",
"outputpairedstats",
"(",
"fname",
",",
"writemode",
",",
"name1",
",",
"n1",
",",
"m1",
",",
"se1",
",",
"min1",
",",
"max1",
",",
"name2",
",",
"n2",
",",
"m2",
",",
"se2",
",",
"min2",
",",
"max2",
",",
"statname",
",",
"stat",
",",
"pr... | Prints or write to a file stats for two groups, using the name, n,
mean, sterr, min and max for each group, as well as the statistic name,
its value, and the associated p-value.
Usage: outputpairedstats(fname,writemode,
name1,n1,mean1,stderr1,min1,max1,
name2,n2,... | [
"Prints",
"or",
"write",
"to",
"a",
"file",
"stats",
"for",
"two",
"groups",
"using",
"the",
"name",
"n",
"mean",
"sterr",
"min",
"and",
"max",
"for",
"each",
"group",
"as",
"well",
"as",
"the",
"statistic",
"name",
"its",
"value",
"and",
"the",
"assoc... | python | train |
jplusplus/statscraper | statscraper/BaseScraperList.py | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/BaseScraperList.py#L17-L21 | def get_by_label(self, label):
""" Return the first item with a specific label,
or None.
"""
return next((x for x in self if x.label == label), None) | [
"def",
"get_by_label",
"(",
"self",
",",
"label",
")",
":",
"return",
"next",
"(",
"(",
"x",
"for",
"x",
"in",
"self",
"if",
"x",
".",
"label",
"==",
"label",
")",
",",
"None",
")"
] | Return the first item with a specific label,
or None. | [
"Return",
"the",
"first",
"item",
"with",
"a",
"specific",
"label",
"or",
"None",
"."
] | python | train |
MartinHjelmare/leicacam | leicacam/async_cam.py | https://github.com/MartinHjelmare/leicacam/blob/1df37bccd34884737d3b5e169fae71dd2f21f1e2/leicacam/async_cam.py#L21-L25 | async def connect(self):
"""Connect to LASAF through a CAM-socket."""
self.reader, self.writer = await asyncio.open_connection(
self.host, self.port, loop=self.loop)
self.welcome_msg = await self.reader.read(self.buffer_size) | [
"async",
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"reader",
",",
"self",
".",
"writer",
"=",
"await",
"asyncio",
".",
"open_connection",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"loop",
"=",
"self",
".",
"loop",
")",
"s... | Connect to LASAF through a CAM-socket. | [
"Connect",
"to",
"LASAF",
"through",
"a",
"CAM",
"-",
"socket",
"."
] | python | test |
DeepHorizons/iarm | iarm/arm_instructions/memory.py | https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/memory.py#L281-L305 | def LDRSH(self, params):
"""
LDRSH Ra, [Rb, Rc]
Load a half word from memory, sign extend, and put into Ra
Ra, Rb, and Rc must be low registers
"""
# TODO LDRSH cant use immediates
Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params)... | [
"def",
"LDRSH",
"(",
"self",
",",
"params",
")",
":",
"# TODO LDRSH cant use immediates",
"Ra",
",",
"Rb",
",",
"Rc",
"=",
"self",
".",
"get_three_parameters",
"(",
"self",
".",
"THREE_PARAMETER_WITH_BRACKETS",
",",
"params",
")",
"self",
".",
"check_arguments",... | LDRSH Ra, [Rb, Rc]
Load a half word from memory, sign extend, and put into Ra
Ra, Rb, and Rc must be low registers | [
"LDRSH",
"Ra",
"[",
"Rb",
"Rc",
"]"
] | python | train |
riverrun/drat | drat/analysis.py | https://github.com/riverrun/drat/blob/50cbbf69c022b6ca6641cd55386813b0695c21f5/drat/analysis.py#L81-L88 | def dale_chall(self, diff_count, words, sentences):
"""Calculate Dale-Chall readability score."""
pdw = diff_count / words * 100
asl = words / sentences
raw = 0.1579 * (pdw) + 0.0496 * asl
if pdw > 5:
return raw + 3.6365
return raw | [
"def",
"dale_chall",
"(",
"self",
",",
"diff_count",
",",
"words",
",",
"sentences",
")",
":",
"pdw",
"=",
"diff_count",
"/",
"words",
"*",
"100",
"asl",
"=",
"words",
"/",
"sentences",
"raw",
"=",
"0.1579",
"*",
"(",
"pdw",
")",
"+",
"0.0496",
"*",
... | Calculate Dale-Chall readability score. | [
"Calculate",
"Dale",
"-",
"Chall",
"readability",
"score",
"."
] | python | train |
nugget/python-insteonplm | insteonplm/states/onOff.py | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/states/onOff.py#L563-L567 | def set_led_brightness(self, brightness):
"""Set the LED brightness for the current group/button."""
set_cmd = self._create_set_property_msg("_led_brightness", 0x07,
brightness)
self._send_method(set_cmd, self._property_set) | [
"def",
"set_led_brightness",
"(",
"self",
",",
"brightness",
")",
":",
"set_cmd",
"=",
"self",
".",
"_create_set_property_msg",
"(",
"\"_led_brightness\"",
",",
"0x07",
",",
"brightness",
")",
"self",
".",
"_send_method",
"(",
"set_cmd",
",",
"self",
".",
"_pr... | Set the LED brightness for the current group/button. | [
"Set",
"the",
"LED",
"brightness",
"for",
"the",
"current",
"group",
"/",
"button",
"."
] | python | train |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/bson/__init__.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/bson/__init__.py#L863-L893 | def decode_iter(data, codec_options=DEFAULT_CODEC_OPTIONS):
"""Decode BSON data to multiple documents as a generator.
Works similarly to the decode_all function, but yields one document at a
time.
`data` must be a string of concatenated, valid, BSON-encoded
documents.
:Parameters:
- `da... | [
"def",
"decode_iter",
"(",
"data",
",",
"codec_options",
"=",
"DEFAULT_CODEC_OPTIONS",
")",
":",
"if",
"not",
"isinstance",
"(",
"codec_options",
",",
"CodecOptions",
")",
":",
"raise",
"_CODEC_OPTIONS_TYPE_ERROR",
"position",
"=",
"0",
"end",
"=",
"len",
"(",
... | Decode BSON data to multiple documents as a generator.
Works similarly to the decode_all function, but yields one document at a
time.
`data` must be a string of concatenated, valid, BSON-encoded
documents.
:Parameters:
- `data`: BSON data
- `codec_options` (optional): An instance of
... | [
"Decode",
"BSON",
"data",
"to",
"multiple",
"documents",
"as",
"a",
"generator",
"."
] | python | train |
etingof/pyasn1 | pyasn1/type/univ.py | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L968-L987 | def fromHexString(value):
"""Create a |ASN.1| object initialized from the hex string.
Parameters
----------
value: :class:`str`
Text string like 'DEADBEEF'
"""
r = []
p = []
for v in value:
if p:
r.append(int(p + v,... | [
"def",
"fromHexString",
"(",
"value",
")",
":",
"r",
"=",
"[",
"]",
"p",
"=",
"[",
"]",
"for",
"v",
"in",
"value",
":",
"if",
"p",
":",
"r",
".",
"append",
"(",
"int",
"(",
"p",
"+",
"v",
",",
"16",
")",
")",
"p",
"=",
"None",
"else",
":"... | Create a |ASN.1| object initialized from the hex string.
Parameters
----------
value: :class:`str`
Text string like 'DEADBEEF' | [
"Create",
"a",
"|ASN",
".",
"1|",
"object",
"initialized",
"from",
"the",
"hex",
"string",
"."
] | python | train |
etcher-be/emiz | emiz/avwx/core.py | https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L61-L70 | def unpack_fraction(num: str) -> str:
"""
Returns unpacked fraction string 5/2 -> 2 1/2
"""
nums = [int(n) for n in num.split('/') if n]
if len(nums) == 2 and nums[0] > nums[1]:
over = nums[0] // nums[1]
rem = nums[0] % nums[1]
return f'{over} {rem}/{nums[1]}'
return num | [
"def",
"unpack_fraction",
"(",
"num",
":",
"str",
")",
"->",
"str",
":",
"nums",
"=",
"[",
"int",
"(",
"n",
")",
"for",
"n",
"in",
"num",
".",
"split",
"(",
"'/'",
")",
"if",
"n",
"]",
"if",
"len",
"(",
"nums",
")",
"==",
"2",
"and",
"nums",
... | Returns unpacked fraction string 5/2 -> 2 1/2 | [
"Returns",
"unpacked",
"fraction",
"string",
"5",
"/",
"2",
"-",
">",
"2",
"1",
"/",
"2"
] | python | train |
faucamp/python-gsmmodem | gsmmodem/serial_comms.py | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/serial_comms.py#L83-L118 | def _readLoop(self):
""" Read thread main loop
Reads lines from the connected device
"""
try:
readTermSeq = list(self.RX_EOL_SEQ)
readTermLen = len(readTermSeq)
rxBuffer = []
while self.alive:
data = self.serial.rea... | [
"def",
"_readLoop",
"(",
"self",
")",
":",
"try",
":",
"readTermSeq",
"=",
"list",
"(",
"self",
".",
"RX_EOL_SEQ",
")",
"readTermLen",
"=",
"len",
"(",
"readTermSeq",
")",
"rxBuffer",
"=",
"[",
"]",
"while",
"self",
".",
"alive",
":",
"data",
"=",
"s... | Read thread main loop
Reads lines from the connected device | [
"Read",
"thread",
"main",
"loop",
"Reads",
"lines",
"from",
"the",
"connected",
"device"
] | python | train |
cackharot/suds-py3 | suds/properties.py | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/properties.py#L322-L335 | def unlink(self, *others):
"""
Unlink (disassociate) the specified properties object.
@param others: The list object to unlink. Unspecified means unlink all.
@type others: [L{Properties},..]
@return: self
@rtype: L{Properties}
"""
if not len(others):
... | [
"def",
"unlink",
"(",
"self",
",",
"*",
"others",
")",
":",
"if",
"not",
"len",
"(",
"others",
")",
":",
"others",
"=",
"self",
".",
"links",
"[",
":",
"]",
"for",
"p",
"in",
"self",
".",
"links",
"[",
":",
"]",
":",
"if",
"p",
"in",
"others"... | Unlink (disassociate) the specified properties object.
@param others: The list object to unlink. Unspecified means unlink all.
@type others: [L{Properties},..]
@return: self
@rtype: L{Properties} | [
"Unlink",
"(",
"disassociate",
")",
"the",
"specified",
"properties",
"object",
"."
] | python | train |
OCA/openupgradelib | openupgradelib/openupgrade.py | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L180-L220 | def allow_pgcodes(cr, *codes):
"""Context manager that will omit specified error codes.
E.g., suppose you expect a migration to produce unique constraint
violations and you want to ignore them. Then you could just do::
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.ex... | [
"def",
"allow_pgcodes",
"(",
"cr",
",",
"*",
"codes",
")",
":",
"try",
":",
"with",
"cr",
".",
"savepoint",
"(",
")",
":",
"with",
"core",
".",
"tools",
".",
"mute_logger",
"(",
"'odoo.sql_db'",
")",
":",
"yield",
"except",
"(",
"ProgrammingError",
","... | Context manager that will omit specified error codes.
E.g., suppose you expect a migration to produce unique constraint
violations and you want to ignore them. Then you could just do::
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.execute("INSERT INTO me (name) SELECT na... | [
"Context",
"manager",
"that",
"will",
"omit",
"specified",
"error",
"codes",
"."
] | python | train |
andreasjansson/head-in-the-clouds | headintheclouds/dependencies/PyDbLite/PyDbLite.py | https://github.com/andreasjansson/head-in-the-clouds/blob/32c1d00d01036834dc94368e7f38b0afd3f7a82f/headintheclouds/dependencies/PyDbLite/PyDbLite.py#L240-L247 | def commit(self):
"""Write the database to a file"""
out = open(self.name,'wb')
cPickle.dump(self.fields,out,self.protocol)
cPickle.dump(self.next_id,out,self.protocol)
cPickle.dump(self.records,out,self.protocol)
cPickle.dump(self.indices,out,self.protocol)
... | [
"def",
"commit",
"(",
"self",
")",
":",
"out",
"=",
"open",
"(",
"self",
".",
"name",
",",
"'wb'",
")",
"cPickle",
".",
"dump",
"(",
"self",
".",
"fields",
",",
"out",
",",
"self",
".",
"protocol",
")",
"cPickle",
".",
"dump",
"(",
"self",
".",
... | Write the database to a file | [
"Write",
"the",
"database",
"to",
"a",
"file"
] | python | train |
O365/python-o365 | O365/excel.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/excel.py#L1364-L1395 | def update(self, *, name=None, show_headers=None, show_totals=None, style=None):
"""
Updates this table
:param str name: the name of the table
:param bool show_headers: whether or not to show the headers
:param bool show_totals: whether or not to show the totals
:param st... | [
"def",
"update",
"(",
"self",
",",
"*",
",",
"name",
"=",
"None",
",",
"show_headers",
"=",
"None",
",",
"show_totals",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
"and",
"show_headers",
"is",
"None",
"and",
"show_to... | Updates this table
:param str name: the name of the table
:param bool show_headers: whether or not to show the headers
:param bool show_totals: whether or not to show the totals
:param str style: the style of the table
:return: Success or Failure | [
"Updates",
"this",
"table",
":",
"param",
"str",
"name",
":",
"the",
"name",
"of",
"the",
"table",
":",
"param",
"bool",
"show_headers",
":",
"whether",
"or",
"not",
"to",
"show",
"the",
"headers",
":",
"param",
"bool",
"show_totals",
":",
"whether",
"or... | python | train |
rq/rq-scheduler | rq_scheduler/scheduler.py | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L68-L80 | def acquire_lock(self):
"""
Acquire lock before scheduling jobs to prevent another scheduler
from scheduling jobs at the same time.
This function returns True if a lock is acquired. False otherwise.
"""
key = '%s_lock' % self.scheduler_key
now = time.time()
... | [
"def",
"acquire_lock",
"(",
"self",
")",
":",
"key",
"=",
"'%s_lock'",
"%",
"self",
".",
"scheduler_key",
"now",
"=",
"time",
".",
"time",
"(",
")",
"expires",
"=",
"int",
"(",
"self",
".",
"_interval",
")",
"+",
"10",
"self",
".",
"_lock_acquired",
... | Acquire lock before scheduling jobs to prevent another scheduler
from scheduling jobs at the same time.
This function returns True if a lock is acquired. False otherwise. | [
"Acquire",
"lock",
"before",
"scheduling",
"jobs",
"to",
"prevent",
"another",
"scheduler",
"from",
"scheduling",
"jobs",
"at",
"the",
"same",
"time",
"."
] | python | train |
ecordell/pymacaroons | pymacaroons/serializers/json_serializer.py | https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/serializers/json_serializer.py#L172-L181 | def _read_json_binary_field(deserialized, field):
''' Read the value of a JSON field that may be string or base64-encoded.
'''
val = deserialized.get(field)
if val is not None:
return utils.convert_to_bytes(val)
val = deserialized.get(field + '64')
if val is None:
return None
... | [
"def",
"_read_json_binary_field",
"(",
"deserialized",
",",
"field",
")",
":",
"val",
"=",
"deserialized",
".",
"get",
"(",
"field",
")",
"if",
"val",
"is",
"not",
"None",
":",
"return",
"utils",
".",
"convert_to_bytes",
"(",
"val",
")",
"val",
"=",
"des... | Read the value of a JSON field that may be string or base64-encoded. | [
"Read",
"the",
"value",
"of",
"a",
"JSON",
"field",
"that",
"may",
"be",
"string",
"or",
"base64",
"-",
"encoded",
"."
] | python | train |
goshuirc/irc | girc/features.py | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/features.py#L48-L86 | def _simplify_feature_value(self, name, value):
"""Return simplified and more pythonic feature values."""
if name == 'prefix':
channel_modes, channel_chars = value.split(')')
channel_modes = channel_modes[1:]
# [::-1] to reverse order and go from lowest to highest pr... | [
"def",
"_simplify_feature_value",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"name",
"==",
"'prefix'",
":",
"channel_modes",
",",
"channel_chars",
"=",
"value",
".",
"split",
"(",
"')'",
")",
"channel_modes",
"=",
"channel_modes",
"[",
"1",
":... | Return simplified and more pythonic feature values. | [
"Return",
"simplified",
"and",
"more",
"pythonic",
"feature",
"values",
"."
] | python | train |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L7915-L8212 | def resample(self, rule, how=None, axis=0, fill_method=None, closed=None,
label=None, convention='start', kind=None, loffset=None,
limit=None, base=0, on=None, level=None):
"""
Resample time-series data.
Convenience method for frequency conversion and resamplin... | [
"def",
"resample",
"(",
"self",
",",
"rule",
",",
"how",
"=",
"None",
",",
"axis",
"=",
"0",
",",
"fill_method",
"=",
"None",
",",
"closed",
"=",
"None",
",",
"label",
"=",
"None",
",",
"convention",
"=",
"'start'",
",",
"kind",
"=",
"None",
",",
... | Resample time-series data.
Convenience method for frequency conversion and resampling of time
series. Object must have a datetime-like index (`DatetimeIndex`,
`PeriodIndex`, or `TimedeltaIndex`), or pass datetime-like values
to the `on` or `level` keyword.
Parameters
--... | [
"Resample",
"time",
"-",
"series",
"data",
"."
] | python | train |
horazont/aioxmpp | aioxmpp/pubsub/service.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L357-L390 | def unsubscribe(self, jid, node=None, *,
subscription_jid=None,
subid=None):
"""
Unsubscribe from a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to unsubscribe from.
... | [
"def",
"unsubscribe",
"(",
"self",
",",
"jid",
",",
"node",
"=",
"None",
",",
"*",
",",
"subscription_jid",
"=",
"None",
",",
"subid",
"=",
"None",
")",
":",
"subscription_jid",
"=",
"subscription_jid",
"or",
"self",
".",
"client",
".",
"local_jid",
".",... | Unsubscribe from a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to unsubscribe from.
:type node: :class:`str`
:param subscription_jid: The address to subscribe from the service.
:type subscription_j... | [
"Unsubscribe",
"from",
"a",
"node",
"."
] | python | train |
google/transitfeed | merge.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L193-L216 | def _GenerateStatsTable(self, feed_merger):
"""Generate an HTML table of merge statistics.
Args:
feed_merger: The FeedMerger instance.
Returns:
The generated HTML as a string.
"""
rows = []
rows.append('<tr><th class="header"/><th class="header">Merged</th>'
'<th cl... | [
"def",
"_GenerateStatsTable",
"(",
"self",
",",
"feed_merger",
")",
":",
"rows",
"=",
"[",
"]",
"rows",
".",
"append",
"(",
"'<tr><th class=\"header\"/><th class=\"header\">Merged</th>'",
"'<th class=\"header\">Copied from old feed</th>'",
"'<th class=\"header\">Copied from new f... | Generate an HTML table of merge statistics.
Args:
feed_merger: The FeedMerger instance.
Returns:
The generated HTML as a string. | [
"Generate",
"an",
"HTML",
"table",
"of",
"merge",
"statistics",
"."
] | python | train |
ska-sa/purr | Purr/LogEntry.py | https://github.com/ska-sa/purr/blob/4c848768d0485d0f88b30850d0d5372221b21b66/Purr/LogEntry.py#L372-L384 | def setPrevUpNextLinks(self, prev=None, up=None, next=None):
"""Sets Prev link to point to the LogEntry object "prev". Set that object's Next link to point to us. Sets the "up" link to the URL 'up' (if up != None.)
Sets the Next link to the entry 'next' (if next != None), or to nothing if next == ''."""... | [
"def",
"setPrevUpNextLinks",
"(",
"self",
",",
"prev",
"=",
"None",
",",
"up",
"=",
"None",
",",
"next",
"=",
"None",
")",
":",
"if",
"prev",
"is",
"not",
"None",
":",
"if",
"prev",
":",
"self",
".",
"_prev_link",
"=",
"quote_url",
"(",
"prev",
"."... | Sets Prev link to point to the LogEntry object "prev". Set that object's Next link to point to us. Sets the "up" link to the URL 'up' (if up != None.)
Sets the Next link to the entry 'next' (if next != None), or to nothing if next == ''. | [
"Sets",
"Prev",
"link",
"to",
"point",
"to",
"the",
"LogEntry",
"object",
"prev",
".",
"Set",
"that",
"object",
"s",
"Next",
"link",
"to",
"point",
"to",
"us",
".",
"Sets",
"the",
"up",
"link",
"to",
"the",
"URL",
"up",
"(",
"if",
"up",
"!",
"=",
... | python | train |
bububa/pyTOP | pyTOP/simba.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/simba.py#L367-L378 | def update(self, campaign_id, title, is_smooth, online_status, nick=None):
'''xxxxx.xxxxx.campaign.update
===================================
更新一个推广计划,可以设置推广计划名字、是否平滑消耗,只有在设置了日限额后平滑消耗才会产生作用。'''
request = TOPRequest('xxxxx.xxxxx.campaign.update')
request['campaign_id'] = campaign_... | [
"def",
"update",
"(",
"self",
",",
"campaign_id",
",",
"title",
",",
"is_smooth",
",",
"online_status",
",",
"nick",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'xxxxx.xxxxx.campaign.update'",
")",
"request",
"[",
"'campaign_id'",
"]",
"=",
"c... | xxxxx.xxxxx.campaign.update
===================================
更新一个推广计划,可以设置推广计划名字、是否平滑消耗,只有在设置了日限额后平滑消耗才会产生作用。 | [
"xxxxx",
".",
"xxxxx",
".",
"campaign",
".",
"update",
"===================================",
"更新一个推广计划,可以设置推广计划名字、是否平滑消耗,只有在设置了日限额后平滑消耗才会产生作用。"
] | python | train |
ib-lundgren/flask-oauthprovider | examples/mongo_demoprovider/login.py | https://github.com/ib-lundgren/flask-oauthprovider/blob/6c91e8c11fc3cee410cb755d52d9d2c5331ee324/examples/mongo_demoprovider/login.py#L65-L82 | def create_profile():
"""If this is the user's first login, the create_or_login function
will redirect here so that the user can set up his profile.
"""
if g.user is not None or 'openid' not in session:
return redirect(url_for('index'))
if request.method == 'POST':
name = request.for... | [
"def",
"create_profile",
"(",
")",
":",
"if",
"g",
".",
"user",
"is",
"not",
"None",
"or",
"'openid'",
"not",
"in",
"session",
":",
"return",
"redirect",
"(",
"url_for",
"(",
"'index'",
")",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"... | If this is the user's first login, the create_or_login function
will redirect here so that the user can set up his profile. | [
"If",
"this",
"is",
"the",
"user",
"s",
"first",
"login",
"the",
"create_or_login",
"function",
"will",
"redirect",
"here",
"so",
"that",
"the",
"user",
"can",
"set",
"up",
"his",
"profile",
"."
] | python | train |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/genetic_balancer.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/genetic_balancer.py#L1097-L1104 | def pending_assignment(self):
"""Return the pending partition assignment that this state represents."""
return {
self.partitions[pid].name: [
self.brokers[bid].id for bid in self.replicas[pid]
]
for pid in set(self.pending_partitions)
} | [
"def",
"pending_assignment",
"(",
"self",
")",
":",
"return",
"{",
"self",
".",
"partitions",
"[",
"pid",
"]",
".",
"name",
":",
"[",
"self",
".",
"brokers",
"[",
"bid",
"]",
".",
"id",
"for",
"bid",
"in",
"self",
".",
"replicas",
"[",
"pid",
"]",
... | Return the pending partition assignment that this state represents. | [
"Return",
"the",
"pending",
"partition",
"assignment",
"that",
"this",
"state",
"represents",
"."
] | python | train |
madedotcom/photon-pump | photonpump/messages.py | https://github.com/madedotcom/photon-pump/blob/ff0736c9cacd43c1f783c9668eefb53d03a3a93e/photonpump/messages.py#L155-L170 | def from_bytes(cls, data):
"""
I am so sorry.
"""
len_username = int.from_bytes(data[0:2], byteorder="big")
offset_username = 2 + len_username
username = data[2:offset_username].decode("UTF-8")
offset_password = 2 + offset_username
len_password = int.from_... | [
"def",
"from_bytes",
"(",
"cls",
",",
"data",
")",
":",
"len_username",
"=",
"int",
".",
"from_bytes",
"(",
"data",
"[",
"0",
":",
"2",
"]",
",",
"byteorder",
"=",
"\"big\"",
")",
"offset_username",
"=",
"2",
"+",
"len_username",
"username",
"=",
"data... | I am so sorry. | [
"I",
"am",
"so",
"sorry",
"."
] | python | train |
orbingol/NURBS-Python | geomdl/_tessellate.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_tessellate.py#L217-L246 | def surface_tessellate(v1, v2, v3, v4, vidx, tidx, trim_curves, tessellate_args):
""" Triangular tessellation algorithm for surfaces with no trims.
This function can be directly used as an input to :func:`.make_triangle_mesh` using ``tessellate_func`` keyword
argument.
:param v1: vertex 1
:type v1... | [
"def",
"surface_tessellate",
"(",
"v1",
",",
"v2",
",",
"v3",
",",
"v4",
",",
"vidx",
",",
"tidx",
",",
"trim_curves",
",",
"tessellate_args",
")",
":",
"# Triangulate vertices",
"tris",
"=",
"polygon_triangulate",
"(",
"tidx",
",",
"v1",
",",
"v2",
",",
... | Triangular tessellation algorithm for surfaces with no trims.
This function can be directly used as an input to :func:`.make_triangle_mesh` using ``tessellate_func`` keyword
argument.
:param v1: vertex 1
:type v1: Vertex
:param v2: vertex 2
:type v2: Vertex
:param v3: vertex 3
:type v3... | [
"Triangular",
"tessellation",
"algorithm",
"for",
"surfaces",
"with",
"no",
"trims",
"."
] | python | train |
p3trus/slave | slave/protocol.py | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/protocol.py#L117-L147 | def parse_response(self, response, header=None):
"""Parses the response message.
The following graph shows the structure of response messages.
::
+----------+
+--+ data sep +<-+
... | [
"def",
"parse_response",
"(",
"self",
",",
"response",
",",
"header",
"=",
"None",
")",
":",
"response",
"=",
"response",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
"if",
"header",
":",
"header",
"=",
"\"\"",
".",
"join",
"(",
"(",
"self",
"."... | Parses the response message.
The following graph shows the structure of response messages.
::
+----------+
+--+ data sep +<-+
| +---------... | [
"Parses",
"the",
"response",
"message",
"."
] | python | train |
coinkite/connectrum | connectrum/client.py | https://github.com/coinkite/connectrum/blob/99948f92cc5c3ecb1a8a70146294014e608e50fc/connectrum/client.py#L279-L294 | def subscribe(self, method, *params):
'''
Perform a remote command which will stream events/data to us.
Expects a method name, which look like:
server.peers.subscribe
.. and sometimes take arguments, all of which are positional.
Returns a tup... | [
"def",
"subscribe",
"(",
"self",
",",
"method",
",",
"*",
"params",
")",
":",
"assert",
"'.'",
"in",
"method",
"assert",
"method",
".",
"endswith",
"(",
"'subscribe'",
")",
"return",
"self",
".",
"_send_request",
"(",
"method",
",",
"params",
",",
"is_su... | Perform a remote command which will stream events/data to us.
Expects a method name, which look like:
server.peers.subscribe
.. and sometimes take arguments, all of which are positional.
Returns a tuple: (Future, asyncio.Queue).
The future will have ... | [
"Perform",
"a",
"remote",
"command",
"which",
"will",
"stream",
"events",
"/",
"data",
"to",
"us",
"."
] | python | train |
hydpy-dev/hydpy | hydpy/auxs/xmltools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/xmltools.py#L1396-L1516 | def item(self):
""" ToDo
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface, pub
>>> hp = HydPy('LahnH')
>>> pub.timegrids = '1996-01-01', '1996-01-06', '1d'
>>> with TestIO()... | [
"def",
"item",
"(",
"self",
")",
":",
"target",
"=",
"f'{self.master.name}.{self.name}'",
"if",
"self",
".",
"master",
".",
"name",
"==",
"'nodes'",
":",
"master",
"=",
"self",
".",
"master",
".",
"name",
"itemgroup",
"=",
"self",
".",
"master",
".",
"ma... | ToDo
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface, pub
>>> hp = HydPy('LahnH')
>>> pub.timegrids = '1996-01-01', '1996-01-06', '1d'
>>> with TestIO():
... hp.prepare... | [
"ToDo"
] | python | train |
dhermes/bezier | docs/make_images.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1130-L1138 | def classify_intersection8(s, curve1, surface1, curve2, surface2):
"""Image for :func:`._surface_helpers.classify_intersection` docstring."""
if NO_IMAGES:
return
ax = classify_help(s, curve1, surface1, curve2, surface2, None)
ax.set_xlim(-1.125, 1.125)
ax.set_ylim(-0.125, 1.125)
save_i... | [
"def",
"classify_intersection8",
"(",
"s",
",",
"curve1",
",",
"surface1",
",",
"curve2",
",",
"surface2",
")",
":",
"if",
"NO_IMAGES",
":",
"return",
"ax",
"=",
"classify_help",
"(",
"s",
",",
"curve1",
",",
"surface1",
",",
"curve2",
",",
"surface2",
"... | Image for :func:`._surface_helpers.classify_intersection` docstring. | [
"Image",
"for",
":",
"func",
":",
".",
"_surface_helpers",
".",
"classify_intersection",
"docstring",
"."
] | python | train |
saltstack/salt | salt/modules/kubernetesmod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1563-L1583 | def __dict_to_service_spec(spec):
'''
Converts a dictionary into kubernetes V1ServiceSpec instance.
'''
spec_obj = kubernetes.client.V1ServiceSpec()
for key, value in iteritems(spec): # pylint: disable=too-many-nested-blocks
if key == 'ports':
spec_obj.ports = []
for... | [
"def",
"__dict_to_service_spec",
"(",
"spec",
")",
":",
"spec_obj",
"=",
"kubernetes",
".",
"client",
".",
"V1ServiceSpec",
"(",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"spec",
")",
":",
"# pylint: disable=too-many-nested-blocks",
"if",
"key",
... | Converts a dictionary into kubernetes V1ServiceSpec instance. | [
"Converts",
"a",
"dictionary",
"into",
"kubernetes",
"V1ServiceSpec",
"instance",
"."
] | python | train |
google/tangent | tangent/naming.py | https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/naming.py#L171-L184 | def unique(self, name):
"""Make a variable name unique by appending a number if needed."""
# Make sure the name is valid
name = self.valid(name)
# Make sure it's not too long
name = self.trim(name)
# Now make sure it's unique
unique_name = name
i = 2
while unique_name in self.names:
... | [
"def",
"unique",
"(",
"self",
",",
"name",
")",
":",
"# Make sure the name is valid",
"name",
"=",
"self",
".",
"valid",
"(",
"name",
")",
"# Make sure it's not too long",
"name",
"=",
"self",
".",
"trim",
"(",
"name",
")",
"# Now make sure it's unique",
"unique... | Make a variable name unique by appending a number if needed. | [
"Make",
"a",
"variable",
"name",
"unique",
"by",
"appending",
"a",
"number",
"if",
"needed",
"."
] | python | train |
HPAC/matchpy | matchpy/matching/many_to_one.py | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L369-L392 | def _internal_add(self, pattern: Pattern, label, renaming) -> int:
"""Add a new pattern to the matcher.
Equivalent patterns are not added again. However, patterns that are structurally equivalent,
but have different constraints or different variable names are distinguished by the matcher.
... | [
"def",
"_internal_add",
"(",
"self",
",",
"pattern",
":",
"Pattern",
",",
"label",
",",
"renaming",
")",
"->",
"int",
":",
"pattern_index",
"=",
"len",
"(",
"self",
".",
"patterns",
")",
"renamed_constraints",
"=",
"[",
"c",
".",
"with_renamed_vars",
"(",
... | Add a new pattern to the matcher.
Equivalent patterns are not added again. However, patterns that are structurally equivalent,
but have different constraints or different variable names are distinguished by the matcher.
Args:
pattern: The pattern to add.
Returns:
... | [
"Add",
"a",
"new",
"pattern",
"to",
"the",
"matcher",
"."
] | python | train |
Jammy2211/PyAutoLens | autolens/data/array/grids.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L1034-L1067 | def relocated_grid_from_grid_jit(grid, border_grid):
""" Relocate the coordinates of a grid to its border if they are outside the border. This is performed as \
follows:
1) Use the mean value of the grid's y and x coordinates to determine the origin of the grid.
2) Compute the radial di... | [
"def",
"relocated_grid_from_grid_jit",
"(",
"grid",
",",
"border_grid",
")",
":",
"border_origin",
"=",
"np",
".",
"zeros",
"(",
"2",
")",
"border_origin",
"[",
"0",
"]",
"=",
"np",
".",
"mean",
"(",
"border_grid",
"[",
":",
",",
"0",
"]",
")",
"border... | Relocate the coordinates of a grid to its border if they are outside the border. This is performed as \
follows:
1) Use the mean value of the grid's y and x coordinates to determine the origin of the grid.
2) Compute the radial distance of every grid coordinate from the origin.
3) For e... | [
"Relocate",
"the",
"coordinates",
"of",
"a",
"grid",
"to",
"its",
"border",
"if",
"they",
"are",
"outside",
"the",
"border",
".",
"This",
"is",
"performed",
"as",
"\\",
"follows",
":"
] | python | valid |
coops/r53 | src/r53/r53.py | https://github.com/coops/r53/blob/3c4e7242ad65b0e1ad4ba6b4ac893c7d501ceb0a/src/r53/r53.py#L39-L71 | def fetch_config(zone, conn):
"""Fetch all pieces of a Route 53 config from Amazon.
Args: zone: string, hosted zone id.
conn: boto.route53.Route53Connection
Returns: list of ElementTrees, one for each piece of config."""
more_to_fetch = True
cfg_chunks = []
next_name = None
next_type = None
nex... | [
"def",
"fetch_config",
"(",
"zone",
",",
"conn",
")",
":",
"more_to_fetch",
"=",
"True",
"cfg_chunks",
"=",
"[",
"]",
"next_name",
"=",
"None",
"next_type",
"=",
"None",
"next_identifier",
"=",
"None",
"while",
"more_to_fetch",
"==",
"True",
":",
"more_to_fe... | Fetch all pieces of a Route 53 config from Amazon.
Args: zone: string, hosted zone id.
conn: boto.route53.Route53Connection
Returns: list of ElementTrees, one for each piece of config. | [
"Fetch",
"all",
"pieces",
"of",
"a",
"Route",
"53",
"config",
"from",
"Amazon",
"."
] | python | test |
barrust/mediawiki | setup.py | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/setup.py#L14-L18 | def read_file(filepath):
""" read the file """
with io.open(filepath, "r") as filepointer:
res = filepointer.read()
return res | [
"def",
"read_file",
"(",
"filepath",
")",
":",
"with",
"io",
".",
"open",
"(",
"filepath",
",",
"\"r\"",
")",
"as",
"filepointer",
":",
"res",
"=",
"filepointer",
".",
"read",
"(",
")",
"return",
"res"
] | read the file | [
"read",
"the",
"file"
] | python | train |
saltstack/salt | salt/cloud/clouds/digitalocean.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L124-L152 | def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
fetch = True
... | [
"def",
"avail_images",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_images function must be called with '",
"'-f or --function, or with the --list-images option'",
")",
"fetch",
"=",
"True",
"pag... | Return a list of the images that are on the provider | [
"Return",
"a",
"list",
"of",
"the",
"images",
"that",
"are",
"on",
"the",
"provider"
] | python | train |
fridex/json2sql | json2sql/json2sql.py | https://github.com/fridex/json2sql/blob/a0851dd79827a684319b03fb899e129f81ff2d3a/json2sql/json2sql.py#L67-L110 | def json2sql(raw_json=None, **definition): # pylint: disable=too-many-branches
"""Convert raw dictionary, JSON/YAML to SQL statement.
:param raw_json: raw JSON/YAML or file to convert to SQL statement
:type raw_json: str or file
:return: raw SQL statement
:rtype: str
"""
if raw_json and de... | [
"def",
"json2sql",
"(",
"raw_json",
"=",
"None",
",",
"*",
"*",
"definition",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"raw_json",
"and",
"definition",
":",
"raise",
"InputError",
"(",
"\"Cannot process dict and kwargs input at the same time\"",
")",
"defi... | Convert raw dictionary, JSON/YAML to SQL statement.
:param raw_json: raw JSON/YAML or file to convert to SQL statement
:type raw_json: str or file
:return: raw SQL statement
:rtype: str | [
"Convert",
"raw",
"dictionary",
"JSON",
"/",
"YAML",
"to",
"SQL",
"statement",
"."
] | python | train |
davidhuser/dhis2.py | dhis2/utils.py | https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L102-L116 | def version_to_int(value):
"""
Convert version info to integer
:param value: the version received from system/info, e.g. "2.28"
:return: integer from version, e.g. 28, None if it couldn't be parsed
"""
# remove '-SNAPSHOT'
value = value.replace('-SNAPSHOT', '')
# remove '-RCx'
if '-R... | [
"def",
"version_to_int",
"(",
"value",
")",
":",
"# remove '-SNAPSHOT'",
"value",
"=",
"value",
".",
"replace",
"(",
"'-SNAPSHOT'",
",",
"''",
")",
"# remove '-RCx'",
"if",
"'-RC'",
"in",
"value",
":",
"value",
"=",
"value",
".",
"split",
"(",
"'-RC'",
","... | Convert version info to integer
:param value: the version received from system/info, e.g. "2.28"
:return: integer from version, e.g. 28, None if it couldn't be parsed | [
"Convert",
"version",
"info",
"to",
"integer",
":",
"param",
"value",
":",
"the",
"version",
"received",
"from",
"system",
"/",
"info",
"e",
".",
"g",
".",
"2",
".",
"28",
":",
"return",
":",
"integer",
"from",
"version",
"e",
".",
"g",
".",
"28",
... | python | train |
saltstack/salt | salt/cloud/clouds/nova.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/nova.py#L1357-L1362 | def virtual_interface_create(name, net_name, **kwargs):
'''
Create private networks
'''
conn = get_conn()
return conn.virtual_interface_create(name, net_name) | [
"def",
"virtual_interface_create",
"(",
"name",
",",
"net_name",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"get_conn",
"(",
")",
"return",
"conn",
".",
"virtual_interface_create",
"(",
"name",
",",
"net_name",
")"
] | Create private networks | [
"Create",
"private",
"networks"
] | python | train |
saltstack/salt | salt/modules/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L3128-L3173 | def write(path, *args, **kwargs):
'''
.. versionadded:: 2014.7.0
Write text to a file, overwriting any existing contents.
path
path to file
`*args`
strings to write to the file
CLI Example:
.. code-block:: bash
salt '*' file.write /etc/motd \\
"W... | [
"def",
"write",
"(",
"path",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"'args'",
"in",
"kwargs",
":",
"if",
"isinstance",
"(",
"kwargs",
"[",
"'args'",
"]",
","... | .. versionadded:: 2014.7.0
Write text to a file, overwriting any existing contents.
path
path to file
`*args`
strings to write to the file
CLI Example:
.. code-block:: bash
salt '*' file.write /etc/motd \\
"With all thine offerings thou shalt offer salt.... | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | python | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/context.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/context.py#L812-L818 | def getFile(self, name, relative=None):
"""
Returns a file name or None
"""
if self.pathCallback is not None:
return getFile(self._getFileDeprecated(name, relative))
return getFile(name, relative or self.pathDirectory) | [
"def",
"getFile",
"(",
"self",
",",
"name",
",",
"relative",
"=",
"None",
")",
":",
"if",
"self",
".",
"pathCallback",
"is",
"not",
"None",
":",
"return",
"getFile",
"(",
"self",
".",
"_getFileDeprecated",
"(",
"name",
",",
"relative",
")",
")",
"retur... | Returns a file name or None | [
"Returns",
"a",
"file",
"name",
"or",
"None"
] | python | train |
vladimarius/pyap | pyap/parser.py | https://github.com/vladimarius/pyap/blob/7896b5293982a30c1443e0c81c1ca32eeb8db15c/pyap/parser.py#L68-L79 | def _parse_address(self, address_string):
'''Parses address into parts'''
match = utils.match(self.rules, address_string, flags=re.VERBOSE | re.U)
if match:
match_as_dict = match.groupdict()
match_as_dict.update({'country_id': self.country})
# combine results
... | [
"def",
"_parse_address",
"(",
"self",
",",
"address_string",
")",
":",
"match",
"=",
"utils",
".",
"match",
"(",
"self",
".",
"rules",
",",
"address_string",
",",
"flags",
"=",
"re",
".",
"VERBOSE",
"|",
"re",
".",
"U",
")",
"if",
"match",
":",
"matc... | Parses address into parts | [
"Parses",
"address",
"into",
"parts"
] | python | train |
nickmckay/LiPD-utilities | Matlab/bagit.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L263-L319 | def save(self, processes=1, manifests=False):
"""
save will persist any changes that have been made to the bag
metadata (self.info).
If you have modified the payload of the bag (added, modified,
removed files in the data directory) and want to regenerate manifests
set th... | [
"def",
"save",
"(",
"self",
",",
"processes",
"=",
"1",
",",
"manifests",
"=",
"False",
")",
":",
"# Error checking",
"if",
"not",
"self",
".",
"path",
":",
"raise",
"BagError",
"(",
"\"Bag does not have a path.\"",
")",
"# Change working directory to bag director... | save will persist any changes that have been made to the bag
metadata (self.info).
If you have modified the payload of the bag (added, modified,
removed files in the data directory) and want to regenerate manifests
set the manifests parameter to True. The default is False since you
... | [
"save",
"will",
"persist",
"any",
"changes",
"that",
"have",
"been",
"made",
"to",
"the",
"bag",
"metadata",
"(",
"self",
".",
"info",
")",
"."
] | python | train |
saltstack/salt | salt/states/iptables.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/iptables.py#L617-L732 | def delete(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain th... | [
"def",
"delete",
"(",
"name",
",",
"table",
"=",
"'filter'",
",",
"family",
"=",
"'ipv4'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
... | .. versionadded:: 2014.1.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either ipv... | [
"..",
"versionadded",
"::",
"2014",
".",
"1",
".",
"0"
] | python | train |
scopus-api/scopus | scopus/deprecated_/scopus_author.py | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_author.py#L256-L260 | def get_document_eids(self, *args, **kwds):
"""Return list of EIDs for the author using ScopusSearch."""
search = ScopusSearch('au-id({})'.format(self.author_id),
*args, **kwds)
return search.get_eids() | [
"def",
"get_document_eids",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"search",
"=",
"ScopusSearch",
"(",
"'au-id({})'",
".",
"format",
"(",
"self",
".",
"author_id",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"return",
... | Return list of EIDs for the author using ScopusSearch. | [
"Return",
"list",
"of",
"EIDs",
"for",
"the",
"author",
"using",
"ScopusSearch",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xview.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xview.py#L984-L1001 | def registerView(viewType, location='Central'):
"""
Registers the inputed view type to the given location. The location \
is just a way to group and organize potential view plugins for a \
particular widget, and is determined per application. This eases \
use when building a pl... | [
"def",
"registerView",
"(",
"viewType",
",",
"location",
"=",
"'Central'",
")",
":",
"# update the dispatch signals",
"sigs",
"=",
"getattr",
"(",
"viewType",
",",
"'__xview_signals__'",
",",
"[",
"]",
")",
"XView",
".",
"dispatch",
"(",
"location",
")",
".",
... | Registers the inputed view type to the given location. The location \
is just a way to group and organize potential view plugins for a \
particular widget, and is determined per application. This eases \
use when building a plugin based system. It has no relevance to the \
XView class... | [
"Registers",
"the",
"inputed",
"view",
"type",
"to",
"the",
"given",
"location",
".",
"The",
"location",
"\\",
"is",
"just",
"a",
"way",
"to",
"group",
"and",
"organize",
"potential",
"view",
"plugins",
"for",
"a",
"\\",
"particular",
"widget",
"and",
"is"... | python | train |
PGower/PyCanvas | pycanvas/apis/grade_change_log.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/grade_change_log.py#L73-L98 | def query_by_student(self, student_id, end_time=None, start_time=None):
"""
Query by student.
List grade change events for a given student.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - student_id
"""ID"""
path["stud... | [
"def",
"query_by_student",
"(",
"self",
",",
"student_id",
",",
"end_time",
"=",
"None",
",",
"start_time",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - student_id\r",
"\"\"\"ID\"\"\"",
... | Query by student.
List grade change events for a given student. | [
"Query",
"by",
"student",
".",
"List",
"grade",
"change",
"events",
"for",
"a",
"given",
"student",
"."
] | python | train |
bunq/sdk_python | bunq/sdk/model/generated/endpoint.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L14938-L14982 | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._counter_alias is not None:
r... | [
"def",
"is_all_field_none",
"(",
"self",
")",
":",
"if",
"self",
".",
"_id_",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_created",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_updated",
"is",
"not",
"None",
... | :rtype: bool | [
":",
"rtype",
":",
"bool"
] | python | train |
dnanexus/dx-toolkit | src/python/dxpy/api.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L275-L281 | def applet_list_projects(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /applet-xxxx/listProjects API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects
"""
return DXHTTPRequest('/%s/listProjec... | [
"def",
"applet_list_projects",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/listProjects'",
"%",
"object_id",
",",
"input_params",
",",
"always_... | Invokes the /applet-xxxx/listProjects API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects | [
"Invokes",
"the",
"/",
"applet",
"-",
"xxxx",
"/",
"listProjects",
"API",
"method",
"."
] | python | train |
ValvePython/steam | steam/core/crypto.py | https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/core/crypto.py#L34-L45 | def generate_session_key(hmac_secret=b''):
"""
:param hmac_secret: optional HMAC
:type hmac_secret: :class:`bytes`
:return: (session_key, encrypted_session_key) tuple
:rtype: :class:`tuple`
"""
session_key = random_bytes(32)
encrypted_session_key = PKCS1_OAEP.new(UniverseKey.Public, SHA1... | [
"def",
"generate_session_key",
"(",
"hmac_secret",
"=",
"b''",
")",
":",
"session_key",
"=",
"random_bytes",
"(",
"32",
")",
"encrypted_session_key",
"=",
"PKCS1_OAEP",
".",
"new",
"(",
"UniverseKey",
".",
"Public",
",",
"SHA1",
")",
".",
"encrypt",
"(",
"se... | :param hmac_secret: optional HMAC
:type hmac_secret: :class:`bytes`
:return: (session_key, encrypted_session_key) tuple
:rtype: :class:`tuple` | [
":",
"param",
"hmac_secret",
":",
"optional",
"HMAC",
":",
"type",
"hmac_secret",
":",
":",
"class",
":",
"bytes",
":",
"return",
":",
"(",
"session_key",
"encrypted_session_key",
")",
"tuple",
":",
"rtype",
":",
":",
"class",
":",
"tuple"
] | python | train |
econ-ark/HARK | HARK/interpolation.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/interpolation.py#L3371-L3410 | def calcLogSumChoiceProbs(Vals, sigma):
'''
Returns the final optimal value and choice probabilities given the choice
specific value functions `Vals`. Probabilities are degenerate if sigma == 0.0.
Parameters
----------
Vals : [numpy.array]
A numpy.array that holds choice specific values ... | [
"def",
"calcLogSumChoiceProbs",
"(",
"Vals",
",",
"sigma",
")",
":",
"# Assumes that NaNs have been replaced by -numpy.inf or similar",
"if",
"sigma",
"==",
"0.0",
":",
"# We could construct a linear index here and use unravel_index.",
"Pflat",
"=",
"np",
".",
"argmax",
"(",
... | Returns the final optimal value and choice probabilities given the choice
specific value functions `Vals`. Probabilities are degenerate if sigma == 0.0.
Parameters
----------
Vals : [numpy.array]
A numpy.array that holds choice specific values at common grid points.
sigma : float
A n... | [
"Returns",
"the",
"final",
"optimal",
"value",
"and",
"choice",
"probabilities",
"given",
"the",
"choice",
"specific",
"value",
"functions",
"Vals",
".",
"Probabilities",
"are",
"degenerate",
"if",
"sigma",
"==",
"0",
".",
"0",
".",
"Parameters",
"----------",
... | python | train |
sgaynetdinov/py-vkontakte | vk/auth.py | https://github.com/sgaynetdinov/py-vkontakte/blob/c09654f89008b5847418bb66f1f9c408cd7aa128/vk/auth.py#L35-L76 | def get_url_authcode_flow_user(client_id, redirect_uri, display="page", scope=None, state=None):
"""Authorization Code Flow for User Access Token
Use Authorization Code Flow to run VK API methods from the server side of an application.
Access token received this way is not bound to an ip address but set of... | [
"def",
"get_url_authcode_flow_user",
"(",
"client_id",
",",
"redirect_uri",
",",
"display",
"=",
"\"page\"",
",",
"scope",
"=",
"None",
",",
"state",
"=",
"None",
")",
":",
"url",
"=",
"\"https://oauth.vk.com/authorize\"",
"params",
"=",
"{",
"\"client_id\"",
":... | Authorization Code Flow for User Access Token
Use Authorization Code Flow to run VK API methods from the server side of an application.
Access token received this way is not bound to an ip address but set of permissions that can be granted is limited for security reasons.
Args:
client_id (int): Ap... | [
"Authorization",
"Code",
"Flow",
"for",
"User",
"Access",
"Token"
] | python | train |
cyface/django-termsandconditions | termsandconditions/pipeline.py | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/pipeline.py#L28-L36 | def redirect_to_terms_accept(current_path='/', slug='default'):
"""Redirect the user to the terms and conditions accept page."""
redirect_url_parts = list(urlparse(ACCEPT_TERMS_PATH))
if slug != 'default':
redirect_url_parts[2] += slug
querystring = QueryDict(redirect_url_parts[4], mutable=True)... | [
"def",
"redirect_to_terms_accept",
"(",
"current_path",
"=",
"'/'",
",",
"slug",
"=",
"'default'",
")",
":",
"redirect_url_parts",
"=",
"list",
"(",
"urlparse",
"(",
"ACCEPT_TERMS_PATH",
")",
")",
"if",
"slug",
"!=",
"'default'",
":",
"redirect_url_parts",
"[",
... | Redirect the user to the terms and conditions accept page. | [
"Redirect",
"the",
"user",
"to",
"the",
"terms",
"and",
"conditions",
"accept",
"page",
"."
] | python | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/tools.py | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/tools.py#L95-L129 | def load_with_cache(file_, recache=False, sampling=1,
columns=None, temp_dir='.', data_type='int16'):
"""@brief This function loads a file from the current directory and saves
the cached file to later executions. It's also possible to make a recache
or a subsampling of the signal and cho... | [
"def",
"load_with_cache",
"(",
"file_",
",",
"recache",
"=",
"False",
",",
"sampling",
"=",
"1",
",",
"columns",
"=",
"None",
",",
"temp_dir",
"=",
"'.'",
",",
"data_type",
"=",
"'int16'",
")",
":",
"cfile",
"=",
"'%s.npy'",
"%",
"file_",
"if",
"(",
... | @brief This function loads a file from the current directory and saves
the cached file to later executions. It's also possible to make a recache
or a subsampling of the signal and choose only a few columns of the signal,
to accelerate the opening process.
@param file String: the name of the file to ope... | [
"@brief",
"This",
"function",
"loads",
"a",
"file",
"from",
"the",
"current",
"directory",
"and",
"saves",
"the",
"cached",
"file",
"to",
"later",
"executions",
".",
"It",
"s",
"also",
"possible",
"to",
"make",
"a",
"recache",
"or",
"a",
"subsampling",
"of... | python | train |
lsbardel/python-stdnet | stdnet/utils/py2py3.py | https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/utils/py2py3.py#L94-L101 | def to_string(s, encoding=None, errors='strict'):
"""Inverse of to_bytes"""
encoding = encoding or 'utf-8'
if isinstance(s, bytes):
return s.decode(encoding, errors)
if not is_string(s):
s = string_type(s)
return s | [
"def",
"to_string",
"(",
"s",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
")",
":",
"encoding",
"=",
"encoding",
"or",
"'utf-8'",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"return",
"s",
".",
"decode",
"(",
"encoding",
"... | Inverse of to_bytes | [
"Inverse",
"of",
"to_bytes"
] | python | train |
waqasbhatti/astrobase | astrobase/fakelcs/recovery.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/fakelcs/recovery.py#L683-L831 | def variable_index_gridsearch_magbin(simbasedir,
stetson_stdev_range=(1.0,20.0),
inveta_stdev_range=(1.0,20.0),
iqr_stdev_range=(1.0,20.0),
ngridpoints=32,
... | [
"def",
"variable_index_gridsearch_magbin",
"(",
"simbasedir",
",",
"stetson_stdev_range",
"=",
"(",
"1.0",
",",
"20.0",
")",
",",
"inveta_stdev_range",
"=",
"(",
"1.0",
",",
"20.0",
")",
",",
"iqr_stdev_range",
"=",
"(",
"1.0",
",",
"20.0",
")",
",",
"ngridp... | This runs a variable index grid search per magbin.
For each magbin, this does a grid search using the stetson and inveta ranges
provided and tries to optimize the Matthews Correlation Coefficient (best
value is +1.0), indicating the best possible separation of variables
vs. nonvariables. The thresholds... | [
"This",
"runs",
"a",
"variable",
"index",
"grid",
"search",
"per",
"magbin",
"."
] | python | valid |
toomore/goristock | grs/goristock.py | https://github.com/toomore/goristock/blob/e61f57f11a626cfbc4afbf66337fd9d1c51e3e71/grs/goristock.py#L455-L459 | def MAVOL_serial(self,days,rev=0):
""" see make_serial()
成較量移動平均 list 化,資料格式請見 def make_serial()
"""
return self.make_serial(self.stock_vol,days,rev=0) | [
"def",
"MAVOL_serial",
"(",
"self",
",",
"days",
",",
"rev",
"=",
"0",
")",
":",
"return",
"self",
".",
"make_serial",
"(",
"self",
".",
"stock_vol",
",",
"days",
",",
"rev",
"=",
"0",
")"
] | see make_serial()
成較量移動平均 list 化,資料格式請見 def make_serial() | [
"see",
"make_serial",
"()",
"成較量移動平均",
"list",
"化,資料格式請見",
"def",
"make_serial",
"()"
] | python | train |
honsiorovskyi/codeharvester | src/codeharvester/harvester.py | https://github.com/honsiorovskyi/codeharvester/blob/301b907b32ef9bbdb7099657100fbd3829c3ecc8/src/codeharvester/harvester.py#L107-L150 | def replace_requirements(self, infilename, outfile_initial=None):
"""
Recursively replaces the requirements in the files with the content of the requirements.
Returns final temporary file opened for reading.
"""
infile = open(infilename, 'r')
# extract the requirements ... | [
"def",
"replace_requirements",
"(",
"self",
",",
"infilename",
",",
"outfile_initial",
"=",
"None",
")",
":",
"infile",
"=",
"open",
"(",
"infilename",
",",
"'r'",
")",
"# extract the requirements for this file that were not skipped from the global database",
"_indexes",
... | Recursively replaces the requirements in the files with the content of the requirements.
Returns final temporary file opened for reading. | [
"Recursively",
"replaces",
"the",
"requirements",
"in",
"the",
"files",
"with",
"the",
"content",
"of",
"the",
"requirements",
".",
"Returns",
"final",
"temporary",
"file",
"opened",
"for",
"reading",
"."
] | python | train |
jayvdb/flake8-putty | flake8_putty/extension.py | https://github.com/jayvdb/flake8-putty/blob/854b2c6daef409974c2f5e9c5acaf0a069b0ff23/flake8_putty/extension.py#L44-L69 | def putty_ignore_code(options, code):
"""Implement pep8 'ignore_code' hook."""
reporter, line_number, offset, text, check = get_reporter_state()
try:
line = reporter.lines[line_number - 1]
except IndexError:
line = ''
options.ignore = options._orig_ignore
options.select = option... | [
"def",
"putty_ignore_code",
"(",
"options",
",",
"code",
")",
":",
"reporter",
",",
"line_number",
",",
"offset",
",",
"text",
",",
"check",
"=",
"get_reporter_state",
"(",
")",
"try",
":",
"line",
"=",
"reporter",
".",
"lines",
"[",
"line_number",
"-",
... | Implement pep8 'ignore_code' hook. | [
"Implement",
"pep8",
"ignore_code",
"hook",
"."
] | python | train |
slarse/clanimtk | clanimtk/core.py | https://github.com/slarse/clanimtk/blob/cb93d2e914c3ecc4e0007745ff4d546318cf3902/clanimtk/core.py#L252-L270 | def _get_back_up_generator(frame_function, *args, **kwargs):
"""Create a generator for the provided animation function that backs up
the cursor after a frame. Assumes that the animation function provides
a generator that yields strings of constant width and height.
Args:
frame_function: A funct... | [
"def",
"_get_back_up_generator",
"(",
"frame_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lines",
"=",
"next",
"(",
"frame_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
".",
"split",
"(",
"'\\n'",
")",
"width",
"... | Create a generator for the provided animation function that backs up
the cursor after a frame. Assumes that the animation function provides
a generator that yields strings of constant width and height.
Args:
frame_function: A function that returns a FrameGenerator.
args: Arguments for frame... | [
"Create",
"a",
"generator",
"for",
"the",
"provided",
"animation",
"function",
"that",
"backs",
"up",
"the",
"cursor",
"after",
"a",
"frame",
".",
"Assumes",
"that",
"the",
"animation",
"function",
"provides",
"a",
"generator",
"that",
"yields",
"strings",
"of... | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/terminal/embed.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/terminal/embed.py#L254-L283 | def embed(**kwargs):
"""Call this to embed IPython at the current point in your program.
The first invocation of this will create an :class:`InteractiveShellEmbed`
instance and then call it. Consecutive calls just call the already
created instance.
Here is a simple example::
from IPython... | [
"def",
"embed",
"(",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"kwargs",
".",
"get",
"(",
"'config'",
")",
"header",
"=",
"kwargs",
".",
"pop",
"(",
"'header'",
",",
"u''",
")",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"load_default_confi... | Call this to embed IPython at the current point in your program.
The first invocation of this will create an :class:`InteractiveShellEmbed`
instance and then call it. Consecutive calls just call the already
created instance.
Here is a simple example::
from IPython import embed
a = 10... | [
"Call",
"this",
"to",
"embed",
"IPython",
"at",
"the",
"current",
"point",
"in",
"your",
"program",
"."
] | python | test |
saltstack/salt | salt/utils/network.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L173-L183 | def generate_minion_id():
'''
Return only first element of the hostname from all possible list.
:return:
'''
try:
ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first())
except TypeError:
ret = None
return ret or 'localhost' | [
"def",
"generate_minion_id",
"(",
")",
":",
"try",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"_generate_minion_id",
"(",
")",
".",
"first",
"(",
")",
")",
"except",
"TypeError",
":",
"ret",
"=",
"None",
"return",
... | Return only first element of the hostname from all possible list.
:return: | [
"Return",
"only",
"first",
"element",
"of",
"the",
"hostname",
"from",
"all",
"possible",
"list",
"."
] | python | train |
PyCQA/astroid | astroid/protocols.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/protocols.py#L402-L439 | def _resolve_assignment_parts(parts, assign_path, context):
"""recursive function to resolve multiple assignments"""
assign_path = assign_path[:]
index = assign_path.pop(0)
for part in parts:
assigned = None
if isinstance(part, nodes.Dict):
# A dictionary in an iterating cont... | [
"def",
"_resolve_assignment_parts",
"(",
"parts",
",",
"assign_path",
",",
"context",
")",
":",
"assign_path",
"=",
"assign_path",
"[",
":",
"]",
"index",
"=",
"assign_path",
".",
"pop",
"(",
"0",
")",
"for",
"part",
"in",
"parts",
":",
"assigned",
"=",
... | recursive function to resolve multiple assignments | [
"recursive",
"function",
"to",
"resolve",
"multiple",
"assignments"
] | python | train |
Cue/scales | src/greplin/scales/flaskhandler.py | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/flaskhandler.py#L64-L74 | def serveInBackground(port, serverName, prefix='/status/'):
"""Convenience function: spawn a background server thread that will
serve HTTP requests to get the status. Returns the thread."""
import flask, threading
from wsgiref.simple_server import make_server
app = flask.Flask(__name__)
registerStatsHandler... | [
"def",
"serveInBackground",
"(",
"port",
",",
"serverName",
",",
"prefix",
"=",
"'/status/'",
")",
":",
"import",
"flask",
",",
"threading",
"from",
"wsgiref",
".",
"simple_server",
"import",
"make_server",
"app",
"=",
"flask",
".",
"Flask",
"(",
"__name__",
... | Convenience function: spawn a background server thread that will
serve HTTP requests to get the status. Returns the thread. | [
"Convenience",
"function",
":",
"spawn",
"a",
"background",
"server",
"thread",
"that",
"will",
"serve",
"HTTP",
"requests",
"to",
"get",
"the",
"status",
".",
"Returns",
"the",
"thread",
"."
] | python | train |
abe-winter/pg13-py | pg13/pgmock_dbapi2.py | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pgmock_dbapi2.py#L195-L201 | def call_cur(f):
"decorator for opening a connection and passing a cursor to the function"
@functools.wraps(f)
def f2(self, *args, **kwargs):
with self.withcur() as cur:
return f(self, cur, *args, **kwargs)
return f2 | [
"def",
"call_cur",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"f2",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"withcur",
"(",
")",
"as",
"cur",
":",
"return",
"f",
"(... | decorator for opening a connection and passing a cursor to the function | [
"decorator",
"for",
"opening",
"a",
"connection",
"and",
"passing",
"a",
"cursor",
"to",
"the",
"function"
] | python | train |
mitsei/dlkit | dlkit/json_/authorization/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/authorization/sessions.py#L3247-L3266 | def is_descendant_of_vault(self, id_, vault_id):
"""Tests if an ``Id`` is a descendant of a vault.
arg: id (osid.id.Id): an ``Id``
arg: vault_id (osid.id.Id): the ``Id`` of a vault
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``vault_id,`` ``f... | [
"def",
"is_descendant_of_vault",
"(",
"self",
",",
"id_",
",",
"vault_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.is_descendant_of_bin",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_... | Tests if an ``Id`` is a descendant of a vault.
arg: id (osid.id.Id): an ``Id``
arg: vault_id (osid.id.Id): the ``Id`` of a vault
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``vault_id,`` ``false`` otherwise
raise: NotFound - ``vault_id`` not... | [
"Tests",
"if",
"an",
"Id",
"is",
"a",
"descendant",
"of",
"a",
"vault",
"."
] | python | train |
hobson/aima | aima/text.py | https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L153-L155 | def present_results(self, query_text, n=10):
"Get results for the query and present them."
self.present(self.query(query_text, n)) | [
"def",
"present_results",
"(",
"self",
",",
"query_text",
",",
"n",
"=",
"10",
")",
":",
"self",
".",
"present",
"(",
"self",
".",
"query",
"(",
"query_text",
",",
"n",
")",
")"
] | Get results for the query and present them. | [
"Get",
"results",
"for",
"the",
"query",
"and",
"present",
"them",
"."
] | python | valid |
hazelcast/hazelcast-remote-controller | python-controller/hzrc/RemoteController.py | https://github.com/hazelcast/hazelcast-remote-controller/blob/41b9e7d2d722b69ff79642eb34b702c9a6087635/python-controller/hzrc/RemoteController.py#L366-L373 | def resumeMember(self, clusterId, memberId):
"""
Parameters:
- clusterId
- memberId
"""
self.send_resumeMember(clusterId, memberId)
return self.recv_resumeMember() | [
"def",
"resumeMember",
"(",
"self",
",",
"clusterId",
",",
"memberId",
")",
":",
"self",
".",
"send_resumeMember",
"(",
"clusterId",
",",
"memberId",
")",
"return",
"self",
".",
"recv_resumeMember",
"(",
")"
] | Parameters:
- clusterId
- memberId | [
"Parameters",
":",
"-",
"clusterId",
"-",
"memberId"
] | python | train |
saltstack/salt | salt/scripts.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L552-L563 | def salt_support():
'''
Run Salt Support that collects system data, logs etc for debug and support purposes.
:return:
'''
import salt.cli.support.collector
if '' in sys.path:
sys.path.remove('')
client = salt.cli.support.collector.SaltSupport()
_install_signal_handlers(client)
... | [
"def",
"salt_support",
"(",
")",
":",
"import",
"salt",
".",
"cli",
".",
"support",
".",
"collector",
"if",
"''",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"remove",
"(",
"''",
")",
"client",
"=",
"salt",
".",
"cli",
".",
"support",
... | Run Salt Support that collects system data, logs etc for debug and support purposes.
:return: | [
"Run",
"Salt",
"Support",
"that",
"collects",
"system",
"data",
"logs",
"etc",
"for",
"debug",
"and",
"support",
"purposes",
".",
":",
"return",
":"
] | python | train |
skorch-dev/skorch | examples/nuclei_image_segmentation/utils.py | https://github.com/skorch-dev/skorch/blob/5b9b8b7b7712cb6e5aaa759d9608ea6269d5bcd3/examples/nuclei_image_segmentation/utils.py#L42-L62 | def plot_mask_cell(true_mask,
predicted_mask,
cell,
suffix,
ax1,
ax2,
ax3,
padding=16):
"""Plots a single cell with a its true mask and predicuted mask"""
for ax in [ax1, ax2, ax3... | [
"def",
"plot_mask_cell",
"(",
"true_mask",
",",
"predicted_mask",
",",
"cell",
",",
"suffix",
",",
"ax1",
",",
"ax2",
",",
"ax3",
",",
"padding",
"=",
"16",
")",
":",
"for",
"ax",
"in",
"[",
"ax1",
",",
"ax2",
",",
"ax3",
"]",
":",
"ax",
".",
"gr... | Plots a single cell with a its true mask and predicuted mask | [
"Plots",
"a",
"single",
"cell",
"with",
"a",
"its",
"true",
"mask",
"and",
"predicuted",
"mask"
] | python | train |
src-d/modelforge | modelforge/meta.py | https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/meta.py#L73-L95 | def extract_model_meta(base_meta: dict, extra_meta: dict, model_url: str) -> dict:
"""
Merge the metadata from the backend and the extra metadata into a dict which is suitable for \
`index.json`.
:param base_meta: tree["meta"] :class:`dict` containing data from the backend.
:param extra_meta: dict ... | [
"def",
"extract_model_meta",
"(",
"base_meta",
":",
"dict",
",",
"extra_meta",
":",
"dict",
",",
"model_url",
":",
"str",
")",
"->",
"dict",
":",
"meta",
"=",
"{",
"\"default\"",
":",
"{",
"\"default\"",
":",
"base_meta",
"[",
"\"uuid\"",
"]",
",",
"\"de... | Merge the metadata from the backend and the extra metadata into a dict which is suitable for \
`index.json`.
:param base_meta: tree["meta"] :class:`dict` containing data from the backend.
:param extra_meta: dict containing data from the user, similar to `template_meta.json`.
:param model_url: public UR... | [
"Merge",
"the",
"metadata",
"from",
"the",
"backend",
"and",
"the",
"extra",
"metadata",
"into",
"a",
"dict",
"which",
"is",
"suitable",
"for",
"\\",
"index",
".",
"json",
"."
] | python | train |
python-gitlab/python-gitlab | gitlab/v4/objects.py | https://github.com/python-gitlab/python-gitlab/blob/16de1b03fde3dbbe8f851614dd1d8c09de102fe5/gitlab/v4/objects.py#L1544-L1557 | def cherry_pick(self, branch, **kwargs):
"""Cherry-pick a commit into a branch.
Args:
branch (str): Name of target branch
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
... | [
"def",
"cherry_pick",
"(",
"self",
",",
"branch",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"'%s/%s/cherry_pick'",
"%",
"(",
"self",
".",
"manager",
".",
"path",
",",
"self",
".",
"get_id",
"(",
")",
")",
"post_data",
"=",
"{",
"'branch'",
":",... | Cherry-pick a commit into a branch.
Args:
branch (str): Name of target branch
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCherryPickError: If the cherry-pick could no... | [
"Cherry",
"-",
"pick",
"a",
"commit",
"into",
"a",
"branch",
"."
] | python | train |
lpantano/seqcluster | seqcluster/libs/inputs.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/inputs.py#L27-L55 | def parse_ma_file(seq_obj, in_file):
"""
read seqs.ma file and create dict with
sequence object
"""
name = ""
index = 1
total = defaultdict(int)
with open(in_file) as handle_in:
line = handle_in.readline().strip()
cols = line.split("\t")
samples = cols[2:]
... | [
"def",
"parse_ma_file",
"(",
"seq_obj",
",",
"in_file",
")",
":",
"name",
"=",
"\"\"",
"index",
"=",
"1",
"total",
"=",
"defaultdict",
"(",
"int",
")",
"with",
"open",
"(",
"in_file",
")",
"as",
"handle_in",
":",
"line",
"=",
"handle_in",
".",
"readlin... | read seqs.ma file and create dict with
sequence object | [
"read",
"seqs",
".",
"ma",
"file",
"and",
"create",
"dict",
"with",
"sequence",
"object"
] | python | train |
Esri/ArcREST | src/arcrest/ags/layer.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/layer.py#L1344-L1347 | def asJSON(self):
""" returns the data source as JSON """
self._json = json.dumps(self.asDictionary)
return self._json | [
"def",
"asJSON",
"(",
"self",
")",
":",
"self",
".",
"_json",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"asDictionary",
")",
"return",
"self",
".",
"_json"
] | returns the data source as JSON | [
"returns",
"the",
"data",
"source",
"as",
"JSON"
] | python | train |
saltstack/salt | salt/modules/pkgin.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkgin.py#L645-L660 | def file_list(package, **kwargs):
'''
List the files that belong to a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list nginx
'''
ret = file_dict(package)
files = []
for pkg_files in six.itervalues(ret['files']):
files.extend(pkg_files)
ret['files'... | [
"def",
"file_list",
"(",
"package",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"file_dict",
"(",
"package",
")",
"files",
"=",
"[",
"]",
"for",
"pkg_files",
"in",
"six",
".",
"itervalues",
"(",
"ret",
"[",
"'files'",
"]",
")",
":",
"files",
"."... | List the files that belong to a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list nginx | [
"List",
"the",
"files",
"that",
"belong",
"to",
"a",
"package",
"."
] | python | train |
delph-in/pydelphin | delphin/mrs/eds.py | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/eds.py#L224-L258 | def from_triples(cls, triples):
"""
Decode triples, as from :meth:`to_triples`, into an Eds object.
"""
nids, nd, edges = [], {}, []
for src, rel, tgt in triples:
if src not in nd:
nids.append(src)
nd[src] = {'pred': None, 'lnk': None, ... | [
"def",
"from_triples",
"(",
"cls",
",",
"triples",
")",
":",
"nids",
",",
"nd",
",",
"edges",
"=",
"[",
"]",
",",
"{",
"}",
",",
"[",
"]",
"for",
"src",
",",
"rel",
",",
"tgt",
"in",
"triples",
":",
"if",
"src",
"not",
"in",
"nd",
":",
"nids"... | Decode triples, as from :meth:`to_triples`, into an Eds object. | [
"Decode",
"triples",
"as",
"from",
":",
"meth",
":",
"to_triples",
"into",
"an",
"Eds",
"object",
"."
] | python | train |
Garee/pytodoist | pytodoist/todoist.py | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L135-L167 | def register_with_google(full_name, email, oauth2_token,
lang=None, timezone=None):
"""Register a new Todoist account by linking a Google account.
:param full_name: The user's full name.
:type full_name: str
:param email: The user's email address.
:type email: str
:para... | [
"def",
"register_with_google",
"(",
"full_name",
",",
"email",
",",
"oauth2_token",
",",
"lang",
"=",
"None",
",",
"timezone",
"=",
"None",
")",
":",
"response",
"=",
"API",
".",
"login_with_google",
"(",
"email",
",",
"oauth2_token",
",",
"auto_signup",
"="... | Register a new Todoist account by linking a Google account.
:param full_name: The user's full name.
:type full_name: str
:param email: The user's email address.
:type email: str
:param oauth2_token: The oauth2 token associated with the email.
:type oauth2_token: str
:param lang: The user's ... | [
"Register",
"a",
"new",
"Todoist",
"account",
"by",
"linking",
"a",
"Google",
"account",
"."
] | python | train |
django-treebeard/django-treebeard | treebeard/models.py | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/models.py#L317-L329 | def get_next_sibling(self):
"""
:returns:
The next node's sibling, or None if it was the rightmost
sibling.
"""
siblings = self.get_siblings()
ids = [obj.pk for obj in siblings]
if self.pk in ids:
idx = ids.index(self.pk)
i... | [
"def",
"get_next_sibling",
"(",
"self",
")",
":",
"siblings",
"=",
"self",
".",
"get_siblings",
"(",
")",
"ids",
"=",
"[",
"obj",
".",
"pk",
"for",
"obj",
"in",
"siblings",
"]",
"if",
"self",
".",
"pk",
"in",
"ids",
":",
"idx",
"=",
"ids",
".",
"... | :returns:
The next node's sibling, or None if it was the rightmost
sibling. | [
":",
"returns",
":"
] | python | train |
IBMStreams/pypi.streamsx | streamsx/topology/state.py | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/state.py#L177-L190 | def operator_driven(drain_timeout=_DEFAULT_DRAIN, reset_timeout=_DEFAULT_RESET, max_consecutive_attempts=_DEFAULT_ATTEMPTS):
"""Define an operator-driven consistent region configuration.
The source operator triggers drain and checkpoint cycles for the region.
Args:
drain_timeout: Th... | [
"def",
"operator_driven",
"(",
"drain_timeout",
"=",
"_DEFAULT_DRAIN",
",",
"reset_timeout",
"=",
"_DEFAULT_RESET",
",",
"max_consecutive_attempts",
"=",
"_DEFAULT_ATTEMPTS",
")",
":",
"return",
"ConsistentRegionConfig",
"(",
"trigger",
"=",
"ConsistentRegionConfig",
".",... | Define an operator-driven consistent region configuration.
The source operator triggers drain and checkpoint cycles for the region.
Args:
drain_timeout: The drain timeout, as either a :py:class:`datetime.timedelta` value or the number of seconds as a `float`. If not specified, the default ... | [
"Define",
"an",
"operator",
"-",
"driven",
"consistent",
"region",
"configuration",
".",
"The",
"source",
"operator",
"triggers",
"drain",
"and",
"checkpoint",
"cycles",
"for",
"the",
"region",
"."
] | python | train |
noahbenson/pimms | pimms/immutable.py | https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/immutable.py#L444-L461 | def param(f):
'''
The @param decorator, usable in an immutable class (see immutable), specifies that the following
function is actually a transformation on an input parameter; the parameter is required, and is
set to the value returned by the function decorated by the parameter; i.e., if you decorate t... | [
"def",
"param",
"(",
"f",
")",
":",
"(",
"args",
",",
"varargs",
",",
"kwargs",
",",
"dflts",
")",
"=",
"getargspec_py27like",
"(",
"f",
")",
"if",
"varargs",
"is",
"not",
"None",
"or",
"kwargs",
"is",
"not",
"None",
"or",
"dflts",
":",
"raise",
"V... | The @param decorator, usable in an immutable class (see immutable), specifies that the following
function is actually a transformation on an input parameter; the parameter is required, and is
set to the value returned by the function decorated by the parameter; i.e., if you decorate the
function abc with @... | [
"The"
] | python | train |
MisterWil/abodepy | abodepy/__init__.py | https://github.com/MisterWil/abodepy/blob/6f84bb428fd1da98855f55083cd427bebbcc57ae/abodepy/__init__.py#L330-L350 | def set_setting(self, setting, value, area='1', validate_value=True):
"""Set an abode system setting to a given value."""
setting = setting.lower()
if setting not in CONST.ALL_SETTINGS:
raise AbodeException(ERROR.INVALID_SETTING, CONST.ALL_SETTINGS)
if setting in CONST.PANE... | [
"def",
"set_setting",
"(",
"self",
",",
"setting",
",",
"value",
",",
"area",
"=",
"'1'",
",",
"validate_value",
"=",
"True",
")",
":",
"setting",
"=",
"setting",
".",
"lower",
"(",
")",
"if",
"setting",
"not",
"in",
"CONST",
".",
"ALL_SETTINGS",
":",
... | Set an abode system setting to a given value. | [
"Set",
"an",
"abode",
"system",
"setting",
"to",
"a",
"given",
"value",
"."
] | python | train |
openmicroscopy/omero-marshal | omero_marshal/legacy/affinetransform.py | https://github.com/openmicroscopy/omero-marshal/blob/0f427927b471a19f14b434452de88e16d621c487/omero_marshal/legacy/affinetransform.py#L38-L83 | def convert_svg_transform(self, transform):
"""
Converts a string representing a SVG transform into
AffineTransform fields.
See https://www.w3.org/TR/SVG/coords.html#TransformAttribute for the
specification of the transform strings. skewX and skewY are not
supported.
... | [
"def",
"convert_svg_transform",
"(",
"self",
",",
"transform",
")",
":",
"tr",
",",
"args",
"=",
"transform",
"[",
":",
"-",
"1",
"]",
".",
"split",
"(",
"'('",
")",
"a",
"=",
"map",
"(",
"float",
",",
"args",
".",
"split",
"(",
"' '",
")",
")",
... | Converts a string representing a SVG transform into
AffineTransform fields.
See https://www.w3.org/TR/SVG/coords.html#TransformAttribute for the
specification of the transform strings. skewX and skewY are not
supported.
Raises:
ValueError: If transform is not a valid ... | [
"Converts",
"a",
"string",
"representing",
"a",
"SVG",
"transform",
"into",
"AffineTransform",
"fields",
".",
"See",
"https",
":",
"//",
"www",
".",
"w3",
".",
"org",
"/",
"TR",
"/",
"SVG",
"/",
"coords",
".",
"html#TransformAttribute",
"for",
"the",
"spec... | python | train |
nitmir/django-cas-server | cas_server/cas.py | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/cas.py#L185-L188 | def verify_ticket(self, ticket):
"""Verifies CAS 2.0+/3.0+ XML-based authentication ticket and returns extended attributes"""
(response, charset) = self.get_verification_response(ticket)
return self.verify_response(response, charset) | [
"def",
"verify_ticket",
"(",
"self",
",",
"ticket",
")",
":",
"(",
"response",
",",
"charset",
")",
"=",
"self",
".",
"get_verification_response",
"(",
"ticket",
")",
"return",
"self",
".",
"verify_response",
"(",
"response",
",",
"charset",
")"
] | Verifies CAS 2.0+/3.0+ XML-based authentication ticket and returns extended attributes | [
"Verifies",
"CAS",
"2",
".",
"0",
"+",
"/",
"3",
".",
"0",
"+",
"XML",
"-",
"based",
"authentication",
"ticket",
"and",
"returns",
"extended",
"attributes"
] | python | train |
ismms-himc/clustergrammer2 | clustergrammer2/clustergrammer_fun/categories.py | https://github.com/ismms-himc/clustergrammer2/blob/5acea9bff7eda546cf0647b9e3647f631eb6f5f5/clustergrammer2/clustergrammer_fun/categories.py#L137-L234 | def calc_cat_clust_order(net, inst_rc):
'''
cluster category subset of data
'''
from .__init__ import Network
from copy import deepcopy
from . import calc_clust, run_filter
inst_keys = list(net.dat['node_info'][inst_rc].keys())
all_cats = [x for x in inst_keys if 'cat-' in x]
if len(all_cats) > 0:
... | [
"def",
"calc_cat_clust_order",
"(",
"net",
",",
"inst_rc",
")",
":",
"from",
".",
"__init__",
"import",
"Network",
"from",
"copy",
"import",
"deepcopy",
"from",
".",
"import",
"calc_clust",
",",
"run_filter",
"inst_keys",
"=",
"list",
"(",
"net",
".",
"dat",... | cluster category subset of data | [
"cluster",
"category",
"subset",
"of",
"data"
] | python | train |
mdgoldberg/sportsref | sportsref/nfl/boxscores.py | https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nfl/boxscores.py#L224-L236 | def over_under(self):
"""
Returns the over/under for the game as a float, or np.nan if not
available.
"""
doc = self.get_doc()
table = doc('table#game_info')
giTable = sportsref.utils.parse_info_table(table)
if 'over_under' in giTable:
ou = giT... | [
"def",
"over_under",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"get_doc",
"(",
")",
"table",
"=",
"doc",
"(",
"'table#game_info'",
")",
"giTable",
"=",
"sportsref",
".",
"utils",
".",
"parse_info_table",
"(",
"table",
")",
"if",
"'over_under'",
"in... | Returns the over/under for the game as a float, or np.nan if not
available. | [
"Returns",
"the",
"over",
"/",
"under",
"for",
"the",
"game",
"as",
"a",
"float",
"or",
"np",
".",
"nan",
"if",
"not",
"available",
"."
] | python | test |
gem/oq-engine | openquake/baselib/node.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L757-L771 | def context(fname, node):
"""
Context manager managing exceptions and adding line number of the
current node and name of the current file to the error message.
:param fname: the current file being processed
:param node: the current node being processed
"""
try:
yield node
except... | [
"def",
"context",
"(",
"fname",
",",
"node",
")",
":",
"try",
":",
"yield",
"node",
"except",
"Exception",
":",
"etype",
",",
"exc",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'node %s: %s, line %s of %s'",
"%",
"(",
"striptag",
"("... | Context manager managing exceptions and adding line number of the
current node and name of the current file to the error message.
:param fname: the current file being processed
:param node: the current node being processed | [
"Context",
"manager",
"managing",
"exceptions",
"and",
"adding",
"line",
"number",
"of",
"the",
"current",
"node",
"and",
"name",
"of",
"the",
"current",
"file",
"to",
"the",
"error",
"message",
"."
] | python | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L203-L217 | def _SGraphFromJsonTree(json_str):
"""
Convert the Json Tree to SGraph
"""
g = json.loads(json_str)
vertices = [_Vertex(x['id'],
dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'id']))
for x in g['vertices']]
edges = [... | [
"def",
"_SGraphFromJsonTree",
"(",
"json_str",
")",
":",
"g",
"=",
"json",
".",
"loads",
"(",
"json_str",
")",
"vertices",
"=",
"[",
"_Vertex",
"(",
"x",
"[",
"'id'",
"]",
",",
"dict",
"(",
"[",
"(",
"str",
"(",
"k",
")",
",",
"v",
")",
"for",
... | Convert the Json Tree to SGraph | [
"Convert",
"the",
"Json",
"Tree",
"to",
"SGraph"
] | python | train |
line/line-bot-sdk-python | linebot/utils.py | https://github.com/line/line-bot-sdk-python/blob/1b38bfc2497ff3e3c75be4b50e0f1b7425a07ce0/linebot/utils.py#L39-L47 | def to_camel_case(text):
"""Convert to camel case.
:param str text:
:rtype: str
:return:
"""
split = text.split('_')
return split[0] + "".join(x.title() for x in split[1:]) | [
"def",
"to_camel_case",
"(",
"text",
")",
":",
"split",
"=",
"text",
".",
"split",
"(",
"'_'",
")",
"return",
"split",
"[",
"0",
"]",
"+",
"\"\"",
".",
"join",
"(",
"x",
".",
"title",
"(",
")",
"for",
"x",
"in",
"split",
"[",
"1",
":",
"]",
"... | Convert to camel case.
:param str text:
:rtype: str
:return: | [
"Convert",
"to",
"camel",
"case",
"."
] | python | train |
HDI-Project/MLBlocks | mlblocks/primitives.py | https://github.com/HDI-Project/MLBlocks/blob/e1ca77bce3c4537c0800a4c1395e1b6bbde5465d/mlblocks/primitives.py#L82-L117 | def load_primitive(name):
"""Locate and load the JSON annotation of the given primitive.
All the paths found in PRIMTIVE_PATHS will be scanned to find a JSON file
with the given name, and as soon as a JSON with the given name is found it
is returned.
Args:
name (str): name of the primitive... | [
"def",
"load_primitive",
"(",
"name",
")",
":",
"for",
"base_path",
"in",
"get_primitives_paths",
"(",
")",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"number_of_parts",
"=",
"len",
"(",
"parts",
")",
"for",
"folder_parts",
"in",
"range",
... | Locate and load the JSON annotation of the given primitive.
All the paths found in PRIMTIVE_PATHS will be scanned to find a JSON file
with the given name, and as soon as a JSON with the given name is found it
is returned.
Args:
name (str): name of the primitive to look for. The name should
... | [
"Locate",
"and",
"load",
"the",
"JSON",
"annotation",
"of",
"the",
"given",
"primitive",
"."
] | python | train |
prompt-toolkit/pymux | pymux/server.py | https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/server.py#L137-L158 | def _create_app(self, color_depth, term='xterm'):
"""
Create CommandLineInterface for this client.
Called when the client wants to attach the UI to the server.
"""
output = Vt100_Output(_SocketStdout(self._send_packet),
lambda: self.size,
... | [
"def",
"_create_app",
"(",
"self",
",",
"color_depth",
",",
"term",
"=",
"'xterm'",
")",
":",
"output",
"=",
"Vt100_Output",
"(",
"_SocketStdout",
"(",
"self",
".",
"_send_packet",
")",
",",
"lambda",
":",
"self",
".",
"size",
",",
"term",
"=",
"term",
... | Create CommandLineInterface for this client.
Called when the client wants to attach the UI to the server. | [
"Create",
"CommandLineInterface",
"for",
"this",
"client",
".",
"Called",
"when",
"the",
"client",
"wants",
"to",
"attach",
"the",
"UI",
"to",
"the",
"server",
"."
] | python | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L268-L278 | def _get_arguments(self, action_node):
"""
Returns a dictionary of arguments for the given action_node.
"""
arguments = {}
argument_nodes = action_node.iterfind(
r'./ns:argumentList/ns:argument', namespaces={'ns': self.namespace})
for argument_node in argument... | [
"def",
"_get_arguments",
"(",
"self",
",",
"action_node",
")",
":",
"arguments",
"=",
"{",
"}",
"argument_nodes",
"=",
"action_node",
".",
"iterfind",
"(",
"r'./ns:argumentList/ns:argument'",
",",
"namespaces",
"=",
"{",
"'ns'",
":",
"self",
".",
"namespace",
... | Returns a dictionary of arguments for the given action_node. | [
"Returns",
"a",
"dictionary",
"of",
"arguments",
"for",
"the",
"given",
"action_node",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.