repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
awslabs/serverless-application-model | examples/apps/lex-make-appointment-python/lambda_function.py | https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L172-L184 | def is_available(time, duration, availabilities):
"""
Helper function to check if the given time and duration fits within a known set of availability windows.
Duration is assumed to be one of 30, 60 (meaning minutes). Availabilities is expected to contain entries of the format HH:MM.
"""
if duratio... | [
"def",
"is_available",
"(",
"time",
",",
"duration",
",",
"availabilities",
")",
":",
"if",
"duration",
"==",
"30",
":",
"return",
"time",
"in",
"availabilities",
"elif",
"duration",
"==",
"60",
":",
"second_half_hour_time",
"=",
"increment_time_by_thirty_mins",
... | Helper function to check if the given time and duration fits within a known set of availability windows.
Duration is assumed to be one of 30, 60 (meaning minutes). Availabilities is expected to contain entries of the format HH:MM. | [
"Helper",
"function",
"to",
"check",
"if",
"the",
"given",
"time",
"and",
"duration",
"fits",
"within",
"a",
"known",
"set",
"of",
"availability",
"windows",
".",
"Duration",
"is",
"assumed",
"to",
"be",
"one",
"of",
"30",
"60",
"(",
"meaning",
"minutes",
... | python | train |
chrismattmann/tika-python | tika/tika.py | https://github.com/chrismattmann/tika-python/blob/ffd3879ac3eaa9142c0fb6557cc1dc52d458a75a/tika/tika.py#L605-L670 | def startServer(tikaServerJar, java_path = TikaJava, serverHost = ServerHost, port = Port, classpath=None, config_path=None):
'''
Starts Tika Server
:param tikaServerJar: path to tika server jar
:param serverHost: the host interface address to be used for binding the service
:param port: the host po... | [
"def",
"startServer",
"(",
"tikaServerJar",
",",
"java_path",
"=",
"TikaJava",
",",
"serverHost",
"=",
"ServerHost",
",",
"port",
"=",
"Port",
",",
"classpath",
"=",
"None",
",",
"config_path",
"=",
"None",
")",
":",
"if",
"classpath",
"is",
"None",
":",
... | Starts Tika Server
:param tikaServerJar: path to tika server jar
:param serverHost: the host interface address to be used for binding the service
:param port: the host port to be used for binding the service
:param classpath: Class path value to pass to JVM
:return: None | [
"Starts",
"Tika",
"Server",
":",
"param",
"tikaServerJar",
":",
"path",
"to",
"tika",
"server",
"jar",
":",
"param",
"serverHost",
":",
"the",
"host",
"interface",
"address",
"to",
"be",
"used",
"for",
"binding",
"the",
"service",
":",
"param",
"port",
":"... | python | train |
seebass/django-tooling | django_tooling/registeradmin.py | https://github.com/seebass/django-tooling/blob/aaee703040b299cae560c501c94b18e0c2620f0d/django_tooling/registeradmin.py#L5-L9 | def registerAdminSite(appName, excludeModels=[]):
"""Registers the models of the app with the given "appName" for the admin site"""
for model in apps.get_app_config(appName).get_models():
if model not in excludeModels:
admin.site.register(model) | [
"def",
"registerAdminSite",
"(",
"appName",
",",
"excludeModels",
"=",
"[",
"]",
")",
":",
"for",
"model",
"in",
"apps",
".",
"get_app_config",
"(",
"appName",
")",
".",
"get_models",
"(",
")",
":",
"if",
"model",
"not",
"in",
"excludeModels",
":",
"admi... | Registers the models of the app with the given "appName" for the admin site | [
"Registers",
"the",
"models",
"of",
"the",
"app",
"with",
"the",
"given",
"appName",
"for",
"the",
"admin",
"site"
] | python | test |
pytroll/pyspectral | pyspectral/solar.py | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/solar.py#L117-L121 | def inband_solarflux(self, rsr, scale=1.0, **options):
"""Derive the inband solar flux for a given instrument relative
spectral response valid for an earth-sun distance of one AU.
"""
return self._band_calculations(rsr, True, scale, **options) | [
"def",
"inband_solarflux",
"(",
"self",
",",
"rsr",
",",
"scale",
"=",
"1.0",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"_band_calculations",
"(",
"rsr",
",",
"True",
",",
"scale",
",",
"*",
"*",
"options",
")"
] | Derive the inband solar flux for a given instrument relative
spectral response valid for an earth-sun distance of one AU. | [
"Derive",
"the",
"inband",
"solar",
"flux",
"for",
"a",
"given",
"instrument",
"relative",
"spectral",
"response",
"valid",
"for",
"an",
"earth",
"-",
"sun",
"distance",
"of",
"one",
"AU",
"."
] | python | train |
jobovy/galpy | galpy/orbit/OrbitTop.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L215-L233 | def r(self,*args,**kwargs):
"""
NAME:
r
PURPOSE:
return spherical radius at time t
INPUT:
t - (optional) time at which to get the radius
ro= (Object-wide default) physical scale for distances to use to convert
use_physical= use to ov... | [
"def",
"r",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thiso",
"=",
"self",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"onet",
"=",
"(",
"len",
"(",
"thiso",
".",
"shape",
")",
"==",
"1",
")",
"if",
"onet",
":",... | NAME:
r
PURPOSE:
return spherical radius at time t
INPUT:
t - (optional) time at which to get the radius
ro= (Object-wide default) physical scale for distances to use to convert
use_physical= use to override Object-wide default for using a physical ... | [
"NAME",
":",
"r",
"PURPOSE",
":",
"return",
"spherical",
"radius",
"at",
"time",
"t",
"INPUT",
":",
"t",
"-",
"(",
"optional",
")",
"time",
"at",
"which",
"to",
"get",
"the",
"radius",
"ro",
"=",
"(",
"Object",
"-",
"wide",
"default",
")",
"physical"... | python | train |
ungarj/s2reader | s2reader/s2reader.py | https://github.com/ungarj/s2reader/blob/376fd7ee1d15cce0849709c149d694663a7bc0ef/s2reader/s2reader.py#L321-L339 | def footprint(self):
"""Find and return footprint as Shapely Polygon."""
# Check whether product or granule footprint needs to be calculated.
tile_geocoding = self._metadata.iter("Tile_Geocoding").next()
resolution = 10
searchstring = ".//*[@resolution='%s']" % resolution
... | [
"def",
"footprint",
"(",
"self",
")",
":",
"# Check whether product or granule footprint needs to be calculated.",
"tile_geocoding",
"=",
"self",
".",
"_metadata",
".",
"iter",
"(",
"\"Tile_Geocoding\"",
")",
".",
"next",
"(",
")",
"resolution",
"=",
"10",
"searchstri... | Find and return footprint as Shapely Polygon. | [
"Find",
"and",
"return",
"footprint",
"as",
"Shapely",
"Polygon",
"."
] | python | train |
tensorflow/lucid | lucid/optvis/param/color.py | https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/color.py#L32-L46 | def _linear_decorelate_color(t):
"""Multiply input by sqrt of emperical (ImageNet) color correlation matrix.
If you interpret t's innermost dimension as describing colors in a
decorrelated version of the color space (which is a very natural way to
describe colors -- see discussion in Feature Visualization ar... | [
"def",
"_linear_decorelate_color",
"(",
"t",
")",
":",
"# check that inner dimension is 3?",
"t_flat",
"=",
"tf",
".",
"reshape",
"(",
"t",
",",
"[",
"-",
"1",
",",
"3",
"]",
")",
"color_correlation_normalized",
"=",
"color_correlation_svd_sqrt",
"/",
"max_norm_sv... | Multiply input by sqrt of emperical (ImageNet) color correlation matrix.
If you interpret t's innermost dimension as describing colors in a
decorrelated version of the color space (which is a very natural way to
describe colors -- see discussion in Feature Visualization article) the way
to map back to normal... | [
"Multiply",
"input",
"by",
"sqrt",
"of",
"emperical",
"(",
"ImageNet",
")",
"color",
"correlation",
"matrix",
".",
"If",
"you",
"interpret",
"t",
"s",
"innermost",
"dimension",
"as",
"describing",
"colors",
"in",
"a",
"decorrelated",
"version",
"of",
"the",
... | python | train |
mitsei/dlkit | dlkit/json_/resource/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/resource/sessions.py#L780-L815 | def get_resource_form_for_create(self, resource_record_types):
"""Gets the resource form for creating new resources.
A new form should be requested for each create transaction.
arg: resource_record_types (osid.type.Type[]): array of
resource record types
return: (osi... | [
"def",
"get_resource_form_for_create",
"(",
"self",
",",
"resource_record_types",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.get_resource_form_for_create_template",
"for",
"arg",
"in",
"resource_record_types",
":",
"if",
"not",
"isinstance",
... | Gets the resource form for creating new resources.
A new form should be requested for each create transaction.
arg: resource_record_types (osid.type.Type[]): array of
resource record types
return: (osid.resource.ResourceForm) - the resource form
raise: NullArgument ... | [
"Gets",
"the",
"resource",
"form",
"for",
"creating",
"new",
"resources",
"."
] | python | train |
angr/angr | angr/analyses/reassembler.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/reassembler.py#L2615-L2639 | def _cgc_package_list_identifier(self, data_addr, data_size):
"""
Identifies the CGC package list associated with the CGC binary.
:param int data_addr: Address of the data in memory.
:param int data_size: Maximum size possible.
:return: A 2-tuple of data type and size.
:... | [
"def",
"_cgc_package_list_identifier",
"(",
"self",
",",
"data_addr",
",",
"data_size",
")",
":",
"if",
"data_size",
"<",
"100",
":",
"return",
"None",
",",
"None",
"data",
"=",
"self",
".",
"fast_memory_load",
"(",
"data_addr",
",",
"data_size",
",",
"str",... | Identifies the CGC package list associated with the CGC binary.
:param int data_addr: Address of the data in memory.
:param int data_size: Maximum size possible.
:return: A 2-tuple of data type and size.
:rtype: tuple | [
"Identifies",
"the",
"CGC",
"package",
"list",
"associated",
"with",
"the",
"CGC",
"binary",
"."
] | python | train |
pytorch/text | torchtext/data/utils.py | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/utils.py#L89-L98 | def interleave_keys(a, b):
"""Interleave bits from two sort keys to form a joint sort key.
Examples that are similar in both of the provided keys will have similar
values for the key defined by this function. Useful for tasks with two
text fields like machine translation or natural language inference.
... | [
"def",
"interleave_keys",
"(",
"a",
",",
"b",
")",
":",
"def",
"interleave",
"(",
"args",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"x",
"for",
"t",
"in",
"zip",
"(",
"*",
"args",
")",
"for",
"x",
"in",
"t",
"]",
")",
"return",
"int",
... | Interleave bits from two sort keys to form a joint sort key.
Examples that are similar in both of the provided keys will have similar
values for the key defined by this function. Useful for tasks with two
text fields like machine translation or natural language inference. | [
"Interleave",
"bits",
"from",
"two",
"sort",
"keys",
"to",
"form",
"a",
"joint",
"sort",
"key",
"."
] | python | train |
blockstack/blockstack-core | blockstack/lib/nameset/db.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1020-L1125 | def namedb_state_transition( cur, opcode, op_data, block_id, vtxindex, txid, history_id, cur_record, record_table, constraints_ignored=[] ):
"""
Given an operation (opcode, op_data), a point in time (block_id, vtxindex, txid), and a current
record (history_id, cur_record), apply the operation to the record ... | [
"def",
"namedb_state_transition",
"(",
"cur",
",",
"opcode",
",",
"op_data",
",",
"block_id",
",",
"vtxindex",
",",
"txid",
",",
"history_id",
",",
"cur_record",
",",
"record_table",
",",
"constraints_ignored",
"=",
"[",
"]",
")",
":",
"# sanity check: must be a... | Given an operation (opcode, op_data), a point in time (block_id, vtxindex, txid), and a current
record (history_id, cur_record), apply the operation to the record and save the delta to the record's
history. Also, insert or update the new record into the db.
The cur_record must exist already.
Return t... | [
"Given",
"an",
"operation",
"(",
"opcode",
"op_data",
")",
"a",
"point",
"in",
"time",
"(",
"block_id",
"vtxindex",
"txid",
")",
"and",
"a",
"current",
"record",
"(",
"history_id",
"cur_record",
")",
"apply",
"the",
"operation",
"to",
"the",
"record",
"and... | python | train |
mathandy/svgpathtools | svgpathtools/path.py | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L1676-L1680 | def unit_tangent(self, t):
"""returns the unit tangent vector of the segment at t (centered at
the origin and expressed as a complex number)."""
dseg = self.derivative(t)
return dseg/abs(dseg) | [
"def",
"unit_tangent",
"(",
"self",
",",
"t",
")",
":",
"dseg",
"=",
"self",
".",
"derivative",
"(",
"t",
")",
"return",
"dseg",
"/",
"abs",
"(",
"dseg",
")"
] | returns the unit tangent vector of the segment at t (centered at
the origin and expressed as a complex number). | [
"returns",
"the",
"unit",
"tangent",
"vector",
"of",
"the",
"segment",
"at",
"t",
"(",
"centered",
"at",
"the",
"origin",
"and",
"expressed",
"as",
"a",
"complex",
"number",
")",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py#L38-L49 | def fwdl_status_output_fwdl_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fwdl_status = ET.Element("fwdl_status")
config = fwdl_status
output = ET.SubElement(fwdl_status, "output")
fwdl_state = ET.SubElement(output, "fwdl-state")
... | [
"def",
"fwdl_status_output_fwdl_state",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"fwdl_status",
"=",
"ET",
".",
"Element",
"(",
"\"fwdl_status\"",
")",
"config",
"=",
"fwdl_status",
"output"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
thespacedoctor/qubits | qubits/universe.py | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/universe.py#L439-L478 | def random_peak_magnitudes(
log,
peakMagnitudeDistributions,
snTypesArray,
plot=True):
"""
*Generate a numpy array of random (distribution weighted) peak magnitudes for the given sn types.*
**Key Arguments:**
- ``log`` -- logger
- ``peakMagnitudeDistributions... | [
"def",
"random_peak_magnitudes",
"(",
"log",
",",
"peakMagnitudeDistributions",
",",
"snTypesArray",
",",
"plot",
"=",
"True",
")",
":",
"################ > IMPORTS ################",
"## STANDARD LIB ##",
"## THIRD PARTY ##",
"import",
"matplotlib",
".",
"pyplot",
"as",
... | *Generate a numpy array of random (distribution weighted) peak magnitudes for the given sn types.*
**Key Arguments:**
- ``log`` -- logger
- ``peakMagnitudeDistributions`` -- yaml style dictionary of peak magnitude distributions
- ``snTypesArray`` -- the pre-generated array of random sn type... | [
"*",
"Generate",
"a",
"numpy",
"array",
"of",
"random",
"(",
"distribution",
"weighted",
")",
"peak",
"magnitudes",
"for",
"the",
"given",
"sn",
"types",
".",
"*"
] | python | train |
bitesofcode/projexui | projexui/xapplication.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xapplication.py#L492-L505 | def unregisterWalkthrough(self, walkthrough):
"""
Unregisters the inputed walkthrough from the application walkthroug
list.
:param walkthrough | <XWalkthrough>
"""
if type(walkthrough) in (str, unicode):
walkthrough = self.findWalkthrough... | [
"def",
"unregisterWalkthrough",
"(",
"self",
",",
"walkthrough",
")",
":",
"if",
"type",
"(",
"walkthrough",
")",
"in",
"(",
"str",
",",
"unicode",
")",
":",
"walkthrough",
"=",
"self",
".",
"findWalkthrough",
"(",
"walkthrough",
")",
"try",
":",
"self",
... | Unregisters the inputed walkthrough from the application walkthroug
list.
:param walkthrough | <XWalkthrough> | [
"Unregisters",
"the",
"inputed",
"walkthrough",
"from",
"the",
"application",
"walkthroug",
"list",
".",
":",
"param",
"walkthrough",
"|",
"<XWalkthrough",
">"
] | python | train |
urinieto/msaf | msaf/algorithms/interface.py | https://github.com/urinieto/msaf/blob/9dbb57d77a1310465a65cc40f1641d083ca74385/msaf/algorithms/interface.py#L85-L100 | def _preprocess(self, valid_features=["pcp", "tonnetz", "mfcc",
"cqt", "tempogram"]):
"""This method obtains the actual features."""
# Use specific feature
if self.feature_str not in valid_features:
raise RuntimeError("Feature %s in not valid... | [
"def",
"_preprocess",
"(",
"self",
",",
"valid_features",
"=",
"[",
"\"pcp\"",
",",
"\"tonnetz\"",
",",
"\"mfcc\"",
",",
"\"cqt\"",
",",
"\"tempogram\"",
"]",
")",
":",
"# Use specific feature",
"if",
"self",
".",
"feature_str",
"not",
"in",
"valid_features",
... | This method obtains the actual features. | [
"This",
"method",
"obtains",
"the",
"actual",
"features",
"."
] | python | test |
bprinty/gems | gems/datatypes.py | https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L466-L486 | def json(self):
"""
Return JSON representation of object.
"""
if self.meta_type == 'list':
ret = []
for dat in self._list:
if not isinstance(dat, composite):
ret.append(dat)
else:
ret.append(d... | [
"def",
"json",
"(",
"self",
")",
":",
"if",
"self",
".",
"meta_type",
"==",
"'list'",
":",
"ret",
"=",
"[",
"]",
"for",
"dat",
"in",
"self",
".",
"_list",
":",
"if",
"not",
"isinstance",
"(",
"dat",
",",
"composite",
")",
":",
"ret",
".",
"append... | Return JSON representation of object. | [
"Return",
"JSON",
"representation",
"of",
"object",
"."
] | python | valid |
the01/python-paps | paps/si/sensorClientAdapter.py | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/sensorClientAdapter.py#L90-L106 | def on_person_update(self, people):
"""
People have changed
Should always include all people
(all that were added via on_person_new)
:param people: People to update
:type people: list[paps.people.People]
:rtype: None
:raises Exception: On error (for now ... | [
"def",
"on_person_update",
"(",
"self",
",",
"people",
")",
":",
"try",
":",
"self",
".",
"sensor_client",
".",
"person_update",
"(",
"people",
")",
"except",
":",
"self",
".",
"exception",
"(",
"\"Failed to update people\"",
")",
"raise",
"Exception",
"(",
... | People have changed
Should always include all people
(all that were added via on_person_new)
:param people: People to update
:type people: list[paps.people.People]
:rtype: None
:raises Exception: On error (for now just an exception) | [
"People",
"have",
"changed"
] | python | train |
Britefury/batchup | batchup/config.py | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/config.py#L127-L146 | def compute_sha256(path):
"""
Compute the SHA-256 hash of the file at the given path
Parameters
----------
path: str
The path of the file
Returns
-------
str
The SHA-256 HEX digest
"""
hasher = hashlib.sha256()
with open(path, 'rb') as f:
# 10MB chun... | [
"def",
"compute_sha256",
"(",
"path",
")",
":",
"hasher",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"# 10MB chunks",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"... | Compute the SHA-256 hash of the file at the given path
Parameters
----------
path: str
The path of the file
Returns
-------
str
The SHA-256 HEX digest | [
"Compute",
"the",
"SHA",
"-",
"256",
"hash",
"of",
"the",
"file",
"at",
"the",
"given",
"path"
] | python | train |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L4299-L4304 | def newCDataBlock(self, content, len):
"""Creation of a new node containing a CDATA block. """
ret = libxml2mod.xmlNewCDataBlock(self._o, content, len)
if ret is None:raise treeError('xmlNewCDataBlock() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | [
"def",
"newCDataBlock",
"(",
"self",
",",
"content",
",",
"len",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewCDataBlock",
"(",
"self",
".",
"_o",
",",
"content",
",",
"len",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewCD... | Creation of a new node containing a CDATA block. | [
"Creation",
"of",
"a",
"new",
"node",
"containing",
"a",
"CDATA",
"block",
"."
] | python | train |
miso-belica/jusText | justext/core.py | https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/core.py#L132-L136 | def make_paragraphs(cls, root):
"""Converts DOM into paragraphs."""
handler = cls()
lxml.sax.saxify(root, handler)
return handler.paragraphs | [
"def",
"make_paragraphs",
"(",
"cls",
",",
"root",
")",
":",
"handler",
"=",
"cls",
"(",
")",
"lxml",
".",
"sax",
".",
"saxify",
"(",
"root",
",",
"handler",
")",
"return",
"handler",
".",
"paragraphs"
] | Converts DOM into paragraphs. | [
"Converts",
"DOM",
"into",
"paragraphs",
"."
] | python | train |
saltstack/salt | salt/modules/state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L579-L603 | def template_str(tem, queue=False, **kwargs):
'''
Execute the information stored in a string from an sls template
CLI Example:
.. code-block:: bash
salt '*' state.template_str '<Template String>'
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return co... | [
"def",
"template_str",
"(",
"tem",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
"conflict",
"is",
"not",
"None",
":",
"return",
"conflict",
"opts",
"=",
"salt",
... | Execute the information stored in a string from an sls template
CLI Example:
.. code-block:: bash
salt '*' state.template_str '<Template String>' | [
"Execute",
"the",
"information",
"stored",
"in",
"a",
"string",
"from",
"an",
"sls",
"template"
] | python | train |
mozilla/python_moztelemetry | moztelemetry/standards.py | https://github.com/mozilla/python_moztelemetry/blob/09ddf1ec7d953a4308dfdcb0ed968f27bd5921bb/moztelemetry/standards.py#L130-L140 | def get_last_month_range():
""" Gets the date for the first and the last day of the previous complete month.
:returns: A tuple containing two date objects, for the first and the last day of the month
respectively.
"""
today = date.today()
# Get the last day for the previous month.
... | [
"def",
"get_last_month_range",
"(",
")",
":",
"today",
"=",
"date",
".",
"today",
"(",
")",
"# Get the last day for the previous month.",
"end_of_last_month",
"=",
"snap_to_beginning_of_month",
"(",
"today",
")",
"-",
"timedelta",
"(",
"days",
"=",
"1",
")",
"star... | Gets the date for the first and the last day of the previous complete month.
:returns: A tuple containing two date objects, for the first and the last day of the month
respectively. | [
"Gets",
"the",
"date",
"for",
"the",
"first",
"and",
"the",
"last",
"day",
"of",
"the",
"previous",
"complete",
"month",
"."
] | python | train |
LLNL/scraper | scripts/get_traffic.py | https://github.com/LLNL/scraper/blob/881a316e4c04dfa5a9cf491b7c7f9f997a7c56ea/scripts/get_traffic.py#L233-L254 | def check_data_redundancy(self, file_path='', dict_to_check={}):
"""
Checks the given csv file against the json data scraped for the given
dict. It will remove all data retrieved that has already been recorded
so we don't write redundant data to file. Returns count of rows from
f... | [
"def",
"check_data_redundancy",
"(",
"self",
",",
"file_path",
"=",
"''",
",",
"dict_to_check",
"=",
"{",
"}",
")",
":",
"count",
"=",
"0",
"exists",
"=",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
"previous_dates",
"=",
"{",
"}",
"if",
... | Checks the given csv file against the json data scraped for the given
dict. It will remove all data retrieved that has already been recorded
so we don't write redundant data to file. Returns count of rows from
file. | [
"Checks",
"the",
"given",
"csv",
"file",
"against",
"the",
"json",
"data",
"scraped",
"for",
"the",
"given",
"dict",
".",
"It",
"will",
"remove",
"all",
"data",
"retrieved",
"that",
"has",
"already",
"been",
"recorded",
"so",
"we",
"don",
"t",
"write",
"... | python | test |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L94-L132 | def compile(self):
"""
Compile the OpenType binary.
"""
self.otf = TTFont(sfntVersion=self.sfntVersion)
# only compile vertical metrics tables if vhea metrics a defined
vertical_metrics = [
"openTypeVheaVertTypoAscender",
"openTypeVheaVertTypoDesc... | [
"def",
"compile",
"(",
"self",
")",
":",
"self",
".",
"otf",
"=",
"TTFont",
"(",
"sfntVersion",
"=",
"self",
".",
"sfntVersion",
")",
"# only compile vertical metrics tables if vhea metrics a defined",
"vertical_metrics",
"=",
"[",
"\"openTypeVheaVertTypoAscender\"",
",... | Compile the OpenType binary. | [
"Compile",
"the",
"OpenType",
"binary",
"."
] | python | train |
honzajavorek/redis-collections | redis_collections/sets.py | https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sets.py#L131-L140 | def pop(self):
"""
Remove and return an arbitrary element from the set.
Raises :exc:`KeyError` if the set is empty.
"""
result = self.redis.spop(self.key)
if result is None:
raise KeyError
return self._unpickle(result) | [
"def",
"pop",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"redis",
".",
"spop",
"(",
"self",
".",
"key",
")",
"if",
"result",
"is",
"None",
":",
"raise",
"KeyError",
"return",
"self",
".",
"_unpickle",
"(",
"result",
")"
] | Remove and return an arbitrary element from the set.
Raises :exc:`KeyError` if the set is empty. | [
"Remove",
"and",
"return",
"an",
"arbitrary",
"element",
"from",
"the",
"set",
".",
"Raises",
":",
"exc",
":",
"KeyError",
"if",
"the",
"set",
"is",
"empty",
"."
] | python | train |
apache/incubator-heron | heron/tools/tracker/src/python/config.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/config.py#L44-L49 | def load_configs(self):
"""load config files"""
self.statemgr_config.set_state_locations(self.configs[STATEMGRS_KEY])
if EXTRA_LINKS_KEY in self.configs:
for extra_link in self.configs[EXTRA_LINKS_KEY]:
self.extra_links.append(self.validate_extra_link(extra_link)) | [
"def",
"load_configs",
"(",
"self",
")",
":",
"self",
".",
"statemgr_config",
".",
"set_state_locations",
"(",
"self",
".",
"configs",
"[",
"STATEMGRS_KEY",
"]",
")",
"if",
"EXTRA_LINKS_KEY",
"in",
"self",
".",
"configs",
":",
"for",
"extra_link",
"in",
"sel... | load config files | [
"load",
"config",
"files"
] | python | valid |
googleapis/dialogflow-python-client-v2 | dialogflow_v2/gapic/session_entity_types_client.py | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L351-L415 | def create_session_entity_type(
self,
parent,
session_entity_type,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Creates a session entity type.
Example:
... | [
"def",
"create_session_entity_type",
"(",
"self",
",",
"parent",
",",
"session_entity_type",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"... | Creates a session entity type.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.SessionEntityTypesClient()
>>>
>>> parent = client.session_path('[PROJECT]', '[SESSION]')
>>>
>>> # TODO: Initialize ``session_enti... | [
"Creates",
"a",
"session",
"entity",
"type",
"."
] | python | train |
bfrog/whizzer | whizzer/rpc/dispatch.py | https://github.com/bfrog/whizzer/blob/a1e43084b3ac8c1f3fb4ada081777cdbf791fd77/whizzer/rpc/dispatch.py#L30-L41 | def call(self, function, args=(), kwargs={}):
"""Call a method given some args and kwargs.
function -- string containing the method name to call
args -- arguments, either a list or tuple
returns the result of the method.
May raise an exception if the method isn't in the dict.
... | [
"def",
"call",
"(",
"self",
",",
"function",
",",
"args",
"=",
"(",
")",
",",
"kwargs",
"=",
"{",
"}",
")",
":",
"return",
"self",
".",
"functions",
"[",
"function",
"]",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Call a method given some args and kwargs.
function -- string containing the method name to call
args -- arguments, either a list or tuple
returns the result of the method.
May raise an exception if the method isn't in the dict. | [
"Call",
"a",
"method",
"given",
"some",
"args",
"and",
"kwargs",
"."
] | python | train |
manns/pyspread | pyspread/src/interfaces/xls.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/interfaces/xls.py#L557-L602 | def _cell_attribute_append(self, selection, tab, attributes):
"""Appends to cell_attributes with checks"""
cell_attributes = self.code_array.cell_attributes
thick_bottom_cells = []
thick_right_cells = []
# Does any cell in selection.cells have a larger bottom border?
... | [
"def",
"_cell_attribute_append",
"(",
"self",
",",
"selection",
",",
"tab",
",",
"attributes",
")",
":",
"cell_attributes",
"=",
"self",
".",
"code_array",
".",
"cell_attributes",
"thick_bottom_cells",
"=",
"[",
"]",
"thick_right_cells",
"=",
"[",
"]",
"# Does a... | Appends to cell_attributes with checks | [
"Appends",
"to",
"cell_attributes",
"with",
"checks"
] | python | train |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_1/task_agent/task_agent_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/task_agent/task_agent_client.py#L509-L530 | def get_agent_queues(self, project=None, queue_name=None, action_filter=None):
"""GetAgentQueues.
[Preview API] Get a list of agent queues.
:param str project: Project ID or project name
:param str queue_name: Filter on the agent queue name
:param str action_filter: Filter by whe... | [
"def",
"get_agent_queues",
"(",
"self",
",",
"project",
"=",
"None",
",",
"queue_name",
"=",
"None",
",",
"action_filter",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
... | GetAgentQueues.
[Preview API] Get a list of agent queues.
:param str project: Project ID or project name
:param str queue_name: Filter on the agent queue name
:param str action_filter: Filter by whether the calling user has use or manage permissions
:rtype: [TaskAgentQueue] | [
"GetAgentQueues",
".",
"[",
"Preview",
"API",
"]",
"Get",
"a",
"list",
"of",
"agent",
"queues",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
"project",
"name",
":",
"param",
"str",
"queue_name",
":",
"Filter",
"on",
"the",
"agent",
... | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L751-L765 | def real_log_poisson_loss(top_out,
targets,
model_hparams,
vocab_size,
weights_fn):
"""Poisson loss for real."""
del model_hparams, vocab_size # unused arg
predictions = top_out
if (len(common_layers.shape_l... | [
"def",
"real_log_poisson_loss",
"(",
"top_out",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
",",
"weights_fn",
")",
":",
"del",
"model_hparams",
",",
"vocab_size",
"# unused arg",
"predictions",
"=",
"top_out",
"if",
"(",
"len",
"(",
"common_layers",
... | Poisson loss for real. | [
"Poisson",
"loss",
"for",
"real",
"."
] | python | train |
lawsie/guizero | guizero/Combo.py | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Combo.py#L247-L253 | def clear(self):
"""
Clears all the options in a Combo
"""
self._options = []
self._combo_menu.tk.delete(0, END)
self._selected.set("") | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_options",
"=",
"[",
"]",
"self",
".",
"_combo_menu",
".",
"tk",
".",
"delete",
"(",
"0",
",",
"END",
")",
"self",
".",
"_selected",
".",
"set",
"(",
"\"\"",
")"
] | Clears all the options in a Combo | [
"Clears",
"all",
"the",
"options",
"in",
"a",
"Combo"
] | python | train |
mdavidsaver/p4p | src/p4p/client/thread.py | https://github.com/mdavidsaver/p4p/blob/c5e45eac01edfdad9cc2857bc283c7f2695802b8/src/p4p/client/thread.py#L65-L73 | def close(self):
"""Close subscription.
"""
if self._S is not None:
# after .close() self._event should never be called
self._S.close()
# wait for Cancelled to be delivered
self._evt.wait()
self._S = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_S",
"is",
"not",
"None",
":",
"# after .close() self._event should never be called",
"self",
".",
"_S",
".",
"close",
"(",
")",
"# wait for Cancelled to be delivered",
"self",
".",
"_evt",
".",
"wait",
... | Close subscription. | [
"Close",
"subscription",
"."
] | python | train |
qubell/contrib-python-qubell-client | qubell/__init__.py | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/__init__.py#L47-L61 | def deprecated(func, msg=None):
"""
A decorator which can be used to mark functions
as deprecated.It will result in a deprecation warning being shown
when the function is used.
"""
message = msg or "Use of deprecated function '{}`.".format(func.__name__)
@functools.wraps(func)
def wrap... | [
"def",
"deprecated",
"(",
"func",
",",
"msg",
"=",
"None",
")",
":",
"message",
"=",
"msg",
"or",
"\"Use of deprecated function '{}`.\"",
".",
"format",
"(",
"func",
".",
"__name__",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper_fu... | A decorator which can be used to mark functions
as deprecated.It will result in a deprecation warning being shown
when the function is used. | [
"A",
"decorator",
"which",
"can",
"be",
"used",
"to",
"mark",
"functions",
"as",
"deprecated",
".",
"It",
"will",
"result",
"in",
"a",
"deprecation",
"warning",
"being",
"shown",
"when",
"the",
"function",
"is",
"used",
"."
] | python | train |
wbond/oscrypto | oscrypto/_osx/_security.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/_security.py#L23-L56 | def handle_sec_error(error, exception_class=None):
"""
Checks a Security OSStatus error code and throws an exception if there is an
error to report
:param error:
An OSStatus
:param exception_class:
The exception class to use for the exception if an error occurred
:raises:
... | [
"def",
"handle_sec_error",
"(",
"error",
",",
"exception_class",
"=",
"None",
")",
":",
"if",
"error",
"==",
"0",
":",
"return",
"if",
"error",
"in",
"set",
"(",
"[",
"SecurityConst",
".",
"errSSLClosedNoNotify",
",",
"SecurityConst",
".",
"errSSLClosedAbort",... | Checks a Security OSStatus error code and throws an exception if there is an
error to report
:param error:
An OSStatus
:param exception_class:
The exception class to use for the exception if an error occurred
:raises:
OSError - when the OSStatus contains an error | [
"Checks",
"a",
"Security",
"OSStatus",
"error",
"code",
"and",
"throws",
"an",
"exception",
"if",
"there",
"is",
"an",
"error",
"to",
"report"
] | python | valid |
pandas-dev/pandas | pandas/core/internals/blocks.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/internals/blocks.py#L2109-L2145 | def _try_coerce_args(self, values, other):
"""
Coerce values and other to dtype 'i8'. NaN and NaT convert to
the smallest i8, and will correctly round-trip to NaT if converted
back in _try_coerce_result. values is always ndarray-like, other
may not be
Parameters
... | [
"def",
"_try_coerce_args",
"(",
"self",
",",
"values",
",",
"other",
")",
":",
"values",
"=",
"values",
".",
"view",
"(",
"'i8'",
")",
"if",
"isinstance",
"(",
"other",
",",
"bool",
")",
":",
"raise",
"TypeError",
"elif",
"is_null_datetimelike",
"(",
"ot... | Coerce values and other to dtype 'i8'. NaN and NaT convert to
the smallest i8, and will correctly round-trip to NaT if converted
back in _try_coerce_result. values is always ndarray-like, other
may not be
Parameters
----------
values : ndarray-like
other : ndarra... | [
"Coerce",
"values",
"and",
"other",
"to",
"dtype",
"i8",
".",
"NaN",
"and",
"NaT",
"convert",
"to",
"the",
"smallest",
"i8",
"and",
"will",
"correctly",
"round",
"-",
"trip",
"to",
"NaT",
"if",
"converted",
"back",
"in",
"_try_coerce_result",
".",
"values"... | python | train |
iotile/coretools | iotilebuild/iotile/build/config/site_scons/release.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/release.py#L99-L125 | def copy_extra_files(tile):
"""Copy all files listed in a copy_files and copy_products section.
Files listed in copy_files will be copied from the specified location
in the current component to the specified path under the output
folder.
Files listed in copy_products will be looked up with a Produ... | [
"def",
"copy_extra_files",
"(",
"tile",
")",
":",
"env",
"=",
"Environment",
"(",
"tools",
"=",
"[",
"]",
")",
"outputbase",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'build'",
",",
"'output'",
")",
"for",
"src",
",",
"dest",
"in",
"tile",
".",
"s... | Copy all files listed in a copy_files and copy_products section.
Files listed in copy_files will be copied from the specified location
in the current component to the specified path under the output
folder.
Files listed in copy_products will be looked up with a ProductResolver
and copied copied to... | [
"Copy",
"all",
"files",
"listed",
"in",
"a",
"copy_files",
"and",
"copy_products",
"section",
"."
] | python | train |
quantumlib/Cirq | cirq/protocols/mixture.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/mixture.py#L100-L115 | def has_mixture(val: Any) -> bool:
"""Returns whether the value has a mixture representation.
Returns:
If `val` has a `_has_mixture_` method and its result is not
NotImplemented, that result is returned. Otherwise, if the value
has a `_mixture_` method return True if that has a non-defa... | [
"def",
"has_mixture",
"(",
"val",
":",
"Any",
")",
"->",
"bool",
":",
"getter",
"=",
"getattr",
"(",
"val",
",",
"'_has_mixture_'",
",",
"None",
")",
"result",
"=",
"NotImplemented",
"if",
"getter",
"is",
"None",
"else",
"getter",
"(",
")",
"if",
"resu... | Returns whether the value has a mixture representation.
Returns:
If `val` has a `_has_mixture_` method and its result is not
NotImplemented, that result is returned. Otherwise, if the value
has a `_mixture_` method return True if that has a non-default value.
Returns False if neithe... | [
"Returns",
"whether",
"the",
"value",
"has",
"a",
"mixture",
"representation",
"."
] | python | train |
mortada/fredapi | fredapi/fred.py | https://github.com/mortada/fredapi/blob/d3ca79efccb9525f2752a0d6da90e793e87c3fd8/fredapi/fred.py#L307-L349 | def __get_search_results(self, url, limit, order_by, sort_order, filter):
"""
helper function for getting search results up to specified limit on the number of results. The Fred HTTP API
truncates to 1000 results per request, so this may issue multiple HTTP requests to obtain more available data... | [
"def",
"__get_search_results",
"(",
"self",
",",
"url",
",",
"limit",
",",
"order_by",
",",
"sort_order",
",",
"filter",
")",
":",
"order_by_options",
"=",
"[",
"'search_rank'",
",",
"'series_id'",
",",
"'title'",
",",
"'units'",
",",
"'frequency'",
",",
"'s... | helper function for getting search results up to specified limit on the number of results. The Fred HTTP API
truncates to 1000 results per request, so this may issue multiple HTTP requests to obtain more available data. | [
"helper",
"function",
"for",
"getting",
"search",
"results",
"up",
"to",
"specified",
"limit",
"on",
"the",
"number",
"of",
"results",
".",
"The",
"Fred",
"HTTP",
"API",
"truncates",
"to",
"1000",
"results",
"per",
"request",
"so",
"this",
"may",
"issue",
... | python | train |
incf-nidash/nidmresults | nidmresults/objects/inference.py | https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/objects/inference.py#L189-L223 | def export(self, nidm_version, export_dir):
"""
Create prov entities and activities.
"""
# Create "Excursion set" entity
self.add_attributes((
(PROV['type'], self.type),
(NIDM_IN_COORDINATE_SPACE, self.coord_space.id),
(PROV['label'], self.labe... | [
"def",
"export",
"(",
"self",
",",
"nidm_version",
",",
"export_dir",
")",
":",
"# Create \"Excursion set\" entity",
"self",
".",
"add_attributes",
"(",
"(",
"(",
"PROV",
"[",
"'type'",
"]",
",",
"self",
".",
"type",
")",
",",
"(",
"NIDM_IN_COORDINATE_SPACE",
... | Create prov entities and activities. | [
"Create",
"prov",
"entities",
"and",
"activities",
"."
] | python | train |
kensho-technologies/graphql-compiler | graphql_compiler/compiler/filters.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/filters.py#L17-L37 | def scalar_leaf_only(operator):
"""Ensure the filter function is only applied to scalar leaf types."""
def decorator(f):
"""Decorate the supplied function with the "scalar_leaf_only" logic."""
@wraps(f)
def wrapper(filter_operation_info, context, parameters, *args, **kwargs):
... | [
"def",
"scalar_leaf_only",
"(",
"operator",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"\"\"\"Decorate the supplied function with the \"scalar_leaf_only\" logic.\"\"\"",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"filter_operation_info",
",",
"context",
... | Ensure the filter function is only applied to scalar leaf types. | [
"Ensure",
"the",
"filter",
"function",
"is",
"only",
"applied",
"to",
"scalar",
"leaf",
"types",
"."
] | python | train |
uberVU/mongo-oplogreplay | oplogreplay/oplogwatcher.py | https://github.com/uberVU/mongo-oplogreplay/blob/c1998663f3ccb93c778a7fe5baaf94884251cdc2/oplogreplay/oplogwatcher.py#L38-L76 | def start(self):
""" Starts the OplogWatcher. """
oplog = self.connection.local['oplog.rs']
if self.ts is None:
cursor = oplog.find().sort('$natural', -1)
obj = cursor[0]
if obj:
self.ts = obj['ts']
else:
# In case ... | [
"def",
"start",
"(",
"self",
")",
":",
"oplog",
"=",
"self",
".",
"connection",
".",
"local",
"[",
"'oplog.rs'",
"]",
"if",
"self",
".",
"ts",
"is",
"None",
":",
"cursor",
"=",
"oplog",
".",
"find",
"(",
")",
".",
"sort",
"(",
"'$natural'",
",",
... | Starts the OplogWatcher. | [
"Starts",
"the",
"OplogWatcher",
"."
] | python | train |
mokelly/wabbit_wappa | examples/capitalization_demo.py | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/examples/capitalization_demo.py#L21-L33 | def get_example():
"""Make an example for training and testing. Outputs a tuple
(label, features) where label is +1 if capital letters are the majority,
and -1 otherwise; and features is a list of letters.
"""
features = random.sample(string.ascii_letters, NUM_SAMPLES)
num_capitalized = l... | [
"def",
"get_example",
"(",
")",
":",
"features",
"=",
"random",
".",
"sample",
"(",
"string",
".",
"ascii_letters",
",",
"NUM_SAMPLES",
")",
"num_capitalized",
"=",
"len",
"(",
"[",
"letter",
"for",
"letter",
"in",
"features",
"if",
"letter",
"in",
"string... | Make an example for training and testing. Outputs a tuple
(label, features) where label is +1 if capital letters are the majority,
and -1 otherwise; and features is a list of letters. | [
"Make",
"an",
"example",
"for",
"training",
"and",
"testing",
".",
"Outputs",
"a",
"tuple",
"(",
"label",
"features",
")",
"where",
"label",
"is",
"+",
"1",
"if",
"capital",
"letters",
"are",
"the",
"majority",
"and",
"-",
"1",
"otherwise",
";",
"and",
... | python | train |
h2oai/h2o-3 | h2o-py/h2o/job.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/job.py#L45-L81 | def poll(self, verbose_model_scoring_history = False):
"""
Wait until the job finishes.
This method will continuously query the server about the status of the job, until the job reaches a
completion. During this time we will display (in stdout) a progress bar with % completion status.
... | [
"def",
"poll",
"(",
"self",
",",
"verbose_model_scoring_history",
"=",
"False",
")",
":",
"try",
":",
"hidden",
"=",
"not",
"H2OJob",
".",
"__PROGRESS_BAR__",
"pb",
"=",
"ProgressBar",
"(",
"title",
"=",
"self",
".",
"_job_type",
"+",
"\" progress\"",
",",
... | Wait until the job finishes.
This method will continuously query the server about the status of the job, until the job reaches a
completion. During this time we will display (in stdout) a progress bar with % completion status. | [
"Wait",
"until",
"the",
"job",
"finishes",
"."
] | python | test |
facelessuser/pyspelling | pyspelling/__init__.py | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L532-L567 | def setup_command(self, encoding, options, personal_dict, file_name=None):
"""Setup command."""
cmd = [
self.binary,
'-l'
]
if encoding:
cmd.extend(['-i', encoding])
if personal_dict:
cmd.extend(['-p', personal_dict])
al... | [
"def",
"setup_command",
"(",
"self",
",",
"encoding",
",",
"options",
",",
"personal_dict",
",",
"file_name",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"self",
".",
"binary",
",",
"'-l'",
"]",
"if",
"encoding",
":",
"cmd",
".",
"extend",
"(",
"[",
"'-i... | Setup command. | [
"Setup",
"command",
"."
] | python | train |
smarie/python-parsyfiles | parsyfiles/plugins_optional/support_for_pandas.py | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_optional/support_for_pandas.py#L82-L97 | def get_default_pandas_parsers() -> List[AnyParser]:
"""
Utility method to return the default parsers able to parse a dictionary from a file.
:return:
"""
return [SingleFileParserFunction(parser_function=read_dataframe_from_xls,
streaming_mode=False,
... | [
"def",
"get_default_pandas_parsers",
"(",
")",
"->",
"List",
"[",
"AnyParser",
"]",
":",
"return",
"[",
"SingleFileParserFunction",
"(",
"parser_function",
"=",
"read_dataframe_from_xls",
",",
"streaming_mode",
"=",
"False",
",",
"supported_exts",
"=",
"{",
"'.xls'"... | Utility method to return the default parsers able to parse a dictionary from a file.
:return: | [
"Utility",
"method",
"to",
"return",
"the",
"default",
"parsers",
"able",
"to",
"parse",
"a",
"dictionary",
"from",
"a",
"file",
".",
":",
"return",
":"
] | python | train |
pedrotgn/pyactor | pyactor/context.py | https://github.com/pedrotgn/pyactor/blob/24d98d134dd4228f2ba38e83611e9c3f50ec2fd4/pyactor/context.py#L152-L176 | def load_transport(self, url):
'''
For remote communication. Sets the communication dispatcher of the host
at the address and port specified.
The scheme must be http if using a XMLRPC dispatcher.
amqp for RabbitMQ communications.
This methos is internal. Automatically c... | [
"def",
"load_transport",
"(",
"self",
",",
"url",
")",
":",
"aurl",
"=",
"urlparse",
"(",
"url",
")",
"addrl",
"=",
"aurl",
".",
"netloc",
".",
"split",
"(",
"':'",
")",
"self",
".",
"addr",
"=",
"addrl",
"[",
"0",
"]",
",",
"addrl",
"[",
"1",
... | For remote communication. Sets the communication dispatcher of the host
at the address and port specified.
The scheme must be http if using a XMLRPC dispatcher.
amqp for RabbitMQ communications.
This methos is internal. Automatically called when creating the host.
:param str. ... | [
"For",
"remote",
"communication",
".",
"Sets",
"the",
"communication",
"dispatcher",
"of",
"the",
"host",
"at",
"the",
"address",
"and",
"port",
"specified",
"."
] | python | train |
davenquinn/Attitude | attitude/orientation/pca.py | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L297-L307 | def angular_errors(self, degrees=True):
"""
Minimum and maximum angular errors
corresponding to 1st and 2nd axes
of PCA distribution.
"""
hyp_axes = self.method(self)
v = angular_errors(hyp_axes)
if degrees:
v = N.degrees(v)
return tupl... | [
"def",
"angular_errors",
"(",
"self",
",",
"degrees",
"=",
"True",
")",
":",
"hyp_axes",
"=",
"self",
".",
"method",
"(",
"self",
")",
"v",
"=",
"angular_errors",
"(",
"hyp_axes",
")",
"if",
"degrees",
":",
"v",
"=",
"N",
".",
"degrees",
"(",
"v",
... | Minimum and maximum angular errors
corresponding to 1st and 2nd axes
of PCA distribution. | [
"Minimum",
"and",
"maximum",
"angular",
"errors",
"corresponding",
"to",
"1st",
"and",
"2nd",
"axes",
"of",
"PCA",
"distribution",
"."
] | python | train |
dnanexus/dx-toolkit | src/python/dxpy/api.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L21-L27 | def analysis_describe(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /analysis-xxxx/describe API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fanalysis-xxxx%2Fdescribe
"""
return DXHTTPRequest('/%s/d... | [
"def",
"analysis_describe",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/describe'",
"%",
"object_id",
",",
"input_params",
",",
"always_retry",... | Invokes the /analysis-xxxx/describe API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fanalysis-xxxx%2Fdescribe | [
"Invokes",
"the",
"/",
"analysis",
"-",
"xxxx",
"/",
"describe",
"API",
"method",
"."
] | python | train |
lorien/grab | grab/proxylist.py | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/proxylist.py#L32-L51 | def parse_proxy_line(line):
"""
Parse proxy details from the raw text line.
The text line could be in one of the following formats:
* host:port
* host:port:username:password
"""
line = line.strip()
match = RE_SIMPLE_PROXY.search(line)
if match:
return match.group(1), match.... | [
"def",
"parse_proxy_line",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"match",
"=",
"RE_SIMPLE_PROXY",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
... | Parse proxy details from the raw text line.
The text line could be in one of the following formats:
* host:port
* host:port:username:password | [
"Parse",
"proxy",
"details",
"from",
"the",
"raw",
"text",
"line",
"."
] | python | train |
areebbeigh/profanityfilter | profanityfilter/profanityfilter.py | https://github.com/areebbeigh/profanityfilter/blob/f7e1c1bb1b7aea401e0d09219610cc690acd5476/profanityfilter/profanityfilter.py#L105-L117 | def censor(self, input_text):
"""Returns input_text with any profane words censored."""
bad_words = self.get_profane_words()
res = input_text
for word in bad_words:
# Apply word boundaries to the bad word
regex_string = r'{0}' if self._no_word_boundaries else r'\... | [
"def",
"censor",
"(",
"self",
",",
"input_text",
")",
":",
"bad_words",
"=",
"self",
".",
"get_profane_words",
"(",
")",
"res",
"=",
"input_text",
"for",
"word",
"in",
"bad_words",
":",
"# Apply word boundaries to the bad word",
"regex_string",
"=",
"r'{0}'",
"i... | Returns input_text with any profane words censored. | [
"Returns",
"input_text",
"with",
"any",
"profane",
"words",
"censored",
"."
] | python | train |
trailofbits/manticore | scripts/binaryninja/manticore_viz/__init__.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/scripts/binaryninja/manticore_viz/__init__.py#L175-L184 | def viz_live_trace(view):
"""
Given a Manticore trace file, highlight the basic blocks.
"""
tv = TraceVisualizer(view, None, live=True)
if tv.workspace is None:
tv.workspace = get_workspace()
# update due to singleton in case we are called after a clear
tv.live_update = True
tv.v... | [
"def",
"viz_live_trace",
"(",
"view",
")",
":",
"tv",
"=",
"TraceVisualizer",
"(",
"view",
",",
"None",
",",
"live",
"=",
"True",
")",
"if",
"tv",
".",
"workspace",
"is",
"None",
":",
"tv",
".",
"workspace",
"=",
"get_workspace",
"(",
")",
"# update du... | Given a Manticore trace file, highlight the basic blocks. | [
"Given",
"a",
"Manticore",
"trace",
"file",
"highlight",
"the",
"basic",
"blocks",
"."
] | python | valid |
ingolemo/python-lenses | lenses/hooks/hook_funcs.py | https://github.com/ingolemo/python-lenses/blob/a3a6ed0a31f6674451e542e7380a8aa16e6f8edf/lenses/hooks/hook_funcs.py#L121-L155 | def setattr(self, name, value):
# type: (Any, Any, Any) -> Any
'''Takes an object, a string, and a value and produces a new object
that is a copy of the original but with the attribute called ``name``
set to ``value``.
The following equality should hold for your definition:
.. code-block:: pyt... | [
"def",
"setattr",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"# type: (Any, Any, Any) -> Any",
"try",
":",
"self",
".",
"_lens_setattr",
"except",
"AttributeError",
":",
"selfcopy",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"builtin_setattr",
"(",
"... | Takes an object, a string, and a value and produces a new object
that is a copy of the original but with the attribute called ``name``
set to ``value``.
The following equality should hold for your definition:
.. code-block:: python
setattr(obj, 'attr', obj.attr) == obj
This function is u... | [
"Takes",
"an",
"object",
"a",
"string",
"and",
"a",
"value",
"and",
"produces",
"a",
"new",
"object",
"that",
"is",
"a",
"copy",
"of",
"the",
"original",
"but",
"with",
"the",
"attribute",
"called",
"name",
"set",
"to",
"value",
"."
] | python | test |
seung-lab/cloud-volume | cloudvolume/txrx.py | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/txrx.py#L263-L271 | def check_grid_aligned(vol, img, offset):
"""Returns (is_aligned, img bounds Bbox, nearest bbox inflated to grid aligned)"""
shape = Vec(*img.shape)[:3]
offset = Vec(*offset)[:3]
bounds = Bbox( offset, shape + offset)
alignment_check = bounds.expand_to_chunk_size(vol.underlying, vol.voxel_offset)
alignment_... | [
"def",
"check_grid_aligned",
"(",
"vol",
",",
"img",
",",
"offset",
")",
":",
"shape",
"=",
"Vec",
"(",
"*",
"img",
".",
"shape",
")",
"[",
":",
"3",
"]",
"offset",
"=",
"Vec",
"(",
"*",
"offset",
")",
"[",
":",
"3",
"]",
"bounds",
"=",
"Bbox",... | Returns (is_aligned, img bounds Bbox, nearest bbox inflated to grid aligned) | [
"Returns",
"(",
"is_aligned",
"img",
"bounds",
"Bbox",
"nearest",
"bbox",
"inflated",
"to",
"grid",
"aligned",
")"
] | python | train |
mrstephenneal/dirutility | dirutility/walk/walk.py | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/walk.py#L227-L235 | def folders(self):
"""Return list of folders in root directory"""
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isdir(full_path):
if not path.startswith('.'):
... | [
"def",
"folders",
"(",
"self",
")",
":",
"for",
"directory",
"in",
"self",
".",
"directory",
":",
"for",
"path",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"path",
... | Return list of folders in root directory | [
"Return",
"list",
"of",
"folders",
"in",
"root",
"directory"
] | python | train |
BerkeleyAutomation/perception | perception/primesense_sensor.py | https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/primesense_sensor.py#L67-L73 | def color_intrinsics(self):
""":obj:`CameraIntrinsics` : The camera intrinsics for the primesense color camera.
"""
return CameraIntrinsics(self._ir_frame, PrimesenseSensor.FOCAL_X, PrimesenseSensor.FOCAL_Y,
PrimesenseSensor.CENTER_X, PrimesenseSensor.CENTER_Y,
... | [
"def",
"color_intrinsics",
"(",
"self",
")",
":",
"return",
"CameraIntrinsics",
"(",
"self",
".",
"_ir_frame",
",",
"PrimesenseSensor",
".",
"FOCAL_X",
",",
"PrimesenseSensor",
".",
"FOCAL_Y",
",",
"PrimesenseSensor",
".",
"CENTER_X",
",",
"PrimesenseSensor",
".",... | :obj:`CameraIntrinsics` : The camera intrinsics for the primesense color camera. | [
":",
"obj",
":",
"CameraIntrinsics",
":",
"The",
"camera",
"intrinsics",
"for",
"the",
"primesense",
"color",
"camera",
"."
] | python | train |
esheldon/fitsio | fitsio/fitslib.py | https://github.com/esheldon/fitsio/blob/a6f07919f457a282fe240adad9d2c30906b71a15/fitsio/fitslib.py#L1053-L1090 | def _append_hdu_info(self, ext):
"""
internal routine
append info for indiciated extension
"""
# raised IOError if not found
hdu_type = self._FITS.movabs_hdu(ext+1)
if hdu_type == IMAGE_HDU:
hdu = ImageHDU(self._FITS, ext, **self.keys)
elif ... | [
"def",
"_append_hdu_info",
"(",
"self",
",",
"ext",
")",
":",
"# raised IOError if not found",
"hdu_type",
"=",
"self",
".",
"_FITS",
".",
"movabs_hdu",
"(",
"ext",
"+",
"1",
")",
"if",
"hdu_type",
"==",
"IMAGE_HDU",
":",
"hdu",
"=",
"ImageHDU",
"(",
"self... | internal routine
append info for indiciated extension | [
"internal",
"routine"
] | python | train |
piglei/uwsgi-sloth | uwsgi_sloth/models.py | https://github.com/piglei/uwsgi-sloth/blob/2834ac5ed17d89ca5f19151c649ac610f6f37bd1/uwsgi_sloth/models.py#L65-L84 | def merge_requests_data_to(to, food={}):
"""Merge a small analyzed result to a big one, this function will modify the
original ``to``"""
if not to:
to.update(food)
to['requests_counter']['normal'] += food['requests_counter']['normal']
to['requests_counter']['slow'] += food['requests_counte... | [
"def",
"merge_requests_data_to",
"(",
"to",
",",
"food",
"=",
"{",
"}",
")",
":",
"if",
"not",
"to",
":",
"to",
".",
"update",
"(",
"food",
")",
"to",
"[",
"'requests_counter'",
"]",
"[",
"'normal'",
"]",
"+=",
"food",
"[",
"'requests_counter'",
"]",
... | Merge a small analyzed result to a big one, this function will modify the
original ``to`` | [
"Merge",
"a",
"small",
"analyzed",
"result",
"to",
"a",
"big",
"one",
"this",
"function",
"will",
"modify",
"the",
"original",
"to"
] | python | train |
delph-in/pydelphin | delphin/mrs/query.py | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L183-L205 | def select_icons(xmrs, left=None, relation=None, right=None):
"""
Return the list of matching ICONS for *xmrs*.
:class:`~delphin.mrs.components.IndividualConstraint` objects for
*xmrs* match if their `left` matches *left*, `relation` matches
*relation*, and `right` matches *right*. The *left*, *rel... | [
"def",
"select_icons",
"(",
"xmrs",
",",
"left",
"=",
"None",
",",
"relation",
"=",
"None",
",",
"right",
"=",
"None",
")",
":",
"icmatch",
"=",
"lambda",
"ic",
":",
"(",
"(",
"left",
"is",
"None",
"or",
"ic",
".",
"left",
"==",
"left",
")",
"and... | Return the list of matching ICONS for *xmrs*.
:class:`~delphin.mrs.components.IndividualConstraint` objects for
*xmrs* match if their `left` matches *left*, `relation` matches
*relation*, and `right` matches *right*. The *left*, *relation*,
and *right* filters are ignored if they are `None`.
Args:... | [
"Return",
"the",
"list",
"of",
"matching",
"ICONS",
"for",
"*",
"xmrs",
"*",
"."
] | python | train |
edx/pa11ycrawler | pa11ycrawler/pipelines/__init__.py | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/__init__.py#L27-L39 | def is_sequence_start_page(self, url):
"""
Does this URL represent the first page in a section sequence? E.g.
/courses/{coursename}/courseware/{block_id}/{section_id}/1
This will return the same page as the pattern
/courses/{coursename}/courseware/{block_id}/{section_id}.
... | [
"def",
"is_sequence_start_page",
"(",
"self",
",",
"url",
")",
":",
"return",
"(",
"len",
"(",
"url",
".",
"path",
".",
"segments",
")",
"==",
"6",
"and",
"url",
".",
"path",
".",
"segments",
"[",
"0",
"]",
"==",
"'courses'",
"and",
"url",
".",
"pa... | Does this URL represent the first page in a section sequence? E.g.
/courses/{coursename}/courseware/{block_id}/{section_id}/1
This will return the same page as the pattern
/courses/{coursename}/courseware/{block_id}/{section_id}. | [
"Does",
"this",
"URL",
"represent",
"the",
"first",
"page",
"in",
"a",
"section",
"sequence?",
"E",
".",
"g",
".",
"/",
"courses",
"/",
"{",
"coursename",
"}",
"/",
"courseware",
"/",
"{",
"block_id",
"}",
"/",
"{",
"section_id",
"}",
"/",
"1",
"This... | python | train |
LordGaav/python-chaos | chaos/amqp/exchange.py | https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/exchange.py#L74-L104 | def publish(self, message, properties=None, mandatory=False):
"""
Publish a message to an AMQP exchange.
Parameters
----------
message: string
Message to publish.
properties: dict
Properties to set on message. This parameter is optional, but if set, at least the following options must be set:
con... | [
"def",
"publish",
"(",
"self",
",",
"message",
",",
"properties",
"=",
"None",
",",
"mandatory",
"=",
"False",
")",
":",
"return",
"publish_message",
"(",
"self",
".",
"channel",
",",
"self",
".",
"exchange_name",
",",
"self",
".",
"default_routing_key",
"... | Publish a message to an AMQP exchange.
Parameters
----------
message: string
Message to publish.
properties: dict
Properties to set on message. This parameter is optional, but if set, at least the following options must be set:
content_type: string - what content_type to specify, default is 'text/pla... | [
"Publish",
"a",
"message",
"to",
"an",
"AMQP",
"exchange",
"."
] | python | train |
quantumlib/Cirq | cirq/protocols/resolve_parameters.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/protocols/resolve_parameters.py#L40-L62 | def is_parameterized(val: Any) -> bool:
"""Returns whether the object is parameterized with any Symbols.
A value is parameterized when it has an `_is_parameterized_` method and
that method returns a truthy value, or if the value is an instance of
sympy.Basic.
Returns:
True if the gate has ... | [
"def",
"is_parameterized",
"(",
"val",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"val",
",",
"sympy",
".",
"Basic",
")",
":",
"return",
"True",
"getter",
"=",
"getattr",
"(",
"val",
",",
"'_is_parameterized_'",
",",
"None",
")",
"res... | Returns whether the object is parameterized with any Symbols.
A value is parameterized when it has an `_is_parameterized_` method and
that method returns a truthy value, or if the value is an instance of
sympy.Basic.
Returns:
True if the gate has any unresolved Symbols
and False otherw... | [
"Returns",
"whether",
"the",
"object",
"is",
"parameterized",
"with",
"any",
"Symbols",
"."
] | python | train |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L323-L334 | def add_key(self, key, first=False):
"""Adds the given key to this row.
:param key: Key to be added to this row.
:param first: BOolean flag that indicates if key is added at the beginning or at the end.
"""
if first:
self.keys = [key] + self.keys
else:
... | [
"def",
"add_key",
"(",
"self",
",",
"key",
",",
"first",
"=",
"False",
")",
":",
"if",
"first",
":",
"self",
".",
"keys",
"=",
"[",
"key",
"]",
"+",
"self",
".",
"keys",
"else",
":",
"self",
".",
"keys",
".",
"append",
"(",
"key",
")",
"if",
... | Adds the given key to this row.
:param key: Key to be added to this row.
:param first: BOolean flag that indicates if key is added at the beginning or at the end. | [
"Adds",
"the",
"given",
"key",
"to",
"this",
"row",
"."
] | python | train |
crytic/slither | slither/solc_parsing/variables/event_variable.py | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/solc_parsing/variables/event_variable.py#L7-L18 | def _analyze_variable_attributes(self, attributes):
"""
Analyze event variable attributes
:param attributes: The event variable attributes to parse.
:return: None
"""
# Check for the indexed attribute
if 'indexed' in attributes:
self._indexed = attrib... | [
"def",
"_analyze_variable_attributes",
"(",
"self",
",",
"attributes",
")",
":",
"# Check for the indexed attribute",
"if",
"'indexed'",
"in",
"attributes",
":",
"self",
".",
"_indexed",
"=",
"attributes",
"[",
"'indexed'",
"]",
"super",
"(",
"EventVariableSolc",
",... | Analyze event variable attributes
:param attributes: The event variable attributes to parse.
:return: None | [
"Analyze",
"event",
"variable",
"attributes",
":",
"param",
"attributes",
":",
"The",
"event",
"variable",
"attributes",
"to",
"parse",
".",
":",
"return",
":",
"None"
] | python | train |
TissueMAPS/TmDeploy | elasticluster/elasticluster/cluster.py | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/cluster.py#L1107-L1132 | def is_alive(self):
"""Checks if the current node is up and running in the cloud. It
only checks the status provided by the cloud interface. Therefore a
node might be running, but not yet ready to ssh into it.
"""
running = False
if not self.instance_id:
retur... | [
"def",
"is_alive",
"(",
"self",
")",
":",
"running",
"=",
"False",
"if",
"not",
"self",
".",
"instance_id",
":",
"return",
"False",
"try",
":",
"log",
".",
"debug",
"(",
"\"Getting information for instance %s\"",
",",
"self",
".",
"instance_id",
")",
"runnin... | Checks if the current node is up and running in the cloud. It
only checks the status provided by the cloud interface. Therefore a
node might be running, but not yet ready to ssh into it. | [
"Checks",
"if",
"the",
"current",
"node",
"is",
"up",
"and",
"running",
"in",
"the",
"cloud",
".",
"It",
"only",
"checks",
"the",
"status",
"provided",
"by",
"the",
"cloud",
"interface",
".",
"Therefore",
"a",
"node",
"might",
"be",
"running",
"but",
"no... | python | train |
datadotworld/data.world-py | datadotworld/client/_swagger/apis/datasets_api.py | https://github.com/datadotworld/data.world-py/blob/ffaeb115f358731ab0b805b0c43b7ff2e3cf0a77/datadotworld/client/_swagger/apis/datasets_api.py#L519-L545 | def delete_files_and_sync_sources(self, owner, id, name, **kwargs):
"""
Delete files
Delete one or more files from a dataset by their name, including files added via URL. **Batching** Note that the `name` parameter can be include multiple times in the query string, once for each file that ... | [
"def",
"delete_files_and_sync_sources",
"(",
"self",
",",
"owner",
",",
"id",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
... | Delete files
Delete one or more files from a dataset by their name, including files added via URL. **Batching** Note that the `name` parameter can be include multiple times in the query string, once for each file that is to be deleted together in a single request.
This method makes a synchronous H... | [
"Delete",
"files",
"Delete",
"one",
"or",
"more",
"files",
"from",
"a",
"dataset",
"by",
"their",
"name",
"including",
"files",
"added",
"via",
"URL",
".",
"**",
"Batching",
"**",
"Note",
"that",
"the",
"name",
"parameter",
"can",
"be",
"include",
"multipl... | python | train |
googlesamples/assistant-sdk-python | google-assistant-sdk/googlesamples/assistant/grpc/devicetool.py | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/devicetool.py#L62-L73 | def pretty_print_model(devicemodel):
"""Prints out a device model in the terminal by parsing dict."""
PRETTY_PRINT_MODEL = """Device Model ID: %(deviceModelId)s
Project ID: %(projectId)s
Device Type: %(deviceType)s"""
logging.info(PRETTY_PRINT_MODEL % devicemodel)
if 'traits' in devicemo... | [
"def",
"pretty_print_model",
"(",
"devicemodel",
")",
":",
"PRETTY_PRINT_MODEL",
"=",
"\"\"\"Device Model ID: %(deviceModelId)s\n Project ID: %(projectId)s\n Device Type: %(deviceType)s\"\"\"",
"logging",
".",
"info",
"(",
"PRETTY_PRINT_MODEL",
"%",
"devicemodel",
")",
... | Prints out a device model in the terminal by parsing dict. | [
"Prints",
"out",
"a",
"device",
"model",
"in",
"the",
"terminal",
"by",
"parsing",
"dict",
"."
] | python | train |
juicer/juicer | juicer/common/Cart.py | https://github.com/juicer/juicer/blob/0c9f0fd59e293d45df6b46e81f675d33221c600d/juicer/common/Cart.py#L99-L119 | def load(self, json_file):
"""
Build a cart from a json file
"""
cart_file = os.path.join(CART_LOCATION, json_file)
try:
cart_body = juicer.utils.read_json_document(cart_file)
except IOError as e:
juicer.utils.Log.log_error('an error occured while ... | [
"def",
"load",
"(",
"self",
",",
"json_file",
")",
":",
"cart_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"CART_LOCATION",
",",
"json_file",
")",
"try",
":",
"cart_body",
"=",
"juicer",
".",
"utils",
".",
"read_json_document",
"(",
"cart_file",
")",... | Build a cart from a json file | [
"Build",
"a",
"cart",
"from",
"a",
"json",
"file"
] | python | train |
GoogleCloudPlatform/appengine-pipelines | python/src/pipeline/util.py | https://github.com/GoogleCloudPlatform/appengine-pipelines/blob/277394648dac3e8214677af898935d07399ac8e1/python/src/pipeline/util.py#L136-L152 | def is_generator_function(obj):
"""Return true if the object is a user-defined generator function.
Generator function objects provides same attributes as functions.
See isfunction.__doc__ for attributes listing.
Adapted from Python 2.6.
Args:
obj: an object to test.
Returns:
true if the object i... | [
"def",
"is_generator_function",
"(",
"obj",
")",
":",
"CO_GENERATOR",
"=",
"0x20",
"return",
"bool",
"(",
"(",
"(",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
"or",
"inspect",
".",
"ismethod",
"(",
"obj",
")",
")",
"and",
"obj",
".",
"func_code",
"... | Return true if the object is a user-defined generator function.
Generator function objects provides same attributes as functions.
See isfunction.__doc__ for attributes listing.
Adapted from Python 2.6.
Args:
obj: an object to test.
Returns:
true if the object is generator function. | [
"Return",
"true",
"if",
"the",
"object",
"is",
"a",
"user",
"-",
"defined",
"generator",
"function",
"."
] | python | train |
numenta/htmresearch | projects/sequence_prediction/reberGrammar/reberSequencePrediction_HMM.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sequence_prediction/reberGrammar/reberSequencePrediction_HMM.py#L143-L175 | def runExperiment():
"""
Experiment 1: Calculate error rate as a function of training sequence numbers
:return:
"""
trainSeqN = [5, 10, 20, 50, 100, 200]
rptPerCondition = 20
correctRateAll = np.zeros((len(trainSeqN), rptPerCondition))
missRateAll = np.zeros((len(trainSeqN), rptPerCondition))
fpRateAl... | [
"def",
"runExperiment",
"(",
")",
":",
"trainSeqN",
"=",
"[",
"5",
",",
"10",
",",
"20",
",",
"50",
",",
"100",
",",
"200",
"]",
"rptPerCondition",
"=",
"20",
"correctRateAll",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"trainSeqN",
")",
",",
... | Experiment 1: Calculate error rate as a function of training sequence numbers
:return: | [
"Experiment",
"1",
":",
"Calculate",
"error",
"rate",
"as",
"a",
"function",
"of",
"training",
"sequence",
"numbers",
":",
"return",
":"
] | python | train |
django-parler/django-parler | parler/views.py | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/views.py#L205-L212 | def get_object(self, queryset=None):
"""
Assign the language for the retrieved object.
"""
object = super(LanguageChoiceMixin, self).get_object(queryset)
if isinstance(object, TranslatableModelMixin):
object.set_current_language(self.get_language(), initialize=True)
... | [
"def",
"get_object",
"(",
"self",
",",
"queryset",
"=",
"None",
")",
":",
"object",
"=",
"super",
"(",
"LanguageChoiceMixin",
",",
"self",
")",
".",
"get_object",
"(",
"queryset",
")",
"if",
"isinstance",
"(",
"object",
",",
"TranslatableModelMixin",
")",
... | Assign the language for the retrieved object. | [
"Assign",
"the",
"language",
"for",
"the",
"retrieved",
"object",
"."
] | python | train |
confirm/ansibleci | ansibleci/config.py | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/config.py#L61-L67 | def add_module(self, module):
'''
Adds configuration parameters from a Python module.
'''
for key, value in module.__dict__.iteritems():
if key[0:2] != '__':
self.__setattr__(attr=key, value=value) | [
"def",
"add_module",
"(",
"self",
",",
"module",
")",
":",
"for",
"key",
",",
"value",
"in",
"module",
".",
"__dict__",
".",
"iteritems",
"(",
")",
":",
"if",
"key",
"[",
"0",
":",
"2",
"]",
"!=",
"'__'",
":",
"self",
".",
"__setattr__",
"(",
"at... | Adds configuration parameters from a Python module. | [
"Adds",
"configuration",
"parameters",
"from",
"a",
"Python",
"module",
"."
] | python | train |
baliame/http-hmac-python | httphmac/v2.py | https://github.com/baliame/http-hmac-python/blob/9884c0cbfdb712f9f37080a8efbfdce82850785f/httphmac/v2.py#L226-L242 | def check(self, request, response, secret):
"""Checks the response for the appropriate signature. Returns True if the signature matches the expected value.
Keyword arguments:
request -- A request object which can be consumed by this API.
response -- A requests response object or compati... | [
"def",
"check",
"(",
"self",
",",
"request",
",",
"response",
",",
"secret",
")",
":",
"auth",
"=",
"request",
".",
"get_header",
"(",
"'Authorization'",
")",
"if",
"auth",
"==",
"''",
":",
"raise",
"KeyError",
"(",
"'Authorization header is required for the r... | Checks the response for the appropriate signature. Returns True if the signature matches the expected value.
Keyword arguments:
request -- A request object which can be consumed by this API.
response -- A requests response object or compatible signed response object.
secret -- The base6... | [
"Checks",
"the",
"response",
"for",
"the",
"appropriate",
"signature",
".",
"Returns",
"True",
"if",
"the",
"signature",
"matches",
"the",
"expected",
"value",
"."
] | python | train |
GPflow/GPflow | gpflow/training/monitor.py | https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/training/monitor.py#L836-L854 | def _eval_summary(self, context: MonitorContext, feed_dict: Optional[Dict]=None) -> None:
"""
Evaluates the summary tensor and writes the result to the event file.
:param context: Monitor context
:param feed_dict: Input values dictionary to be provided to the `session.run`
when e... | [
"def",
"_eval_summary",
"(",
"self",
",",
"context",
":",
"MonitorContext",
",",
"feed_dict",
":",
"Optional",
"[",
"Dict",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if",
"self",
".",
"_summary",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Tensor... | Evaluates the summary tensor and writes the result to the event file.
:param context: Monitor context
:param feed_dict: Input values dictionary to be provided to the `session.run`
when evaluating the summary tensor. | [
"Evaluates",
"the",
"summary",
"tensor",
"and",
"writes",
"the",
"result",
"to",
"the",
"event",
"file",
".",
":",
"param",
"context",
":",
"Monitor",
"context",
":",
"param",
"feed_dict",
":",
"Input",
"values",
"dictionary",
"to",
"be",
"provided",
"to",
... | python | train |
wglass/lighthouse | lighthouse/haproxy/control.py | https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/haproxy/control.py#L97-L119 | def get_info(self):
"""
Parses the output of a "show info" HAProxy command and returns a
simple dictionary of the results.
"""
info_response = self.send_command("show info")
if not info_response:
return {}
def convert_camel_case(string):
... | [
"def",
"get_info",
"(",
"self",
")",
":",
"info_response",
"=",
"self",
".",
"send_command",
"(",
"\"show info\"",
")",
"if",
"not",
"info_response",
":",
"return",
"{",
"}",
"def",
"convert_camel_case",
"(",
"string",
")",
":",
"return",
"all_cap_re",
".",
... | Parses the output of a "show info" HAProxy command and returns a
simple dictionary of the results. | [
"Parses",
"the",
"output",
"of",
"a",
"show",
"info",
"HAProxy",
"command",
"and",
"returns",
"a",
"simple",
"dictionary",
"of",
"the",
"results",
"."
] | python | train |
LLNL/scraper | scraper/tfs/__init__.py | https://github.com/LLNL/scraper/blob/881a316e4c04dfa5a9cf491b7c7f9f997a7c56ea/scraper/tfs/__init__.py#L54-L71 | def create_tfs_core_client(url, token=None):
"""
Create a core_client.py client for a Team Foundation Server Enterprise connection instance
If token is not provided, will attempt to use the TFS_API_TOKEN
environment variable if present.
"""
if token is None:
token = os.environ.get('TFS_... | [
"def",
"create_tfs_core_client",
"(",
"url",
",",
"token",
"=",
"None",
")",
":",
"if",
"token",
"is",
"None",
":",
"token",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TFS_API_TOKEN'",
",",
"None",
")",
"tfs_connection",
"=",
"create_tfs_connection",
"(... | Create a core_client.py client for a Team Foundation Server Enterprise connection instance
If token is not provided, will attempt to use the TFS_API_TOKEN
environment variable if present. | [
"Create",
"a",
"core_client",
".",
"py",
"client",
"for",
"a",
"Team",
"Foundation",
"Server",
"Enterprise",
"connection",
"instance"
] | python | test |
stanfordnlp/stanza | stanza/text/vocab.py | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L153-L174 | def _index2word(self):
"""Mapping from indices to words.
WARNING: this may go out-of-date, because it is a copy, not a view into the Vocab.
:return: a list of strings
"""
# TODO(kelvinguu): it would be nice to just use `dict.viewkeys`, but unfortunately those are not indexable
... | [
"def",
"_index2word",
"(",
"self",
")",
":",
"# TODO(kelvinguu): it would be nice to just use `dict.viewkeys`, but unfortunately those are not indexable",
"compute_index2word",
"=",
"lambda",
":",
"self",
".",
"keys",
"(",
")",
"# this works because self is an OrderedDict",
"# crea... | Mapping from indices to words.
WARNING: this may go out-of-date, because it is a copy, not a view into the Vocab.
:return: a list of strings | [
"Mapping",
"from",
"indices",
"to",
"words",
"."
] | python | train |
znc-sistemas/django-municipios | municipios/utils/ibge.py | https://github.com/znc-sistemas/django-municipios/blob/bdaf56315af7e1db4e0005a241e9fd95271a7ce1/municipios/utils/ibge.py#L54-L120 | def convert_shapefile(shapefilename, srid=4674):
"""
shapefilename: considera nomenclatura de shapefile do IBGE para determinar se é UF
ou Municípios.
ex. 55UF2500GC_SIR.shp para UF e 55MU2500GC_SIR.shp para Municípios
srid: 4674 (Projeção SIRGAS 2000)
"""
# /ho... | [
"def",
"convert_shapefile",
"(",
"shapefilename",
",",
"srid",
"=",
"4674",
")",
":",
"# /home/nando/Desktop/IBGE/2010/55MU2500GC_SIR.shp",
"ds",
"=",
"DataSource",
"(",
"shapefilename",
")",
"is_uf",
"=",
"shapefilename",
".",
"upper",
"(",
")",
".",
"find",
"(",... | shapefilename: considera nomenclatura de shapefile do IBGE para determinar se é UF
ou Municípios.
ex. 55UF2500GC_SIR.shp para UF e 55MU2500GC_SIR.shp para Municípios
srid: 4674 (Projeção SIRGAS 2000) | [
"shapefilename",
":",
"considera",
"nomenclatura",
"de",
"shapefile",
"do",
"IBGE",
"para",
"determinar",
"se",
"é",
"UF",
"ou",
"Municípios",
".",
"ex",
".",
"55UF2500GC_SIR",
".",
"shp",
"para",
"UF",
"e",
"55MU2500GC_SIR",
".",
"shp",
"para",
"Municípios",
... | python | train |
thombashi/pytablereader | pytablereader/sqlite/core.py | https://github.com/thombashi/pytablereader/blob/bc3c057a2cc775bcce690e0e9019c2907b638101/pytablereader/sqlite/core.py#L40-L68 | def load(self):
"""
Extract tabular data as |TableData| instances from a SQLite database
file. |load_source_desc_file|
:return:
Loaded table data iterator.
|load_table_name_desc|
=================== ==============================================
... | [
"def",
"load",
"(",
"self",
")",
":",
"self",
".",
"_validate",
"(",
")",
"formatter",
"=",
"SqliteTableFormatter",
"(",
"self",
".",
"source",
")",
"formatter",
".",
"accept",
"(",
"self",
")",
"return",
"formatter",
".",
"to_table_data",
"(",
")"
] | Extract tabular data as |TableData| instances from a SQLite database
file. |load_source_desc_file|
:return:
Loaded table data iterator.
|load_table_name_desc|
=================== ==============================================
Format specifier Value ... | [
"Extract",
"tabular",
"data",
"as",
"|TableData|",
"instances",
"from",
"a",
"SQLite",
"database",
"file",
".",
"|load_source_desc_file|"
] | python | train |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/sql_io.py | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/sql_io.py#L16-L52 | def smart_insert(df, table, engine, minimal_size=5):
"""An optimized Insert strategy.
**中文文档**
一种优化的将大型DataFrame中的数据, 在有IntegrityError的情况下将所有
好数据存入数据库的方法。
"""
from sqlalchemy.exc import IntegrityError
try:
table_name = table.name
except:
table_name = table
# 首先进行尝... | [
"def",
"smart_insert",
"(",
"df",
",",
"table",
",",
"engine",
",",
"minimal_size",
"=",
"5",
")",
":",
"from",
"sqlalchemy",
".",
"exc",
"import",
"IntegrityError",
"try",
":",
"table_name",
"=",
"table",
".",
"name",
"except",
":",
"table_name",
"=",
"... | An optimized Insert strategy.
**中文文档**
一种优化的将大型DataFrame中的数据, 在有IntegrityError的情况下将所有
好数据存入数据库的方法。 | [
"An",
"optimized",
"Insert",
"strategy",
"."
] | python | train |
gem/oq-engine | openquake/hazardlib/gsim/dowrickrhoades_2005.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/dowrickrhoades_2005.py#L98-L120 | def _compute_mean(self, C, mag, rrup, hypo_depth, delta_R, delta_S,
delta_V, delta_I, vs30):
"""
Compute MMI Intensity Value as per Equation in Table 5 and
Table 7 pag 198.
"""
# mean is calculated for all the 4 classes using the same equation.
# Fo... | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
",",
"hypo_depth",
",",
"delta_R",
",",
"delta_S",
",",
"delta_V",
",",
"delta_I",
",",
"vs30",
")",
":",
"# mean is calculated for all the 4 classes using the same equation.",
"# For DowrickRho... | Compute MMI Intensity Value as per Equation in Table 5 and
Table 7 pag 198. | [
"Compute",
"MMI",
"Intensity",
"Value",
"as",
"per",
"Equation",
"in",
"Table",
"5",
"and",
"Table",
"7",
"pag",
"198",
"."
] | python | train |
maxcountryman/flask-uploads | flask_uploads.py | https://github.com/maxcountryman/flask-uploads/blob/dc24fa0c53d605876e5b4502cadffdf1a4345b1d/flask_uploads.py#L345-L358 | def path(self, filename, folder=None):
"""
This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
... | [
"def",
"path",
"(",
"self",
",",
"filename",
",",
"folder",
"=",
"None",
")",
":",
"if",
"folder",
"is",
"not",
"None",
":",
"target_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"config",
".",
"destination",
",",
"folder",
")",
"... | This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
to save to. | [
"This",
"returns",
"the",
"absolute",
"path",
"of",
"a",
"file",
"uploaded",
"to",
"this",
"set",
".",
"It",
"doesn",
"t",
"actually",
"check",
"whether",
"said",
"file",
"exists",
"."
] | python | test |
tino/pyFirmata | pyfirmata/util.py | https://github.com/tino/pyFirmata/blob/05881909c4d7c4e808e9ed457144670b2136706e/pyfirmata/util.py#L161-L225 | def pin_list_to_board_dict(pinlist):
"""
Capability Response codes:
INPUT: 0, 1
OUTPUT: 1, 1
ANALOG: 2, 10
PWM: 3, 8
SERV0: 4, 14
I2C: 6, 1
"""
board_dict = {
"digital": [],
"analog": [],
"pwm": [],
"servo": [], # ... | [
"def",
"pin_list_to_board_dict",
"(",
"pinlist",
")",
":",
"board_dict",
"=",
"{",
"\"digital\"",
":",
"[",
"]",
",",
"\"analog\"",
":",
"[",
"]",
",",
"\"pwm\"",
":",
"[",
"]",
",",
"\"servo\"",
":",
"[",
"]",
",",
"# 2.2 specs",
"# 'i2c': [], # 2.3 spec... | Capability Response codes:
INPUT: 0, 1
OUTPUT: 1, 1
ANALOG: 2, 10
PWM: 3, 8
SERV0: 4, 14
I2C: 6, 1 | [
"Capability",
"Response",
"codes",
":",
"INPUT",
":",
"0",
"1",
"OUTPUT",
":",
"1",
"1",
"ANALOG",
":",
"2",
"10",
"PWM",
":",
"3",
"8",
"SERV0",
":",
"4",
"14",
"I2C",
":",
"6",
"1"
] | python | train |
Leeps-Lab/otree-redwood | otree_redwood/models.py | https://github.com/Leeps-Lab/otree-redwood/blob/59212f61a256ef77e0a9ed392ff497ea83ee6245/otree_redwood/models.py#L135-L142 | def _on_disconnect(self, participant):
"""Trigger the :meth:`when_player_disconnects` callback."""
player = None
for p in self.get_players():
if p.participant == participant:
player = p
break
self.when_player_disconnects(player) | [
"def",
"_on_disconnect",
"(",
"self",
",",
"participant",
")",
":",
"player",
"=",
"None",
"for",
"p",
"in",
"self",
".",
"get_players",
"(",
")",
":",
"if",
"p",
".",
"participant",
"==",
"participant",
":",
"player",
"=",
"p",
"break",
"self",
".",
... | Trigger the :meth:`when_player_disconnects` callback. | [
"Trigger",
"the",
":",
"meth",
":",
"when_player_disconnects",
"callback",
"."
] | python | train |
rossant/ipymd | ipymd/core/prompt.py | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/prompt.py#L231-L252 | def create_prompt(prompt):
"""Create a prompt manager.
Parameters
----------
prompt : str or class driving from BasePromptManager
The prompt name ('python' or 'ipython') or a custom PromptManager
class.
"""
if prompt is None:
prompt = 'python'
if prompt == 'python'... | [
"def",
"create_prompt",
"(",
"prompt",
")",
":",
"if",
"prompt",
"is",
"None",
":",
"prompt",
"=",
"'python'",
"if",
"prompt",
"==",
"'python'",
":",
"prompt",
"=",
"PythonPromptManager",
"elif",
"prompt",
"==",
"'ipython'",
":",
"prompt",
"=",
"IPythonPromp... | Create a prompt manager.
Parameters
----------
prompt : str or class driving from BasePromptManager
The prompt name ('python' or 'ipython') or a custom PromptManager
class. | [
"Create",
"a",
"prompt",
"manager",
"."
] | python | train |
phaethon/kamene | kamene/utils.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils.py#L1003-L1007 | def wireshark(pktlist, *args):
"""Run wireshark on a list of packets"""
fname = get_temp_file()
wrpcap(fname, pktlist)
subprocess.Popen([conf.prog.wireshark, "-r", fname] + list(args)) | [
"def",
"wireshark",
"(",
"pktlist",
",",
"*",
"args",
")",
":",
"fname",
"=",
"get_temp_file",
"(",
")",
"wrpcap",
"(",
"fname",
",",
"pktlist",
")",
"subprocess",
".",
"Popen",
"(",
"[",
"conf",
".",
"prog",
".",
"wireshark",
",",
"\"-r\"",
",",
"fn... | Run wireshark on a list of packets | [
"Run",
"wireshark",
"on",
"a",
"list",
"of",
"packets"
] | python | train |
DataONEorg/d1_python | gmn/src/d1_gmn/app/views/create.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/views/create.py#L35-L83 | def create_sciobj(request, sysmeta_pyxb):
"""Create object file and database entries for a new native locally stored (non-
proxied) science object.
This method takes a request object and is only called from the views that
handle:
- MNStorage.create()
- MNStorage.update()
Various sanity ch... | [
"def",
"create_sciobj",
"(",
"request",
",",
"sysmeta_pyxb",
")",
":",
"pid",
"=",
"d1_common",
".",
"xml",
".",
"get_req_val",
"(",
"sysmeta_pyxb",
".",
"identifier",
")",
"set_mn_controlled_values",
"(",
"request",
",",
"sysmeta_pyxb",
",",
"is_modification",
... | Create object file and database entries for a new native locally stored (non-
proxied) science object.
This method takes a request object and is only called from the views that
handle:
- MNStorage.create()
- MNStorage.update()
Various sanity checking is performed. Raises D1 exceptions that ar... | [
"Create",
"object",
"file",
"and",
"database",
"entries",
"for",
"a",
"new",
"native",
"locally",
"stored",
"(",
"non",
"-",
"proxied",
")",
"science",
"object",
"."
] | python | train |
Erotemic/utool | utool/util_str.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L2941-L2967 | def highlight_multi_regex(str_, pat_to_color, reflags=0):
"""
FIXME Use pygments instead. must be mututally exclusive
"""
#import colorama
# from colorama import Fore, Style
#color = Fore.MAGENTA
# color = Fore.RED
#match = re.search(pat, str_, flags=reflags)
colored = str_
to_... | [
"def",
"highlight_multi_regex",
"(",
"str_",
",",
"pat_to_color",
",",
"reflags",
"=",
"0",
")",
":",
"#import colorama",
"# from colorama import Fore, Style",
"#color = Fore.MAGENTA",
"# color = Fore.RED",
"#match = re.search(pat, str_, flags=reflags)",
"colored",
"=",
"str_",... | FIXME Use pygments instead. must be mututally exclusive | [
"FIXME",
"Use",
"pygments",
"instead",
".",
"must",
"be",
"mututally",
"exclusive"
] | python | train |
lsbardel/python-stdnet | stdnet/backends/redisb/client/prefixed.py | https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/backends/redisb/client/prefixed.py#L122-L125 | def execute_command(self, cmnd, *args, **options):
"Execute a command and return a parsed response"
args, options = self.preprocess_command(cmnd, *args, **options)
return self.client.execute_command(cmnd, *args, **options) | [
"def",
"execute_command",
"(",
"self",
",",
"cmnd",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"args",
",",
"options",
"=",
"self",
".",
"preprocess_command",
"(",
"cmnd",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
"return",
"self",
... | Execute a command and return a parsed response | [
"Execute",
"a",
"command",
"and",
"return",
"a",
"parsed",
"response"
] | python | train |
inveniosoftware-contrib/invenio-classifier | requirements.py | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/requirements.py#L59-L101 | def parse_pip_file(path):
"""Parse pip requirements file."""
# requirement lines sorted by importance
# also collect other pip commands
rdev = dict()
rnormal = []
stuff = []
try:
with open(path) as f:
for line in f:
line = line.strip()
# ... | [
"def",
"parse_pip_file",
"(",
"path",
")",
":",
"# requirement lines sorted by importance",
"# also collect other pip commands",
"rdev",
"=",
"dict",
"(",
")",
"rnormal",
"=",
"[",
"]",
"stuff",
"=",
"[",
"]",
"try",
":",
"with",
"open",
"(",
"path",
")",
"as"... | Parse pip requirements file. | [
"Parse",
"pip",
"requirements",
"file",
"."
] | python | train |
coleifer/walrus | walrus/models.py | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/models.py#L752-L767 | def query_delete(cls, expression=None):
"""
Delete model instances matching the given expression (if
specified). If no expression is provided, then all model instances
will be deleted.
:param expression: A boolean expression to filter by.
"""
if expression is not... | [
"def",
"query_delete",
"(",
"cls",
",",
"expression",
"=",
"None",
")",
":",
"if",
"expression",
"is",
"not",
"None",
":",
"executor",
"=",
"Executor",
"(",
"cls",
".",
"__database__",
")",
"result",
"=",
"executor",
".",
"execute",
"(",
"expression",
")... | Delete model instances matching the given expression (if
specified). If no expression is provided, then all model instances
will be deleted.
:param expression: A boolean expression to filter by. | [
"Delete",
"model",
"instances",
"matching",
"the",
"given",
"expression",
"(",
"if",
"specified",
")",
".",
"If",
"no",
"expression",
"is",
"provided",
"then",
"all",
"model",
"instances",
"will",
"be",
"deleted",
"."
] | python | train |
smarie/python-valid8 | valid8/entry_points_annotations.py | https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points_annotations.py#L666-L696 | def decorate_several_with_validation(func,
_out_=None, # type: ValidationFuncs
none_policy=None, # type: int
**validation_funcs # type: ValidationFuncs
):
# ... | [
"def",
"decorate_several_with_validation",
"(",
"func",
",",
"_out_",
"=",
"None",
",",
"# type: ValidationFuncs",
"none_policy",
"=",
"None",
",",
"# type: int",
"*",
"*",
"validation_funcs",
"# type: ValidationFuncs",
")",
":",
"# type: (...) -> Callable",
"# add valida... | This method is equivalent to applying `decorate_with_validation` once for each of the provided arguments of
the function `func` as well as output `_out_`. validation_funcs keyword arguments are validation functions for each
arg name.
Note that this method is less flexible than decorate_with_validation sinc... | [
"This",
"method",
"is",
"equivalent",
"to",
"applying",
"decorate_with_validation",
"once",
"for",
"each",
"of",
"the",
"provided",
"arguments",
"of",
"the",
"function",
"func",
"as",
"well",
"as",
"output",
"_out_",
".",
"validation_funcs",
"keyword",
"arguments"... | python | train |
gwpy/gwpy | gwpy/signal/filter_design.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/signal/filter_design.py#L500-L566 | def bandpass(flow, fhigh, sample_rate, fstop=None, gpass=2, gstop=30,
type='iir', **kwargs):
"""Design a band-pass filter for the given cutoff frequencies
Parameters
----------
flow : `float`
lower corner frequency of pass band
fhigh : `float`
upper corner frequency of... | [
"def",
"bandpass",
"(",
"flow",
",",
"fhigh",
",",
"sample_rate",
",",
"fstop",
"=",
"None",
",",
"gpass",
"=",
"2",
",",
"gstop",
"=",
"30",
",",
"type",
"=",
"'iir'",
",",
"*",
"*",
"kwargs",
")",
":",
"sample_rate",
"=",
"_as_float",
"(",
"sampl... | Design a band-pass filter for the given cutoff frequencies
Parameters
----------
flow : `float`
lower corner frequency of pass band
fhigh : `float`
upper corner frequency of pass band
sample_rate : `float`
sampling rate of target data
fstop : `tuple` of `float`, optio... | [
"Design",
"a",
"band",
"-",
"pass",
"filter",
"for",
"the",
"given",
"cutoff",
"frequencies"
] | python | train |
helixyte/everest | everest/ini.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/ini.py#L32-L44 | def options(self, parser, env=None):
"""
Adds command-line options for this plugin.
"""
if env is None:
env = os.environ
env_opt_name = 'NOSE_%s' % self.__dest_opt_name.upper()
parser.add_option("--%s" % self.__opt_name,
dest=self.__d... | [
"def",
"options",
"(",
"self",
",",
"parser",
",",
"env",
"=",
"None",
")",
":",
"if",
"env",
"is",
"None",
":",
"env",
"=",
"os",
".",
"environ",
"env_opt_name",
"=",
"'NOSE_%s'",
"%",
"self",
".",
"__dest_opt_name",
".",
"upper",
"(",
")",
"parser"... | Adds command-line options for this plugin. | [
"Adds",
"command",
"-",
"line",
"options",
"for",
"this",
"plugin",
"."
] | python | train |
BlueBrain/NeuroM | neurom/morphmath.py | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/morphmath.py#L316-L325 | def segment_area(seg):
'''Compute the surface area of a segment.
Approximated as a conical frustum. Does not include the surface area
of the bounding circles.
'''
r0 = seg[0][COLS.R]
r1 = seg[1][COLS.R]
h2 = point_dist2(seg[0], seg[1])
return math.pi * (r0 + r1) * math.sqrt((r0 - r1) **... | [
"def",
"segment_area",
"(",
"seg",
")",
":",
"r0",
"=",
"seg",
"[",
"0",
"]",
"[",
"COLS",
".",
"R",
"]",
"r1",
"=",
"seg",
"[",
"1",
"]",
"[",
"COLS",
".",
"R",
"]",
"h2",
"=",
"point_dist2",
"(",
"seg",
"[",
"0",
"]",
",",
"seg",
"[",
"... | Compute the surface area of a segment.
Approximated as a conical frustum. Does not include the surface area
of the bounding circles. | [
"Compute",
"the",
"surface",
"area",
"of",
"a",
"segment",
"."
] | python | train |
sebdah/dynamic-dynamodb | dynamic_dynamodb/calculators.py | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/calculators.py#L118-L151 | def decrease_writes_in_units(
current_provisioning, units, min_provisioned_writes, log_tag):
""" Decrease the current_provisioning with units units
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type units: int
:param units: How many units should we d... | [
"def",
"decrease_writes_in_units",
"(",
"current_provisioning",
",",
"units",
",",
"min_provisioned_writes",
",",
"log_tag",
")",
":",
"updated_provisioning",
"=",
"int",
"(",
"current_provisioning",
")",
"-",
"int",
"(",
"units",
")",
"min_provisioned_writes",
"=",
... | Decrease the current_provisioning with units units
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type units: int
:param units: How many units should we decrease with
:returns: int -- New provisioning value
:type min_provisioned_writes: int
:param min... | [
"Decrease",
"the",
"current_provisioning",
"with",
"units",
"units"
] | python | train |
luckydonald/pytgbot | pytgbot/api_types/receivable/payments.py | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/payments.py#L544-L561 | def to_array(self):
"""
Serializes this SuccessfulPayment to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(SuccessfulPayment, self).to_array()
array['currency'] = u(self.currency) # py2: type unicode, py3: type s... | [
"def",
"to_array",
"(",
"self",
")",
":",
"array",
"=",
"super",
"(",
"SuccessfulPayment",
",",
"self",
")",
".",
"to_array",
"(",
")",
"array",
"[",
"'currency'",
"]",
"=",
"u",
"(",
"self",
".",
"currency",
")",
"# py2: type unicode, py3: type str",
"arr... | Serializes this SuccessfulPayment to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | [
"Serializes",
"this",
"SuccessfulPayment",
"to",
"a",
"dictionary",
"."
] | python | train |
Shinichi-Nakagawa/pitchpx | pitchpx/game/inning.py | https://github.com/Shinichi-Nakagawa/pitchpx/blob/5747402a0b3416f5e910b479e100df858f0b6440/pitchpx/game/inning.py#L551-L572 | def _inning_events(self, soup, inning_number, inning_id, hit_location):
"""
Inning Events.
:param soup: Beautifulsoup object
:param inning_number: Inning Number
:param inning_id: Inning Id(0:home, 1:away)
:param hit_location: Hitlocation data(dict)
"""
# a... | [
"def",
"_inning_events",
"(",
"self",
",",
"soup",
",",
"inning_number",
",",
"inning_id",
",",
"hit_location",
")",
":",
"# at bat(batter box data) & pitching data",
"out_ct",
"=",
"0",
"for",
"ab",
"in",
"soup",
".",
"find_all",
"(",
"'atbat'",
")",
":",
"# ... | Inning Events.
:param soup: Beautifulsoup object
:param inning_number: Inning Number
:param inning_id: Inning Id(0:home, 1:away)
:param hit_location: Hitlocation data(dict) | [
"Inning",
"Events",
".",
":",
"param",
"soup",
":",
"Beautifulsoup",
"object",
":",
"param",
"inning_number",
":",
"Inning",
"Number",
":",
"param",
"inning_id",
":",
"Inning",
"Id",
"(",
"0",
":",
"home",
"1",
":",
"away",
")",
":",
"param",
"hit_locati... | python | train |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L3053-L3067 | def save(self, filename, incl_uniqueid=False):
"""
Save the Parameter to a JSON-formatted ASCII file
:parameter str filename: relative or fullpath to the file
:return: filename
:rtype: str
"""
filename = os.path.expanduser(filename)
f = open(filename, 'w'... | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"incl_uniqueid",
"=",
"False",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"json",
".",
"dump",
"(",
"s... | Save the Parameter to a JSON-formatted ASCII file
:parameter str filename: relative or fullpath to the file
:return: filename
:rtype: str | [
"Save",
"the",
"Parameter",
"to",
"a",
"JSON",
"-",
"formatted",
"ASCII",
"file"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.