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 |
|---|---|---|---|---|---|---|---|---|
pantsbuild/pex | pex/vendor/_vendored/wheel/wheel/signatures/__init__.py | https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/vendor/_vendored/wheel/wheel/signatures/__init__.py#L29-L52 | def sign(payload, keypair):
"""Return a JWS-JS format signature given a JSON-serializable payload and
an Ed25519 keypair."""
get_ed25519ll()
#
header = {
"alg": ALG,
"jwk": {
"kty": ALG, # alg -> kty in jwk-08.
"vk": native(url... | [
"def",
"sign",
"(",
"payload",
",",
"keypair",
")",
":",
"get_ed25519ll",
"(",
")",
"#",
"header",
"=",
"{",
"\"alg\"",
":",
"ALG",
",",
"\"jwk\"",
":",
"{",
"\"kty\"",
":",
"ALG",
",",
"# alg -> kty in jwk-08.",
"\"vk\"",
":",
"native",
"(",
"urlsafe_b6... | Return a JWS-JS format signature given a JSON-serializable payload and
an Ed25519 keypair. | [
"Return",
"a",
"JWS",
"-",
"JS",
"format",
"signature",
"given",
"a",
"JSON",
"-",
"serializable",
"payload",
"and",
"an",
"Ed25519",
"keypair",
"."
] | python | train |
ionelmc/python-cogen | examples/static-serve.py | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/examples/static-serve.py#L76-L87 | def get_entries(path):
"""Return sorted lists of directories and files in the given path."""
dirs, files = [], []
for entry in os.listdir(path):
# Categorize entry as directory or file.
if os.path.isdir(os.path.join(path, entry)):
dirs.append(entry)
else:
... | [
"def",
"get_entries",
"(",
"path",
")",
":",
"dirs",
",",
"files",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"entry",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"# Categorize entry as directory or file.\r",
"if",
"os",
".",
"path",
".",
"isdir",
"("... | Return sorted lists of directories and files in the given path. | [
"Return",
"sorted",
"lists",
"of",
"directories",
"and",
"files",
"in",
"the",
"given",
"path",
"."
] | python | train |
thomasballinger/trellocardupdate | trellocardupdate/trelloupdate.py | https://github.com/thomasballinger/trellocardupdate/blob/16a648fa15efef144c07cd56fcdb1d8920fac889/trellocardupdate/trelloupdate.py#L110-L116 | def ask_for_board_id(self):
"""Factored out in case interface isn't keyboard"""
board_id = raw_input("paste in board id or url: ").strip()
m = re.search(r"(?:https?://)?(?:trello.com)?/?b?/?([a-zA-Z]{8})/(?:.*)", board_id)
if m:
board_id = m.group(1)
return board_id | [
"def",
"ask_for_board_id",
"(",
"self",
")",
":",
"board_id",
"=",
"raw_input",
"(",
"\"paste in board id or url: \"",
")",
".",
"strip",
"(",
")",
"m",
"=",
"re",
".",
"search",
"(",
"r\"(?:https?://)?(?:trello.com)?/?b?/?([a-zA-Z]{8})/(?:.*)\"",
",",
"board_id",
"... | Factored out in case interface isn't keyboard | [
"Factored",
"out",
"in",
"case",
"interface",
"isn",
"t",
"keyboard"
] | python | train |
marshallward/f90nml | f90nml/namelist.py | https://github.com/marshallward/f90nml/blob/4932cabc5221afc844ee6a5b4a05ceb8bd4a2711/f90nml/namelist.py#L705-L708 | def _f90complex(self, value):
"""Return a Fortran 90 representation of a complex number."""
return '({0:{fmt}}, {1:{fmt}})'.format(value.real, value.imag,
fmt=self.float_format) | [
"def",
"_f90complex",
"(",
"self",
",",
"value",
")",
":",
"return",
"'({0:{fmt}}, {1:{fmt}})'",
".",
"format",
"(",
"value",
".",
"real",
",",
"value",
".",
"imag",
",",
"fmt",
"=",
"self",
".",
"float_format",
")"
] | Return a Fortran 90 representation of a complex number. | [
"Return",
"a",
"Fortran",
"90",
"representation",
"of",
"a",
"complex",
"number",
"."
] | python | train |
duniter/duniter-python-api | duniterpy/api/bma/blockchain.py | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/api/bma/blockchain.py#L429-L437 | async def hardship(client: Client, pubkey: str) -> dict:
"""
GET hardship level for given member's public key for writing next block
:param client: Client to connect to the api
:param pubkey: Public key of the member
:return:
"""
return await client.get(MODULE + '/hardship/%s' % pubkey, sc... | [
"async",
"def",
"hardship",
"(",
"client",
":",
"Client",
",",
"pubkey",
":",
"str",
")",
"->",
"dict",
":",
"return",
"await",
"client",
".",
"get",
"(",
"MODULE",
"+",
"'/hardship/%s'",
"%",
"pubkey",
",",
"schema",
"=",
"HARDSHIP_SCHEMA",
")"
] | GET hardship level for given member's public key for writing next block
:param client: Client to connect to the api
:param pubkey: Public key of the member
:return: | [
"GET",
"hardship",
"level",
"for",
"given",
"member",
"s",
"public",
"key",
"for",
"writing",
"next",
"block"
] | python | train |
summa-tx/riemann | riemann/tx/tx_builder.py | https://github.com/summa-tx/riemann/blob/04ae336dfd4007ceaed748daadc91cc32fa278ec/riemann/tx/tx_builder.py#L35-L59 | def make_pkh_output_script(pubkey, witness=False):
'''
bytearray -> bytearray
'''
if witness and not riemann.network.SEGWIT:
raise ValueError(
'Network {} does not support witness scripts.'
.format(riemann.get_current_network_name()))
output_script = bytearray()
... | [
"def",
"make_pkh_output_script",
"(",
"pubkey",
",",
"witness",
"=",
"False",
")",
":",
"if",
"witness",
"and",
"not",
"riemann",
".",
"network",
".",
"SEGWIT",
":",
"raise",
"ValueError",
"(",
"'Network {} does not support witness scripts.'",
".",
"format",
"(",
... | bytearray -> bytearray | [
"bytearray",
"-",
">",
"bytearray"
] | python | train |
tango-controls/pytango | tango/databaseds/database.py | https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/databaseds/database.py#L914-L929 | def DbDeleteServer(self, argin):
""" Delete server from the database but dont delete device properties
:param argin: Device server name
:type: tango.DevString
:return:
:rtype: tango.DevVoid """
self._log.debug("In DbDeleteServer()")
if '*' in argin or '%' in arg... | [
"def",
"DbDeleteServer",
"(",
"self",
",",
"argin",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"In DbDeleteServer()\"",
")",
"if",
"'*'",
"in",
"argin",
"or",
"'%'",
"in",
"argin",
"or",
"not",
"'/'",
"in",
"argin",
":",
"self",
".",
"warn_str... | Delete server from the database but dont delete device properties
:param argin: Device server name
:type: tango.DevString
:return:
:rtype: tango.DevVoid | [
"Delete",
"server",
"from",
"the",
"database",
"but",
"dont",
"delete",
"device",
"properties"
] | python | train |
ttu/ruuvitag-sensor | ruuvitag_sensor/decoder.py | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/decoder.py#L60-L66 | def _get_temperature(self, decoded):
'''Return temperature in celsius'''
temp = (decoded[2] & 127) + decoded[3] / 100
sign = (decoded[2] >> 7) & 1
if sign == 0:
return round(temp, 2)
return round(-1 * temp, 2) | [
"def",
"_get_temperature",
"(",
"self",
",",
"decoded",
")",
":",
"temp",
"=",
"(",
"decoded",
"[",
"2",
"]",
"&",
"127",
")",
"+",
"decoded",
"[",
"3",
"]",
"/",
"100",
"sign",
"=",
"(",
"decoded",
"[",
"2",
"]",
">>",
"7",
")",
"&",
"1",
"i... | Return temperature in celsius | [
"Return",
"temperature",
"in",
"celsius"
] | python | train |
odlgroup/odl | odl/operator/operator.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/operator.py#L1384-L1410 | def derivative(self, x):
"""Return the operator derivative.
The derivative of the operator composition follows the chain
rule:
``OperatorComp(left, right).derivative(y) ==
OperatorComp(left.derivative(right(y)), right.derivative(y))``
Parameters
-------... | [
"def",
"derivative",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"is_linear",
":",
"return",
"self",
"else",
":",
"if",
"self",
".",
"left",
".",
"is_linear",
":",
"left_deriv",
"=",
"self",
".",
"left",
"else",
":",
"left_deriv",
"=",
"self"... | Return the operator derivative.
The derivative of the operator composition follows the chain
rule:
``OperatorComp(left, right).derivative(y) ==
OperatorComp(left.derivative(right(y)), right.derivative(y))``
Parameters
----------
x : `domain` `element-li... | [
"Return",
"the",
"operator",
"derivative",
"."
] | python | train |
h2oai/h2o-3 | h2o-bindings/bin/bindings.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-bindings/bin/bindings.py#L199-L295 | def endpoints(raw=False):
"""
Return the list of REST API endpoints. The data is enriched with the following fields:
class_name: which back-end class handles this endpoint (the class is derived from the URL);
ischema: input schema object (input_schema is the schema's name)
oschema: output sche... | [
"def",
"endpoints",
"(",
"raw",
"=",
"False",
")",
":",
"json",
"=",
"_request_or_exit",
"(",
"\"/3/Metadata/endpoints\"",
")",
"if",
"raw",
":",
"return",
"json",
"schmap",
"=",
"schemas_map",
"(",
")",
"apinames",
"=",
"{",
"}",
"# Used for checking for api ... | Return the list of REST API endpoints. The data is enriched with the following fields:
class_name: which back-end class handles this endpoint (the class is derived from the URL);
ischema: input schema object (input_schema is the schema's name)
oschema: output schema object (output_schema is the schema... | [
"Return",
"the",
"list",
"of",
"REST",
"API",
"endpoints",
".",
"The",
"data",
"is",
"enriched",
"with",
"the",
"following",
"fields",
":",
"class_name",
":",
"which",
"back",
"-",
"end",
"class",
"handles",
"this",
"endpoint",
"(",
"the",
"class",
"is",
... | python | test |
manns/pyspread | pyspread/src/gui/_toolbars.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_toolbars.py#L344-L353 | def OnUpdate(self, event):
"""Updates the toolbar states"""
attributes = event.attr
self._update_buttoncell(attributes["button_cell"])
self.Refresh()
event.Skip() | [
"def",
"OnUpdate",
"(",
"self",
",",
"event",
")",
":",
"attributes",
"=",
"event",
".",
"attr",
"self",
".",
"_update_buttoncell",
"(",
"attributes",
"[",
"\"button_cell\"",
"]",
")",
"self",
".",
"Refresh",
"(",
")",
"event",
".",
"Skip",
"(",
")"
] | Updates the toolbar states | [
"Updates",
"the",
"toolbar",
"states"
] | python | train |
wonambi-python/wonambi | wonambi/widgets/notes.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1406-L1409 | def remove_event(self, name=None, time=None, chan=None):
"""Action: remove single event."""
self.annot.remove_event(name=name, time=time, chan=chan)
self.update_annotations() | [
"def",
"remove_event",
"(",
"self",
",",
"name",
"=",
"None",
",",
"time",
"=",
"None",
",",
"chan",
"=",
"None",
")",
":",
"self",
".",
"annot",
".",
"remove_event",
"(",
"name",
"=",
"name",
",",
"time",
"=",
"time",
",",
"chan",
"=",
"chan",
"... | Action: remove single event. | [
"Action",
":",
"remove",
"single",
"event",
"."
] | python | train |
KeplerGO/K2fov | K2fov/fov.py | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L618-L634 | def plotSpacecraftYAxis(self, maptype=None):
"""Plot a line pointing in the direction of the spacecraft
y-axis (i.e normal to the solar panel
"""
if maptype is None:
maptype=self.defaultMap
#Plot direction of spacecraft +y axis. The subtraction of
#90 degrees... | [
"def",
"plotSpacecraftYAxis",
"(",
"self",
",",
"maptype",
"=",
"None",
")",
":",
"if",
"maptype",
"is",
"None",
":",
"maptype",
"=",
"self",
".",
"defaultMap",
"#Plot direction of spacecraft +y axis. The subtraction of",
"#90 degrees accounts for the different defintions o... | Plot a line pointing in the direction of the spacecraft
y-axis (i.e normal to the solar panel | [
"Plot",
"a",
"line",
"pointing",
"in",
"the",
"direction",
"of",
"the",
"spacecraft",
"y",
"-",
"axis",
"(",
"i",
".",
"e",
"normal",
"to",
"the",
"solar",
"panel"
] | python | train |
raphaelgyory/django-rest-messaging | rest_messaging/models.py | https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L230-L250 | def get_lasts_messages_of_threads(self, participant_id, check_who_read=True, check_is_notification=True):
""" Returns the last message in each thread """
# we get the last message for each thread
# we must query the messages using two queries because only Postgres supports .order_by('thread', '-... | [
"def",
"get_lasts_messages_of_threads",
"(",
"self",
",",
"participant_id",
",",
"check_who_read",
"=",
"True",
",",
"check_is_notification",
"=",
"True",
")",
":",
"# we get the last message for each thread",
"# we must query the messages using two queries because only Postgres su... | Returns the last message in each thread | [
"Returns",
"the",
"last",
"message",
"in",
"each",
"thread"
] | python | train |
ioam/lancet | lancet/core.py | https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L54-L63 | def pprint_args(self, pos_args, keyword_args, infix_operator=None, extra_params={}):
"""
Method to define the positional arguments and keyword order
for pretty printing.
"""
if infix_operator and not (len(pos_args)==2 and keyword_args==[]):
raise Exception('Infix form... | [
"def",
"pprint_args",
"(",
"self",
",",
"pos_args",
",",
"keyword_args",
",",
"infix_operator",
"=",
"None",
",",
"extra_params",
"=",
"{",
"}",
")",
":",
"if",
"infix_operator",
"and",
"not",
"(",
"len",
"(",
"pos_args",
")",
"==",
"2",
"and",
"keyword_... | Method to define the positional arguments and keyword order
for pretty printing. | [
"Method",
"to",
"define",
"the",
"positional",
"arguments",
"and",
"keyword",
"order",
"for",
"pretty",
"printing",
"."
] | python | valid |
callowayproject/Calloway | calloway/apps/custom_registration/backends/email/__init__.py | https://github.com/callowayproject/Calloway/blob/d22e98d41fbd298ab6393ba7bd84a75528be9f81/calloway/apps/custom_registration/backends/email/__init__.py#L147-L169 | def send_activation_email(self, user, profile, password, site):
"""
Custom send email method to supplied the activation link and
new generated password.
"""
ctx_dict = { 'password': password,
'site': site,
'activation_key': profile.act... | [
"def",
"send_activation_email",
"(",
"self",
",",
"user",
",",
"profile",
",",
"password",
",",
"site",
")",
":",
"ctx_dict",
"=",
"{",
"'password'",
":",
"password",
",",
"'site'",
":",
"site",
",",
"'activation_key'",
":",
"profile",
".",
"activation_key",... | Custom send email method to supplied the activation link and
new generated password. | [
"Custom",
"send",
"email",
"method",
"to",
"supplied",
"the",
"activation",
"link",
"and",
"new",
"generated",
"password",
"."
] | python | train |
osrg/ryu | ryu/lib/ovs/vsctl.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/lib/ovs/vsctl.py#L1167-L1190 | def _do_main(self, commands):
"""
:type commands: list of VSCtlCommand
"""
self._reset()
self._init_schema_helper()
self._run_prerequisites(commands)
idl_ = idl.Idl(self.remote, self.schema_helper)
seqno = idl_.change_seqno
while True:
... | [
"def",
"_do_main",
"(",
"self",
",",
"commands",
")",
":",
"self",
".",
"_reset",
"(",
")",
"self",
".",
"_init_schema_helper",
"(",
")",
"self",
".",
"_run_prerequisites",
"(",
"commands",
")",
"idl_",
"=",
"idl",
".",
"Idl",
"(",
"self",
".",
"remote... | :type commands: list of VSCtlCommand | [
":",
"type",
"commands",
":",
"list",
"of",
"VSCtlCommand"
] | python | train |
arista-eosplus/pyeapi | pyeapi/api/interfaces.py | https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/api/interfaces.py#L447-L467 | def set_flowcontrol_send(self, name, value=None, default=False,
disable=False):
"""Configures the interface flowcontrol send value
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
... | [
"def",
"set_flowcontrol_send",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
",",
"default",
"=",
"False",
",",
"disable",
"=",
"False",
")",
":",
"return",
"self",
".",
"set_flowcontrol",
"(",
"name",
",",
"'send'",
",",
"value",
",",
"default",
... | Configures the interface flowcontrol send value
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
value (boolean): True if the interface should enable sending flow
control packets, otherwise False
... | [
"Configures",
"the",
"interface",
"flowcontrol",
"send",
"value"
] | python | train |
ktbyers/netmiko | netmiko/cisco_base_connection.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/cisco_base_connection.py#L31-L39 | def check_config_mode(self, check_string=")#", pattern=""):
"""
Checks if the device is in configuration mode or not.
Cisco IOS devices abbreviate the prompt at 20 chars in config mode
"""
return super(CiscoBaseConnection, self).check_config_mode(
check_string=check_... | [
"def",
"check_config_mode",
"(",
"self",
",",
"check_string",
"=",
"\")#\"",
",",
"pattern",
"=",
"\"\"",
")",
":",
"return",
"super",
"(",
"CiscoBaseConnection",
",",
"self",
")",
".",
"check_config_mode",
"(",
"check_string",
"=",
"check_string",
",",
"patte... | Checks if the device is in configuration mode or not.
Cisco IOS devices abbreviate the prompt at 20 chars in config mode | [
"Checks",
"if",
"the",
"device",
"is",
"in",
"configuration",
"mode",
"or",
"not",
"."
] | python | train |
bloomreach/s4cmd | s4cmd.py | https://github.com/bloomreach/s4cmd/blob/bb51075bf43703e7cd95aa39288cf7732ec13a6d/s4cmd.py#L1734-L1737 | def du_handler(self, args):
'''Handler for size command'''
for src, size in self.s3handler().size(args[1:]):
message('%s\t%s' % (size, src)) | [
"def",
"du_handler",
"(",
"self",
",",
"args",
")",
":",
"for",
"src",
",",
"size",
"in",
"self",
".",
"s3handler",
"(",
")",
".",
"size",
"(",
"args",
"[",
"1",
":",
"]",
")",
":",
"message",
"(",
"'%s\\t%s'",
"%",
"(",
"size",
",",
"src",
")"... | Handler for size command | [
"Handler",
"for",
"size",
"command"
] | python | test |
KoffeinFlummi/Chronyk | chronyk/chronyk.py | https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L64-L72 | def _gmtime(timestamp):
"""Custom gmtime because yada yada.
"""
try:
return time.gmtime(timestamp)
except OSError:
dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
dst = int(_isdst(dt))
return time.struct_time(dt.timetuple()[:8] + tuple([dst])) | [
"def",
"_gmtime",
"(",
"timestamp",
")",
":",
"try",
":",
"return",
"time",
".",
"gmtime",
"(",
"timestamp",
")",
"except",
"OSError",
":",
"dt",
"=",
"datetime",
".",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
"+",
"datetime",
".",
"timedelta... | Custom gmtime because yada yada. | [
"Custom",
"gmtime",
"because",
"yada",
"yada",
"."
] | python | train |
Calysto/calysto | calysto/ai/conx.py | https://github.com/Calysto/calysto/blob/20813c0f48096317aa775d03a5c6b20f12fafc93/calysto/ai/conx.py#L1973-L2039 | def propagate(self, **args):
"""
Propagates activation through the network. Optionally, takes input layer names
as keywords, and their associated activations. If input layer(s) are given, then
propagate() will return the output layer's activation. If there is more than
one output... | [
"def",
"propagate",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"self",
".",
"prePropagate",
"(",
"*",
"*",
"args",
")",
"for",
"key",
"in",
"args",
":",
"layer",
"=",
"self",
".",
"getLayer",
"(",
"key",
")",
"if",
"layer",
".",
"kind",
"==",
... | Propagates activation through the network. Optionally, takes input layer names
as keywords, and their associated activations. If input layer(s) are given, then
propagate() will return the output layer's activation. If there is more than
one output layer, then a dictionary is returned.
E... | [
"Propagates",
"activation",
"through",
"the",
"network",
".",
"Optionally",
"takes",
"input",
"layer",
"names",
"as",
"keywords",
"and",
"their",
"associated",
"activations",
".",
"If",
"input",
"layer",
"(",
"s",
")",
"are",
"given",
"then",
"propagate",
"()"... | python | train |
gem/oq-engine | openquake/hmtk/sources/point_source.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/point_source.py#L115-L141 | def create_geometry(self, input_geometry, upper_depth, lower_depth):
'''
If geometry is defined as a numpy array then create instance of
nhlib.geo.point.Point class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (point) as ... | [
"def",
"create_geometry",
"(",
"self",
",",
"input_geometry",
",",
"upper_depth",
",",
"lower_depth",
")",
":",
"self",
".",
"_check_seismogenic_depths",
"(",
"upper_depth",
",",
"lower_depth",
")",
"# Check/create the geometry class",
"if",
"not",
"isinstance",
"(",
... | If geometry is defined as a numpy array then create instance of
nhlib.geo.point.Point class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (point) as either
i) instance of nhlib.geo.point.Point class
ii) numpy.ndarr... | [
"If",
"geometry",
"is",
"defined",
"as",
"a",
"numpy",
"array",
"then",
"create",
"instance",
"of",
"nhlib",
".",
"geo",
".",
"point",
".",
"Point",
"class",
"otherwise",
"if",
"already",
"instance",
"of",
"class",
"accept",
"class"
] | python | train |
Alignak-monitoring/alignak | alignak/daemons/schedulerdaemon.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/schedulerdaemon.py#L311-L501 | def setup_new_conf(self):
# pylint: disable=too-many-statements, too-many-branches, too-many-locals
"""Setup new conf received for scheduler
:return: None
"""
# Execute the base class treatment...
super(Alignak, self).setup_new_conf()
# ...then our own specific ... | [
"def",
"setup_new_conf",
"(",
"self",
")",
":",
"# pylint: disable=too-many-statements, too-many-branches, too-many-locals",
"# Execute the base class treatment...",
"super",
"(",
"Alignak",
",",
"self",
")",
".",
"setup_new_conf",
"(",
")",
"# ...then our own specific treatment!... | Setup new conf received for scheduler
:return: None | [
"Setup",
"new",
"conf",
"received",
"for",
"scheduler"
] | python | train |
ANTsX/ANTsPy | ants/utils/scalar_rgb_vector.py | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/scalar_rgb_vector.py#L78-L106 | def rgb_to_vector(image):
"""
Convert an RGB ANTsImage to a Vector ANTsImage
Arguments
---------
image : ANTsImage
RGB image to be converted
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni_rg... | [
"def",
"rgb_to_vector",
"(",
"image",
")",
":",
"if",
"image",
".",
"pixeltype",
"!=",
"'unsigned char'",
":",
"image",
"=",
"image",
".",
"clone",
"(",
"'unsigned char'",
")",
"idim",
"=",
"image",
".",
"dimension",
"libfn",
"=",
"utils",
".",
"get_lib_fn... | Convert an RGB ANTsImage to a Vector ANTsImage
Arguments
---------
image : ANTsImage
RGB image to be converted
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni_rgb = mni.scalar_to_rgb()
>>> mni_ve... | [
"Convert",
"an",
"RGB",
"ANTsImage",
"to",
"a",
"Vector",
"ANTsImage"
] | python | train |
portfors-lab/sparkle | sparkle/run/acquisition_manager.py | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/run/acquisition_manager.py#L421-L432 | def calibration_template(self):
"""Gets the template documentation for the both the tone curve calibration and noise calibration
:returns: dict -- all information necessary to recreate calibration objects
"""
temp = {}
temp['tone_doc'] = self.tone_calibrator.stimulus.templateDoc... | [
"def",
"calibration_template",
"(",
"self",
")",
":",
"temp",
"=",
"{",
"}",
"temp",
"[",
"'tone_doc'",
"]",
"=",
"self",
".",
"tone_calibrator",
".",
"stimulus",
".",
"templateDoc",
"(",
")",
"comp_doc",
"=",
"[",
"]",
"for",
"calstim",
"in",
"self",
... | Gets the template documentation for the both the tone curve calibration and noise calibration
:returns: dict -- all information necessary to recreate calibration objects | [
"Gets",
"the",
"template",
"documentation",
"for",
"the",
"both",
"the",
"tone",
"curve",
"calibration",
"and",
"noise",
"calibration"
] | python | train |
pallets/werkzeug | src/werkzeug/routing.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/routing.py#L2083-L2200 | def build(
self,
endpoint,
values=None,
method=None,
force_external=False,
append_unknown=True,
):
"""Building URLs works pretty much the other way round. Instead of
`match` you call `build` and pass it the endpoint and a dict of
arguments for... | [
"def",
"build",
"(",
"self",
",",
"endpoint",
",",
"values",
"=",
"None",
",",
"method",
"=",
"None",
",",
"force_external",
"=",
"False",
",",
"append_unknown",
"=",
"True",
",",
")",
":",
"self",
".",
"map",
".",
"update",
"(",
")",
"if",
"values",... | Building URLs works pretty much the other way round. Instead of
`match` you call `build` and pass it the endpoint and a dict of
arguments for the placeholders.
The `build` function also accepts an argument called `force_external`
which, if you set it to `True` will force external URLs.... | [
"Building",
"URLs",
"works",
"pretty",
"much",
"the",
"other",
"way",
"round",
".",
"Instead",
"of",
"match",
"you",
"call",
"build",
"and",
"pass",
"it",
"the",
"endpoint",
"and",
"a",
"dict",
"of",
"arguments",
"for",
"the",
"placeholders",
"."
] | python | train |
tensorflow/cleverhans | cleverhans/attacks/carlini_wagner_l2.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/carlini_wagner_l2.py#L87-L143 | def parse_params(self,
y=None,
y_target=None,
batch_size=1,
confidence=0,
learning_rate=5e-3,
binary_search_steps=5,
max_iterations=1000,
abort_early=True,
... | [
"def",
"parse_params",
"(",
"self",
",",
"y",
"=",
"None",
",",
"y_target",
"=",
"None",
",",
"batch_size",
"=",
"1",
",",
"confidence",
"=",
"0",
",",
"learning_rate",
"=",
"5e-3",
",",
"binary_search_steps",
"=",
"5",
",",
"max_iterations",
"=",
"1000"... | :param y: (optional) A tensor with the true labels for an untargeted
attack. If None (and y_target is None) then use the
original labels the classifier assigns.
:param y_target: (optional) A tensor with the target labels for a
targeted attack.
:param confidence: Confide... | [
":",
"param",
"y",
":",
"(",
"optional",
")",
"A",
"tensor",
"with",
"the",
"true",
"labels",
"for",
"an",
"untargeted",
"attack",
".",
"If",
"None",
"(",
"and",
"y_target",
"is",
"None",
")",
"then",
"use",
"the",
"original",
"labels",
"the",
"classif... | python | train |
pandas-dev/pandas | pandas/core/internals/blocks.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/internals/blocks.py#L1564-L1597 | def putmask(self, mask, new, align=True, inplace=False, axis=0,
transpose=False):
"""
putmask the data to the block; we must be a single block and not
generate other blocks
return the resulting block
Parameters
----------
mask : the condition to... | [
"def",
"putmask",
"(",
"self",
",",
"mask",
",",
"new",
",",
"align",
"=",
"True",
",",
"inplace",
"=",
"False",
",",
"axis",
"=",
"0",
",",
"transpose",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
... | putmask the data to the block; we must be a single block and not
generate other blocks
return the resulting block
Parameters
----------
mask : the condition to respect
new : a ndarray/object
align : boolean, perform alignment on other/cond, default is True
... | [
"putmask",
"the",
"data",
"to",
"the",
"block",
";",
"we",
"must",
"be",
"a",
"single",
"block",
"and",
"not",
"generate",
"other",
"blocks"
] | python | train |
pyrogram/pyrogram | pyrogram/client/client.py | https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/client/client.py#L357-L398 | def stop(self):
"""Use this method to manually stop the Client.
Requires no parameters.
Raises:
``ConnectionError`` in case you try to stop an already stopped Client.
"""
if not self.is_started:
raise ConnectionError("Client is already stopped")
... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_started",
":",
"raise",
"ConnectionError",
"(",
"\"Client is already stopped\"",
")",
"if",
"self",
".",
"takeout_id",
":",
"self",
".",
"send",
"(",
"functions",
".",
"account",
".",
"Fin... | Use this method to manually stop the Client.
Requires no parameters.
Raises:
``ConnectionError`` in case you try to stop an already stopped Client. | [
"Use",
"this",
"method",
"to",
"manually",
"stop",
"the",
"Client",
".",
"Requires",
"no",
"parameters",
"."
] | python | train |
PyCQA/pylint | pylint/pyreverse/diadefslib.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diadefslib.py#L40-L45 | def get_title(self, node):
"""get title for objects"""
title = node.name
if self.module_names:
title = "%s.%s" % (node.root().name, title)
return title | [
"def",
"get_title",
"(",
"self",
",",
"node",
")",
":",
"title",
"=",
"node",
".",
"name",
"if",
"self",
".",
"module_names",
":",
"title",
"=",
"\"%s.%s\"",
"%",
"(",
"node",
".",
"root",
"(",
")",
".",
"name",
",",
"title",
")",
"return",
"title"... | get title for objects | [
"get",
"title",
"for",
"objects"
] | python | test |
shoebot/shoebot | shoebot/data/bezier.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/bezier.py#L92-L98 | def _append_element(self, render_func, pe):
'''
Append a render function and the parameters to pass
an equivilent PathElement, or the PathElement itself.
'''
self._render_funcs.append(render_func)
self._elements.append(pe) | [
"def",
"_append_element",
"(",
"self",
",",
"render_func",
",",
"pe",
")",
":",
"self",
".",
"_render_funcs",
".",
"append",
"(",
"render_func",
")",
"self",
".",
"_elements",
".",
"append",
"(",
"pe",
")"
] | Append a render function and the parameters to pass
an equivilent PathElement, or the PathElement itself. | [
"Append",
"a",
"render",
"function",
"and",
"the",
"parameters",
"to",
"pass",
"an",
"equivilent",
"PathElement",
"or",
"the",
"PathElement",
"itself",
"."
] | python | valid |
chop-dbhi/varify-data-warehouse | vdw/variants/migrations/0009_rename_evs_maf_datafields.py | https://github.com/chop-dbhi/varify-data-warehouse/blob/1600ee1bc5fae6c68fd03b23624467298570cca8/vdw/variants/migrations/0009_rename_evs_maf_datafields.py#L9-L15 | def forwards(self, orm):
"Write your forwards methods here."
fields = orm['avocado.DataField'].objects.filter(app_name='variants',
model_name='evs', field_name__in=('all_maf', 'aa_maf', 'ea_maf'))
for f in fields:
f.field_name = f.field_name.replace('maf', 'af')
... | [
"def",
"forwards",
"(",
"self",
",",
"orm",
")",
":",
"fields",
"=",
"orm",
"[",
"'avocado.DataField'",
"]",
".",
"objects",
".",
"filter",
"(",
"app_name",
"=",
"'variants'",
",",
"model_name",
"=",
"'evs'",
",",
"field_name__in",
"=",
"(",
"'all_maf'",
... | Write your forwards methods here. | [
"Write",
"your",
"forwards",
"methods",
"here",
"."
] | python | train |
mitsei/dlkit | dlkit/records/osid/base_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/osid/base_records.py#L52-L97 | def _get_asset_content(self, asset_id, asset_content_type_str=None, asset_content_id=None):
"""stub"""
rm = self.my_osid_object._get_provider_manager('REPOSITORY')
if 'assignedBankIds' in self.my_osid_object._my_map:
if self.my_osid_object._proxy is not None:
als = rm... | [
"def",
"_get_asset_content",
"(",
"self",
",",
"asset_id",
",",
"asset_content_type_str",
"=",
"None",
",",
"asset_content_id",
"=",
"None",
")",
":",
"rm",
"=",
"self",
".",
"my_osid_object",
".",
"_get_provider_manager",
"(",
"'REPOSITORY'",
")",
"if",
"'assig... | stub | [
"stub"
] | python | train |
SoCo/SoCo | soco/music_library.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L336-L398 | def browse(self, ml_item=None, start=0, max_items=100,
full_album_art_uri=False, search_term=None, subcategories=None):
"""Browse (get sub-elements from) a music library item.
Args:
ml_item (`DidlItem`): the item to browse, if left out or
`None`, items at the ... | [
"def",
"browse",
"(",
"self",
",",
"ml_item",
"=",
"None",
",",
"start",
"=",
"0",
",",
"max_items",
"=",
"100",
",",
"full_album_art_uri",
"=",
"False",
",",
"search_term",
"=",
"None",
",",
"subcategories",
"=",
"None",
")",
":",
"if",
"ml_item",
"is... | Browse (get sub-elements from) a music library item.
Args:
ml_item (`DidlItem`): the item to browse, if left out or
`None`, items at the root level will be searched.
start (int): the starting index of the results.
max_items (int): the maximum number of items ... | [
"Browse",
"(",
"get",
"sub",
"-",
"elements",
"from",
")",
"a",
"music",
"library",
"item",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/lib/pretty.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/pretty.py#L568-L575 | def _super_pprint(obj, p, cycle):
"""The pprint for the super type."""
p.begin_group(8, '<super: ')
p.pretty(obj.__self_class__)
p.text(',')
p.breakable()
p.pretty(obj.__self__)
p.end_group(8, '>') | [
"def",
"_super_pprint",
"(",
"obj",
",",
"p",
",",
"cycle",
")",
":",
"p",
".",
"begin_group",
"(",
"8",
",",
"'<super: '",
")",
"p",
".",
"pretty",
"(",
"obj",
".",
"__self_class__",
")",
"p",
".",
"text",
"(",
"','",
")",
"p",
".",
"breakable",
... | The pprint for the super type. | [
"The",
"pprint",
"for",
"the",
"super",
"type",
"."
] | python | test |
ladybug-tools/ladybug | ladybug/header.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/header.py#L105-L109 | def duplicate(self):
"""Return a copy of the header."""
a_per = self.analysis_period.duplicate() if self.analysis_period else None
return self.__class__(self.data_type, self.unit,
a_per, deepcopy(self.metadata)) | [
"def",
"duplicate",
"(",
"self",
")",
":",
"a_per",
"=",
"self",
".",
"analysis_period",
".",
"duplicate",
"(",
")",
"if",
"self",
".",
"analysis_period",
"else",
"None",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"data_type",
",",
"self",
"."... | Return a copy of the header. | [
"Return",
"a",
"copy",
"of",
"the",
"header",
"."
] | python | train |
jurismarches/chopper | chopper/html/extractor.py | https://github.com/jurismarches/chopper/blob/53c5489a53e3a5d205a5cb207df751c09633e7ce/chopper/html/extractor.py#L40-L68 | def parse(self):
"""
Returns a cleaned lxml ElementTree
:returns: Whether the cleaned HTML has matches or not
:rtype: bool
"""
# Create the element tree
self.tree = self._build_tree(self.html_contents)
# Get explicits elements to keep and discard
... | [
"def",
"parse",
"(",
"self",
")",
":",
"# Create the element tree",
"self",
".",
"tree",
"=",
"self",
".",
"_build_tree",
"(",
"self",
".",
"html_contents",
")",
"# Get explicits elements to keep and discard",
"self",
".",
"elts_to_keep",
"=",
"self",
".",
"_get_e... | Returns a cleaned lxml ElementTree
:returns: Whether the cleaned HTML has matches or not
:rtype: bool | [
"Returns",
"a",
"cleaned",
"lxml",
"ElementTree"
] | python | train |
wonambi-python/wonambi | wonambi/widgets/analysis.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1043-L1098 | def toggle_pac(self):
"""Enable and disable PAC options."""
if Pac is not None:
pac_on = self.pac['pac_on'].get_value()
self.pac['prep'].setEnabled(pac_on)
self.pac['box_metric'].setEnabled(pac_on)
self.pac['box_complex'].setEnabled(pac_on)
sel... | [
"def",
"toggle_pac",
"(",
"self",
")",
":",
"if",
"Pac",
"is",
"not",
"None",
":",
"pac_on",
"=",
"self",
".",
"pac",
"[",
"'pac_on'",
"]",
".",
"get_value",
"(",
")",
"self",
".",
"pac",
"[",
"'prep'",
"]",
".",
"setEnabled",
"(",
"pac_on",
")",
... | Enable and disable PAC options. | [
"Enable",
"and",
"disable",
"PAC",
"options",
"."
] | python | train |
hardbyte/python-can | can/interfaces/systec/ucan.py | https://github.com/hardbyte/python-can/blob/cdc5254d96072df7739263623f3e920628a7d214/can/interfaces/systec/ucan.py#L855-L866 | def check_support_user_port(cls, hw_info_ex):
"""
Checks whether the module supports a user I/O port.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the module supports a user I/O port, oth... | [
"def",
"check_support_user_port",
"(",
"cls",
",",
"hw_info_ex",
")",
":",
"return",
"(",
"(",
"hw_info_ex",
".",
"m_dwProductCode",
"&",
"PRODCODE_MASK_PID",
")",
"!=",
"ProductCode",
".",
"PRODCODE_PID_BASIC",
")",
"and",
"(",
"(",
"hw_info_ex",
".",
"m_dwProd... | Checks whether the module supports a user I/O port.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the module supports a user I/O port, otherwise False.
:rtype: bool | [
"Checks",
"whether",
"the",
"module",
"supports",
"a",
"user",
"I",
"/",
"O",
"port",
"."
] | python | train |
brian-rose/climlab | climlab/utils/thermo.py | https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/utils/thermo.py#L177-L185 | def Planck_frequency(nu, T):
'''The Planck function B(nu,T):
the flux density for blackbody radiation in frequency space
nu is frequency in 1/s
T is temperature in Kelvin
Formula (3.1) from Raymond Pierrehumbert, "Principles of Planetary Climate"
'''
return 2*hPlanck*nu**3/c_light**2/(exp(h... | [
"def",
"Planck_frequency",
"(",
"nu",
",",
"T",
")",
":",
"return",
"2",
"*",
"hPlanck",
"*",
"nu",
"**",
"3",
"/",
"c_light",
"**",
"2",
"/",
"(",
"exp",
"(",
"hPlanck",
"*",
"nu",
"/",
"kBoltzmann",
"/",
"T",
")",
"-",
"1",
")"
] | The Planck function B(nu,T):
the flux density for blackbody radiation in frequency space
nu is frequency in 1/s
T is temperature in Kelvin
Formula (3.1) from Raymond Pierrehumbert, "Principles of Planetary Climate" | [
"The",
"Planck",
"function",
"B",
"(",
"nu",
"T",
")",
":",
"the",
"flux",
"density",
"for",
"blackbody",
"radiation",
"in",
"frequency",
"space",
"nu",
"is",
"frequency",
"in",
"1",
"/",
"s",
"T",
"is",
"temperature",
"in",
"Kelvin"
] | python | train |
ttm/socialLegacy | social/tw.py | https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/tw.py#L293-L307 | def searchTag(self,HTAG="#python"):
"""Set Twitter search or stream criteria for the selection of tweets"""
self.t = Twython(app_key =self.app_key ,
app_secret =self.app_secret ,
oauth_token =self.oauth_token ... | [
"def",
"searchTag",
"(",
"self",
",",
"HTAG",
"=",
"\"#python\"",
")",
":",
"self",
".",
"t",
"=",
"Twython",
"(",
"app_key",
"=",
"self",
".",
"app_key",
",",
"app_secret",
"=",
"self",
".",
"app_secret",
",",
"oauth_token",
"=",
"self",
".",
"oauth_t... | Set Twitter search or stream criteria for the selection of tweets | [
"Set",
"Twitter",
"search",
"or",
"stream",
"criteria",
"for",
"the",
"selection",
"of",
"tweets"
] | python | train |
cggh/scikit-allel | allel/stats/sf.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/stats/sf.py#L333-L367 | def joint_sfs_folded_scaled(ac1, ac2, n1=None, n2=None):
"""Compute the joint folded site frequency spectrum between two
populations, scaled such that a constant value is expected across the
spectrum for neutral variation, constant population size and unrelated
populations.
Parameters
---------... | [
"def",
"joint_sfs_folded_scaled",
"(",
"ac1",
",",
"ac2",
",",
"n1",
"=",
"None",
",",
"n2",
"=",
"None",
")",
":",
"# noqa",
"# check inputs",
"ac1",
",",
"n1",
"=",
"_check_ac_n",
"(",
"ac1",
",",
"n1",
")",
"ac2",
",",
"n2",
"=",
"_check_ac_n",
"(... | Compute the joint folded site frequency spectrum between two
populations, scaled such that a constant value is expected across the
spectrum for neutral variation, constant population size and unrelated
populations.
Parameters
----------
ac1 : array_like, int, shape (n_variants, 2)
Allel... | [
"Compute",
"the",
"joint",
"folded",
"site",
"frequency",
"spectrum",
"between",
"two",
"populations",
"scaled",
"such",
"that",
"a",
"constant",
"value",
"is",
"expected",
"across",
"the",
"spectrum",
"for",
"neutral",
"variation",
"constant",
"population",
"size... | python | train |
Basic-Components/msgpack-rpc-protocol | python/pymprpc/client/sync.py | https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/sync.py#L171-L214 | def _status_code_check(self, response: Dict[str, Any]):
"""检查响应码并进行对不同的响应进行处理.
主要包括:
+ 编码在500~599段为服务异常,直接抛出对应异常
+ 编码在400~499段为调用异常,为对应ID的future设置异常
+ 编码在300~399段为警告,会抛出对应警告
+ 编码在200~399段为执行成功响应,将结果设置给对应ID的future.
+ 编码在100~199段为服务器响应,主要是处理验证响应和心跳响应
Param... | [
"def",
"_status_code_check",
"(",
"self",
",",
"response",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
":",
"code",
"=",
"response",
".",
"get",
"(",
"\"CODE\"",
")",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"resv:{}\"",
".",
"format",
"("... | 检查响应码并进行对不同的响应进行处理.
主要包括:
+ 编码在500~599段为服务异常,直接抛出对应异常
+ 编码在400~499段为调用异常,为对应ID的future设置异常
+ 编码在300~399段为警告,会抛出对应警告
+ 编码在200~399段为执行成功响应,将结果设置给对应ID的future.
+ 编码在100~199段为服务器响应,主要是处理验证响应和心跳响应
Parameters:
response (Dict[str, Any]): - 响应的python字典形式数据
... | [
"检查响应码并进行对不同的响应进行处理",
"."
] | python | train |
senaite/senaite.core | bika/lims/decorators.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/decorators.py#L33-L42 | def XXX_REMOVEME(func):
"""Decorator for dead code removal
"""
@wraps(func)
def decorator(self, *args, **kwargs):
msg = "~~~~~~~ XXX REMOVEME marked method called: {}.{}".format(
self.__class__.__name__, func.func_name)
raise RuntimeError(msg)
return func(self, *args,... | [
"def",
"XXX_REMOVEME",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"decorator",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"\"~~~~~~~ XXX REMOVEME marked method called: {}.{}\"",
".",
"format",
"(",
"sel... | Decorator for dead code removal | [
"Decorator",
"for",
"dead",
"code",
"removal"
] | python | train |
dahlia/sqlalchemy-imageattach | sqlalchemy_imageattach/entity.py | https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L457-L494 | def _original_images(self, **kwargs):
"""A list of the original images.
:returns: A list of the original images.
:rtype: :class:`typing.Sequence`\ [:class:`Image`]
"""
def test(image):
if not image.original:
return False
for filter, value... | [
"def",
"_original_images",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"test",
"(",
"image",
")",
":",
"if",
"not",
"image",
".",
"original",
":",
"return",
"False",
"for",
"filter",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
... | A list of the original images.
:returns: A list of the original images.
:rtype: :class:`typing.Sequence`\ [:class:`Image`] | [
"A",
"list",
"of",
"the",
"original",
"images",
"."
] | python | train |
belbio/bel | bel/lang/partialparse.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L365-L408 | def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors]:
"""Add argument types to parsed function data structure
Args:
parsed: function and arg locations in BEL string
errors: error messages
Returns:
(parsed, errors): parsed, arguments with arg types plus error messa... | [
"def",
"arg_types",
"(",
"parsed",
":",
"Parsed",
",",
"errors",
":",
"Errors",
")",
"->",
"Tuple",
"[",
"Parsed",
",",
"Errors",
"]",
":",
"func_pattern",
"=",
"re",
".",
"compile",
"(",
"r\"\\s*[a-zA-Z]+\\(\"",
")",
"nsarg_pattern",
"=",
"re",
".",
"co... | Add argument types to parsed function data structure
Args:
parsed: function and arg locations in BEL string
errors: error messages
Returns:
(parsed, errors): parsed, arguments with arg types plus error messages | [
"Add",
"argument",
"types",
"to",
"parsed",
"function",
"data",
"structure"
] | python | train |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L643-L653 | def delete(self, count=1):
"""
Delete specified number of characters and Return the deleted text.
"""
if self.cursor_position < len(self.text):
deleted = self.document.text_after_cursor[:count]
self.text = self.text[:self.cursor_position] + \
self.... | [
"def",
"delete",
"(",
"self",
",",
"count",
"=",
"1",
")",
":",
"if",
"self",
".",
"cursor_position",
"<",
"len",
"(",
"self",
".",
"text",
")",
":",
"deleted",
"=",
"self",
".",
"document",
".",
"text_after_cursor",
"[",
":",
"count",
"]",
"self",
... | Delete specified number of characters and Return the deleted text. | [
"Delete",
"specified",
"number",
"of",
"characters",
"and",
"Return",
"the",
"deleted",
"text",
"."
] | python | train |
sashahart/cookies | cookies.py | https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L659-L678 | def _parse_response(header_data, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"""Turn one or more lines of 'Set-Cookie:' header data into a list of dicts
mapping attribute names to attribute values (as plain strings).
"""
cookie_dicts = []
for line in Definitions.EOL.sp... | [
"def",
"_parse_response",
"(",
"header_data",
",",
"ignore_bad_cookies",
"=",
"False",
",",
"ignore_bad_attributes",
"=",
"True",
")",
":",
"cookie_dicts",
"=",
"[",
"]",
"for",
"line",
"in",
"Definitions",
".",
"EOL",
".",
"split",
"(",
"header_data",
".",
... | Turn one or more lines of 'Set-Cookie:' header data into a list of dicts
mapping attribute names to attribute values (as plain strings). | [
"Turn",
"one",
"or",
"more",
"lines",
"of",
"Set",
"-",
"Cookie",
":",
"header",
"data",
"into",
"a",
"list",
"of",
"dicts",
"mapping",
"attribute",
"names",
"to",
"attribute",
"values",
"(",
"as",
"plain",
"strings",
")",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/structural/convert.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/convert.py#L65-L80 | def to_bed(call, sample, work_dir, calls, data):
"""Create a simplified BED file from caller specific input.
"""
out_file = os.path.join(work_dir, "%s-%s-flat.bed" % (sample, call["variantcaller"]))
if call.get("vrn_file") and not utils.file_uptodate(out_file, call["vrn_file"]):
with file_transa... | [
"def",
"to_bed",
"(",
"call",
",",
"sample",
",",
"work_dir",
",",
"calls",
",",
"data",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s-%s-flat.bed\"",
"%",
"(",
"sample",
",",
"call",
"[",
"\"variantcaller\"",
"... | Create a simplified BED file from caller specific input. | [
"Create",
"a",
"simplified",
"BED",
"file",
"from",
"caller",
"specific",
"input",
"."
] | python | train |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/__init__.py | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/__init__.py#L705-L710 | def run_async(self, time_limit):
''' Run this module asynchronously and return a poller. '''
self.background = time_limit
results = self.run()
return results, poller.AsyncPoller(results, self) | [
"def",
"run_async",
"(",
"self",
",",
"time_limit",
")",
":",
"self",
".",
"background",
"=",
"time_limit",
"results",
"=",
"self",
".",
"run",
"(",
")",
"return",
"results",
",",
"poller",
".",
"AsyncPoller",
"(",
"results",
",",
"self",
")"
] | Run this module asynchronously and return a poller. | [
"Run",
"this",
"module",
"asynchronously",
"and",
"return",
"a",
"poller",
"."
] | python | train |
manns/pyspread | pyspread/src/lib/_grid_cairo_renderer.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/_grid_cairo_renderer.py#L444-L471 | def draw_bitmap(self, content):
"""Draws bitmap cell content to context"""
if content.HasAlpha():
image = wx.ImageFromBitmap(content)
image.ConvertAlphaToMask()
image.SetMask(False)
content = wx.BitmapFromImage(image)
ims = wx.lib.wxcairo.ImageSu... | [
"def",
"draw_bitmap",
"(",
"self",
",",
"content",
")",
":",
"if",
"content",
".",
"HasAlpha",
"(",
")",
":",
"image",
"=",
"wx",
".",
"ImageFromBitmap",
"(",
"content",
")",
"image",
".",
"ConvertAlphaToMask",
"(",
")",
"image",
".",
"SetMask",
"(",
"... | Draws bitmap cell content to context | [
"Draws",
"bitmap",
"cell",
"content",
"to",
"context"
] | python | train |
HazyResearch/pdftotree | pdftotree/visual/visual_utils.py | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/visual/visual_utils.py#L74-L141 | def get_bboxes(
img,
mask,
nb_boxes=100,
score_thresh=0.5,
iou_thresh=0.2,
prop_size=0.09,
prop_scale=1.2,
):
"""
Uses selective search to generate candidate bounding boxes and keeps the
ones that have the largest iou with the predicted mask.
:param img: original image
:... | [
"def",
"get_bboxes",
"(",
"img",
",",
"mask",
",",
"nb_boxes",
"=",
"100",
",",
"score_thresh",
"=",
"0.5",
",",
"iou_thresh",
"=",
"0.2",
",",
"prop_size",
"=",
"0.09",
",",
"prop_scale",
"=",
"1.2",
",",
")",
":",
"min_size",
"=",
"int",
"(",
"img"... | Uses selective search to generate candidate bounding boxes and keeps the
ones that have the largest iou with the predicted mask.
:param img: original image
:param mask: predicted mask
:param nb_boxes: max number of candidate bounding boxes
:param score_thresh: scre threshold to consider prediction ... | [
"Uses",
"selective",
"search",
"to",
"generate",
"candidate",
"bounding",
"boxes",
"and",
"keeps",
"the",
"ones",
"that",
"have",
"the",
"largest",
"iou",
"with",
"the",
"predicted",
"mask",
"."
] | python | train |
Scille/autobahn-sync | autobahn_sync/core.py | https://github.com/Scille/autobahn-sync/blob/d75fceff0d1aee61fa6dd0168eb1cd40794ad827/autobahn_sync/core.py#L55-L89 | def run_in_twisted(self, url=DEFAULT_AUTOBAHN_ROUTER, realm=DEFAULT_AUTOBAHN_REALM,
authmethods=None, authid=None, authrole=None, authextra=None,
callback=None, **kwargs):
"""
Start the WAMP connection. Given we cannot run synchronous stuff inside the
... | [
"def",
"run_in_twisted",
"(",
"self",
",",
"url",
"=",
"DEFAULT_AUTOBAHN_ROUTER",
",",
"realm",
"=",
"DEFAULT_AUTOBAHN_REALM",
",",
"authmethods",
"=",
"None",
",",
"authid",
"=",
"None",
",",
"authrole",
"=",
"None",
",",
"authextra",
"=",
"None",
",",
"cal... | Start the WAMP connection. Given we cannot run synchronous stuff inside the
twisted thread, use this function (which returns immediately) to do the
initialization from a spawned thread.
:param callback: function that will be called inside the spawned thread.
Put the rest of you init (or... | [
"Start",
"the",
"WAMP",
"connection",
".",
"Given",
"we",
"cannot",
"run",
"synchronous",
"stuff",
"inside",
"the",
"twisted",
"thread",
"use",
"this",
"function",
"(",
"which",
"returns",
"immediately",
")",
"to",
"do",
"the",
"initialization",
"from",
"a",
... | python | train |
drhagen/parsita | parsita/parsers.py | https://github.com/drhagen/parsita/blob/d97414a05541f48231381f607d1d2e6b50781d39/parsita/parsers.py#L318-L330 | def opt(parser: Union[Parser, Sequence[Input]]) -> OptionalParser:
"""Optionally match a parser.
An ``OptionalParser`` attempts to match ``parser``. If it succeeds, it
returns a list of length one with the value returned by the parser as the
only element. If it fails, it returns an empty list.
Arg... | [
"def",
"opt",
"(",
"parser",
":",
"Union",
"[",
"Parser",
",",
"Sequence",
"[",
"Input",
"]",
"]",
")",
"->",
"OptionalParser",
":",
"if",
"isinstance",
"(",
"parser",
",",
"str",
")",
":",
"parser",
"=",
"lit",
"(",
"parser",
")",
"return",
"Optiona... | Optionally match a parser.
An ``OptionalParser`` attempts to match ``parser``. If it succeeds, it
returns a list of length one with the value returned by the parser as the
only element. If it fails, it returns an empty list.
Args:
parser: Parser or literal | [
"Optionally",
"match",
"a",
"parser",
"."
] | python | test |
ryanjdillon/pylleo | pylleo/utils.py | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L104-L119 | def nearest(items, pivot):
'''Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Valu... | [
"def",
"nearest",
"(",
"items",
",",
"pivot",
")",
":",
"return",
"min",
"(",
"items",
",",
"key",
"=",
"lambda",
"x",
":",
"abs",
"(",
"x",
"-",
"pivot",
")",
")"
] | Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Value in items nearest to `pivot` | [
"Find",
"nearest",
"value",
"in",
"array",
"including",
"datetimes"
] | python | train |
siemens/django-dingos | dingos/models.py | https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/models.py#L946-L969 | def embedded_in(self):
"""
Used in the view for the InfoObject (in order to be able to use the standard class-based object view.
Should be removed from here and put into a proper custom view for the object.
This query only returns embedding objects of the latest revision: to change
... | [
"def",
"embedded_in",
"(",
"self",
")",
":",
"return",
"self",
".",
"_DCM",
"[",
"'InfoObject2Fact'",
"]",
".",
"objects",
".",
"filter",
"(",
"fact__value_iobject_id",
"=",
"self",
".",
"identifier",
")",
".",
"filter",
"(",
"iobject__timestamp",
"=",
"F",
... | Used in the view for the InfoObject (in order to be able to use the standard class-based object view.
Should be removed from here and put into a proper custom view for the object.
This query only returns embedding objects of the latest revision: to change
this, the filter 'iobject__timestamp=F(... | [
"Used",
"in",
"the",
"view",
"for",
"the",
"InfoObject",
"(",
"in",
"order",
"to",
"be",
"able",
"to",
"use",
"the",
"standard",
"class",
"-",
"based",
"object",
"view",
".",
"Should",
"be",
"removed",
"from",
"here",
"and",
"put",
"into",
"a",
"proper... | python | train |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1310-L1313 | def p_with_statement(self, p):
"""with_statement : WITH LPAREN expr RPAREN statement"""
p[0] = self.asttypes.With(expr=p[3], statement=p[5])
p[0].setpos(p) | [
"def",
"p_with_statement",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"With",
"(",
"expr",
"=",
"p",
"[",
"3",
"]",
",",
"statement",
"=",
"p",
"[",
"5",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpo... | with_statement : WITH LPAREN expr RPAREN statement | [
"with_statement",
":",
"WITH",
"LPAREN",
"expr",
"RPAREN",
"statement"
] | python | train |
EasyPost/pystalk | pystalk/client.py | https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L482-L493 | def bury_job(self, job_id, pri=65536):
"""Mark the given job_id as buried. The job must have been previously reserved by this connection
:param job_id: Job to bury
:param pri: Priority for the newly-buried job. If not passed, will keep its current priority
:type pri: int
"""
... | [
"def",
"bury_job",
"(",
"self",
",",
"job_id",
",",
"pri",
"=",
"65536",
")",
":",
"if",
"hasattr",
"(",
"job_id",
",",
"'job_id'",
")",
":",
"job_id",
"=",
"job_id",
".",
"job_id",
"with",
"self",
".",
"_sock_ctx",
"(",
")",
"as",
"socket",
":",
"... | Mark the given job_id as buried. The job must have been previously reserved by this connection
:param job_id: Job to bury
:param pri: Priority for the newly-buried job. If not passed, will keep its current priority
:type pri: int | [
"Mark",
"the",
"given",
"job_id",
"as",
"buried",
".",
"The",
"job",
"must",
"have",
"been",
"previously",
"reserved",
"by",
"this",
"connection"
] | python | train |
onelogin/python-saml | src/onelogin/saml2/auth.py | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/auth.py#L444-L457 | def build_request_signature(self, saml_request, relay_state, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1):
"""
Builds the Signature of the SAML Request.
:param saml_request: The SAML Request
:type saml_request: string
:param relay_state: The target URL the user should be r... | [
"def",
"build_request_signature",
"(",
"self",
",",
"saml_request",
",",
"relay_state",
",",
"sign_algorithm",
"=",
"OneLogin_Saml2_Constants",
".",
"RSA_SHA1",
")",
":",
"return",
"self",
".",
"__build_signature",
"(",
"saml_request",
",",
"relay_state",
",",
"'SAM... | Builds the Signature of the SAML Request.
:param saml_request: The SAML Request
:type saml_request: string
:param relay_state: The target URL the user should be redirected to
:type relay_state: string
:param sign_algorithm: Signature algorithm method
:type sign_algorit... | [
"Builds",
"the",
"Signature",
"of",
"the",
"SAML",
"Request",
"."
] | python | train |
fhcrc/taxtastic | taxtastic/taxonomy.py | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/taxonomy.py#L457-L481 | def verify_rank_integrity(self, tax_id, rank, parent_id, children):
"""Confirm that for each node the parent ranks and children ranks are
coherent
"""
def _lower(n1, n2):
return self.ranks.index(n1) < self.ranks.index(n2)
if rank not in self.ranks:
raise... | [
"def",
"verify_rank_integrity",
"(",
"self",
",",
"tax_id",
",",
"rank",
",",
"parent_id",
",",
"children",
")",
":",
"def",
"_lower",
"(",
"n1",
",",
"n2",
")",
":",
"return",
"self",
".",
"ranks",
".",
"index",
"(",
"n1",
")",
"<",
"self",
".",
"... | Confirm that for each node the parent ranks and children ranks are
coherent | [
"Confirm",
"that",
"for",
"each",
"node",
"the",
"parent",
"ranks",
"and",
"children",
"ranks",
"are",
"coherent"
] | python | train |
pycontribs/pyrax | pyrax/cloudblockstorage.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudblockstorage.py#L438-L451 | def _configure_manager(self):
"""
Create the manager to handle the instances, and also another
to handle flavors.
"""
self._manager = CloudBlockStorageManager(self,
resource_class=CloudBlockStorageVolume, response_key="volume",
uri_base="volumes")
... | [
"def",
"_configure_manager",
"(",
"self",
")",
":",
"self",
".",
"_manager",
"=",
"CloudBlockStorageManager",
"(",
"self",
",",
"resource_class",
"=",
"CloudBlockStorageVolume",
",",
"response_key",
"=",
"\"volume\"",
",",
"uri_base",
"=",
"\"volumes\"",
")",
"sel... | Create the manager to handle the instances, and also another
to handle flavors. | [
"Create",
"the",
"manager",
"to",
"handle",
"the",
"instances",
"and",
"also",
"another",
"to",
"handle",
"flavors",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/trax/learning_rate.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/learning_rate.py#L42-L92 | def MultifactorSchedule(history=None,
factors="constant * linear_warmup * rsqrt_decay",
constant=0.1,
warmup_steps=100,
decay_factor=0.5,
steps_per_decay=20000):
"""Factor-based learning rate schedu... | [
"def",
"MultifactorSchedule",
"(",
"history",
"=",
"None",
",",
"factors",
"=",
"\"constant * linear_warmup * rsqrt_decay\"",
",",
"constant",
"=",
"0.1",
",",
"warmup_steps",
"=",
"100",
",",
"decay_factor",
"=",
"0.5",
",",
"steps_per_decay",
"=",
"20000",
")",
... | Factor-based learning rate schedule.
Interprets factors in the factors string which can consist of:
* constant: interpreted as the constant value,
* linear_warmup: interpreted as linear warmup until warmup_steps,
* rsqrt_decay: divide by square root of max(step, warmup_steps)
* decay_every: Every k steps dec... | [
"Factor",
"-",
"based",
"learning",
"rate",
"schedule",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/repository/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/sessions.py#L1478-L1502 | def delete_asset(self, asset_id):
"""Deletes an ``Asset``.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to
remove
raise: NotFound - ``asset_id`` not found
raise: NullArgument - ``asset_id`` is ``null``
raise: OperationFailed - unable to complete ... | [
"def",
"delete_asset",
"(",
"self",
",",
"asset_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.delete_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'repository'",
",",
"collection",
"=",
"'Asset'",
",",
"runtime",... | Deletes an ``Asset``.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to
remove
raise: NotFound - ``asset_id`` not found
raise: NullArgument - ``asset_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - au... | [
"Deletes",
"an",
"Asset",
"."
] | python | train |
flo-compbio/genometools | genometools/ontology/ontology.py | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/ontology.py#L159-L184 | def write_pickle(self, path, compress=False):
"""Serialize the current `GOParser` object and store it in a pickle file.
Parameters
----------
path: str
Path of the output file.
compress: bool, optional
Whether to compress the file using gzip.
Ret... | [
"def",
"write_pickle",
"(",
"self",
",",
"path",
",",
"compress",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"'Writing pickle to \"%s\"...'",
",",
"path",
")",
"if",
"compress",
":",
"with",
"gzip",
".",
"open",
"(",
"path",
",",
"'wb'",
")",
... | Serialize the current `GOParser` object and store it in a pickle file.
Parameters
----------
path: str
Path of the output file.
compress: bool, optional
Whether to compress the file using gzip.
Returns
-------
None
Notes
... | [
"Serialize",
"the",
"current",
"GOParser",
"object",
"and",
"store",
"it",
"in",
"a",
"pickle",
"file",
"."
] | python | train |
LordGaav/python-chaos | chaos/threading/scheduler.py | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/threading/scheduler.py#L90-L105 | def setStopAction(self, action, *args, **kwargs):
"""
Set a function to call when run() is stopping, after the main action is called.
Parameters
----------
action: function pointer
The function to call.
*args
Positional arguments to pass to action.
**kwargs:
Keyword arguments to pass to action.
... | [
"def",
"setStopAction",
"(",
"self",
",",
"action",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"stop_action",
"=",
"action",
"self",
".",
"stop_args",
"=",
"args",
"self",
".",
"stop_kwargs",
"=",
"kwargs"
] | Set a function to call when run() is stopping, after the main action is called.
Parameters
----------
action: function pointer
The function to call.
*args
Positional arguments to pass to action.
**kwargs:
Keyword arguments to pass to action. | [
"Set",
"a",
"function",
"to",
"call",
"when",
"run",
"()",
"is",
"stopping",
"after",
"the",
"main",
"action",
"is",
"called",
"."
] | python | train |
jsvine/spectra | spectra/grapefruit.py | https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L495-L533 | def HsvToRgb(h, s, v):
'''Convert the color from RGB coordinates to HSV.
Parameters:
:h:
The Hus component value [0...1]
:s:
The Saturation component value [0...1]
:v:
The Value component [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r... | [
"def",
"HsvToRgb",
"(",
"h",
",",
"s",
",",
"v",
")",
":",
"if",
"s",
"==",
"0",
":",
"return",
"(",
"v",
",",
"v",
",",
"v",
")",
"# achromatic (gray)",
"h",
"/=",
"60.0",
"h",
"=",
"h",
"%",
"6.0",
"i",
"=",
"int",
"(",
"h",
")",
"f",
"... | Convert the color from RGB coordinates to HSV.
Parameters:
:h:
The Hus component value [0...1]
:s:
The Saturation component value [0...1]
:v:
The Value component [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
... | [
"Convert",
"the",
"color",
"from",
"RGB",
"coordinates",
"to",
"HSV",
"."
] | python | train |
rwl/pylon | pylon/io/matpower.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/matpower.py#L906-L915 | def write_area_data(self, file):
""" Writes area data to file.
"""
file.write("%% area data" + "\n")
file.write("%\tno.\tprice_ref_bus" + "\n")
file.write("areas = [" + "\n")
# TODO: Implement areas
file.write("\t1\t1;" + "\n")
file.write("];" + "\n") | [
"def",
"write_area_data",
"(",
"self",
",",
"file",
")",
":",
"file",
".",
"write",
"(",
"\"%% area data\"",
"+",
"\"\\n\"",
")",
"file",
".",
"write",
"(",
"\"%\\tno.\\tprice_ref_bus\"",
"+",
"\"\\n\"",
")",
"file",
".",
"write",
"(",
"\"areas = [\"",
"+",
... | Writes area data to file. | [
"Writes",
"area",
"data",
"to",
"file",
"."
] | python | train |
Telefonica/toolium | toolium/behave/env_utils.py | https://github.com/Telefonica/toolium/blob/56847c243b3a98876df74c184b75e43f8810e475/toolium/behave/env_utils.py#L178-L185 | def __print_step_by_console(self, step):
"""
print the step by console if the show variable is enabled
:param step: step text
"""
step_list = step.split(u'\n')
for s in step_list:
self.logger.by_console(u' %s' % repr(s).replace("u'", "").replace("'", "")) | [
"def",
"__print_step_by_console",
"(",
"self",
",",
"step",
")",
":",
"step_list",
"=",
"step",
".",
"split",
"(",
"u'\\n'",
")",
"for",
"s",
"in",
"step_list",
":",
"self",
".",
"logger",
".",
"by_console",
"(",
"u' %s'",
"%",
"repr",
"(",
"s",
")"... | print the step by console if the show variable is enabled
:param step: step text | [
"print",
"the",
"step",
"by",
"console",
"if",
"the",
"show",
"variable",
"is",
"enabled",
":",
"param",
"step",
":",
"step",
"text"
] | python | train |
iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L58-L87 | def register_monitor(self, devices, events, callback):
"""Register a callback when events happen.
If this method is called, it is guaranteed to take effect before the
next call to ``_notify_event`` after this method returns. This method
is safe to call from within a callback that is it... | [
"def",
"register_monitor",
"(",
"self",
",",
"devices",
",",
"events",
",",
"callback",
")",
":",
"# Ensure we don't exhaust any iterables",
"events",
"=",
"list",
"(",
"events",
")",
"devices",
"=",
"list",
"(",
"devices",
")",
"for",
"event",
"in",
"events",... | Register a callback when events happen.
If this method is called, it is guaranteed to take effect before the
next call to ``_notify_event`` after this method returns. This method
is safe to call from within a callback that is itself called by
``notify_event``.
See :meth:`Abstr... | [
"Register",
"a",
"callback",
"when",
"events",
"happen",
"."
] | python | train |
fhs/pyhdf | pyhdf/SD.py | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/SD.py#L1147-L1176 | def info(self):
"""Retrieve info about the attribute : name, data type and
number of values.
Args::
no argument
Returns::
3-element tuple holding:
- attribute name
- attribute data type (see constants SDC.xxx)
- number of values in t... | [
"def",
"info",
"(",
"self",
")",
":",
"if",
"self",
".",
"_index",
"is",
"None",
":",
"try",
":",
"self",
".",
"_index",
"=",
"self",
".",
"_obj",
".",
"findattr",
"(",
"self",
".",
"_name",
")",
"except",
"HDF4Error",
":",
"raise",
"HDF4Error",
"(... | Retrieve info about the attribute : name, data type and
number of values.
Args::
no argument
Returns::
3-element tuple holding:
- attribute name
- attribute data type (see constants SDC.xxx)
- number of values in the attribute; for a string-... | [
"Retrieve",
"info",
"about",
"the",
"attribute",
":",
"name",
"data",
"type",
"and",
"number",
"of",
"values",
"."
] | python | train |
pgjones/quart | quart/wrappers/request.py | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/request.py#L158-L171 | async def get_data(self, raw: bool=True) -> AnyStr:
"""The request body data."""
try:
body_future = asyncio.ensure_future(self.body)
raw_data = await asyncio.wait_for(body_future, timeout=self.body_timeout)
except asyncio.TimeoutError:
body_future.cancel()
... | [
"async",
"def",
"get_data",
"(",
"self",
",",
"raw",
":",
"bool",
"=",
"True",
")",
"->",
"AnyStr",
":",
"try",
":",
"body_future",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"body",
")",
"raw_data",
"=",
"await",
"asyncio",
".",
"wait_for... | The request body data. | [
"The",
"request",
"body",
"data",
"."
] | python | train |
markovmodel/msmtools | msmtools/flux/dense/tpt.py | https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/flux/dense/tpt.py#L186-L210 | def coarsegrain(F, sets):
r"""Coarse-grains the flux to the given sets
$fc_{i,j} = \sum_{i \in I,j \in J} f_{i,j}$
Note that if you coarse-grain a net flux, it does not necessarily have a net
flux property anymore. If want to make sure you get a netflux,
use to_netflux(coarsegrain(F,sets)).
Pa... | [
"def",
"coarsegrain",
"(",
"F",
",",
"sets",
")",
":",
"nnew",
"=",
"len",
"(",
"sets",
")",
"Fc",
"=",
"np",
".",
"zeros",
"(",
"(",
"nnew",
",",
"nnew",
")",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"nnew",
"-",
"1",
")",
":",
"for"... | r"""Coarse-grains the flux to the given sets
$fc_{i,j} = \sum_{i \in I,j \in J} f_{i,j}$
Note that if you coarse-grain a net flux, it does not necessarily have a net
flux property anymore. If want to make sure you get a netflux,
use to_netflux(coarsegrain(F,sets)).
Parameters
----------
F ... | [
"r",
"Coarse",
"-",
"grains",
"the",
"flux",
"to",
"the",
"given",
"sets"
] | python | train |
sam-cox/pytides | pytides/tide.py | https://github.com/sam-cox/pytides/blob/63a2507299002f1979ea55a17a82561158d685f7/pytides/tide.py#L260-L268 | def normalize(self):
"""
Adapt self.model so that amplitudes are positive and phases are in [0,360) as per convention
"""
for i, (_, amplitude, phase) in enumerate(self.model):
if amplitude < 0:
self.model['amplitude'][i] = -amplitude
self.model['phase'][i] = phase + 180.0
self.model['phase'][i] =... | [
"def",
"normalize",
"(",
"self",
")",
":",
"for",
"i",
",",
"(",
"_",
",",
"amplitude",
",",
"phase",
")",
"in",
"enumerate",
"(",
"self",
".",
"model",
")",
":",
"if",
"amplitude",
"<",
"0",
":",
"self",
".",
"model",
"[",
"'amplitude'",
"]",
"[... | Adapt self.model so that amplitudes are positive and phases are in [0,360) as per convention | [
"Adapt",
"self",
".",
"model",
"so",
"that",
"amplitudes",
"are",
"positive",
"and",
"phases",
"are",
"in",
"[",
"0",
"360",
")",
"as",
"per",
"convention"
] | python | train |
Rafiot/PubSubLogger | pubsublogger/subscriber.py | https://github.com/Rafiot/PubSubLogger/blob/4f28ad673f42ee2ec7792d414d325aef9a56da53/pubsublogger/subscriber.py#L94-L109 | def mail_setup(path):
"""
Set the variables to be able to send emails.
:param path: path to the config file
"""
global dest_mails
global smtp_server
global smtp_port
global src_server
config = configparser.RawConfigParser()
config.readfp(path)
dest_mails = config.get('mail',... | [
"def",
"mail_setup",
"(",
"path",
")",
":",
"global",
"dest_mails",
"global",
"smtp_server",
"global",
"smtp_port",
"global",
"src_server",
"config",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"config",
".",
"readfp",
"(",
"path",
")",
"dest_mails",
... | Set the variables to be able to send emails.
:param path: path to the config file | [
"Set",
"the",
"variables",
"to",
"be",
"able",
"to",
"send",
"emails",
"."
] | python | train |
androguard/androguard | androguard/core/analysis/analysis.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/analysis/analysis.py#L1555-L1613 | def get_call_graph(self, classname=".*", methodname=".*", descriptor=".*",
accessflags=".*", no_isolated=False, entry_points=[]):
"""
Generate a directed graph based on the methods found by the filters applied.
The filters are the same as in
:meth:`~androguard.core... | [
"def",
"get_call_graph",
"(",
"self",
",",
"classname",
"=",
"\".*\"",
",",
"methodname",
"=",
"\".*\"",
",",
"descriptor",
"=",
"\".*\"",
",",
"accessflags",
"=",
"\".*\"",
",",
"no_isolated",
"=",
"False",
",",
"entry_points",
"=",
"[",
"]",
")",
":",
... | Generate a directed graph based on the methods found by the filters applied.
The filters are the same as in
:meth:`~androguard.core.analaysis.analaysis.Analysis.find_methods`
A networkx.DiGraph is returned, containing all edges only once!
that means, if a method calls some method twice ... | [
"Generate",
"a",
"directed",
"graph",
"based",
"on",
"the",
"methods",
"found",
"by",
"the",
"filters",
"applied",
".",
"The",
"filters",
"are",
"the",
"same",
"as",
"in",
":",
"meth",
":",
"~androguard",
".",
"core",
".",
"analaysis",
".",
"analaysis",
... | python | train |
Azure/blobxfer | blobxfer/models/azure.py | https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/models/azure.py#L355-L387 | def populate_from_file(
self, sa, file, path, vio=None, store_raw_metadata=False,
snapshot=None):
# type: (StorageEntity, blobxfer.operations.azure.StorageAccount,
# azure.storage.file.models.File, str,
# blobxfer.models.metadata.VectoredStripe, bool, str) -... | [
"def",
"populate_from_file",
"(",
"self",
",",
"sa",
",",
"file",
",",
"path",
",",
"vio",
"=",
"None",
",",
"store_raw_metadata",
"=",
"False",
",",
"snapshot",
"=",
"None",
")",
":",
"# type: (StorageEntity, blobxfer.operations.azure.StorageAccount,",
"# az... | Populate properties from File
:param StorageEntity self: this
:param blobxfer.operations.azure.StorageAccount sa: storage account
:param azure.storage.file.models.File file: file to populate from
:param str path: full path to file
:param blobxfer.models.metadata.VectoredStripe vi... | [
"Populate",
"properties",
"from",
"File",
":",
"param",
"StorageEntity",
"self",
":",
"this",
":",
"param",
"blobxfer",
".",
"operations",
".",
"azure",
".",
"StorageAccount",
"sa",
":",
"storage",
"account",
":",
"param",
"azure",
".",
"storage",
".",
"file... | python | train |
StackStorm/pybind | pybind/nos/v6_0_2f/interface/tengigabitethernet/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/interface/tengigabitethernet/__init__.py#L1082-L1106 | def _set_dot1x(self, v, load=False):
"""
Setter method for dot1x, mapped from YANG variable /interface/tengigabitethernet/dot1x (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_dot1x is considered as a private
method. Backends looking to populate this vari... | [
"def",
"_set_dot1x",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | Setter method for dot1x, mapped from YANG variable /interface/tengigabitethernet/dot1x (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_dot1x is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_do... | [
"Setter",
"method",
"for",
"dot1x",
"mapped",
"from",
"YANG",
"variable",
"/",
"interface",
"/",
"tengigabitethernet",
"/",
"dot1x",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
... | python | train |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/pefile.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/pefile.py#L2790-L2815 | def parse_resource_entry(self, rva):
"""Parse a directory entry from the resources directory."""
try:
data = self.get_data( rva, Structure(self.__IMAGE_RESOURCE_DIRECTORY_ENTRY_format__).sizeof() )
except PEFormatError, excp:
# A warning will be added by the caller if th... | [
"def",
"parse_resource_entry",
"(",
"self",
",",
"rva",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"get_data",
"(",
"rva",
",",
"Structure",
"(",
"self",
".",
"__IMAGE_RESOURCE_DIRECTORY_ENTRY_format__",
")",
".",
"sizeof",
"(",
")",
")",
"except",
"P... | Parse a directory entry from the resources directory. | [
"Parse",
"a",
"directory",
"entry",
"from",
"the",
"resources",
"directory",
"."
] | python | train |
datastax/python-driver | cassandra/cluster.py | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1283-L1289 | def connection_factory(self, endpoint, *args, **kwargs):
"""
Called to create a new connection with proper configuration.
Intended for internal use only.
"""
kwargs = self._make_connection_kwargs(endpoint, kwargs)
return self.connection_class.factory(endpoint, self.connec... | [
"def",
"connection_factory",
"(",
"self",
",",
"endpoint",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"self",
".",
"_make_connection_kwargs",
"(",
"endpoint",
",",
"kwargs",
")",
"return",
"self",
".",
"connection_class",
".",
"fac... | Called to create a new connection with proper configuration.
Intended for internal use only. | [
"Called",
"to",
"create",
"a",
"new",
"connection",
"with",
"proper",
"configuration",
".",
"Intended",
"for",
"internal",
"use",
"only",
"."
] | python | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_checker.py | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_checker.py#L183-L212 | def allow(self, ctx, ops):
''' Checks that the authorizer's request is authorized to
perform all the given operations. Note that allow does not check
first party caveats - if there is more than one macaroon that may
authorize the request, it will choose the first one that does
re... | [
"def",
"allow",
"(",
"self",
",",
"ctx",
",",
"ops",
")",
":",
"auth_info",
",",
"_",
"=",
"self",
".",
"allow_any",
"(",
"ctx",
",",
"ops",
")",
"return",
"auth_info"
] | Checks that the authorizer's request is authorized to
perform all the given operations. Note that allow does not check
first party caveats - if there is more than one macaroon that may
authorize the request, it will choose the first one that does
regardless.
If all the operation... | [
"Checks",
"that",
"the",
"authorizer",
"s",
"request",
"is",
"authorized",
"to",
"perform",
"all",
"the",
"given",
"operations",
".",
"Note",
"that",
"allow",
"does",
"not",
"check",
"first",
"party",
"caveats",
"-",
"if",
"there",
"is",
"more",
"than",
"o... | python | train |
bitesofcode/projexui | projexui/configs/xschemeconfig.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/configs/xschemeconfig.py#L113-L121 | def reset( self ):
"""
Resets the colors to the default settings.
"""
dataSet = self.dataSet()
if ( not dataSet ):
dataSet = XScheme()
dataSet.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"dataSet",
"=",
"self",
".",
"dataSet",
"(",
")",
"if",
"(",
"not",
"dataSet",
")",
":",
"dataSet",
"=",
"XScheme",
"(",
")",
"dataSet",
".",
"reset",
"(",
")"
] | Resets the colors to the default settings. | [
"Resets",
"the",
"colors",
"to",
"the",
"default",
"settings",
"."
] | python | train |
72squared/redpipe | redpipe/keyspaces.py | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L2043-L2055 | def hincrby(self, name, key, amount=1):
"""
Increment the value of the field.
:param name: str the name of the redis key
:param increment: int
:param field: str
:return: Future()
"""
with self.pipe as pipe:
return pipe.hincrby(self.redis_k... | [
"def",
"hincrby",
"(",
"self",
",",
"name",
",",
"key",
",",
"amount",
"=",
"1",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"hincrby",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"self",
".",
"membe... | Increment the value of the field.
:param name: str the name of the redis key
:param increment: int
:param field: str
:return: Future() | [
"Increment",
"the",
"value",
"of",
"the",
"field",
"."
] | python | train |
DLR-RM/RAFCON | source/rafcon/gui/models/container_state.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/container_state.py#L72-L86 | def _load_child_state_models(self, load_meta_data):
"""Adds models for each child state of the state
:param bool load_meta_data: Whether to load the meta data of the child state
"""
self.states = {}
# Create model for each child class
child_states = self.state.states
... | [
"def",
"_load_child_state_models",
"(",
"self",
",",
"load_meta_data",
")",
":",
"self",
".",
"states",
"=",
"{",
"}",
"# Create model for each child class",
"child_states",
"=",
"self",
".",
"state",
".",
"states",
"for",
"child_state",
"in",
"child_states",
".",... | Adds models for each child state of the state
:param bool load_meta_data: Whether to load the meta data of the child state | [
"Adds",
"models",
"for",
"each",
"child",
"state",
"of",
"the",
"state"
] | python | train |
Erotemic/utool | utool/util_progress.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_progress.py#L808-L821 | def _get_timethresh_heuristics(self):
"""
resonably decent hueristics for how much time to wait before
updating progress.
"""
if self.length > 1E5:
time_thresh = 2.5
elif self.length > 1E4:
time_thresh = 2.0
elif self.length > 1E3:
... | [
"def",
"_get_timethresh_heuristics",
"(",
"self",
")",
":",
"if",
"self",
".",
"length",
">",
"1E5",
":",
"time_thresh",
"=",
"2.5",
"elif",
"self",
".",
"length",
">",
"1E4",
":",
"time_thresh",
"=",
"2.0",
"elif",
"self",
".",
"length",
">",
"1E3",
"... | resonably decent hueristics for how much time to wait before
updating progress. | [
"resonably",
"decent",
"hueristics",
"for",
"how",
"much",
"time",
"to",
"wait",
"before",
"updating",
"progress",
"."
] | python | train |
DAI-Lab/Copulas | copulas/__init__.py | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/__init__.py#L56-L112 | def vectorize(function):
"""Allow a method that only accepts scalars to accept vectors too.
This decorator has two different behaviors depending on the dimensionality of the
array passed as an argument:
**1-d array**
It will work under the assumption that the `function` argument is a callable
... | [
"def",
"vectorize",
"(",
"function",
")",
":",
"def",
"decorated",
"(",
"self",
",",
"X",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"X",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"function",
"(",
"s... | Allow a method that only accepts scalars to accept vectors too.
This decorator has two different behaviors depending on the dimensionality of the
array passed as an argument:
**1-d array**
It will work under the assumption that the `function` argument is a callable
with signature::
funct... | [
"Allow",
"a",
"method",
"that",
"only",
"accepts",
"scalars",
"to",
"accept",
"vectors",
"too",
"."
] | python | train |
ael-code/pyFsdb | fsdb/config.py | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/config.py#L57-L62 | def to_json_format(conf):
'''Convert fields of a python dictionary to be dumped in json format'''
if 'fmode' in conf:
conf['fmode'] = oct(conf['fmode'])[-3:]
if 'dmode' in conf:
conf['dmode'] = oct(conf['dmode'])[-3:] | [
"def",
"to_json_format",
"(",
"conf",
")",
":",
"if",
"'fmode'",
"in",
"conf",
":",
"conf",
"[",
"'fmode'",
"]",
"=",
"oct",
"(",
"conf",
"[",
"'fmode'",
"]",
")",
"[",
"-",
"3",
":",
"]",
"if",
"'dmode'",
"in",
"conf",
":",
"conf",
"[",
"'dmode'... | Convert fields of a python dictionary to be dumped in json format | [
"Convert",
"fields",
"of",
"a",
"python",
"dictionary",
"to",
"be",
"dumped",
"in",
"json",
"format"
] | python | train |
pyamg/pyamg | pyamg/amg_core/bindthem.py | https://github.com/pyamg/pyamg/blob/89dc54aa27e278f65d2f54bdaf16ab97d7768fa6/pyamg/amg_core/bindthem.py#L193-L306 | def build_plugin(headerfile, ch, comments, inst, remaps):
"""
Take a header file (headerfile) and a parse tree (ch)
and build the pybind11 plugin
headerfile: somefile.h
ch: parse tree from CppHeaderParser
comments: a dictionary of comments
inst: files to instantiate
remaps: list of ... | [
"def",
"build_plugin",
"(",
"headerfile",
",",
"ch",
",",
"comments",
",",
"inst",
",",
"remaps",
")",
":",
"headerfilename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"headerfile",
")",
"[",
"0",
"]",
"indent",
"=",
"' '",
"plugin",
"=",
"''",
... | Take a header file (headerfile) and a parse tree (ch)
and build the pybind11 plugin
headerfile: somefile.h
ch: parse tree from CppHeaderParser
comments: a dictionary of comments
inst: files to instantiate
remaps: list of remaps | [
"Take",
"a",
"header",
"file",
"(",
"headerfile",
")",
"and",
"a",
"parse",
"tree",
"(",
"ch",
")",
"and",
"build",
"the",
"pybind11",
"plugin"
] | python | train |
nugget/python-insteonplm | insteonplm/states/dimmable.py | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/states/dimmable.py#L193-L205 | def set_level(self, val):
"""Set the devive ON LEVEL."""
if val == 0:
self.off()
else:
setlevel = 255
if val < 1:
setlevel = val * 100
elif val <= 0xff:
setlevel = val
set_command = StandardSend(
... | [
"def",
"set_level",
"(",
"self",
",",
"val",
")",
":",
"if",
"val",
"==",
"0",
":",
"self",
".",
"off",
"(",
")",
"else",
":",
"setlevel",
"=",
"255",
"if",
"val",
"<",
"1",
":",
"setlevel",
"=",
"val",
"*",
"100",
"elif",
"val",
"<=",
"0xff",
... | Set the devive ON LEVEL. | [
"Set",
"the",
"devive",
"ON",
"LEVEL",
"."
] | python | train |
OLC-Bioinformatics/sipprverse | method.py | https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/method.py#L228-L261 | def complete(self):
"""
Determine if the analyses of the strains are complete e.g. there are no missing GDCS genes, and the
sample.general.bestassemblyfile != 'NA'
"""
# Boolean to store the completeness of the analyses
allcomplete = True
# Clear the list of samp... | [
"def",
"complete",
"(",
"self",
")",
":",
"# Boolean to store the completeness of the analyses",
"allcomplete",
"=",
"True",
"# Clear the list of samples that still require more sequence data",
"self",
".",
"incomplete",
"=",
"list",
"(",
")",
"for",
"sample",
"in",
"self",... | Determine if the analyses of the strains are complete e.g. there are no missing GDCS genes, and the
sample.general.bestassemblyfile != 'NA' | [
"Determine",
"if",
"the",
"analyses",
"of",
"the",
"strains",
"are",
"complete",
"e",
".",
"g",
".",
"there",
"are",
"no",
"missing",
"GDCS",
"genes",
"and",
"the",
"sample",
".",
"general",
".",
"bestassemblyfile",
"!",
"=",
"NA"
] | python | train |
authomatic/authomatic | authomatic/core.py | https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L212-L228 | def id_to_name(config, short_name):
"""
Returns the provider :doc:`config` key based on it's ``id`` value.
:param dict config:
:doc:`config`.
:param id:
Value of the id parameter in the :ref:`config` to search for.
"""
for k, v in list(config.items()):
if v.get('id') =... | [
"def",
"id_to_name",
"(",
"config",
",",
"short_name",
")",
":",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"config",
".",
"items",
"(",
")",
")",
":",
"if",
"v",
".",
"get",
"(",
"'id'",
")",
"==",
"short_name",
":",
"return",
"k",
"raise",
"Excep... | Returns the provider :doc:`config` key based on it's ``id`` value.
:param dict config:
:doc:`config`.
:param id:
Value of the id parameter in the :ref:`config` to search for. | [
"Returns",
"the",
"provider",
":",
"doc",
":",
"config",
"key",
"based",
"on",
"it",
"s",
"id",
"value",
"."
] | python | test |
Cito/DBUtils | DBUtils/SteadyDB.py | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L111-L139 | def connect(
creator, maxusage=None, setsession=None,
failures=None, ping=1, closeable=True, *args, **kwargs):
"""A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 c... | [
"def",
"connect",
"(",
"creator",
",",
"maxusage",
"=",
"None",
",",
"setsession",
"=",
"None",
",",
"failures",
"=",
"None",
",",
"ping",
"=",
"1",
",",
"closeable",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Stea... | A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 compliant database module
maxusage: maximum usage limit for the underlying DB-API 2 connection
(number of database operatio... | [
"A",
"tough",
"version",
"of",
"the",
"connection",
"constructor",
"of",
"a",
"DB",
"-",
"API",
"2",
"module",
"."
] | python | train |
twilio/twilio-python | twilio/rest/preview/marketplace/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/preview/marketplace/__init__.py#L29-L35 | def installed_add_ons(self):
"""
:rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnList
"""
if self._installed_add_ons is None:
self._installed_add_ons = InstalledAddOnList(self)
return self._installed_add_ons | [
"def",
"installed_add_ons",
"(",
"self",
")",
":",
"if",
"self",
".",
"_installed_add_ons",
"is",
"None",
":",
"self",
".",
"_installed_add_ons",
"=",
"InstalledAddOnList",
"(",
"self",
")",
"return",
"self",
".",
"_installed_add_ons"
] | :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnList | [
":",
"rtype",
":",
"twilio",
".",
"rest",
".",
"preview",
".",
"marketplace",
".",
"installed_add_on",
".",
"InstalledAddOnList"
] | python | train |
mongodb/mongo-python-driver | pymongo/message.py | https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/message.py#L608-L615 | def update(collection_name, upsert, multi, spec,
doc, safe, last_error_args, check_keys, opts, ctx=None):
"""Get an **update** message."""
if ctx:
return _update_compressed(
collection_name, upsert, multi, spec, doc, check_keys, opts, ctx)
return _update_uncompressed(collectio... | [
"def",
"update",
"(",
"collection_name",
",",
"upsert",
",",
"multi",
",",
"spec",
",",
"doc",
",",
"safe",
",",
"last_error_args",
",",
"check_keys",
",",
"opts",
",",
"ctx",
"=",
"None",
")",
":",
"if",
"ctx",
":",
"return",
"_update_compressed",
"(",
... | Get an **update** message. | [
"Get",
"an",
"**",
"update",
"**",
"message",
"."
] | python | train |
quodlibet/mutagen | mutagen/_util.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L824-L857 | def insert_bytes(fobj, size, offset, BUFFER_SIZE=2 ** 16):
"""Insert size bytes of empty space starting at offset.
fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails.
Args:
fo... | [
"def",
"insert_bytes",
"(",
"fobj",
",",
"size",
",",
"offset",
",",
"BUFFER_SIZE",
"=",
"2",
"**",
"16",
")",
":",
"if",
"size",
"<",
"0",
"or",
"offset",
"<",
"0",
":",
"raise",
"ValueError",
"fobj",
".",
"seek",
"(",
"0",
",",
"2",
")",
"files... | Insert size bytes of empty space starting at offset.
fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails.
Args:
fobj (fileobj)
size (int): The amount of space to insert
... | [
"Insert",
"size",
"bytes",
"of",
"empty",
"space",
"starting",
"at",
"offset",
"."
] | python | train |
airspeed-velocity/asv | asv/extern/asizeof.py | https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L354-L360 | def _derive_typedef(typ):
'''Return single, existing super type typedef or None.
'''
v = [v for v in _values(_typedefs) if _issubclass(typ, v.type)]
if len(v) == 1:
return v[0]
return None | [
"def",
"_derive_typedef",
"(",
"typ",
")",
":",
"v",
"=",
"[",
"v",
"for",
"v",
"in",
"_values",
"(",
"_typedefs",
")",
"if",
"_issubclass",
"(",
"typ",
",",
"v",
".",
"type",
")",
"]",
"if",
"len",
"(",
"v",
")",
"==",
"1",
":",
"return",
"v",... | Return single, existing super type typedef or None. | [
"Return",
"single",
"existing",
"super",
"type",
"typedef",
"or",
"None",
"."
] | python | train |
PyCQA/pylint | pylint/pyreverse/diadefslib.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diadefslib.py#L75-L79 | def show_node(self, node):
"""true if builtins and not show_builtins"""
if self.config.show_builtin:
return True
return node.root().name != BUILTINS_NAME | [
"def",
"show_node",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"config",
".",
"show_builtin",
":",
"return",
"True",
"return",
"node",
".",
"root",
"(",
")",
".",
"name",
"!=",
"BUILTINS_NAME"
] | true if builtins and not show_builtins | [
"true",
"if",
"builtins",
"and",
"not",
"show_builtins"
] | python | test |
MillionIntegrals/vel | vel/rl/api/rollout.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L59-L76 | def shuffled_batches(self, batch_size):
""" Generate randomized batches of data """
if batch_size >= self.size:
yield self
else:
batch_splits = math_util.divide_ceiling(self.size, batch_size)
indices = list(range(self.size))
np.random.shuffle(indic... | [
"def",
"shuffled_batches",
"(",
"self",
",",
"batch_size",
")",
":",
"if",
"batch_size",
">=",
"self",
".",
"size",
":",
"yield",
"self",
"else",
":",
"batch_splits",
"=",
"math_util",
".",
"divide_ceiling",
"(",
"self",
".",
"size",
",",
"batch_size",
")"... | Generate randomized batches of data | [
"Generate",
"randomized",
"batches",
"of",
"data"
] | python | train |
kodexlab/reliure | reliure/pipeline.py | https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/pipeline.py#L164-L172 | def print_options(self):
""" print description of the component options
"""
summary = []
for opt_name, opt in self.options.items():
if opt.hidden:
continue
summary.append(opt.summary())
print("\n".join(summary)) | [
"def",
"print_options",
"(",
"self",
")",
":",
"summary",
"=",
"[",
"]",
"for",
"opt_name",
",",
"opt",
"in",
"self",
".",
"options",
".",
"items",
"(",
")",
":",
"if",
"opt",
".",
"hidden",
":",
"continue",
"summary",
".",
"append",
"(",
"opt",
".... | print description of the component options | [
"print",
"description",
"of",
"the",
"component",
"options"
] | python | train |
UCBerkeleySETI/blimpy | blimpy/calib_utils/calib_plots.py | https://github.com/UCBerkeleySETI/blimpy/blob/b8822d3e3e911944370d84371a91fa0c29e9772e/blimpy/calib_utils/calib_plots.py#L167-L215 | def plot_gain_offsets(dio_cross,dio_chan_per_coarse=8,feedtype='l',ax1=None,ax2=None,legend=True,**kwargs):
'''
Plots the calculated gain offsets of each coarse channel along with
the time averaged power spectra of the X and Y feeds
'''
#Get ON-OFF ND spectra
Idiff,Qdiff,Udiff,Vdiff,freqs = get_... | [
"def",
"plot_gain_offsets",
"(",
"dio_cross",
",",
"dio_chan_per_coarse",
"=",
"8",
",",
"feedtype",
"=",
"'l'",
",",
"ax1",
"=",
"None",
",",
"ax2",
"=",
"None",
",",
"legend",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"#Get ON-OFF ND spectra",
"I... | Plots the calculated gain offsets of each coarse channel along with
the time averaged power spectra of the X and Y feeds | [
"Plots",
"the",
"calculated",
"gain",
"offsets",
"of",
"each",
"coarse",
"channel",
"along",
"with",
"the",
"time",
"averaged",
"power",
"spectra",
"of",
"the",
"X",
"and",
"Y",
"feeds"
] | python | test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.