repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
ucfopen/canvasapi | canvasapi/canvas.py | https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L812-L834 | def get_appointment_group(self, appointment_group):
"""
Return single Appointment Group by id
:calls: `GET /api/v1/appointment_groups/:id \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.show>`_
:param appointment_group: The ID of the ... | [
"def",
"get_appointment_group",
"(",
"self",
",",
"appointment_group",
")",
":",
"from",
"canvasapi",
".",
"appointment_group",
"import",
"AppointmentGroup",
"appointment_group_id",
"=",
"obj_or_id",
"(",
"appointment_group",
",",
"\"appointment_group\"",
",",
"(",
"App... | Return single Appointment Group by id
:calls: `GET /api/v1/appointment_groups/:id \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.show>`_
:param appointment_group: The ID of the appointment group.
:type appointment_group: :class:`canvasapi.ap... | [
"Return",
"single",
"Appointment",
"Group",
"by",
"id"
] | python | train | 38.695652 |
rkargon/pixelsorter | pixelsorter/edge_detection.py | https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/edge_detection.py#L29-L58 | def edge_detect(image, size):
"""
Applies a Sobel filter to the given image.
:param image: An image as a list of (R,G,B) values
:param size: The size of the image as a tuple (width, height)
:return: An array of the Sobel gradient value of each image pixel
This value roughly corresponds to how mu... | [
"def",
"edge_detect",
"(",
"image",
",",
"size",
")",
":",
"# TODO get edge data for boundaries",
"width",
",",
"height",
"=",
"size",
"edge_data",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"image",
")",
"gray_scale_img",
"=",
"list",
"(",
"map",
"(",
"luma",
... | Applies a Sobel filter to the given image.
:param image: An image as a list of (R,G,B) values
:param size: The size of the image as a tuple (width, height)
:return: An array of the Sobel gradient value of each image pixel
This value roughly corresponds to how much of an "edge" a pixel is. | [
"Applies",
"a",
"Sobel",
"filter",
"to",
"the",
"given",
"image",
".",
":",
"param",
"image",
":",
"An",
"image",
"as",
"a",
"list",
"of",
"(",
"R",
"G",
"B",
")",
"values",
":",
"param",
"size",
":",
"The",
"size",
"of",
"the",
"image",
"as",
"a... | python | train | 39.633333 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L468-L476 | def tag(self):
"""
Get the string representation of the tag used to annotate the status in VOSpace.
@return: str
"""
return "{}{}_{}{:02d}".format(self.target.prefix,
self,
self.target.version,
... | [
"def",
"tag",
"(",
"self",
")",
":",
"return",
"\"{}{}_{}{:02d}\"",
".",
"format",
"(",
"self",
".",
"target",
".",
"prefix",
",",
"self",
",",
"self",
".",
"target",
".",
"version",
",",
"self",
".",
"target",
".",
"ccd",
")"
] | Get the string representation of the tag used to annotate the status in VOSpace.
@return: str | [
"Get",
"the",
"string",
"representation",
"of",
"the",
"tag",
"used",
"to",
"annotate",
"the",
"status",
"in",
"VOSpace",
"."
] | python | train | 39.555556 |
LonamiWebs/Telethon | telethon/client/telegrambaseclient.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/client/telegrambaseclient.py#L535-L559 | async def _get_cdn_client(self, cdn_redirect):
"""Similar to ._borrow_exported_client, but for CDNs"""
# TODO Implement
raise NotImplementedError
session = self._exported_sessions.get(cdn_redirect.dc_id)
if not session:
dc = await self._get_dc(cdn_redirect.dc_id, cdn=... | [
"async",
"def",
"_get_cdn_client",
"(",
"self",
",",
"cdn_redirect",
")",
":",
"# TODO Implement",
"raise",
"NotImplementedError",
"session",
"=",
"self",
".",
"_exported_sessions",
".",
"get",
"(",
"cdn_redirect",
".",
"dc_id",
")",
"if",
"not",
"session",
":",... | Similar to ._borrow_exported_client, but for CDNs | [
"Similar",
"to",
".",
"_borrow_exported_client",
"but",
"for",
"CDNs"
] | python | train | 44.52 |
tango-controls/pytango | tango/databaseds/database.py | https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/databaseds/database.py#L652-L677 | def DbDeleteDeviceAttribute(self, argin):
""" Delete device attribute properties from database
:param argin: Str[0] = Device name
Str[1] = Attribute name
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid """
self._log.debug("In DbDeleteDeviceAttribut... | [
"def",
"DbDeleteDeviceAttribute",
"(",
"self",
",",
"argin",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"In DbDeleteDeviceAttribute()\"",
")",
"if",
"len",
"(",
"argin",
")",
"<",
"2",
":",
"self",
".",
"warn_stream",
"(",
"\"DataBase::db_delete_devic... | Delete device attribute properties from database
:param argin: Str[0] = Device name
Str[1] = Attribute name
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid | [
"Delete",
"device",
"attribute",
"properties",
"from",
"database"
] | python | train | 41.5 |
SwoopSearch/pyaddress | address/address.py | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L83-L88 | def parse_address(self, address, line_number=-1):
"""
Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc.
"""
return Address(address, self, line_number, self.logger) | [
"def",
"parse_address",
"(",
"self",
",",
"address",
",",
"line_number",
"=",
"-",
"1",
")",
":",
"return",
"Address",
"(",
"address",
",",
"self",
",",
"line_number",
",",
"self",
".",
"logger",
")"
] | Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc. | [
"Return",
"an",
"Address",
"object",
"from",
"the",
"given",
"address",
".",
"Passes",
"itself",
"to",
"the",
"Address",
"constructor",
"to",
"use",
"all",
"the",
"custom",
"loaded",
"suffixes",
"cities",
"etc",
"."
] | python | train | 48.333333 |
pypa/pipenv | pipenv/project.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/project.py#L581-L590 | def _lockfile(self):
"""Pipfile.lock divided by PyPI and external dependencies."""
pfile = pipfile.load(self.pipfile_location, inject_env=False)
lockfile = json.loads(pfile.lock())
for section in ("default", "develop"):
lock_section = lockfile.get(section, {})
for... | [
"def",
"_lockfile",
"(",
"self",
")",
":",
"pfile",
"=",
"pipfile",
".",
"load",
"(",
"self",
".",
"pipfile_location",
",",
"inject_env",
"=",
"False",
")",
"lockfile",
"=",
"json",
".",
"loads",
"(",
"pfile",
".",
"lock",
"(",
")",
")",
"for",
"sect... | Pipfile.lock divided by PyPI and external dependencies. | [
"Pipfile",
".",
"lock",
"divided",
"by",
"PyPI",
"and",
"external",
"dependencies",
"."
] | python | train | 48.1 |
ssalentin/plip | plip/modules/supplemental.py | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L101-L112 | def vecangle(v1, v2, deg=True):
"""Calculate the angle between two vectors
:param v1: coordinates of vector v1
:param v2: coordinates of vector v2
:returns : angle in degree or rad
"""
if np.array_equal(v1, v2):
return 0.0
dm = np.dot(v1, v2)
cm = np.linalg.norm(v1) * np.linalg.n... | [
"def",
"vecangle",
"(",
"v1",
",",
"v2",
",",
"deg",
"=",
"True",
")",
":",
"if",
"np",
".",
"array_equal",
"(",
"v1",
",",
"v2",
")",
":",
"return",
"0.0",
"dm",
"=",
"np",
".",
"dot",
"(",
"v1",
",",
"v2",
")",
"cm",
"=",
"np",
".",
"lina... | Calculate the angle between two vectors
:param v1: coordinates of vector v1
:param v2: coordinates of vector v2
:returns : angle in degree or rad | [
"Calculate",
"the",
"angle",
"between",
"two",
"vectors",
":",
"param",
"v1",
":",
"coordinates",
"of",
"vector",
"v1",
":",
"param",
"v2",
":",
"coordinates",
"of",
"vector",
"v2",
":",
"returns",
":",
"angle",
"in",
"degree",
"or",
"rad"
] | python | train | 38.25 |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wsj_parsing.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wsj_parsing.py#L106-L133 | def token_generator(tree_path, source_token_vocab, target_token_vocab,
eos=None):
"""Generator for parsing as a sequence-to-sequence task that uses tokens.
This generator assumes the files at source_path and target_path have
the same number of lines and yields dictionaries of "inputs" and "ta... | [
"def",
"token_generator",
"(",
"tree_path",
",",
"source_token_vocab",
",",
"target_token_vocab",
",",
"eos",
"=",
"None",
")",
":",
"eos_list",
"=",
"[",
"]",
"if",
"eos",
"is",
"None",
"else",
"[",
"eos",
"]",
"with",
"tf",
".",
"gfile",
".",
"GFile",
... | Generator for parsing as a sequence-to-sequence task that uses tokens.
This generator assumes the files at source_path and target_path have
the same number of lines and yields dictionaries of "inputs" and "targets"
where inputs and targets are token ids from source and target lines
converted to integers using ... | [
"Generator",
"for",
"parsing",
"as",
"a",
"sequence",
"-",
"to",
"-",
"sequence",
"task",
"that",
"uses",
"tokens",
"."
] | python | train | 47.642857 |
apple/turicreate | src/unity/python/doc/source/sphinx_turicreate_ext/pycon.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/doc/source/sphinx_turicreate_ext/pycon.py#L10-L30 | def main():
"""
Print lines of input along with output.
"""
source_lines = (line.rstrip() for line in sys.stdin)
console = InteractiveInterpreter()
console.runsource('import turicreate')
source = ''
try:
while True:
source = source_lines.next()
more = cons... | [
"def",
"main",
"(",
")",
":",
"source_lines",
"=",
"(",
"line",
".",
"rstrip",
"(",
")",
"for",
"line",
"in",
"sys",
".",
"stdin",
")",
"console",
"=",
"InteractiveInterpreter",
"(",
")",
"console",
".",
"runsource",
"(",
"'import turicreate'",
")",
"sou... | Print lines of input along with output. | [
"Print",
"lines",
"of",
"input",
"along",
"with",
"output",
"."
] | python | train | 30.666667 |
saltstack/salt | salt/modules/bcache.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bcache.py#L57-L79 | def uuid(dev=None):
'''
Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0
'''
try:
if dev is None:
... | [
"def",
"uuid",
"(",
"dev",
"=",
"None",
")",
":",
"try",
":",
"if",
"dev",
"is",
"None",
":",
"# take the only directory in /sys/fs/bcache and return it's basename",
"return",
"list",
"(",
"salt",
".",
"utils",
".",
"path",
".",
"os_walk",
"(",
"'/sys/fs/bcache/... | Return the bcache UUID of a block device.
If no device is given, the Cache UUID is returned.
CLI example:
.. code-block:: bash
salt '*' bcache.uuid
salt '*' bcache.uuid /dev/sda
salt '*' bcache.uuid bcache0 | [
"Return",
"the",
"bcache",
"UUID",
"of",
"a",
"block",
"device",
".",
"If",
"no",
"device",
"is",
"given",
"the",
"Cache",
"UUID",
"is",
"returned",
"."
] | python | train | 28.043478 |
secdev/scapy | scapy/layers/ipsec.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/ipsec.py#L562-L598 | def verify(self, pkt, key):
"""
Check that the integrity check value (icv) of a packet is valid.
@param pkt: a packet that contains a valid encrypted ESP or AH layer
@param key: the authentication key, a byte string
@raise IPSecIntegrityError: if the integrity check fails... | [
"def",
"verify",
"(",
"self",
",",
"pkt",
",",
"key",
")",
":",
"if",
"not",
"self",
".",
"mac",
"or",
"self",
".",
"icv_size",
"==",
"0",
":",
"return",
"mac",
"=",
"self",
".",
"new_mac",
"(",
"key",
")",
"pkt_icv",
"=",
"'not found'",
"computed_... | Check that the integrity check value (icv) of a packet is valid.
@param pkt: a packet that contains a valid encrypted ESP or AH layer
@param key: the authentication key, a byte string
@raise IPSecIntegrityError: if the integrity check fails | [
"Check",
"that",
"the",
"integrity",
"check",
"value",
"(",
"icv",
")",
"of",
"a",
"packet",
"is",
"valid",
"."
] | python | train | 36.648649 |
Jammy2211/PyAutoLens | autolens/model/inversion/util/pixelization_util.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/util/pixelization_util.py#L5-L30 | def rectangular_neighbors_from_shape(shape):
"""Compute the neighbors of every pixel as a list of the pixel index's each pixel shares a vertex with.
The uniformity of the rectangular grid's geometry is used to compute this.
"""
pixels = shape[0]*shape[1]
pixel_neighbors = -1 * np.ones(shape=(pix... | [
"def",
"rectangular_neighbors_from_shape",
"(",
"shape",
")",
":",
"pixels",
"=",
"shape",
"[",
"0",
"]",
"*",
"shape",
"[",
"1",
"]",
"pixel_neighbors",
"=",
"-",
"1",
"*",
"np",
".",
"ones",
"(",
"shape",
"=",
"(",
"pixels",
",",
"4",
")",
")",
"... | Compute the neighbors of every pixel as a list of the pixel index's each pixel shares a vertex with.
The uniformity of the rectangular grid's geometry is used to compute this. | [
"Compute",
"the",
"neighbors",
"of",
"every",
"pixel",
"as",
"a",
"list",
"of",
"the",
"pixel",
"index",
"s",
"each",
"pixel",
"shares",
"a",
"vertex",
"with",
"."
] | python | valid | 60.769231 |
mikedh/trimesh | trimesh/transformations.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/transformations.py#L1086-L1146 | def euler_matrix(ai, aj, ak, axes='sxyz'):
"""Return homogeneous rotation matrix from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> R = euler_matrix(1, 2, 3, 'syxz')
>>> np.allclose(np.sum(R[0]), -1.34... | [
"def",
"euler_matrix",
"(",
"ai",
",",
"aj",
",",
"ak",
",",
"axes",
"=",
"'sxyz'",
")",
":",
"try",
":",
"firstaxis",
",",
"parity",
",",
"repetition",
",",
"frame",
"=",
"_AXES2TUPLE",
"[",
"axes",
"]",
"except",
"(",
"AttributeError",
",",
"KeyError... | Return homogeneous rotation matrix from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> R = euler_matrix(1, 2, 3, 'syxz')
>>> np.allclose(np.sum(R[0]), -1.34786452)
True
>>> R = euler_matrix(1, 2, 3,... | [
"Return",
"homogeneous",
"rotation",
"matrix",
"from",
"Euler",
"angles",
"and",
"axis",
"sequence",
"."
] | python | train | 28.672131 |
xenon-middleware/pyxenon | xenon/server.py | https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/server.py#L116-L151 | def init(port=None, do_not_exit=False, disable_tls=False, log_level='WARNING'):
"""Start the Xenon GRPC server on the specified port, or, if a service
is already running on that port, connect to that.
If no port is given, a random port is selected. This means that, by
default, every python instance wil... | [
"def",
"init",
"(",
"port",
"=",
"None",
",",
"do_not_exit",
"=",
"False",
",",
"disable_tls",
"=",
"False",
",",
"log_level",
"=",
"'WARNING'",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'xenon'",
")",
"logger",
".",
"setLevel",
"(",
... | Start the Xenon GRPC server on the specified port, or, if a service
is already running on that port, connect to that.
If no port is given, a random port is selected. This means that, by
default, every python instance will start its own instance of a xenon-grpc
process.
:param port: the port number... | [
"Start",
"the",
"Xenon",
"GRPC",
"server",
"on",
"the",
"specified",
"port",
"or",
"if",
"a",
"service",
"is",
"already",
"running",
"on",
"that",
"port",
"connect",
"to",
"that",
"."
] | python | train | 35.305556 |
ArchiveTeam/wpull | wpull/application/tasks/shutdown.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/shutdown.py#L54-L60 | def _update_exit_code_from_stats(cls, statistics: Statistics,
app: Application):
'''Set the current exit code based on the Statistics.'''
for error_type in statistics.errors:
exit_code = app.ERROR_CODE_MAP.get(error_type)
if exit_code:
... | [
"def",
"_update_exit_code_from_stats",
"(",
"cls",
",",
"statistics",
":",
"Statistics",
",",
"app",
":",
"Application",
")",
":",
"for",
"error_type",
"in",
"statistics",
".",
"errors",
":",
"exit_code",
"=",
"app",
".",
"ERROR_CODE_MAP",
".",
"get",
"(",
"... | Set the current exit code based on the Statistics. | [
"Set",
"the",
"current",
"exit",
"code",
"based",
"on",
"the",
"Statistics",
"."
] | python | train | 50.571429 |
jtwhite79/pyemu | pyemu/la.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/la.py#L932-L1011 | def get(self,par_names=None,obs_names=None,astype=None):
"""method to get a new LinearAnalysis class using a
subset of parameters and/or observations
Parameters
----------
par_names : list
par names for new object
obs_names : list
obs names for ne... | [
"def",
"get",
"(",
"self",
",",
"par_names",
"=",
"None",
",",
"obs_names",
"=",
"None",
",",
"astype",
"=",
"None",
")",
":",
"# make sure we aren't fooling with unwanted prior information",
"self",
".",
"clean",
"(",
")",
"# if there is nothing to do but copy",
"i... | method to get a new LinearAnalysis class using a
subset of parameters and/or observations
Parameters
----------
par_names : list
par names for new object
obs_names : list
obs names for new object
astype : pyemu.Schur or pyemu.ErrVar
ty... | [
"method",
"to",
"get",
"a",
"new",
"LinearAnalysis",
"class",
"using",
"a",
"subset",
"of",
"parameters",
"and",
"/",
"or",
"observations"
] | python | train | 38.775 |
kressi/terminalplot | terminalplot/terminalplot.py | https://github.com/kressi/terminalplot/blob/af05f3fe0793c957cc0b0ebf4afbe54c72d18b66/terminalplot/terminalplot.py#L7-L38 | def plot(x, y, rows=None, columns=None):
"""
x, y list of values on x- and y-axis
plot those values within canvas size (rows and columns)
"""
if not rows or not columns:
rows, columns = get_terminal_size()
# offset for caption
rows -= 4
# Scale points such that they fit on canva... | [
"def",
"plot",
"(",
"x",
",",
"y",
",",
"rows",
"=",
"None",
",",
"columns",
"=",
"None",
")",
":",
"if",
"not",
"rows",
"or",
"not",
"columns",
":",
"rows",
",",
"columns",
"=",
"get_terminal_size",
"(",
")",
"# offset for caption",
"rows",
"-=",
"4... | x, y list of values on x- and y-axis
plot those values within canvas size (rows and columns) | [
"x",
"y",
"list",
"of",
"values",
"on",
"x",
"-",
"and",
"y",
"-",
"axis",
"plot",
"those",
"values",
"within",
"canvas",
"size",
"(",
"rows",
"and",
"columns",
")"
] | python | train | 26.3125 |
saltstack/salt | salt/modules/groupadd.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/groupadd.py#L109-L135 | def info(name, root=None):
'''
Return information about a group
name
Name of the group
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' group.info foo
'''
if root is not None:
getgrnam = functools.partial(_getgrnam, root=root)
... | [
"def",
"info",
"(",
"name",
",",
"root",
"=",
"None",
")",
":",
"if",
"root",
"is",
"not",
"None",
":",
"getgrnam",
"=",
"functools",
".",
"partial",
"(",
"_getgrnam",
",",
"root",
"=",
"root",
")",
"else",
":",
"getgrnam",
"=",
"functools",
".",
"... | Return information about a group
name
Name of the group
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' group.info foo | [
"Return",
"information",
"about",
"a",
"group"
] | python | train | 17.814815 |
saltstack/salt | salt/modules/smartos_vmadm.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L459-L489 | def get(vm, key='uuid'):
'''
Output the JSON object describing a VM
vm : string
vm to be targeted
key : string [uuid|alias|hostname]
value type of 'vm' parameter
CLI Example:
.. code-block:: bash
salt '*' vmadm.get 186da9ab-7392-4f55-91a5-b8f1fe770543
salt '*'... | [
"def",
"get",
"(",
"vm",
",",
"key",
"=",
"'uuid'",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"key",
"not",
"in",
"[",
"'uuid'",
",",
"'alias'",
",",
"'hostname'",
"]",
":",
"ret",
"[",
"'Error'",
"]",
"=",
"'Key must be either uuid, alias or hostname'",
"... | Output the JSON object describing a VM
vm : string
vm to be targeted
key : string [uuid|alias|hostname]
value type of 'vm' parameter
CLI Example:
.. code-block:: bash
salt '*' vmadm.get 186da9ab-7392-4f55-91a5-b8f1fe770543
salt '*' vmadm.get nacl key=alias | [
"Output",
"the",
"JSON",
"object",
"describing",
"a",
"VM"
] | python | train | 27.870968 |
saltstack/salt | salt/modules/boto_kms.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L80-L98 | def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None,
profile=None):
'''
Create a display name for a key.
CLI example::
salt myminion boto_kms.create_alias 'alias/mykey' key_id
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profi... | [
"def",
"create_alias",
"(",
"alias_name",
",",
"target_key_id",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
... | Create a display name for a key.
CLI example::
salt myminion boto_kms.create_alias 'alias/mykey' key_id | [
"Create",
"a",
"display",
"name",
"for",
"a",
"key",
"."
] | python | train | 28.789474 |
tornadoweb/tornado | tornado/ioloop.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L460-L532 | def run_sync(self, func: Callable, timeout: float = None) -> Any:
"""Starts the `IOLoop`, runs the given function, and stops the loop.
The function must return either an awaitable object or
``None``. If the function returns an awaitable object, the
`IOLoop` will run until the awaitable ... | [
"def",
"run_sync",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"timeout",
":",
"float",
"=",
"None",
")",
"->",
"Any",
":",
"future_cell",
"=",
"[",
"None",
"]",
"# type: List[Optional[Future]]",
"def",
"run",
"(",
")",
"->",
"None",
":",
"try",
":... | Starts the `IOLoop`, runs the given function, and stops the loop.
The function must return either an awaitable object or
``None``. If the function returns an awaitable object, the
`IOLoop` will run until the awaitable is resolved (and
`run_sync()` will return the awaitable's result). If... | [
"Starts",
"the",
"IOLoop",
"runs",
"the",
"given",
"function",
"and",
"stops",
"the",
"loop",
"."
] | python | train | 38.90411 |
henzk/ape | ape/main.py | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/main.py#L137-L172 | def main():
"""
Entry point when used via command line.
Features are given using the environment variable ``PRODUCT_EQUATION``.
If it is not set, ``PRODUCT_EQUATION_FILENAME`` is tried: if it points
to an existing equation file that selection is used.
(if ``APE_PREPEND_FEATURES`` is given, tho... | [
"def",
"main",
"(",
")",
":",
"# check APE_PREPEND_FEATURES",
"features",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'APE_PREPEND_FEATURES'",
",",
"''",
")",
".",
"split",
"(",
")",
"# features can be specified inline in PRODUCT_EQUATION",
"inline_features",
"=",
... | Entry point when used via command line.
Features are given using the environment variable ``PRODUCT_EQUATION``.
If it is not set, ``PRODUCT_EQUATION_FILENAME`` is tried: if it points
to an existing equation file that selection is used.
(if ``APE_PREPEND_FEATURES`` is given, those features are prepende... | [
"Entry",
"point",
"when",
"used",
"via",
"command",
"line",
"."
] | python | train | 38.638889 |
ewels/MultiQC | multiqc/modules/picard/ValidateSamFile.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/ValidateSamFile.py#L110-L137 | def _parse_reports_by_type(self):
""" Returns a data dictionary
Goes through logs and parses them based on 'No errors found', VERBOSE or SUMMARY type.
"""
data = dict()
for file_meta in self.find_log_files('picard/sam_file_validation', filehandles=True):
sample = file_meta['s_name']
... | [
"def",
"_parse_reports_by_type",
"(",
"self",
")",
":",
"data",
"=",
"dict",
"(",
")",
"for",
"file_meta",
"in",
"self",
".",
"find_log_files",
"(",
"'picard/sam_file_validation'",
",",
"filehandles",
"=",
"True",
")",
":",
"sample",
"=",
"file_meta",
"[",
"... | Returns a data dictionary
Goes through logs and parses them based on 'No errors found', VERBOSE or SUMMARY type. | [
"Returns",
"a",
"data",
"dictionary"
] | python | train | 32.642857 |
secdev/scapy | scapy/contrib/pnio_rpc.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/contrib/pnio_rpc.py#L969-L975 | def can_handle(cls, pkt, rpc):
"""heuristical guess_payload_class"""
# type = 0 => request
if rpc.getfieldval("type") == 0 and \
str(rpc.object_uuid).startswith("dea00000-6c97-11d1-8271-"):
return True
return False | [
"def",
"can_handle",
"(",
"cls",
",",
"pkt",
",",
"rpc",
")",
":",
"# type = 0 => request",
"if",
"rpc",
".",
"getfieldval",
"(",
"\"type\"",
")",
"==",
"0",
"and",
"str",
"(",
"rpc",
".",
"object_uuid",
")",
".",
"startswith",
"(",
"\"dea00000-6c97-11d1-8... | heuristical guess_payload_class | [
"heuristical",
"guess_payload_class"
] | python | train | 38.285714 |
bunq/sdk_python | bunq/sdk/client.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/client.py#L455-L465 | def url_params_previous_page(self):
"""
:rtype: dict[str, str]
"""
self.assert_has_previous_page()
params = {self.PARAM_OLDER_ID: str(self.older_id)}
self._add_count_to_params_if_needed(params)
return params | [
"def",
"url_params_previous_page",
"(",
"self",
")",
":",
"self",
".",
"assert_has_previous_page",
"(",
")",
"params",
"=",
"{",
"self",
".",
"PARAM_OLDER_ID",
":",
"str",
"(",
"self",
".",
"older_id",
")",
"}",
"self",
".",
"_add_count_to_params_if_needed",
"... | :rtype: dict[str, str] | [
":",
"rtype",
":",
"dict",
"[",
"str",
"str",
"]"
] | python | train | 23.272727 |
saltstack/salt | salt/modules/boto_iam.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1525-L1572 | def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None):
'''
Lists the server certificates stored in IAM that have the specified path prefix.
.. versionadded:: ???
:param path_prefix:
The path prefix for filtering the results. For example: /company/serv... | [
"def",
"list_server_certificates",
"(",
"path_prefix",
"=",
"'/'",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"retries",
"=",
"10",
"sleep",
"=",
"6",
"conn",
"=",
"__utils__",... | Lists the server certificates stored in IAM that have the specified path prefix.
.. versionadded:: ???
:param path_prefix:
The path prefix for filtering the results. For example: /company/servercerts would get
all server certificates for which the path starts with /company/servercerts .
... | [
"Lists",
"the",
"server",
"certificates",
"stored",
"in",
"IAM",
"that",
"have",
"the",
"specified",
"path",
"prefix",
"."
] | python | train | 46.104167 |
apache/incubator-heron | heron/executor/src/python/heron_executor.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/executor/src/python/heron_executor.py#L991-L1023 | def start_process_monitor(self):
""" Monitor all processes in processes_to_monitor dict,
restarting any if they fail, up to max_runs times.
"""
# Now wait for any child to die
Log.info("Start process monitor")
while True:
if len(self.processes_to_monitor) > 0:
(pid, status) = os.wa... | [
"def",
"start_process_monitor",
"(",
"self",
")",
":",
"# Now wait for any child to die",
"Log",
".",
"info",
"(",
"\"Start process monitor\"",
")",
"while",
"True",
":",
"if",
"len",
"(",
"self",
".",
"processes_to_monitor",
")",
">",
"0",
":",
"(",
"pid",
",... | Monitor all processes in processes_to_monitor dict,
restarting any if they fail, up to max_runs times. | [
"Monitor",
"all",
"processes",
"in",
"processes_to_monitor",
"dict",
"restarting",
"any",
"if",
"they",
"fail",
"up",
"to",
"max_runs",
"times",
"."
] | python | valid | 42.484848 |
crackinglandia/pype32 | pype32/pype32.py | https://github.com/crackinglandia/pype32/blob/192fd14dfc0dd36d953739a81c17fbaf5e3d6076/pype32/pype32.py#L958-L974 | def _parseResourceDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the C{IMAGE_RESOURCE_DIRECTORY} directory.
@type rva: int
@param rva: The RVA where the C{IMAGE_RESOURCE_DIRECTORY} starts.
@type size: int
@param size: The size of the C{IMAG... | [
"def",
"_parseResourceDirectory",
"(",
"self",
",",
"rva",
",",
"size",
",",
"magic",
"=",
"consts",
".",
"PE32",
")",
":",
"return",
"self",
".",
"getDataAtRva",
"(",
"rva",
",",
"size",
")"
] | Parses the C{IMAGE_RESOURCE_DIRECTORY} directory.
@type rva: int
@param rva: The RVA where the C{IMAGE_RESOURCE_DIRECTORY} starts.
@type size: int
@param size: The size of the C{IMAGE_RESOURCE_DIRECTORY} directory.
@type magic: int
@param magic... | [
"Parses",
"the",
"C",
"{",
"IMAGE_RESOURCE_DIRECTORY",
"}",
"directory",
"."
] | python | train | 36.058824 |
evhub/coconut | coconut/compiler/compiler.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/compiler.py#L1771-L1786 | def await_item_handle(self, original, loc, tokens):
"""Check for Python 3.5 await expression."""
internal_assert(len(tokens) == 1, "invalid await statement tokens", tokens)
if not self.target:
self.make_err(
CoconutTargetError,
"await requires a specif... | [
"def",
"await_item_handle",
"(",
"self",
",",
"original",
",",
"loc",
",",
"tokens",
")",
":",
"internal_assert",
"(",
"len",
"(",
"tokens",
")",
"==",
"1",
",",
"\"invalid await statement tokens\"",
",",
"tokens",
")",
"if",
"not",
"self",
".",
"target",
... | Check for Python 3.5 await expression. | [
"Check",
"for",
"Python",
"3",
".",
"5",
"await",
"expression",
"."
] | python | train | 40.5625 |
priestc/moneywagon | moneywagon/bip38.py | https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/bip38.py#L372-L397 | def generate_address(self, passphrase):
"""
Make sure the confirm code is valid for the given password and address.
"""
inter = Bip38IntermediatePoint.create(passphrase, ownersalt=self.ownersalt)
public_key = privtopub(inter.passpoint)
# from Bip38EncryptedPrivateKey.c... | [
"def",
"generate_address",
"(",
"self",
",",
"passphrase",
")",
":",
"inter",
"=",
"Bip38IntermediatePoint",
".",
"create",
"(",
"passphrase",
",",
"ownersalt",
"=",
"self",
".",
"ownersalt",
")",
"public_key",
"=",
"privtopub",
"(",
"inter",
".",
"passpoint",... | Make sure the confirm code is valid for the given password and address. | [
"Make",
"sure",
"the",
"confirm",
"code",
"is",
"valid",
"for",
"the",
"given",
"password",
"and",
"address",
"."
] | python | train | 35.076923 |
ubc/ubcpi | ubcpi/answer_pool.py | https://github.com/ubc/ubcpi/blob/7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e/ubcpi/answer_pool.py#L91-L95 | def offer_random(pool, answer, rationale, student_id, options):
"""
The random selection algorithm. The same as simple algorithm
"""
offer_simple(pool, answer, rationale, student_id, options) | [
"def",
"offer_random",
"(",
"pool",
",",
"answer",
",",
"rationale",
",",
"student_id",
",",
"options",
")",
":",
"offer_simple",
"(",
"pool",
",",
"answer",
",",
"rationale",
",",
"student_id",
",",
"options",
")"
] | The random selection algorithm. The same as simple algorithm | [
"The",
"random",
"selection",
"algorithm",
".",
"The",
"same",
"as",
"simple",
"algorithm"
] | python | train | 40.6 |
talkincode/txradius | txradius/mschap/mppe.py | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/mschap/mppe.py#L96-L126 | def get_master_key(password_hash_hash, nt_response):
"""
GetMasterKey(
IN 16-octet PasswordHashHash,
IN 24-octet NTResponse,
OUT 16-octet MasterKey )
{
20-octet Digest
ZeroMemory(Digest, sizeof(Digest));
/*
* SHSInit(), SHSUpdate() and SHSFinal()
* are an implem... | [
"def",
"get_master_key",
"(",
"password_hash_hash",
",",
"nt_response",
")",
":",
"sha_hash",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"sha_hash",
".",
"update",
"(",
"password_hash_hash",
")",
"sha_hash",
".",
"update",
"(",
"nt_response",
")",
"sha_hash",
".",... | GetMasterKey(
IN 16-octet PasswordHashHash,
IN 24-octet NTResponse,
OUT 16-octet MasterKey )
{
20-octet Digest
ZeroMemory(Digest, sizeof(Digest));
/*
* SHSInit(), SHSUpdate() and SHSFinal()
* are an implementation of the Secure Hash Standard [7].
*/
SHSIn... | [
"GetMasterKey",
"(",
"IN",
"16",
"-",
"octet",
"PasswordHashHash",
"IN",
"24",
"-",
"octet",
"NTResponse",
"OUT",
"16",
"-",
"octet",
"MasterKey",
")",
"{",
"20",
"-",
"octet",
"Digest"
] | python | train | 24.129032 |
shapiromatron/bmds | bmds/models/base.py | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L316-L323 | def write_dfile(self):
"""
Write the generated d_file to a temporary file.
"""
f_in = self.tempfiles.get_tempfile(prefix="bmds-", suffix=".(d)")
with open(f_in, "w") as f:
f.write(self.as_dfile())
return f_in | [
"def",
"write_dfile",
"(",
"self",
")",
":",
"f_in",
"=",
"self",
".",
"tempfiles",
".",
"get_tempfile",
"(",
"prefix",
"=",
"\"bmds-\"",
",",
"suffix",
"=",
"\".(d)\"",
")",
"with",
"open",
"(",
"f_in",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
... | Write the generated d_file to a temporary file. | [
"Write",
"the",
"generated",
"d_file",
"to",
"a",
"temporary",
"file",
"."
] | python | train | 32.625 |
jupyter-widgets/jupyterlab-sidecar | setupbase.py | https://github.com/jupyter-widgets/jupyterlab-sidecar/blob/8889d09f1a0933e2cbee06d4874f720b075b29e8/setupbase.py#L89-L104 | def ensure_python(specs):
"""Given a list of range specifiers for python, ensure compatibility.
"""
if not isinstance(specs, (list, tuple)):
specs = [specs]
v = sys.version_info
part = '%s.%s' % (v.major, v.minor)
for spec in specs:
if part == spec:
return
try... | [
"def",
"ensure_python",
"(",
"specs",
")",
":",
"if",
"not",
"isinstance",
"(",
"specs",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"specs",
"=",
"[",
"specs",
"]",
"v",
"=",
"sys",
".",
"version_info",
"part",
"=",
"'%s.%s'",
"%",
"(",
"v",
... | Given a list of range specifiers for python, ensure compatibility. | [
"Given",
"a",
"list",
"of",
"range",
"specifiers",
"for",
"python",
"ensure",
"compatibility",
"."
] | python | test | 29.3125 |
bertrandvidal/parse_this | parse_this/__init__.py | https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/__init__.py#L159-L187 | def _set_class_parser(self, init_parser, methods_to_parse, cls):
"""Creates the complete argument parser for the decorated class.
Args:
init_parser: argument parser for the __init__ method or None
methods_to_parse: dict of method name pointing to their associated
arg... | [
"def",
"_set_class_parser",
"(",
"self",
",",
"init_parser",
",",
"methods_to_parse",
",",
"cls",
")",
":",
"top_level_parents",
"=",
"[",
"init_parser",
"]",
"if",
"init_parser",
"else",
"[",
"]",
"description",
"=",
"self",
".",
"_description",
"or",
"cls",
... | Creates the complete argument parser for the decorated class.
Args:
init_parser: argument parser for the __init__ method or None
methods_to_parse: dict of method name pointing to their associated
argument parser
cls: the class we are decorating
Returns:
... | [
"Creates",
"the",
"complete",
"argument",
"parser",
"for",
"the",
"decorated",
"class",
"."
] | python | train | 52 |
ethpm/py-ethpm | ethpm/tools/builder.py | https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/tools/builder.py#L134-L142 | def get_names_and_paths(compiler_output: Dict[str, Any]) -> Dict[str, str]:
"""
Return a mapping of contract name to relative path as defined in compiler output.
"""
return {
contract_name: make_path_relative(path)
for path in compiler_output
for contract_name in compiler_output[... | [
"def",
"get_names_and_paths",
"(",
"compiler_output",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"return",
"{",
"contract_name",
":",
"make_path_relative",
"(",
"path",
")",
"for",
"path",
"in",
"compil... | Return a mapping of contract name to relative path as defined in compiler output. | [
"Return",
"a",
"mapping",
"of",
"contract",
"name",
"to",
"relative",
"path",
"as",
"defined",
"in",
"compiler",
"output",
"."
] | python | train | 36.666667 |
onicagroup/runway | runway/templates/stacker/tfstate_blueprints/tf_state.py | https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/templates/stacker/tfstate_blueprints/tf_state.py#L29-L150 | def create_template(self):
"""Create template (main function called by Stacker)."""
template = self.template
variables = self.get_variables()
self.template.add_version('2010-09-09')
self.template.add_description('Terraform State Resources')
# Conditions
for i in ... | [
"def",
"create_template",
"(",
"self",
")",
":",
"template",
"=",
"self",
".",
"template",
"variables",
"=",
"self",
".",
"get_variables",
"(",
")",
"self",
".",
"template",
".",
"add_version",
"(",
"'2010-09-09'",
")",
"self",
".",
"template",
".",
"add_d... | Create template (main function called by Stacker). | [
"Create",
"template",
"(",
"main",
"function",
"called",
"by",
"Stacker",
")",
"."
] | python | train | 36.647541 |
PyGithub/PyGithub | github/Repository.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/Repository.py#L1339-L1349 | def get_assignees(self):
"""
:calls: `GET /repos/:owner/:repo/assignees <http://developer.github.com/v3/issues/assignees>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
return github.PaginatedList.PaginatedList(
github... | [
"def",
"get_assignees",
"(",
"self",
")",
":",
"return",
"github",
".",
"PaginatedList",
".",
"PaginatedList",
"(",
"github",
".",
"NamedUser",
".",
"NamedUser",
",",
"self",
".",
"_requester",
",",
"self",
".",
"url",
"+",
"\"/assignees\"",
",",
"None",
"... | :calls: `GET /repos/:owner/:repo/assignees <http://developer.github.com/v3/issues/assignees>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` | [
":",
"calls",
":",
"GET",
"/",
"repos",
"/",
":",
"owner",
"/",
":",
"repo",
"/",
"assignees",
"<http",
":",
"//",
"developer",
".",
"github",
".",
"com",
"/",
"v3",
"/",
"issues",
"/",
"assignees",
">",
"_",
":",
"rtype",
":",
":",
"class",
":",... | python | train | 38.545455 |
learningequality/ricecooker | ricecooker/utils/pdf.py | https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/pdf.py#L139-L152 | def write_pagerange(self, pagerange, prefix=''):
"""
Save the subset of pages specified in `pagerange` (dict) as separate PDF.
e.g. pagerange = {'title':'First chapter', 'page_start':0, 'page_end':5}
"""
writer = PdfFileWriter()
slug = "".join([c for c in pagerange['title... | [
"def",
"write_pagerange",
"(",
"self",
",",
"pagerange",
",",
"prefix",
"=",
"''",
")",
":",
"writer",
"=",
"PdfFileWriter",
"(",
")",
"slug",
"=",
"\"\"",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"pagerange",
"[",
"'title'",
"]",
".",
"replace"... | Save the subset of pages specified in `pagerange` (dict) as separate PDF.
e.g. pagerange = {'title':'First chapter', 'page_start':0, 'page_end':5} | [
"Save",
"the",
"subset",
"of",
"pages",
"specified",
"in",
"pagerange",
"(",
"dict",
")",
"as",
"separate",
"PDF",
".",
"e",
".",
"g",
".",
"pagerange",
"=",
"{",
"title",
":",
"First",
"chapter",
"page_start",
":",
"0",
"page_end",
":",
"5",
"}"
] | python | train | 54.642857 |
Iotic-Labs/py-IoticAgent | src/IoticAgent/IOT/Client.py | https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L285-L311 | def register_catchall_controlreq(self, callback, callback_parsed=None):
"""
Registers a callback that is called for all control requests received by your Thing
`Example`
#!python
def controlreq_callback(data):
print(data)
...
clie... | [
"def",
"register_catchall_controlreq",
"(",
"self",
",",
"callback",
",",
"callback_parsed",
"=",
"None",
")",
":",
"if",
"callback_parsed",
":",
"callback",
"=",
"self",
".",
"_get_parsed_control_callback",
"(",
"callback_parsed",
",",
"callback",
")",
"return",
... | Registers a callback that is called for all control requests received by your Thing
`Example`
#!python
def controlreq_callback(data):
print(data)
...
client.register_catchall_controlreq(controlreq_callback)
`callback` (required) the func... | [
"Registers",
"a",
"callback",
"that",
"is",
"called",
"for",
"all",
"control",
"requests",
"received",
"by",
"your",
"Thing"
] | python | train | 50.481481 |
Nukesor/pueue | pueue/daemon/logger.py | https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/logger.py#L72-L75 | def rotate(self, log):
"""Move the current log to a new file with timestamp and create a new empty log file."""
self.write(log, rotate=True)
self.write({}) | [
"def",
"rotate",
"(",
"self",
",",
"log",
")",
":",
"self",
".",
"write",
"(",
"log",
",",
"rotate",
"=",
"True",
")",
"self",
".",
"write",
"(",
"{",
"}",
")"
] | Move the current log to a new file with timestamp and create a new empty log file. | [
"Move",
"the",
"current",
"log",
"to",
"a",
"new",
"file",
"with",
"timestamp",
"and",
"create",
"a",
"new",
"empty",
"log",
"file",
"."
] | python | train | 44 |
Erotemic/ubelt | ubelt/util_dict.py | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_dict.py#L256-L314 | def find_duplicates(items, k=2, key=None):
"""
Find all duplicate items in a list.
Search for all items that appear more than `k` times and return a mapping
from each (k)-duplicate item to the positions it appeared in.
Args:
items (Iterable): hashable items possibly containing duplicates
... | [
"def",
"find_duplicates",
"(",
"items",
",",
"k",
"=",
"2",
",",
"key",
"=",
"None",
")",
":",
"# Build mapping from items to the indices at which they appear",
"# if key is not None:",
"# items = map(key, items)",
"duplicates",
"=",
"defaultdict",
"(",
"list",
")",
... | Find all duplicate items in a list.
Search for all items that appear more than `k` times and return a mapping
from each (k)-duplicate item to the positions it appeared in.
Args:
items (Iterable): hashable items possibly containing duplicates
k (int): only return items that appear at least ... | [
"Find",
"all",
"duplicate",
"items",
"in",
"a",
"list",
"."
] | python | valid | 36.40678 |
google/grr | grr/server/grr_response_server/queue_manager.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L152-L163 | def Copy(self):
"""Return a copy of the queue manager.
Returns:
Copy of the QueueManager object.
NOTE: pending writes/deletions are not copied. On the other hand, if the
original object has a frozen timestamp, a copy will have it as well.
"""
result = QueueManager(store=self.data_store, tok... | [
"def",
"Copy",
"(",
"self",
")",
":",
"result",
"=",
"QueueManager",
"(",
"store",
"=",
"self",
".",
"data_store",
",",
"token",
"=",
"self",
".",
"token",
")",
"result",
".",
"prev_frozen_timestamps",
"=",
"self",
".",
"prev_frozen_timestamps",
"result",
... | Return a copy of the queue manager.
Returns:
Copy of the QueueManager object.
NOTE: pending writes/deletions are not copied. On the other hand, if the
original object has a frozen timestamp, a copy will have it as well. | [
"Return",
"a",
"copy",
"of",
"the",
"queue",
"manager",
"."
] | python | train | 38.083333 |
elapouya/python-textops | textops/base.py | https://github.com/elapouya/python-textops/blob/5c63b9074a1acd8dd108725f1b370f6684c941ef/textops/base.py#L444-L446 | def op(cls,text,*args,**kwargs):
""" This method must be overriden in derived classes """
return cls.fn(text,*args,**kwargs) | [
"def",
"op",
"(",
"cls",
",",
"text",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"fn",
"(",
"text",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This method must be overriden in derived classes | [
"This",
"method",
"must",
"be",
"overriden",
"in",
"derived",
"classes"
] | python | train | 46 |
UCL-INGI/INGInious | inginious/client/_zeromq_client.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/_zeromq_client.py#L81-L99 | async def _create_transaction(self, msg, *args, **kwargs):
"""
Create a transaction with the distant server
:param msg: message to be sent
:param args: args to be sent to the coroutines given to `register_transaction`
:param kwargs: kwargs to be sent to the coroutines given to `r... | [
"async",
"def",
"_create_transaction",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"recv_msgs",
",",
"get_key",
",",
"_1",
",",
"_2",
",",
"_3",
"=",
"self",
".",
"_msgs_registered",
"[",
"msg",
".",
"__msgtype__",
"... | Create a transaction with the distant server
:param msg: message to be sent
:param args: args to be sent to the coroutines given to `register_transaction`
:param kwargs: kwargs to be sent to the coroutines given to `register_transaction` | [
"Create",
"a",
"transaction",
"with",
"the",
"distant",
"server",
":",
"param",
"msg",
":",
"message",
"to",
"be",
"sent",
":",
"param",
"args",
":",
"args",
"to",
"be",
"sent",
"to",
"the",
"coroutines",
"given",
"to",
"register_transaction",
":",
"param"... | python | train | 51 |
tensorflow/cleverhans | scripts/compute_accuracy.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/compute_accuracy.py#L53-L98 | def print_accuracies(filepath, train_start=TRAIN_START, train_end=TRAIN_END,
test_start=TEST_START, test_end=TEST_END,
batch_size=BATCH_SIZE, which_set=WHICH_SET,
base_eps_iter=BASE_EPS_ITER,
nb_iter=NB_ITER):
"""
Load a saved model... | [
"def",
"print_accuracies",
"(",
"filepath",
",",
"train_start",
"=",
"TRAIN_START",
",",
"train_end",
"=",
"TRAIN_END",
",",
"test_start",
"=",
"TEST_START",
",",
"test_end",
"=",
"TEST_END",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"which_set",
"=",
"WHICH_SE... | Load a saved model and print out its accuracy on different data distributions
This function works by running a single attack on each example.
This provides a reasonable estimate of the true failure rate quickly, so
long as the model does not suffer from gradient masking.
However, this estimate is mostly intend... | [
"Load",
"a",
"saved",
"model",
"and",
"print",
"out",
"its",
"accuracy",
"on",
"different",
"data",
"distributions"
] | python | train | 40.521739 |
Azure/azure-event-hubs-python | azure/eventprocessorhost/azure_blob_lease.py | https://github.com/Azure/azure-event-hubs-python/blob/737c5f966557ada2cf10fa0d8f3c19671ae96348/azure/eventprocessorhost/azure_blob_lease.py#L40-L51 | def with_blob(self, blob):
"""
Init Azure Blob Lease with existing blob.
"""
content = json.loads(blob.content)
self.partition_id = content["partition_id"]
self.owner = content["owner"]
self.token = content["token"]
self.epoch = content["epoch"]
se... | [
"def",
"with_blob",
"(",
"self",
",",
"blob",
")",
":",
"content",
"=",
"json",
".",
"loads",
"(",
"blob",
".",
"content",
")",
"self",
".",
"partition_id",
"=",
"content",
"[",
"\"partition_id\"",
"]",
"self",
".",
"owner",
"=",
"content",
"[",
"\"own... | Init Azure Blob Lease with existing blob. | [
"Init",
"Azure",
"Blob",
"Lease",
"with",
"existing",
"blob",
"."
] | python | train | 39.5 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_validate.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L140-L158 | def check_import_stdlib(module):
"""Check if module is in Python stdlib.
Args:
module (str): The name of the module to check.
Returns:
bool: Returns True if the module is in the stdlib or template.
"""
if (
module in stdlib_list('2.7') # pyl... | [
"def",
"check_import_stdlib",
"(",
"module",
")",
":",
"if",
"(",
"module",
"in",
"stdlib_list",
"(",
"'2.7'",
")",
"# pylint: disable=R0916",
"or",
"module",
"in",
"stdlib_list",
"(",
"'3.4'",
")",
"or",
"module",
"in",
"stdlib_list",
"(",
"'3.5'",
")",
"or... | Check if module is in Python stdlib.
Args:
module (str): The name of the module to check.
Returns:
bool: Returns True if the module is in the stdlib or template. | [
"Check",
"if",
"module",
"is",
"in",
"Python",
"stdlib",
"."
] | python | train | 32.052632 |
onecodex/onecodex | onecodex/lib/upload.py | https://github.com/onecodex/onecodex/blob/326a0a1af140e3a57ccf31c3c9c5e17a5775c13d/onecodex/lib/upload.py#L730-L779 | def upload_document_fileobj(file_obj, file_name, session, documents_resource, log=None):
"""Uploads a single file-like object to the One Codex server directly to S3.
Parameters
----------
file_obj : `FilePassthru`, or a file-like object
If a file-like object is given, its mime-type will be sent... | [
"def",
"upload_document_fileobj",
"(",
"file_obj",
",",
"file_name",
",",
"session",
",",
"documents_resource",
",",
"log",
"=",
"None",
")",
":",
"try",
":",
"fields",
"=",
"documents_resource",
".",
"init_multipart_upload",
"(",
")",
"except",
"requests",
".",... | Uploads a single file-like object to the One Codex server directly to S3.
Parameters
----------
file_obj : `FilePassthru`, or a file-like object
If a file-like object is given, its mime-type will be sent as 'text/plain'. Otherwise,
`FilePassthru` will send a compressed type if the file is g... | [
"Uploads",
"a",
"single",
"file",
"-",
"like",
"object",
"to",
"the",
"One",
"Codex",
"server",
"directly",
"to",
"S3",
"."
] | python | train | 36.82 |
Unidata/MetPy | metpy/units.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/units.py#L163-L189 | def atleast_1d(*arrs):
r"""Convert inputs to arrays with at least one dimension.
Scalars are converted to 1-dimensional arrays, whilst other
higher-dimensional inputs are preserved. This is a thin wrapper
around `numpy.atleast_1d` to preserve units.
Parameters
----------
arrs : arbitrary p... | [
"def",
"atleast_1d",
"(",
"*",
"arrs",
")",
":",
"mags",
"=",
"[",
"a",
".",
"magnitude",
"if",
"hasattr",
"(",
"a",
",",
"'magnitude'",
")",
"else",
"a",
"for",
"a",
"in",
"arrs",
"]",
"orig_units",
"=",
"[",
"a",
".",
"units",
"if",
"hasattr",
... | r"""Convert inputs to arrays with at least one dimension.
Scalars are converted to 1-dimensional arrays, whilst other
higher-dimensional inputs are preserved. This is a thin wrapper
around `numpy.atleast_1d` to preserve units.
Parameters
----------
arrs : arbitrary positional arguments
... | [
"r",
"Convert",
"inputs",
"to",
"arrays",
"with",
"at",
"least",
"one",
"dimension",
"."
] | python | train | 34.074074 |
CivicSpleen/ambry | ambry/orm/partition.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L923-L985 | def dataframe(self, predicate=None, filtered_columns=None, columns=None, df_class=None):
"""Return the partition as a Pandas dataframe
:param predicate: If defined, a callable that is called for each row, and if it returns true, the
row is included in the output.
:param filtered_column... | [
"def",
"dataframe",
"(",
"self",
",",
"predicate",
"=",
"None",
",",
"filtered_columns",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"df_class",
"=",
"None",
")",
":",
"from",
"operator",
"import",
"itemgetter",
"from",
"ambry",
".",
"pands",
"import",
... | Return the partition as a Pandas dataframe
:param predicate: If defined, a callable that is called for each row, and if it returns true, the
row is included in the output.
:param filtered_columns: If defined, the value is a dict of column names and
associated values. Only rows where al... | [
"Return",
"the",
"partition",
"as",
"a",
"Pandas",
"dataframe"
] | python | train | 32.365079 |
tgalal/python-axolotl | axolotl/ecc/curve.py | https://github.com/tgalal/python-axolotl/blob/0c681af4b756f556e23a9bf961abfbc6f82800cc/axolotl/ecc/curve.py#L67-L78 | def verifySignature(ecPublicSigningKey, message, signature):
"""
:type ecPublicSigningKey: ECPublicKey
:type message: bytearray
:type signature: bytearray
"""
if ecPublicSigningKey.getType() == Curve.DJB_TYPE:
result = _curve.verifySignature(ecPublicSigningKe... | [
"def",
"verifySignature",
"(",
"ecPublicSigningKey",
",",
"message",
",",
"signature",
")",
":",
"if",
"ecPublicSigningKey",
".",
"getType",
"(",
")",
"==",
"Curve",
".",
"DJB_TYPE",
":",
"result",
"=",
"_curve",
".",
"verifySignature",
"(",
"ecPublicSigningKey"... | :type ecPublicSigningKey: ECPublicKey
:type message: bytearray
:type signature: bytearray | [
":",
"type",
"ecPublicSigningKey",
":",
"ECPublicKey",
":",
"type",
"message",
":",
"bytearray",
":",
"type",
"signature",
":",
"bytearray"
] | python | train | 40 |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAFetch/QATdx.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1030-L1036 | def QA_fetch_get_stock_info(code, ip=None, port=None):
'股票基本信息'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
market_code = _select_market_code(code)
with api.connect(ip, port):
return api.to_df(api.get_finance_info(market_code, code)) | [
"def",
"QA_fetch_get_stock_info",
"(",
"code",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_mainmarket_ip",
"(",
"ip",
",",
"port",
")",
"api",
"=",
"TdxHq_API",
"(",
")",
"market_code",
"=",
"_select_market_co... | 股票基本信息 | [
"股票基本信息"
] | python | train | 38.285714 |
OpenKMIP/PyKMIP | kmip/pie/client.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/pie/client.py#L135-L155 | def kmip_version(self, value):
"""
Set the KMIP version for the client.
Args:
value (KMIPVersion): A KMIPVersion enumeration
Return:
None
Raises:
ValueError: if value is not a KMIPVersion enumeration
Example:
>>> client.... | [
"def",
"kmip_version",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"enums",
".",
"KMIPVersion",
")",
":",
"self",
".",
"proxy",
".",
"kmip_version",
"=",
"value",
"else",
":",
"raise",
"ValueError",
"(",
"\"KMIP version must... | Set the KMIP version for the client.
Args:
value (KMIPVersion): A KMIPVersion enumeration
Return:
None
Raises:
ValueError: if value is not a KMIPVersion enumeration
Example:
>>> client.kmip_version = enums.KMIPVersion.KMIP_1_1
... | [
"Set",
"the",
"KMIP",
"version",
"for",
"the",
"client",
"."
] | python | test | 26.428571 |
StackStorm/pybind | pybind/slxos/v17s_1_02/mgmt_cluster/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/mgmt_cluster/__init__.py#L95-L116 | def _set_cluster(self, v, load=False):
"""
Setter method for cluster, mapped from YANG variable /mgmt_cluster/cluster (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cluster is considered as a private
method. Backends looking to populate this variable sho... | [
"def",
"_set_cluster",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",... | Setter method for cluster, mapped from YANG variable /mgmt_cluster/cluster (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cluster is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_cluster() di... | [
"Setter",
"method",
"for",
"cluster",
"mapped",
"from",
"YANG",
"variable",
"/",
"mgmt_cluster",
"/",
"cluster",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
... | python | train | 75 |
IRC-SPHERE/HyperStream | hyperstream/stream/stream.py | https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/stream/stream.py#L154-L180 | def window(self, time_interval=None, force_calculation=False):
"""
Gets a view on this stream for the time interval given
:param time_interval: either a TimeInterval object or (start, end) tuple of type str or datetime
:param force_calculation: Whether we should force calculation for th... | [
"def",
"window",
"(",
"self",
",",
"time_interval",
"=",
"None",
",",
"force_calculation",
"=",
"False",
")",
":",
"if",
"not",
"time_interval",
":",
"if",
"self",
".",
"calculated_intervals",
":",
"time_interval",
"=",
"self",
".",
"calculated_intervals",
"["... | Gets a view on this stream for the time interval given
:param time_interval: either a TimeInterval object or (start, end) tuple of type str or datetime
:param force_calculation: Whether we should force calculation for this stream view if data does not exist
:type time_interval: None | Iterable ... | [
"Gets",
"a",
"view",
"on",
"this",
"stream",
"for",
"the",
"time",
"interval",
"given"
] | python | train | 54.518519 |
n1analytics/python-paillier | phe/paillier.py | https://github.com/n1analytics/python-paillier/blob/955f8c0bfa9623be15b75462b121d28acf70f04b/phe/paillier.py#L415-L432 | def decrypt(self, encrypted_number):
"""Return the decrypted & decoded plaintext of *encrypted_number*.
Args:
encrypted_number (EncryptedNumber): encrypted against a known public
key, i.e., one for which the private key is on this keyring.
Returns:
the int or fl... | [
"def",
"decrypt",
"(",
"self",
",",
"encrypted_number",
")",
":",
"relevant_private_key",
"=",
"self",
".",
"__keyring",
"[",
"encrypted_number",
".",
"public_key",
"]",
"return",
"relevant_private_key",
".",
"decrypt",
"(",
"encrypted_number",
")"
] | Return the decrypted & decoded plaintext of *encrypted_number*.
Args:
encrypted_number (EncryptedNumber): encrypted against a known public
key, i.e., one for which the private key is on this keyring.
Returns:
the int or float that *encrypted_number* was holding. N.B. if... | [
"Return",
"the",
"decrypted",
"&",
"decoded",
"plaintext",
"of",
"*",
"encrypted_number",
"*",
"."
] | python | train | 39.611111 |
xflr6/gsheets | gsheets/api.py | https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/api.py#L127-L138 | def findall(self, title=None):
"""Fetch and return a list of spreadsheets with the given title.
Args:
title(str): title/name of the spreadsheets to return, or ``None`` for all
Returns:
list: list of new SpreadSheet instances (possibly empty)
"""
if title ... | [
"def",
"findall",
"(",
"self",
",",
"title",
"=",
"None",
")",
":",
"if",
"title",
"is",
"None",
":",
"return",
"list",
"(",
"self",
")",
"files",
"=",
"backend",
".",
"iterfiles",
"(",
"self",
".",
"_drive",
",",
"name",
"=",
"title",
")",
"return... | Fetch and return a list of spreadsheets with the given title.
Args:
title(str): title/name of the spreadsheets to return, or ``None`` for all
Returns:
list: list of new SpreadSheet instances (possibly empty) | [
"Fetch",
"and",
"return",
"a",
"list",
"of",
"spreadsheets",
"with",
"the",
"given",
"title",
"."
] | python | train | 37.583333 |
sassoo/goldman | goldman/utils/responder_helpers.py | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L41-L52 | def find(model, rid):
""" Find a model from the store by resource id """
validate_rid(model, rid)
rid_field = model.rid_field
model = goldman.sess.store.find(model.RTYPE, rid_field, rid)
if not model:
abort(exceptions.DocumentNotFound)
return model | [
"def",
"find",
"(",
"model",
",",
"rid",
")",
":",
"validate_rid",
"(",
"model",
",",
"rid",
")",
"rid_field",
"=",
"model",
".",
"rid_field",
"model",
"=",
"goldman",
".",
"sess",
".",
"store",
".",
"find",
"(",
"model",
".",
"RTYPE",
",",
"rid_fiel... | Find a model from the store by resource id | [
"Find",
"a",
"model",
"from",
"the",
"store",
"by",
"resource",
"id"
] | python | train | 22.75 |
square/pylink | pylink/util.py | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/util.py#L86-L133 | def progress_bar(iteration,
total,
prefix=None,
suffix=None,
decs=1,
length=100):
"""Creates a console progress bar.
This should be called in a loop to create a progress bar.
See `StackOverflow <http://stackoverflow.com/q... | [
"def",
"progress_bar",
"(",
"iteration",
",",
"total",
",",
"prefix",
"=",
"None",
",",
"suffix",
"=",
"None",
",",
"decs",
"=",
"1",
",",
"length",
"=",
"100",
")",
":",
"if",
"prefix",
"is",
"None",
":",
"prefix",
"=",
"''",
"if",
"suffix",
"is",... | Creates a console progress bar.
This should be called in a loop to create a progress bar.
See `StackOverflow <http://stackoverflow.com/questions/3173320/>`__.
Args:
iteration (int): current iteration
total (int): total iterations
prefix (str): prefix string
suffix (str): suffix st... | [
"Creates",
"a",
"console",
"progress",
"bar",
"."
] | python | train | 26.979167 |
gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L472-L477 | def has_pfn(self, url, site=None):
""" Wrapper of the pegasus hasPFN function, that allows it to be called
outside of specific pegasus functions.
"""
curr_pfn = dax.PFN(url, site)
return self.hasPFN(curr_pfn) | [
"def",
"has_pfn",
"(",
"self",
",",
"url",
",",
"site",
"=",
"None",
")",
":",
"curr_pfn",
"=",
"dax",
".",
"PFN",
"(",
"url",
",",
"site",
")",
"return",
"self",
".",
"hasPFN",
"(",
"curr_pfn",
")"
] | Wrapper of the pegasus hasPFN function, that allows it to be called
outside of specific pegasus functions. | [
"Wrapper",
"of",
"the",
"pegasus",
"hasPFN",
"function",
"that",
"allows",
"it",
"to",
"be",
"called",
"outside",
"of",
"specific",
"pegasus",
"functions",
"."
] | python | train | 40.5 |
TyVik/YaDiskClient | YaDiskClient/YaDiskClient.py | https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L163-L171 | def download(self, path, file):
"""Download remote file to disk."""
resp = self._sendRequest("GET", path)
if resp.status_code == 200:
with open(file, "wb") as f:
f.write(resp.content)
else:
raise YaDiskException(resp.status_code, resp.content) | [
"def",
"download",
"(",
"self",
",",
"path",
",",
"file",
")",
":",
"resp",
"=",
"self",
".",
"_sendRequest",
"(",
"\"GET\"",
",",
"path",
")",
"if",
"resp",
".",
"status_code",
"==",
"200",
":",
"with",
"open",
"(",
"file",
",",
"\"wb\"",
")",
"as... | Download remote file to disk. | [
"Download",
"remote",
"file",
"to",
"disk",
"."
] | python | train | 34.222222 |
MatterMiners/cobald | cobald/daemon/runners/service.py | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/runners/service.py#L54-L82 | def service(flavour):
r"""
Mark a class as implementing a Service
Each Service class must have a ``run`` method, which does not take any arguments.
This method is :py:meth:`~.ServiceRunner.adopt`\ ed after the daemon starts, unless
* the Service has been garbage collected, or
* the ServiceUnit... | [
"def",
"service",
"(",
"flavour",
")",
":",
"def",
"service_unit_decorator",
"(",
"raw_cls",
")",
":",
"__new__",
"=",
"raw_cls",
".",
"__new__",
"def",
"__new_service__",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"__new__",
... | r"""
Mark a class as implementing a Service
Each Service class must have a ``run`` method, which does not take any arguments.
This method is :py:meth:`~.ServiceRunner.adopt`\ ed after the daemon starts, unless
* the Service has been garbage collected, or
* the ServiceUnit has been :py:meth:`~.Serv... | [
"r",
"Mark",
"a",
"class",
"as",
"implementing",
"a",
"Service"
] | python | train | 36.62069 |
riquito/richinput | richinput/terminfo.py | https://github.com/riquito/richinput/blob/858c6068d80377148b89dcf9107f4e46a2b464d4/richinput/terminfo.py#L116-L232 | def load_terminfo(terminal_name=None, fallback='vt100'):
"""
If the environment variable TERM is unset try with `fallback` if not empty.
vt100 is a popular terminal supporting ANSI X3.64.
"""
terminal_name = os.getenv('TERM')
if not terminal_name:
if not fallback:
raise Term... | [
"def",
"load_terminfo",
"(",
"terminal_name",
"=",
"None",
",",
"fallback",
"=",
"'vt100'",
")",
":",
"terminal_name",
"=",
"os",
".",
"getenv",
"(",
"'TERM'",
")",
"if",
"not",
"terminal_name",
":",
"if",
"not",
"fallback",
":",
"raise",
"TerminfoError",
... | If the environment variable TERM is unset try with `fallback` if not empty.
vt100 is a popular terminal supporting ANSI X3.64. | [
"If",
"the",
"environment",
"variable",
"TERM",
"is",
"unset",
"try",
"with",
"fallback",
"if",
"not",
"empty",
".",
"vt100",
"is",
"a",
"popular",
"terminal",
"supporting",
"ANSI",
"X3",
".",
"64",
"."
] | python | train | 36.495726 |
odlgroup/odl | odl/contrib/mrc/mrc.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/mrc/mrc.py#L209-L225 | def header_size(self):
"""Total size of `file`'s header (including extended) in bytes.
The size of the header is determined from `header`. If this is not
possible (i.e., before the header has been read), 0 is returned.
If the header contains an ``'nsymbt'`` entry (size of the extra
... | [
"def",
"header_size",
"(",
"self",
")",
":",
"standard_header_size",
"=",
"MRC_HEADER_SIZE",
"try",
":",
"extra_header_size",
"=",
"int",
"(",
"self",
".",
"header",
"[",
"'nsymbt'",
"]",
"[",
"'value'",
"]",
")",
"except",
"KeyError",
":",
"extra_header_size"... | Total size of `file`'s header (including extended) in bytes.
The size of the header is determined from `header`. If this is not
possible (i.e., before the header has been read), 0 is returned.
If the header contains an ``'nsymbt'`` entry (size of the extra
header in bytes), its value i... | [
"Total",
"size",
"of",
"file",
"s",
"header",
"(",
"including",
"extended",
")",
"in",
"bytes",
"."
] | python | train | 37.058824 |
doloopwhile/PyExecJS | execjs/_external_runtime.py | https://github.com/doloopwhile/PyExecJS/blob/e300f0a8120c0b7b70eed0758c3c85a9bd1a7b9f/execjs/_external_runtime.py#L198-L214 | def _which(command):
"""protected"""
if isinstance(command, str):
command = [command]
command = list(command)
name = command[0]
args = command[1:]
if _is_windows():
pathext = _decode_if_not_text(os.environ.get("PATHEXT", ""))
path = _find_executable(name, pathext.split(o... | [
"def",
"_which",
"(",
"command",
")",
":",
"if",
"isinstance",
"(",
"command",
",",
"str",
")",
":",
"command",
"=",
"[",
"command",
"]",
"command",
"=",
"list",
"(",
"command",
")",
"name",
"=",
"command",
"[",
"0",
"]",
"args",
"=",
"command",
"[... | protected | [
"protected"
] | python | train | 25.058824 |
inveniosoftware/invenio-accounts | invenio_accounts/hash.py | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L31-L36 | def _to_string(val):
"""Convert to text."""
if isinstance(val, binary_type):
return val.decode('utf-8')
assert isinstance(val, text_type)
return val | [
"def",
"_to_string",
"(",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"binary_type",
")",
":",
"return",
"val",
".",
"decode",
"(",
"'utf-8'",
")",
"assert",
"isinstance",
"(",
"val",
",",
"text_type",
")",
"return",
"val"
] | Convert to text. | [
"Convert",
"to",
"text",
"."
] | python | train | 27.833333 |
google/mobly | mobly/controllers/android_device.py | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device.py#L775-L783 | def root_adb(self):
"""Change adb to root mode for this device if allowed.
If executed on a production build, adb will not be switched to root
mode per security restrictions.
"""
self.adb.root()
self.adb.wait_for_device(
timeout=DEFAULT_TIMEOUT_BOOT_COMPLETIO... | [
"def",
"root_adb",
"(",
"self",
")",
":",
"self",
".",
"adb",
".",
"root",
"(",
")",
"self",
".",
"adb",
".",
"wait_for_device",
"(",
"timeout",
"=",
"DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND",
")"
] | Change adb to root mode for this device if allowed.
If executed on a production build, adb will not be switched to root
mode per security restrictions. | [
"Change",
"adb",
"to",
"root",
"mode",
"for",
"this",
"device",
"if",
"allowed",
"."
] | python | train | 35.666667 |
manns/pyspread | pyspread/src/lib/vlc.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L4602-L4610 | def libvlc_media_list_new(p_instance):
'''Create an empty media list.
@param p_instance: libvlc instance.
@return: empty media list, or NULL on error.
'''
f = _Cfunctions.get('libvlc_media_list_new', None) or \
_Cfunction('libvlc_media_list_new', ((1,),), class_result(MediaList),
... | [
"def",
"libvlc_media_list_new",
"(",
"p_instance",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_list_new'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_list_new'",
",",
"(",
"(",
"1",
",",
")",
",",
")",
",",
"class_result... | Create an empty media list.
@param p_instance: libvlc instance.
@return: empty media list, or NULL on error. | [
"Create",
"an",
"empty",
"media",
"list",
"."
] | python | train | 41.333333 |
estnltk/estnltk | estnltk/wordnet_tagger.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/wordnet_tagger.py#L22-L67 | def tag_text(self, text, **kwargs):
"""Annotates `analysis` entries in `corpus` with a list of lemmas` synsets and queried WordNet data in a 'wordnet' entry.
Note
----
Annotates every `analysis` entry with a `wordnet`:{`synsets`:[..]}.
Parameters
----------
te... | [
"def",
"tag_text",
"(",
"self",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"analysis_match",
"in",
"text",
".",
"analysis",
":",
"for",
"candidate",
"in",
"analysis_match",
":",
"if",
"candidate",
"[",
"'partofspeech'",
"]",
"in",
"PYVABAMORF_T... | Annotates `analysis` entries in `corpus` with a list of lemmas` synsets and queried WordNet data in a 'wordnet' entry.
Note
----
Annotates every `analysis` entry with a `wordnet`:{`synsets`:[..]}.
Parameters
----------
text: estnltk.text.Text
Representation ... | [
"Annotates",
"analysis",
"entries",
"in",
"corpus",
"with",
"a",
"list",
"of",
"lemmas",
"synsets",
"and",
"queried",
"WordNet",
"data",
"in",
"a",
"wordnet",
"entry",
"."
] | python | train | 61.152174 |
JawboneHealth/jhhalchemy | jhhalchemy/model/__init__.py | https://github.com/JawboneHealth/jhhalchemy/blob/ca0011d644e404561a142c9d7f0a8a569f1f4f27/jhhalchemy/model/__init__.py#L45-L55 | def read_by(cls, removed=False, **kwargs):
"""
filter_by query helper that handles soft delete logic. If your query conditions require expressions, use read.
:param removed: whether to include soft-deleted rows
:param kwargs: where clause mappings to pass to filter_by
:return: r... | [
"def",
"read_by",
"(",
"cls",
",",
"removed",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"removed",
":",
"kwargs",
"[",
"'time_removed'",
"]",
"=",
"0",
"return",
"cls",
".",
"query",
".",
"filter_by",
"(",
"*",
"*",
"kwargs",
")... | filter_by query helper that handles soft delete logic. If your query conditions require expressions, use read.
:param removed: whether to include soft-deleted rows
:param kwargs: where clause mappings to pass to filter_by
:return: row object generator | [
"filter_by",
"query",
"helper",
"that",
"handles",
"soft",
"delete",
"logic",
".",
"If",
"your",
"query",
"conditions",
"require",
"expressions",
"use",
"read",
"."
] | python | train | 40.818182 |
Vauxoo/cfdilib | cfdilib/cfdicli.py | https://github.com/Vauxoo/cfdilib/blob/acd73d159f62119f3100d963a061820bbe3f93ea/cfdilib/cfdicli.py#L26-L35 | def cli(config, in_file, out_file, verbose):
"""Main Interface to generate xml documents
from custom dictionaries using legal xsd files
complying with legal documents in all countires
around the world.
"""
config.out_file = out_file
config.verbose = verbose
config.in_file = in_file
c... | [
"def",
"cli",
"(",
"config",
",",
"in_file",
",",
"out_file",
",",
"verbose",
")",
":",
"config",
".",
"out_file",
"=",
"out_file",
"config",
".",
"verbose",
"=",
"verbose",
"config",
".",
"in_file",
"=",
"in_file",
"config",
".",
"out_file",
"=",
"out_f... | Main Interface to generate xml documents
from custom dictionaries using legal xsd files
complying with legal documents in all countires
around the world. | [
"Main",
"Interface",
"to",
"generate",
"xml",
"documents",
"from",
"custom",
"dictionaries",
"using",
"legal",
"xsd",
"files",
"complying",
"with",
"legal",
"documents",
"in",
"all",
"countires",
"around",
"the",
"world",
"."
] | python | train | 33.6 |
saltstack/salt | salt/modules/riak.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L157-L179 | def cluster_commit():
'''
Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'cluster commit')
if cmd['retcode'] != 0:
r... | [
"def",
"cluster_commit",
"(",
")",
":",
"ret",
"=",
"{",
"'comment'",
":",
"''",
",",
"'success'",
":",
"False",
"}",
"cmd",
"=",
"__execute_cmd",
"(",
"'riak-admin'",
",",
"'cluster commit'",
")",
"if",
"cmd",
"[",
"'retcode'",
"]",
"!=",
"0",
":",
"r... | Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit | [
"Commit",
"Cluster",
"Changes"
] | python | train | 18.347826 |
trevisanj/a99 | a99/introspection.py | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/introspection.py#L191-L206 | def get_subpackages_names(dir_):
"""Figures out the names of the subpackages of a package
Args:
dir_: (str) path to package directory
Source: http://stackoverflow.com/questions/832004/python-finding-all-packages-inside-a-package
"""
def is_package(d):
d = os.path.join(di... | [
"def",
"get_subpackages_names",
"(",
"dir_",
")",
":",
"def",
"is_package",
"(",
"d",
")",
":",
"d",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_",
",",
"d",
")",
"return",
"os",
".",
"path",
".",
"isdir",
"(",
"d",
")",
"and",
"glob",
".",
... | Figures out the names of the subpackages of a package
Args:
dir_: (str) path to package directory
Source: http://stackoverflow.com/questions/832004/python-finding-all-packages-inside-a-package | [
"Figures",
"out",
"the",
"names",
"of",
"the",
"subpackages",
"of",
"a",
"package",
"Args",
":",
"dir_",
":",
"(",
"str",
")",
"path",
"to",
"package",
"directory",
"Source",
":",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"... | python | train | 29.9375 |
vilisov/gcm | gcm/base.py | https://github.com/vilisov/gcm/blob/a2fb9f027c6c21b44e149c6ca32983a571c8a480/gcm/base.py#L83-L96 | def urlencode_utf8(params):
"""
UTF-8 safe variant of urllib.urlencode.
http://stackoverflow.com/a/8152242
"""
if hasattr(params, 'items'):
params = params.items()
params = (
'='.join((
quote_plus(k.encode('utf8'), safe='/'),
quote_plus(v.encode('utf8'), s... | [
"def",
"urlencode_utf8",
"(",
"params",
")",
":",
"if",
"hasattr",
"(",
"params",
",",
"'items'",
")",
":",
"params",
"=",
"params",
".",
"items",
"(",
")",
"params",
"=",
"(",
"'='",
".",
"join",
"(",
"(",
"quote_plus",
"(",
"k",
".",
"encode",
"(... | UTF-8 safe variant of urllib.urlencode.
http://stackoverflow.com/a/8152242 | [
"UTF",
"-",
"8",
"safe",
"variant",
"of",
"urllib",
".",
"urlencode",
".",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"8152242"
] | python | train | 27.071429 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L290-L321 | def var(self, values, axis=0, weights=None, dtype=None):
"""compute the variance over each group
Parameters
----------
values : array_like, [keys, ...]
values to take variance of per group
axis : int, optional
alternative reduction axis for values
... | [
"def",
"var",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
",",
"weights",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"values",
"=",
"np",
".",
"asarray",
"(",
"values",
")",
"unique",
",",
"mean",
"=",
"self",
".",
"mean",
"(",
"v... | compute the variance over each group
Parameters
----------
values : array_like, [keys, ...]
values to take variance of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
... | [
"compute",
"the",
"variance",
"over",
"each",
"group"
] | python | train | 34.125 |
cjdrake/pyeda | pyeda/logic/aes.py | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/aes.py#L194-L199 | def xtime(b, n):
"""Repeated polynomial multiplication in GF(2^8)."""
b = b.reshape(8)
for _ in range(n):
b = exprzeros(1) + b[:7] ^ uint2exprs(0x1b, 8) & b[7]*8
return b | [
"def",
"xtime",
"(",
"b",
",",
"n",
")",
":",
"b",
"=",
"b",
".",
"reshape",
"(",
"8",
")",
"for",
"_",
"in",
"range",
"(",
"n",
")",
":",
"b",
"=",
"exprzeros",
"(",
"1",
")",
"+",
"b",
"[",
":",
"7",
"]",
"^",
"uint2exprs",
"(",
"0x1b",... | Repeated polynomial multiplication in GF(2^8). | [
"Repeated",
"polynomial",
"multiplication",
"in",
"GF",
"(",
"2^8",
")",
"."
] | python | train | 31.5 |
limodou/uliweb | uliweb/utils/generic.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/generic.py#L60-L101 | def get_sort_field(model=None, sort_field='sort', order_name='asc'):
"""
Get sort column info according request, the data format just likes:
?sort=fieldA.asc&sort=fieldB.desc
or:
?sort=fieldA&sort=fieldB&order=asc&order=desc
default order is 'asc'. `field` can be just l... | [
"def",
"get_sort_field",
"(",
"model",
"=",
"None",
",",
"sort_field",
"=",
"'sort'",
",",
"order_name",
"=",
"'asc'",
")",
":",
"from",
"uliweb",
"import",
"request",
"if",
"request",
".",
"values",
".",
"getlist",
"(",
"'sort'",
")",
":",
"sort_fields",
... | Get sort column info according request, the data format just likes:
?sort=fieldA.asc&sort=fieldB.desc
or:
?sort=fieldA&sort=fieldB&order=asc&order=desc
default order is 'asc'. `field` can be just like `model.field`
:param model: default model, if no model existed in field
... | [
"Get",
"sort",
"column",
"info",
"according",
"request",
"the",
"data",
"format",
"just",
"likes",
":",
"?sort",
"=",
"fieldA",
".",
"asc&sort",
"=",
"fieldB",
".",
"desc",
"or",
":",
"?sort",
"=",
"fieldA&sort",
"=",
"fieldB&order",
"=",
"asc&order",
"=",... | python | train | 33.904762 |
RedFantom/ttkwidgets | ttkwidgets/table.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/table.py#L413-L458 | def configure(self, cnf=None, **kw):
"""
Configure resources of the widget.
To get the list of options for this widget, call the method :meth:`~Table.keys`.
See :meth:`~Table.__init__` for a description of the widget specific option.
"""
if cnf == 'drag_cols':
... | [
"def",
"configure",
"(",
"self",
",",
"cnf",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"cnf",
"==",
"'drag_cols'",
":",
"return",
"'drag_cols'",
",",
"self",
".",
"_drag_cols",
"elif",
"cnf",
"==",
"'drag_rows'",
":",
"return",
"'drag_rows'",
"... | Configure resources of the widget.
To get the list of options for this widget, call the method :meth:`~Table.keys`.
See :meth:`~Table.__init__` for a description of the widget specific option. | [
"Configure",
"resources",
"of",
"the",
"widget",
"."
] | python | train | 40.956522 |
todddeluca/dones | dones.py | https://github.com/todddeluca/dones/blob/6ef56565556987e701fed797a405f0825fe2e15a/dones.py#L286-L293 | def open_url(url, retries=0, sleep=0.5):
'''
Open a mysql connection to a url. Note that if your password has
punctuation characters, it might break the parsing of url.
url: A string in the form "mysql://username:password@host.domain/database"
'''
return open_conn(retries=retries, sleep=sleep,... | [
"def",
"open_url",
"(",
"url",
",",
"retries",
"=",
"0",
",",
"sleep",
"=",
"0.5",
")",
":",
"return",
"open_conn",
"(",
"retries",
"=",
"retries",
",",
"sleep",
"=",
"sleep",
",",
"*",
"*",
"parse_url",
"(",
"url",
")",
")"
] | Open a mysql connection to a url. Note that if your password has
punctuation characters, it might break the parsing of url.
url: A string in the form "mysql://username:password@host.domain/database" | [
"Open",
"a",
"mysql",
"connection",
"to",
"a",
"url",
".",
"Note",
"that",
"if",
"your",
"password",
"has",
"punctuation",
"characters",
"it",
"might",
"break",
"the",
"parsing",
"of",
"url",
"."
] | python | train | 41.375 |
cytoscape/py2cytoscape | py2cytoscape/cyrest/table.py | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/table.py#L160-L176 | def get_value(self,column=None,keyValue=None,table=None,verbose=None):
"""
Returns the value from a cell as specified by row and column ids.
:param column (string, optional): Specifies the name of a column in the tab
le
:param keyValue (string, optional): Specifies a row of ... | [
"def",
"get_value",
"(",
"self",
",",
"column",
"=",
"None",
",",
"keyValue",
"=",
"None",
",",
"table",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"PARAMS",
"=",
"set_param",
"(",
"[",
"'column'",
",",
"'keyValue'",
",",
"'table'",
"]",
","... | Returns the value from a cell as specified by row and column ids.
:param column (string, optional): Specifies the name of a column in the tab
le
:param keyValue (string, optional): Specifies a row of a table using the pr
imary key as the indentifier
:param table (string,... | [
"Returns",
"the",
"value",
"from",
"a",
"cell",
"as",
"specified",
"by",
"row",
"and",
"column",
"ids",
"."
] | python | train | 48.823529 |
CivicSpleen/ambry | ambry/orm/column.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L352-L373 | def convert_numpy_type(cls, dtype):
"""Convert a numpy dtype into a Column datatype. Only handles common
types.
Implemented as a function to decouple from numpy
"""
m = {
'int64': cls.DATATYPE_INTEGER64,
'float64': cls.DATATYPE_FLOAT,
'objec... | [
"def",
"convert_numpy_type",
"(",
"cls",
",",
"dtype",
")",
":",
"m",
"=",
"{",
"'int64'",
":",
"cls",
".",
"DATATYPE_INTEGER64",
",",
"'float64'",
":",
"cls",
".",
"DATATYPE_FLOAT",
",",
"'object'",
":",
"cls",
".",
"DATATYPE_TEXT",
"# Hack. Pandas makes stri... | Convert a numpy dtype into a Column datatype. Only handles common
types.
Implemented as a function to decouple from numpy | [
"Convert",
"a",
"numpy",
"dtype",
"into",
"a",
"Column",
"datatype",
".",
"Only",
"handles",
"common",
"types",
"."
] | python | train | 25.954545 |
SmartTeleMax/iktomi | iktomi/forms/convs.py | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/forms/convs.py#L280-L294 | def clean_value(self, value):
'''
Additional clean action to preprocess value before :meth:`to_python`
method.
Subclasses may define own clean_value method to allow additional clean
actions like html cleanup, etc.
'''
# We have to clean before checking min/max le... | [
"def",
"clean_value",
"(",
"self",
",",
"value",
")",
":",
"# We have to clean before checking min/max length. It's done in",
"# separate method to allow additional clean action in subclasses.",
"if",
"self",
".",
"nontext_replacement",
"is",
"not",
"None",
":",
"value",
"=",
... | Additional clean action to preprocess value before :meth:`to_python`
method.
Subclasses may define own clean_value method to allow additional clean
actions like html cleanup, etc. | [
"Additional",
"clean",
"action",
"to",
"preprocess",
"value",
"before",
":",
"meth",
":",
"to_python",
"method",
"."
] | python | train | 39.6 |
cmbruns/pyopenvr | src/openvr/__init__.py | https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L5417-L5427 | def getComponentButtonMask(self, pchRenderModelName, pchComponentName):
"""
Get the button mask for all buttons associated with this component
If no buttons (or axes) are associated with this component, return 0
Note: multiple components may be associated with the same button. Ex: tw... | [
"def",
"getComponentButtonMask",
"(",
"self",
",",
"pchRenderModelName",
",",
"pchComponentName",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getComponentButtonMask",
"result",
"=",
"fn",
"(",
"pchRenderModelName",
",",
"pchComponentName",
")",
"return... | Get the button mask for all buttons associated with this component
If no buttons (or axes) are associated with this component, return 0
Note: multiple components may be associated with the same button. Ex: two grip buttons on a single controller.
Note: A single component may be associated ... | [
"Get",
"the",
"button",
"mask",
"for",
"all",
"buttons",
"associated",
"with",
"this",
"component",
"If",
"no",
"buttons",
"(",
"or",
"axes",
")",
"are",
"associated",
"with",
"this",
"component",
"return",
"0",
"Note",
":",
"multiple",
"components",
"may",
... | python | train | 57.272727 |
JnyJny/Geometry | Geometry/triangle.py | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L424-L460 | def circumcenter(self):
'''
The intersection of the median perpendicular bisectors, Point.
The center of the circumscribed circle, which is the circle that
passes through all vertices of the triangle.
https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_2
... | [
"def",
"circumcenter",
"(",
"self",
")",
":",
"if",
"self",
".",
"isRight",
":",
"return",
"self",
".",
"hypotenuse",
".",
"midpoint",
"if",
"self",
".",
"A",
".",
"isOrigin",
":",
"t",
"=",
"self",
"else",
":",
"# translate triangle to origin",
"t",
"="... | The intersection of the median perpendicular bisectors, Point.
The center of the circumscribed circle, which is the circle that
passes through all vertices of the triangle.
https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_2
BUG: only finds the circumcenter in t... | [
"The",
"intersection",
"of",
"the",
"median",
"perpendicular",
"bisectors",
"Point",
"."
] | python | train | 30.459459 |
totalgood/nlpia | src/nlpia/book_parser.py | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book_parser.py#L203-L209 | def get_tagged_sections(book_dir=BOOK_PATH, include_tags=None):
""" Get list of (adoc_file_path, (adoc_syntax_tag, raw_line_str))
>>> get_tagged_sections()
[('...src/nlpia/data/book/Appendix F -- Glossary.asc', <generator object filter_tagged_lines at ...>)]
"""
return [(filepath, tag_lines(lines, ... | [
"def",
"get_tagged_sections",
"(",
"book_dir",
"=",
"BOOK_PATH",
",",
"include_tags",
"=",
"None",
")",
":",
"return",
"[",
"(",
"filepath",
",",
"tag_lines",
"(",
"lines",
",",
"include_tags",
"=",
"include_tags",
")",
")",
"for",
"filepath",
",",
"lines",
... | Get list of (adoc_file_path, (adoc_syntax_tag, raw_line_str))
>>> get_tagged_sections()
[('...src/nlpia/data/book/Appendix F -- Glossary.asc', <generator object filter_tagged_lines at ...>)] | [
"Get",
"list",
"of",
"(",
"adoc_file_path",
"(",
"adoc_syntax_tag",
"raw_line_str",
"))"
] | python | train | 55 |
benfb/dars | dars/__init__.py | https://github.com/benfb/dars/blob/66778de8314f7dcec50ef706abcea84a9b3d9c7e/dars/__init__.py#L44-L50 | def splitSong(songToSplit, start1, start2):
"""Split a song into two parts, one starting at start1, the other at start2"""
print "start1 " + str(start1)
print "start2 " + str(start2)
# songs = [songToSplit[:start1+2000], songToSplit[start2-2000:]]
songs = [songToSplit[:start1], songToSplit[start2:]]... | [
"def",
"splitSong",
"(",
"songToSplit",
",",
"start1",
",",
"start2",
")",
":",
"print",
"\"start1 \"",
"+",
"str",
"(",
"start1",
")",
"print",
"\"start2 \"",
"+",
"str",
"(",
"start2",
")",
"# songs = [songToSplit[:start1+2000], songToSplit[start2-2000:]]",
"songs... | Split a song into two parts, one starting at start1, the other at start2 | [
"Split",
"a",
"song",
"into",
"two",
"parts",
"one",
"starting",
"at",
"start1",
"the",
"other",
"at",
"start2"
] | python | train | 47.285714 |
scanny/python-pptx | pptx/chart/data.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/chart/data.py#L281-L293 | def add_series(self, name, values=(), number_format=None):
"""
Add a series to this data set entitled *name* and having the data
points specified by *values*, an iterable of numeric values.
*number_format* specifies how the series values will be displayed,
and may be a string, e.... | [
"def",
"add_series",
"(",
"self",
",",
"name",
",",
"values",
"=",
"(",
")",
",",
"number_format",
"=",
"None",
")",
":",
"series_data",
"=",
"CategorySeriesData",
"(",
"self",
",",
"name",
",",
"number_format",
")",
"self",
".",
"append",
"(",
"series_d... | Add a series to this data set entitled *name* and having the data
points specified by *values*, an iterable of numeric values.
*number_format* specifies how the series values will be displayed,
and may be a string, e.g. '#,##0' corresponding to an Excel number
format. | [
"Add",
"a",
"series",
"to",
"this",
"data",
"set",
"entitled",
"*",
"name",
"*",
"and",
"having",
"the",
"data",
"points",
"specified",
"by",
"*",
"values",
"*",
"an",
"iterable",
"of",
"numeric",
"values",
".",
"*",
"number_format",
"*",
"specifies",
"h... | python | train | 44.769231 |
wummel/linkchecker | linkcheck/logger/html.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logger/html.py#L205-L208 | def write_base (self, url_data):
"""Write url_data.base_ref."""
self.writeln(u"<tr><td>"+self.part("base")+u"</td><td>"+
cgi.escape(url_data.base_ref)+u"</td></tr>") | [
"def",
"write_base",
"(",
"self",
",",
"url_data",
")",
":",
"self",
".",
"writeln",
"(",
"u\"<tr><td>\"",
"+",
"self",
".",
"part",
"(",
"\"base\"",
")",
"+",
"u\"</td><td>\"",
"+",
"cgi",
".",
"escape",
"(",
"url_data",
".",
"base_ref",
")",
"+",
"u\... | Write url_data.base_ref. | [
"Write",
"url_data",
".",
"base_ref",
"."
] | python | train | 49.75 |
pycontribs/pyrax | pyrax/cloudloadbalancers.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudloadbalancers.py#L766-L790 | def update_ssl_termination(self, loadbalancer, securePort=None, enabled=None,
secureTrafficOnly=None):
"""
Updates existing SSL termination information for the load balancer
without affecting the existing certificates/keys.
"""
ssl_info = self.get_ssl_termination(load... | [
"def",
"update_ssl_termination",
"(",
"self",
",",
"loadbalancer",
",",
"securePort",
"=",
"None",
",",
"enabled",
"=",
"None",
",",
"secureTrafficOnly",
"=",
"None",
")",
":",
"ssl_info",
"=",
"self",
".",
"get_ssl_termination",
"(",
"loadbalancer",
")",
"if"... | Updates existing SSL termination information for the load balancer
without affecting the existing certificates/keys. | [
"Updates",
"existing",
"SSL",
"termination",
"information",
"for",
"the",
"load",
"balancer",
"without",
"affecting",
"the",
"existing",
"certificates",
"/",
"keys",
"."
] | python | train | 44.84 |
blockchain/api-v1-client-python | blockchain/blockexplorer.py | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/blockexplorer.py#L11-L24 | def get_block(block_id, api_code=None):
"""Get a single block based on a block hash.
:param str block_id: block hash to look up
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Block` class
"""
resource = 'rawblock/' + block_id
if api_code is not Non... | [
"def",
"get_block",
"(",
"block_id",
",",
"api_code",
"=",
"None",
")",
":",
"resource",
"=",
"'rawblock/'",
"+",
"block_id",
"if",
"api_code",
"is",
"not",
"None",
":",
"resource",
"+=",
"'?api_code='",
"+",
"api_code",
"response",
"=",
"util",
".",
"call... | Get a single block based on a block hash.
:param str block_id: block hash to look up
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Block` class | [
"Get",
"a",
"single",
"block",
"based",
"on",
"a",
"block",
"hash",
"."
] | python | train | 33.214286 |
heikomuller/sco-engine | scoengine/model.py | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L369-L389 | def to_dict(self, model):
"""Create a dictionary serialization for a model.
Parameters
----------
model : ModelHandle
Returns
-------
dict
Dictionary serialization for a model
"""
# Get the basic Json object from the super class
... | [
"def",
"to_dict",
"(",
"self",
",",
"model",
")",
":",
"# Get the basic Json object from the super class",
"obj",
"=",
"super",
"(",
"ModelRegistry",
",",
"self",
")",
".",
"to_dict",
"(",
"model",
")",
"# Add model parameter",
"obj",
"[",
"'parameters'",
"]",
"... | Create a dictionary serialization for a model.
Parameters
----------
model : ModelHandle
Returns
-------
dict
Dictionary serialization for a model | [
"Create",
"a",
"dictionary",
"serialization",
"for",
"a",
"model",
"."
] | python | train | 27.952381 |
pantsbuild/pants | src/python/pants/engine/mapper.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/mapper.py#L91-L127 | def create(cls, spec_path, address_maps):
"""Creates an address family from the given set of address maps.
:param spec_path: The directory prefix shared by all address_maps.
:param address_maps: The family of maps that form this namespace.
:type address_maps: :class:`collections.Iterable` of :class:`Ad... | [
"def",
"create",
"(",
"cls",
",",
"spec_path",
",",
"address_maps",
")",
":",
"if",
"spec_path",
"==",
"'.'",
":",
"spec_path",
"=",
"''",
"for",
"address_map",
"in",
"address_maps",
":",
"if",
"not",
"address_map",
".",
"path",
".",
"startswith",
"(",
"... | Creates an address family from the given set of address maps.
:param spec_path: The directory prefix shared by all address_maps.
:param address_maps: The family of maps that form this namespace.
:type address_maps: :class:`collections.Iterable` of :class:`AddressMap`
:returns: a new address family.
... | [
"Creates",
"an",
"address",
"family",
"from",
"the",
"given",
"set",
"of",
"address",
"maps",
"."
] | python | train | 50.243243 |
tilde-lab/tilde | tilde/core/api.py | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/api.py#L563-L706 | def save(self, calc, session):
'''
Saves tilde_obj into the database
NB: this is the PUBLIC method
@returns checksum, error
'''
checksum = calc.get_checksum()
try:
existing_calc = session.query(model.Calculation).filter(model.Calculation.checksum == c... | [
"def",
"save",
"(",
"self",
",",
"calc",
",",
"session",
")",
":",
"checksum",
"=",
"calc",
".",
"get_checksum",
"(",
")",
"try",
":",
"existing_calc",
"=",
"session",
".",
"query",
"(",
"model",
".",
"Calculation",
")",
".",
"filter",
"(",
"model",
... | Saves tilde_obj into the database
NB: this is the PUBLIC method
@returns checksum, error | [
"Saves",
"tilde_obj",
"into",
"the",
"database",
"NB",
":",
"this",
"is",
"the",
"PUBLIC",
"method"
] | python | train | 54.381944 |
jantman/webhook2lambda2sqs | webhook2lambda2sqs/lambda_func.py | https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/lambda_func.py#L152-L175 | def try_enqueue(conn, queue_name, msg):
"""
Try to enqueue a message. If it succeeds, return the message ID.
:param conn: SQS API connection
:type conn: :py:class:`botocore:SQS.Client`
:param queue_name: name of queue to put message in
:type queue_name: str
:param msg: JSON-serialized messa... | [
"def",
"try_enqueue",
"(",
"conn",
",",
"queue_name",
",",
"msg",
")",
":",
"logger",
".",
"debug",
"(",
"'Getting Queue URL for queue %s'",
",",
"queue_name",
")",
"qurl",
"=",
"conn",
".",
"get_queue_url",
"(",
"QueueName",
"=",
"queue_name",
")",
"[",
"'Q... | Try to enqueue a message. If it succeeds, return the message ID.
:param conn: SQS API connection
:type conn: :py:class:`botocore:SQS.Client`
:param queue_name: name of queue to put message in
:type queue_name: str
:param msg: JSON-serialized message body
:type msg: str
:return: message ID
... | [
"Try",
"to",
"enqueue",
"a",
"message",
".",
"If",
"it",
"succeeds",
"return",
"the",
"message",
"ID",
"."
] | python | train | 33.083333 |
webrecorder/pywb | pywb/apps/frontendapp.py | https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L330-L343 | def serve_record(self, environ, coll='$root', url=''):
"""Serve a URL's content from a WARC/ARC record in replay mode or from the live web in
live, proxy, and record mode.
:param dict environ: The WSGI environment dictionary for the request
:param str coll: The name of the collection th... | [
"def",
"serve_record",
"(",
"self",
",",
"environ",
",",
"coll",
"=",
"'$root'",
",",
"url",
"=",
"''",
")",
":",
"if",
"coll",
"in",
"self",
".",
"warcserver",
".",
"list_fixed_routes",
"(",
")",
":",
"return",
"WbResponse",
".",
"text_response",
"(",
... | Serve a URL's content from a WARC/ARC record in replay mode or from the live web in
live, proxy, and record mode.
:param dict environ: The WSGI environment dictionary for the request
:param str coll: The name of the collection the record is to be served from
:param str url: The URL for ... | [
"Serve",
"a",
"URL",
"s",
"content",
"from",
"a",
"WARC",
"/",
"ARC",
"record",
"in",
"replay",
"mode",
"or",
"from",
"the",
"live",
"web",
"in",
"live",
"proxy",
"and",
"record",
"mode",
"."
] | python | train | 54.785714 |
jrspruitt/ubi_reader | ubireader/ubi/block/sort.py | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/sort.py#L32-L52 | def by_leb(blocks):
"""Sort blocks by Logical Erase Block number.
Arguments:
List:blocks -- List of block objects to sort.
Returns:
List -- Indexes of blocks sorted by LEB.
"""
slist_len = len(blocks)
slist = ['x'] * slist_len
for block in blocks:
if ... | [
"def",
"by_leb",
"(",
"blocks",
")",
":",
"slist_len",
"=",
"len",
"(",
"blocks",
")",
"slist",
"=",
"[",
"'x'",
"]",
"*",
"slist_len",
"for",
"block",
"in",
"blocks",
":",
"if",
"blocks",
"[",
"block",
"]",
".",
"leb_num",
">=",
"slist_len",
":",
... | Sort blocks by Logical Erase Block number.
Arguments:
List:blocks -- List of block objects to sort.
Returns:
List -- Indexes of blocks sorted by LEB. | [
"Sort",
"blocks",
"by",
"Logical",
"Erase",
"Block",
"number",
".",
"Arguments",
":",
"List",
":",
"blocks",
"--",
"List",
"of",
"block",
"objects",
"to",
"sort",
".",
"Returns",
":",
"List",
"--",
"Indexes",
"of",
"blocks",
"sorted",
"by",
"LEB",
"."
] | python | train | 25.857143 |
infinite-library/ghetto | ghetto.py | https://github.com/infinite-library/ghetto/blob/5da999a5121a44e4304902df209edbc05119423a/ghetto.py#L76-L90 | def drop_it(title, filters, blacklist):
"""
The found torrents should be in filters list and shouldn't be in blacklist.
"""
title = title.lower()
matched = False
for f in filters:
if re.match(f, title):
matched = True
if not matched:
return True
for b in black... | [
"def",
"drop_it",
"(",
"title",
",",
"filters",
",",
"blacklist",
")",
":",
"title",
"=",
"title",
".",
"lower",
"(",
")",
"matched",
"=",
"False",
"for",
"f",
"in",
"filters",
":",
"if",
"re",
".",
"match",
"(",
"f",
",",
"title",
")",
":",
"mat... | The found torrents should be in filters list and shouldn't be in blacklist. | [
"The",
"found",
"torrents",
"should",
"be",
"in",
"filters",
"list",
"and",
"shouldn",
"t",
"be",
"in",
"blacklist",
"."
] | python | train | 25.533333 |
MolSSI-BSE/basis_set_exchange | basis_set_exchange/curate/readers/dalton.py | https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/curate/readers/dalton.py#L4-L82 | def read_dalton(basis_lines, fname):
'''Reads Dalton-formatted file data and converts it to a dictionary with the
usual BSE fields
Note that the nwchem format does not store all the fields we
have, so some fields are left blank
'''
skipchars = '$'
basis_lines = [l for l in basis_l... | [
"def",
"read_dalton",
"(",
"basis_lines",
",",
"fname",
")",
":",
"skipchars",
"=",
"'$'",
"basis_lines",
"=",
"[",
"l",
"for",
"l",
"in",
"basis_lines",
"if",
"l",
"and",
"not",
"l",
"[",
"0",
"]",
"in",
"skipchars",
"]",
"bs_data",
"=",
"create_skel"... | Reads Dalton-formatted file data and converts it to a dictionary with the
usual BSE fields
Note that the nwchem format does not store all the fields we
have, so some fields are left blank | [
"Reads",
"Dalton",
"-",
"formatted",
"file",
"data",
"and",
"converts",
"it",
"to",
"a",
"dictionary",
"with",
"the",
"usual",
"BSE",
"fields"
] | python | train | 35.632911 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.