repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L291-L295
def flatten4d3d(x): """Flatten a 4d-tensor into a 3d-tensor by joining width and height.""" xshape = shape_list(x) result = tf.reshape(x, [xshape[0], xshape[1] * xshape[2], xshape[3]]) return result
[ "def", "flatten4d3d", "(", "x", ")", ":", "xshape", "=", "shape_list", "(", "x", ")", "result", "=", "tf", ".", "reshape", "(", "x", ",", "[", "xshape", "[", "0", "]", ",", "xshape", "[", "1", "]", "*", "xshape", "[", "2", "]", ",", "xshape", ...
Flatten a 4d-tensor into a 3d-tensor by joining width and height.
[ "Flatten", "a", "4d", "-", "tensor", "into", "a", "3d", "-", "tensor", "by", "joining", "width", "and", "height", "." ]
python
train
40.4
remind101/stacker_blueprints
stacker_blueprints/policies.py
https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/policies.py#L202-L214
def lambda_vpc_execution_statements(): """Allow Lambda to manipuate EC2 ENIs for VPC support.""" return [ Statement( Effect=Allow, Resource=['*'], Action=[ ec2.CreateNetworkInterface, ec2.DescribeNetworkInterfaces, ec2.D...
[ "def", "lambda_vpc_execution_statements", "(", ")", ":", "return", "[", "Statement", "(", "Effect", "=", "Allow", ",", "Resource", "=", "[", "'*'", "]", ",", "Action", "=", "[", "ec2", ".", "CreateNetworkInterface", ",", "ec2", ".", "DescribeNetworkInterfaces"...
Allow Lambda to manipuate EC2 ENIs for VPC support.
[ "Allow", "Lambda", "to", "manipuate", "EC2", "ENIs", "for", "VPC", "support", "." ]
python
train
27.692308
pipermerriam/flex
flex/validation/common.py
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L365-L398
def validate_object(obj, field_validators=None, non_field_validators=None, schema=None, context=None): """ Takes a mapping and applies a mapping of validator functions to it collecting and reraising any validation errors that occur. """ if schema is None: schema = {} ...
[ "def", "validate_object", "(", "obj", ",", "field_validators", "=", "None", ",", "non_field_validators", "=", "None", ",", "schema", "=", "None", ",", "context", "=", "None", ")", ":", "if", "schema", "is", "None", ":", "schema", "=", "{", "}", "if", "...
Takes a mapping and applies a mapping of validator functions to it collecting and reraising any validation errors that occur.
[ "Takes", "a", "mapping", "and", "applies", "a", "mapping", "of", "validator", "functions", "to", "it", "collecting", "and", "reraising", "any", "validation", "errors", "that", "occur", "." ]
python
train
39.470588
Erotemic/utool
utool/util_graph.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_graph.py#L2150-L2256
def mincost_diameter_augment(graph, max_cost, candidates=None, weight=None, cost=None): """ PROBLEM: Bounded Cost Minimum Diameter Edge Addition (BCMD) Args: graph (nx.Graph): input graph max_cost (float): maximum weighted diamter of the graph weight (str): key of the edge weight at...
[ "def", "mincost_diameter_augment", "(", "graph", ",", "max_cost", ",", "candidates", "=", "None", ",", "weight", "=", "None", ",", "cost", "=", "None", ")", ":", "import", "utool", "as", "ut", "import", "operator", "as", "op", "if", "candidates", "is", "...
PROBLEM: Bounded Cost Minimum Diameter Edge Addition (BCMD) Args: graph (nx.Graph): input graph max_cost (float): maximum weighted diamter of the graph weight (str): key of the edge weight attribute cost (str): key of the edge cost attribute candidates (list): set of non-edg...
[ "PROBLEM", ":", "Bounded", "Cost", "Minimum", "Diameter", "Edge", "Addition", "(", "BCMD", ")" ]
python
train
39.523364
bitlabstudio/django-multilingual-news
multilingual_news/templatetags/multilingual_news_tags.py
https://github.com/bitlabstudio/django-multilingual-news/blob/2ddc076ce2002a9fa462dbba701441879b49a54d/multilingual_news/templatetags/multilingual_news_tags.py#L19-L29
def get_newsentry_meta_description(newsentry): """Returns the meta description for the given entry.""" if newsentry.meta_description: return newsentry.meta_description # If there is no seo addon found, take the info from the placeholders text = newsentry.get_description() if len(text) > 16...
[ "def", "get_newsentry_meta_description", "(", "newsentry", ")", ":", "if", "newsentry", ".", "meta_description", ":", "return", "newsentry", ".", "meta_description", "# If there is no seo addon found, take the info from the placeholders", "text", "=", "newsentry", ".", "get_d...
Returns the meta description for the given entry.
[ "Returns", "the", "meta", "description", "for", "the", "given", "entry", "." ]
python
train
33.727273
digidotcom/python-devicecloud
devicecloud/file_system_service.py
https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/file_system_service.py#L25-L42
def _parse_command_response(response): """Parse an SCI command response into ElementTree XML This is a helper method that takes a Requests Response object of an SCI command response and will parse it into an ElementTree Element representing the root of the XML response. :param response: The reques...
[ "def", "_parse_command_response", "(", "response", ")", ":", "try", ":", "root", "=", "ET", ".", "fromstring", "(", "response", ".", "text", ")", "except", "ET", ".", "ParseError", ":", "raise", "ResponseParseError", "(", "\"Unexpected response format, could not p...
Parse an SCI command response into ElementTree XML This is a helper method that takes a Requests Response object of an SCI command response and will parse it into an ElementTree Element representing the root of the XML response. :param response: The requests response object :return: An ElementTree...
[ "Parse", "an", "SCI", "command", "response", "into", "ElementTree", "XML" ]
python
train
39
BernardFW/bernard
src/bernard/engine/fsm.py
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/fsm.py#L301-L368
async def _handle_message(self, message: BaseMessage, responder: Responder) -> Optional[Dict]: """ Handles a message: find a state and run it. :return: The register that was saved """ async def noop(request: Request, r...
[ "async", "def", "_handle_message", "(", "self", ",", "message", ":", "BaseMessage", ",", "responder", ":", "Responder", ")", "->", "Optional", "[", "Dict", "]", ":", "async", "def", "noop", "(", "request", ":", "Request", ",", "responder", ":", "Responder"...
Handles a message: find a state and run it. :return: The register that was saved
[ "Handles", "a", "message", ":", "find", "a", "state", "and", "run", "it", "." ]
python
train
35.220588
saltstack/salt
salt/modules/netbox.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L340-L391
def create_device(name, role, model, manufacturer, site): ''' .. versionadded:: 2019.2.0 Create a new device with a name, role, model, manufacturer and site. All these components need to be already in Netbox. name The ...
[ "def", "create_device", "(", "name", ",", "role", ",", "model", ",", "manufacturer", ",", "site", ")", ":", "try", ":", "nb_role", "=", "get_", "(", "'dcim'", ",", "'device-roles'", ",", "name", "=", "role", ")", "if", "not", "nb_role", ":", "return", ...
.. versionadded:: 2019.2.0 Create a new device with a name, role, model, manufacturer and site. All these components need to be already in Netbox. name The name of the device, e.g., ``edge_router`` role String of device role, e.g., ``router`` model String of device model, e...
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
python
train
28.961538
fprimex/zdesk
zdesk/zdesk_api.py
https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L1283-L1287
def group_membership_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/group_memberships#show-membership" api_path = "/api/v2/group_memberships/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "group_membership_show", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/group_memberships/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", ...
https://developer.zendesk.com/rest_api/docs/core/group_memberships#show-membership
[ "https", ":", "//", "developer", ".", "zendesk", ".", "com", "/", "rest_api", "/", "docs", "/", "core", "/", "group_memberships#show", "-", "membership" ]
python
train
55.8
sentinel-hub/eo-learn
ml_tools/eolearn/ml_tools/classifier.py
https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/ml_tools/eolearn/ml_tools/classifier.py#L250-L281
def image_predict(self, X): """ Predicts class label for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_p...
[ "def", "image_predict", "(", "self", ",", "X", ")", ":", "self", ".", "_check_image", "(", "X", ")", "patches", ",", "patches_shape", "=", "self", ".", "_to_patches", "(", "X", ")", "predictions", "=", "self", ".", "classifier", ".", "predict", "(", "s...
Predicts class label for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_pixels_x] Target labels or masks.
[ "Predicts", "class", "label", "for", "the", "entire", "image", ".", "Parameters", ":", "-----------", "X", ":", "array", "shape", "=", "[", "n_samples", "n_pixels_y", "n_pixels_x", "n_bands", "]", "Array", "of", "training", "images", "y", ":", "array", "shap...
python
train
33.34375
ihgazni2/elist
elist/elist.py
https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L2198-L2223
def last_continuous_indexes_slice(ol,value): ''' from elist.elist import * ol = [1,"a","a",2,3,"a",4,"a","a","a",5] last_continuous_indexes_slice(ol,"a") ''' length = ol.__len__() end = None slice = [] for i in range(length-1,-1,-1): if(ol[i]==value): ...
[ "def", "last_continuous_indexes_slice", "(", "ol", ",", "value", ")", ":", "length", "=", "ol", ".", "__len__", "(", ")", "end", "=", "None", "slice", "=", "[", "]", "for", "i", "in", "range", "(", "length", "-", "1", ",", "-", "1", ",", "-", "1"...
from elist.elist import * ol = [1,"a","a",2,3,"a",4,"a","a","a",5] last_continuous_indexes_slice(ol,"a")
[ "from", "elist", ".", "elist", "import", "*", "ol", "=", "[", "1", "a", "a", "2", "3", "a", "4", "a", "a", "a", "5", "]", "last_continuous_indexes_slice", "(", "ol", "a", ")" ]
python
valid
23.307692
Azure/azure-sdk-for-python
azure-sdk-tools/packaging_tools/pypi.py
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-sdk-tools/packaging_tools/pypi.py#L49-L58
def get_relevant_versions(self, package_name: str): """Return a tuple: (latest release, latest stable) If there are different, it means the latest is not a stable """ versions = self.get_ordered_versions(package_name) pre_releases = [version for version in versions if not version...
[ "def", "get_relevant_versions", "(", "self", ",", "package_name", ":", "str", ")", ":", "versions", "=", "self", ".", "get_ordered_versions", "(", "package_name", ")", "pre_releases", "=", "[", "version", "for", "version", "in", "versions", "if", "not", "versi...
Return a tuple: (latest release, latest stable) If there are different, it means the latest is not a stable
[ "Return", "a", "tuple", ":", "(", "latest", "release", "latest", "stable", ")", "If", "there", "are", "different", "it", "means", "the", "latest", "is", "not", "a", "stable" ]
python
test
40.8
inasafe/inasafe
safe/report/expressions/infographic.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/infographic.py#L152-L164
def infographic_header_element(impact_function_name, feature, parent): """Get a formatted infographic header sentence for an impact function. For instance: * infographic_header_element('flood') -> 'Estimated impact of a flood' """ _ = feature, parent # NOQA string_format = infographic_header['...
[ "def", "infographic_header_element", "(", "impact_function_name", ",", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "string_format", "=", "infographic_header", "[", "'string_format'", "]", "if", "impact_function_name", ":", "head...
Get a formatted infographic header sentence for an impact function. For instance: * infographic_header_element('flood') -> 'Estimated impact of a flood'
[ "Get", "a", "formatted", "infographic", "header", "sentence", "for", "an", "impact", "function", "." ]
python
train
38.230769
sixty-north/cosmic-ray
src/cosmic_ray/cloning.py
https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/cloning.py#L117-L125
def clone_with_git(repo_uri, dest_path): """Create a clone by cloning a git repository. Args: repo_uri: The URI of the git repository to clone. dest_path: The location to clone to. """ log.info('Cloning git repo %s to %s', repo_uri, dest_path) git.Repo.clone_from(repo_uri, dest_path...
[ "def", "clone_with_git", "(", "repo_uri", ",", "dest_path", ")", ":", "log", ".", "info", "(", "'Cloning git repo %s to %s'", ",", "repo_uri", ",", "dest_path", ")", "git", ".", "Repo", ".", "clone_from", "(", "repo_uri", ",", "dest_path", ",", "depth", "=",...
Create a clone by cloning a git repository. Args: repo_uri: The URI of the git repository to clone. dest_path: The location to clone to.
[ "Create", "a", "clone", "by", "cloning", "a", "git", "repository", "." ]
python
train
35.777778
ARMmbed/yotta
yotta/lib/registry_access.py
https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/registry_access.py#L139-L159
def _handleAuth(fn): ''' Decorator to re-try API calls after asking the user for authentication. ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # auth, , authenticate users, internal from yotta.lib import auth # if yotta is being run noninteractively, then we never retry, but...
[ "def", "_handleAuth", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# auth, , authenticate users, internal", "from", "yotta", ".", "lib", "import", "auth", "# ...
Decorator to re-try API calls after asking the user for authentication.
[ "Decorator", "to", "re", "-", "try", "API", "calls", "after", "asking", "the", "user", "for", "authentication", "." ]
python
valid
47.904762
trec-kba/streamcorpus-pipeline
streamcorpus_pipeline/_pipeline.py
https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/_pipeline.py#L326-L350
def _init_stages(self, config, name): '''Create a list of indirect stages. `name` should be the name of a config item that holds a list of names of stages, for instance, ``writers``. This looks up the names of those stages, then creates and returns the corresponding list of sta...
[ "def", "_init_stages", "(", "self", ",", "config", ",", "name", ")", ":", "if", "name", "not", "in", "config", ":", "return", "[", "]", "return", "[", "self", ".", "create", "(", "stage", ",", "config", ")", "for", "stage", "in", "config", "[", "na...
Create a list of indirect stages. `name` should be the name of a config item that holds a list of names of stages, for instance, ``writers``. This looks up the names of those stages, then creates and returns the corresponding list of stage objects. For instance, if the config ...
[ "Create", "a", "list", "of", "indirect", "stages", "." ]
python
test
36.32
inveniosoftware/invenio-communities
invenio_communities/serializers/schemas/community.py
https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/serializers/schemas/community.py#L67-L90
def envelope(self, data, many): """Wrap result in envelope.""" if not many: return data result = dict( hits=dict( hits=data, total=self.context.get('total', len(data)) ) ) page = self.context.get('page') ...
[ "def", "envelope", "(", "self", ",", "data", ",", "many", ")", ":", "if", "not", "many", ":", "return", "data", "result", "=", "dict", "(", "hits", "=", "dict", "(", "hits", "=", "data", ",", "total", "=", "self", ".", "context", ".", "get", "(",...
Wrap result in envelope.
[ "Wrap", "result", "in", "envelope", "." ]
python
train
26.083333
pyviz/holoviews
holoviews/plotting/bokeh/plot.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/plot.py#L273-L290
def _update_callbacks(self, plot): """ Iterates over all subplots and updates existing CustomJS callbacks with models that were replaced when compositing subplots into a CompositePlot and sets the plot id to match the root level bokeh model. """ subplots = self.tr...
[ "def", "_update_callbacks", "(", "self", ",", "plot", ")", ":", "subplots", "=", "self", ".", "traverse", "(", "lambda", "x", ":", "x", ",", "[", "GenericElementPlot", "]", ")", "merged_tools", "=", "{", "t", ":", "list", "(", "plot", ".", "select", ...
Iterates over all subplots and updates existing CustomJS callbacks with models that were replaced when compositing subplots into a CompositePlot and sets the plot id to match the root level bokeh model.
[ "Iterates", "over", "all", "subplots", "and", "updates", "existing", "CustomJS", "callbacks", "with", "models", "that", "were", "replaced", "when", "compositing", "subplots", "into", "a", "CompositePlot", "and", "sets", "the", "plot", "id", "to", "match", "the",...
python
train
47.888889
numenta/nupic
src/nupic/encoders/category.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/category.py#L137-L169
def decode(self, encoded, parentFieldName=''): """ See the function description in base.py """ # Get the scalar values from the underlying scalar encoder (fieldsDict, fieldNames) = self.encoder.decode(encoded) if len(fieldsDict) == 0: return (fieldsDict, fieldNames) # Expect only 1 field...
[ "def", "decode", "(", "self", ",", "encoded", ",", "parentFieldName", "=", "''", ")", ":", "# Get the scalar values from the underlying scalar encoder", "(", "fieldsDict", ",", "fieldNames", ")", "=", "self", ".", "encoder", ".", "decode", "(", "encoded", ")", "...
See the function description in base.py
[ "See", "the", "function", "description", "in", "base", ".", "py" ]
python
valid
30.333333
adamheins/r12
r12/arm.py
https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/arm.py#L136-L157
def read(self, timeout=READ_TIMEOUT, raw=False): ''' Read data from the arm. Data is returned as a latin_1 encoded string, or raw bytes if 'raw' is True. ''' time.sleep(READ_SLEEP_TIME) raw_out = self.ser.read(self.ser.in_waiting) out = raw_out.decode(OUTPUT_ENCODING) ...
[ "def", "read", "(", "self", ",", "timeout", "=", "READ_TIMEOUT", ",", "raw", "=", "False", ")", ":", "time", ".", "sleep", "(", "READ_SLEEP_TIME", ")", "raw_out", "=", "self", ".", "ser", ".", "read", "(", "self", ".", "ser", ".", "in_waiting", ")", ...
Read data from the arm. Data is returned as a latin_1 encoded string, or raw bytes if 'raw' is True.
[ "Read", "data", "from", "the", "arm", ".", "Data", "is", "returned", "as", "a", "latin_1", "encoded", "string", "or", "raw", "bytes", "if", "raw", "is", "True", "." ]
python
train
36.681818
openvax/isovar
isovar/protein_sequences.py
https://github.com/openvax/isovar/blob/b39b684920e3f6b344851d6598a1a1c67bce913b/isovar/protein_sequences.py#L192-L311
def reads_generator_to_protein_sequences_generator( variant_and_overlapping_reads_generator, transcript_id_whitelist=None, protein_sequence_length=PROTEIN_SEQUENCE_LENGTH, min_alt_rna_reads=MIN_ALT_RNA_READS, min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE, mi...
[ "def", "reads_generator_to_protein_sequences_generator", "(", "variant_and_overlapping_reads_generator", ",", "transcript_id_whitelist", "=", "None", ",", "protein_sequence_length", "=", "PROTEIN_SEQUENCE_LENGTH", ",", "min_alt_rna_reads", "=", "MIN_ALT_RNA_READS", ",", "min_varian...
Translates each coding variant in a collection to one or more Translation objects, which are then aggregated into equivalent ProteinSequence objects. Parameters ---------- variant_and_overlapping_reads_generator : generator Yields sequence of varcode.Variant objects paired with sequences ...
[ "Translates", "each", "coding", "variant", "in", "a", "collection", "to", "one", "or", "more", "Translation", "objects", "which", "are", "then", "aggregated", "into", "equivalent", "ProteinSequence", "objects", "." ]
python
train
44.833333
glormph/msstitch
src/app/actions/mslookup/spectra.py
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mslookup/spectra.py#L4-L19
def create_spectra_lookup(lookup, fn_spectra): """Stores all spectra rt, injection time, and scan nr in db""" to_store = [] mzmlmap = lookup.get_mzmlfile_map() for fn, spectrum in fn_spectra: spec_id = '{}_{}'.format(mzmlmap[fn], spectrum['scan']) mzml_rt = round(float(spectrum['rt']), 1...
[ "def", "create_spectra_lookup", "(", "lookup", ",", "fn_spectra", ")", ":", "to_store", "=", "[", "]", "mzmlmap", "=", "lookup", ".", "get_mzmlfile_map", "(", ")", "for", "fn", ",", "spectrum", "in", "fn_spectra", ":", "spec_id", "=", "'{}_{}'", ".", "form...
Stores all spectra rt, injection time, and scan nr in db
[ "Stores", "all", "spectra", "rt", "injection", "time", "and", "scan", "nr", "in", "db" ]
python
train
43.5625
StyXman/ayrton
ayrton/remote.py
https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/remote.py#L172-L180
def param (self, param, kwargs, default_value=False): """gets a param from kwargs, or uses a default_value. if found, it's removed from kwargs""" if param in kwargs: value= kwargs[param] del kwargs[param] else: value= default_value setattr (sel...
[ "def", "param", "(", "self", ",", "param", ",", "kwargs", ",", "default_value", "=", "False", ")", ":", "if", "param", "in", "kwargs", ":", "value", "=", "kwargs", "[", "param", "]", "del", "kwargs", "[", "param", "]", "else", ":", "value", "=", "d...
gets a param from kwargs, or uses a default_value. if found, it's removed from kwargs
[ "gets", "a", "param", "from", "kwargs", "or", "uses", "a", "default_value", ".", "if", "found", "it", "s", "removed", "from", "kwargs" ]
python
train
36.444444
mretegan/crispy
crispy/gui/quanty.py
https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/quanty.py#L754-L899
def populateWidget(self): """ Populate the widget using data stored in the state object. The order in which the individual widgets are populated follows their arrangment. The models are recreated every time the function is called. This might seem to be an overkill, but i...
[ "def", "populateWidget", "(", "self", ")", ":", "self", ".", "elementComboBox", ".", "setItems", "(", "self", ".", "state", ".", "_elements", ",", "self", ".", "state", ".", "element", ")", "self", ".", "chargeComboBox", ".", "setItems", "(", "self", "."...
Populate the widget using data stored in the state object. The order in which the individual widgets are populated follows their arrangment. The models are recreated every time the function is called. This might seem to be an overkill, but in practice it is very fast. Don't try ...
[ "Populate", "the", "widget", "using", "data", "stored", "in", "the", "state", "object", ".", "The", "order", "in", "which", "the", "individual", "widgets", "are", "populated", "follows", "their", "arrangment", "." ]
python
train
48.027397
4degrees/riffle
source/riffle/browser.py
https://github.com/4degrees/riffle/blob/e5a0d908df8c93ff1ee7abdda8875fd1667df53d/source/riffle/browser.py#L124-L130
def _configureShortcuts(self): '''Add keyboard shortcuts to navigate the filesystem.''' self._upShortcut = QtGui.QShortcut( QtGui.QKeySequence('Backspace'), self ) self._upShortcut.setAutoRepeat(False) self._upShortcut.activated.connect(self._onNavigateUpButtonClicked...
[ "def", "_configureShortcuts", "(", "self", ")", ":", "self", ".", "_upShortcut", "=", "QtGui", ".", "QShortcut", "(", "QtGui", ".", "QKeySequence", "(", "'Backspace'", ")", ",", "self", ")", "self", ".", "_upShortcut", ".", "setAutoRepeat", "(", "False", "...
Add keyboard shortcuts to navigate the filesystem.
[ "Add", "keyboard", "shortcuts", "to", "navigate", "the", "filesystem", "." ]
python
test
45
ciena/afkak
afkak/consumer.py
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/consumer.py#L983-L992
def _commit_timer_stopped(self, lCall): """We're shutting down, clean up our looping call...""" if self._commit_looper is not lCall: log.warning('_commit_timer_stopped with wrong timer:%s not:%s', lCall, self._commit_looper) else: log.debug('_commi...
[ "def", "_commit_timer_stopped", "(", "self", ",", "lCall", ")", ":", "if", "self", ".", "_commit_looper", "is", "not", "lCall", ":", "log", ".", "warning", "(", "'_commit_timer_stopped with wrong timer:%s not:%s'", ",", "lCall", ",", "self", ".", "_commit_looper",...
We're shutting down, clean up our looping call...
[ "We", "re", "shutting", "down", "clean", "up", "our", "looping", "call", "..." ]
python
train
46.5
ssalentin/plip
plip/modules/detection.py
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/detection.py#L159-L208
def pication(rings, pos_charged, protcharged): """Return all pi-Cation interaction between aromatic rings and positively charged groups. For tertiary and quaternary amines, check also the angle between the ring and the nitrogen. """ data = namedtuple( 'pication', 'ring charge distance offset typ...
[ "def", "pication", "(", "rings", ",", "pos_charged", ",", "protcharged", ")", ":", "data", "=", "namedtuple", "(", "'pication'", ",", "'ring charge distance offset type restype resnr reschain restype_l resnr_l reschain_l protcharged'", ")", "pairings", "=", "[", "]", "if"...
Return all pi-Cation interaction between aromatic rings and positively charged groups. For tertiary and quaternary amines, check also the angle between the ring and the nitrogen.
[ "Return", "all", "pi", "-", "Cation", "interaction", "between", "aromatic", "rings", "and", "positively", "charged", "groups", ".", "For", "tertiary", "and", "quaternary", "amines", "check", "also", "the", "angle", "between", "the", "ring", "and", "the", "nitr...
python
train
68.04
tanghaibao/jcvi
jcvi/assembly/automaton.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/automaton.py#L403-L422
def soapX(args): """ %prog soapX folder tag [*.fastq] Run SOAP on a folder of paired reads and apply tag before assembly. Optional *.fastq in the argument list will be symlinked in each folder and co-assembled. """ p = OptionParser(soapX.__doc__) opts, args = p.parse_args(args) if ...
[ "def", "soapX", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "soapX", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "<", "2", ":", "sys", ".", "exit", "(", "not"...
%prog soapX folder tag [*.fastq] Run SOAP on a folder of paired reads and apply tag before assembly. Optional *.fastq in the argument list will be symlinked in each folder and co-assembled.
[ "%prog", "soapX", "folder", "tag", "[", "*", ".", "fastq", "]" ]
python
train
27.65
chrislit/abydos
abydos/stemmer/_porter.py
https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_porter.py#L139-L371
def stem(self, word, early_english=False): """Return Porter stem. Parameters ---------- word : str The word to stem early_english : bool Set to True in order to remove -eth & -est (2nd & 3rd person singular verbal agreement suffixes) ...
[ "def", "stem", "(", "self", ",", "word", ",", "early_english", "=", "False", ")", ":", "# lowercase, normalize, and compose", "word", "=", "normalize", "(", "'NFC'", ",", "text_type", "(", "word", ".", "lower", "(", ")", ")", ")", "# Return word if stem is sho...
Return Porter stem. Parameters ---------- word : str The word to stem early_english : bool Set to True in order to remove -eth & -est (2nd & 3rd person singular verbal agreement suffixes) Returns ------- str Word s...
[ "Return", "Porter", "stem", "." ]
python
valid
34.283262
uw-it-aca/uw-restclients-canvas
uw_canvas/reports.py
https://github.com/uw-it-aca/uw-restclients-canvas/blob/9845faf33d49a8f06908efc22640c001116d6ea2/uw_canvas/reports.py#L149-L164
def get_report_status(self, report): """ Returns the status of a report. https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.show """ if (report.account_id is None or report.type is None or report.report_id is None): rai...
[ "def", "get_report_status", "(", "self", ",", "report", ")", ":", "if", "(", "report", ".", "account_id", "is", "None", "or", "report", ".", "type", "is", "None", "or", "report", ".", "report_id", "is", "None", ")", ":", "raise", "ReportFailureException", ...
Returns the status of a report. https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.show
[ "Returns", "the", "status", "of", "a", "report", "." ]
python
test
36.375
aio-libs/aiodocker
aiodocker/services.py
https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/services.py#L152-L166
async def delete(self, service_id: str) -> bool: """ Remove a service Args: service_id: ID or name of the service Returns: True if successful """ await self.docker._query( "services/{service_id}".format(service_id=service_id), method...
[ "async", "def", "delete", "(", "self", ",", "service_id", ":", "str", ")", "->", "bool", ":", "await", "self", ".", "docker", ".", "_query", "(", "\"services/{service_id}\"", ".", "format", "(", "service_id", "=", "service_id", ")", ",", "method", "=", "...
Remove a service Args: service_id: ID or name of the service Returns: True if successful
[ "Remove", "a", "service" ]
python
train
23
pydata/pandas-gbq
pandas_gbq/schema.py
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/schema.py#L38-L64
def update_schema(schema_old, schema_new): """ Given an old BigQuery schema, update it with a new one. Where a field name is the same, the new will replace the old. Any new fields not present in the old schema will be added. Arguments: schema_old: the old schema to update schema_ne...
[ "def", "update_schema", "(", "schema_old", ",", "schema_new", ")", ":", "old_fields", "=", "schema_old", "[", "\"fields\"", "]", "new_fields", "=", "schema_new", "[", "\"fields\"", "]", "output_fields", "=", "list", "(", "old_fields", ")", "field_indices", "=", ...
Given an old BigQuery schema, update it with a new one. Where a field name is the same, the new will replace the old. Any new fields not present in the old schema will be added. Arguments: schema_old: the old schema to update schema_new: the new schema which will overwrite/extend the old
[ "Given", "an", "old", "BigQuery", "schema", "update", "it", "with", "a", "new", "one", "." ]
python
train
32.481481
ourway/auth
auth/CAS/authorization.py
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L85-L92
def add_role(self, role, description=None): """ Creates a new group """ new_group = AuthGroup(role=role, creator=self.client) try: new_group.save() return True except NotUniqueError: return False
[ "def", "add_role", "(", "self", ",", "role", ",", "description", "=", "None", ")", ":", "new_group", "=", "AuthGroup", "(", "role", "=", "role", ",", "creator", "=", "self", ".", "client", ")", "try", ":", "new_group", ".", "save", "(", ")", "return"...
Creates a new group
[ "Creates", "a", "new", "group" ]
python
train
32
iancmcc/ouimeaux
ouimeaux/subscribe.py
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/subscribe.py#L95-L103
def server(self): """ UDP server to listen for responses. """ server = getattr(self, "_server", None) if server is None: server = WSGIServer(('', self.port), self._handle, log=None) self._server = server return server
[ "def", "server", "(", "self", ")", ":", "server", "=", "getattr", "(", "self", ",", "\"_server\"", ",", "None", ")", "if", "server", "is", "None", ":", "server", "=", "WSGIServer", "(", "(", "''", ",", "self", ".", "port", ")", ",", "self", ".", ...
UDP server to listen for responses.
[ "UDP", "server", "to", "listen", "for", "responses", "." ]
python
train
31.222222
materialsproject/pymatgen
pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py#L634-L641
def is_in_plane(self, pp, dist_tolerance): """ Determines if point pp is in the plane within the tolerance dist_tolerance :param pp: point to be tested :param dist_tolerance: tolerance on the distance to the plane within which point pp is considered in the plane :return: True if ...
[ "def", "is_in_plane", "(", "self", ",", "pp", ",", "dist_tolerance", ")", ":", "return", "np", ".", "abs", "(", "np", ".", "dot", "(", "self", ".", "normal_vector", ",", "pp", ")", "+", "self", ".", "_coefficients", "[", "3", "]", ")", "<=", "dist_...
Determines if point pp is in the plane within the tolerance dist_tolerance :param pp: point to be tested :param dist_tolerance: tolerance on the distance to the plane within which point pp is considered in the plane :return: True if pp is in the plane, False otherwise
[ "Determines", "if", "point", "pp", "is", "in", "the", "plane", "within", "the", "tolerance", "dist_tolerance", ":", "param", "pp", ":", "point", "to", "be", "tested", ":", "param", "dist_tolerance", ":", "tolerance", "on", "the", "distance", "to", "the", "...
python
train
57
dw/mitogen
mitogen/core.py
https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/core.py#L2882-L2893
def start_receive(self, stream): """ Mark the :attr:`receive_side <Stream.receive_side>` on `stream` as ready for reading. Safe to call from any thread. When the associated file descriptor becomes ready for reading, :meth:`BasicStream.on_receive` will be called. """ ...
[ "def", "start_receive", "(", "self", ",", "stream", ")", ":", "_vv", "and", "IOLOG", ".", "debug", "(", "'%r.start_receive(%r)'", ",", "self", ",", "stream", ")", "side", "=", "stream", ".", "receive_side", "assert", "side", "and", "side", ".", "fd", "is...
Mark the :attr:`receive_side <Stream.receive_side>` on `stream` as ready for reading. Safe to call from any thread. When the associated file descriptor becomes ready for reading, :meth:`BasicStream.on_receive` will be called.
[ "Mark", "the", ":", "attr", ":", "receive_side", "<Stream", ".", "receive_side", ">", "on", "stream", "as", "ready", "for", "reading", ".", "Safe", "to", "call", "from", "any", "thread", ".", "When", "the", "associated", "file", "descriptor", "becomes", "r...
python
train
45.75
cedrus-opensource/pyxid
pyxid/__init__.py
https://github.com/cedrus-opensource/pyxid/blob/02dba3a825f0d4f4c0bfa044c6a361492e4c25b6/pyxid/__init__.py#L14-L25
def get_xid_devices(): """ Returns a list of all Xid devices connected to your computer. """ devices = [] scanner = XidScanner() for i in range(scanner.device_count()): com = scanner.device_at_index(i) com.open() device = XidDevice(com) devices.append(device) ...
[ "def", "get_xid_devices", "(", ")", ":", "devices", "=", "[", "]", "scanner", "=", "XidScanner", "(", ")", "for", "i", "in", "range", "(", "scanner", ".", "device_count", "(", ")", ")", ":", "com", "=", "scanner", ".", "device_at_index", "(", "i", ")...
Returns a list of all Xid devices connected to your computer.
[ "Returns", "a", "list", "of", "all", "Xid", "devices", "connected", "to", "your", "computer", "." ]
python
train
26.916667
oceanprotocol/squid-py
squid_py/ocean/ocean_services.py
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_services.py#L12-L27
def create_access_service(price, service_endpoint, consume_endpoint, timeout=None): """ Publish an asset with an `Access` service according to the supplied attributes. :param price: Asset price, int :param service_endpoint: str URL for initiating service access request :param co...
[ "def", "create_access_service", "(", "price", ",", "service_endpoint", ",", "consume_endpoint", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "or", "3600", "# default to one hour timeout", "service", "=", "ServiceDescriptor", ".", "access_service_d...
Publish an asset with an `Access` service according to the supplied attributes. :param price: Asset price, int :param service_endpoint: str URL for initiating service access request :param consume_endpoint: str URL to consume service :param timeout: int amount of time in seconds before ...
[ "Publish", "an", "asset", "with", "an", "Access", "service", "according", "to", "the", "supplied", "attributes", "." ]
python
train
44.5625
senaite/senaite.core
bika/lims/content/worksheet.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/worksheet.py#L1277-L1298
def setMethod(self, method, override_analyses=False): """ Sets the specified method to the Analyses from the Worksheet. Only sets the method if the Analysis allows to keep the integrity. If an analysis has already been assigned to a method, it won't be overriden. ...
[ "def", "setMethod", "(", "self", ",", "method", ",", "override_analyses", "=", "False", ")", ":", "analyses", "=", "[", "an", "for", "an", "in", "self", ".", "getAnalyses", "(", ")", "if", "(", "not", "an", ".", "getMethod", "(", ")", "or", "not", ...
Sets the specified method to the Analyses from the Worksheet. Only sets the method if the Analysis allows to keep the integrity. If an analysis has already been assigned to a method, it won't be overriden. Returns the number of analyses affected.
[ "Sets", "the", "specified", "method", "to", "the", "Analyses", "from", "the", "Worksheet", ".", "Only", "sets", "the", "method", "if", "the", "Analysis", "allows", "to", "keep", "the", "integrity", ".", "If", "an", "analysis", "has", "already", "been", "as...
python
train
40.045455
LionelR/pyair
pyair/xair.py
https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/xair.py#L640-L659
def get_sqltext(self, format_=1): """retourne les requêtes actuellement lancées sur le serveur""" if format_ == 1: _sql = """SELECT u.sid, substr(u.username,1,12) user_name, s.sql_text FROM v$sql s,v$session u WHERE s.hash_value = u.sql_hash_value AND sql...
[ "def", "get_sqltext", "(", "self", ",", "format_", "=", "1", ")", ":", "if", "format_", "==", "1", ":", "_sql", "=", "\"\"\"SELECT u.sid, substr(u.username,1,12) user_name, s.sql_text\n FROM v$sql s,v$session u\n WHERE s.hash_value = u.sql_hash_value\n ...
retourne les requêtes actuellement lancées sur le serveur
[ "retourne", "les", "requêtes", "actuellement", "lancées", "sur", "le", "serveur" ]
python
valid
40.65
CityOfZion/neo-python-core
neocore/IO/BinaryWriter.py
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L341-L356
def WriteVarBytes(self, value, endian="<"): """ Write an integer value in a space saving way to the stream. Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention Args: value (bytes): endian (str): specify the...
[ "def", "WriteVarBytes", "(", "self", ",", "value", ",", "endian", "=", "\"<\"", ")", ":", "length", "=", "len", "(", "value", ")", "self", ".", "WriteVarInt", "(", "length", ",", "endian", ")", "return", "self", ".", "WriteBytes", "(", "value", ",", ...
Write an integer value in a space saving way to the stream. Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention Args: value (bytes): endian (str): specify the endianness. (Default) Little endian ('<'). Use '>' for big endi...
[ "Write", "an", "integer", "value", "in", "a", "space", "saving", "way", "to", "the", "stream", ".", "Read", "more", "about", "variable", "size", "encoding", "here", ":", "http", ":", "//", "docs", ".", "neo", ".", "org", "/", "en", "-", "us", "/", ...
python
train
35.5625
google/grr
grr/server/grr_response_server/file_store.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/file_store.py#L147-L171
def Read(self, length=None): """Reads data.""" if length is None: length = self._length - self._offset if length > self._max_unbound_read: raise OversizedReadError("Attempted to read %d bytes when " "Server.max_unbound_read_size is %d" % ...
[ "def", "Read", "(", "self", ",", "length", "=", "None", ")", ":", "if", "length", "is", "None", ":", "length", "=", "self", ".", "_length", "-", "self", ".", "_offset", "if", "length", ">", "self", ".", "_max_unbound_read", ":", "raise", "OversizedRead...
Reads data.
[ "Reads", "data", "." ]
python
train
26.28
anttttti/Wordbatch
wordbatch/batcher.py
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/batcher.py#L77-L102
def split_batches(self, data, minibatch_size= None): """Split data into minibatches with a specified size Parameters ---------- data: iterable and indexable List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames. minibatch_size: int Expected sizes of minibatc...
[ "def", "split_batches", "(", "self", ",", "data", ",", "minibatch_size", "=", "None", ")", ":", "if", "minibatch_size", "==", "None", ":", "minibatch_size", "=", "self", ".", "minibatch_size", "if", "isinstance", "(", "data", ",", "list", ")", "or", "isins...
Split data into minibatches with a specified size Parameters ---------- data: iterable and indexable List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames. minibatch_size: int Expected sizes of minibatches split from the data. Returns ------- data_split...
[ "Split", "data", "into", "minibatches", "with", "a", "specified", "size" ]
python
train
37.269231
hydpy-dev/hydpy
hydpy/core/hydpytools.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/hydpytools.py#L517-L528
def endnodes(self): """|Nodes| object containing all |Node| objects currently handled by the |HydPy| object which define a downstream end point of a network.""" endnodes = devicetools.Nodes() for node in self.nodes: for element in node.exits: if ((element in s...
[ "def", "endnodes", "(", "self", ")", ":", "endnodes", "=", "devicetools", ".", "Nodes", "(", ")", "for", "node", "in", "self", ".", "nodes", ":", "for", "element", "in", "node", ".", "exits", ":", "if", "(", "(", "element", "in", "self", ".", "elem...
|Nodes| object containing all |Node| objects currently handled by the |HydPy| object which define a downstream end point of a network.
[ "|Nodes|", "object", "containing", "all", "|Node|", "objects", "currently", "handled", "by", "the", "|HydPy|", "object", "which", "define", "a", "downstream", "end", "point", "of", "a", "network", "." ]
python
train
40.416667
jay-johnson/spylunking
spylunking/mp_splunk_publisher.py
https://github.com/jay-johnson/spylunking/blob/95cc86776f04ec5935cf04e291cf18798345d6cb/spylunking/mp_splunk_publisher.py#L261-L290
def start_worker( self): """start_worker Start the helper worker process to package queued messages and send them to Splunk """ # Start a worker thread responsible for sending logs if not self.is_shutting_down(shutdown_event=self.shutdown_event) \ ...
[ "def", "start_worker", "(", "self", ")", ":", "# Start a worker thread responsible for sending logs", "if", "not", "self", ".", "is_shutting_down", "(", "shutdown_event", "=", "self", ".", "shutdown_event", ")", "and", "self", ".", "sleep_interval", ">", "0.1", ":",...
start_worker Start the helper worker process to package queued messages and send them to Splunk
[ "start_worker" ]
python
train
35.8
openstack/proliantutils
proliantutils/ilo/common.py
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/common.py#L184-L192
def get_filename_and_extension_of(target_file): """Gets the base filename and extension of the target file. :param target_file: the complete path of the target file :returns: base filename and extension """ base_target_filename = os.path.basename(target_file) file_name, file_ext_with_dot = os.p...
[ "def", "get_filename_and_extension_of", "(", "target_file", ")", ":", "base_target_filename", "=", "os", ".", "path", ".", "basename", "(", "target_file", ")", "file_name", ",", "file_ext_with_dot", "=", "os", ".", "path", ".", "splitext", "(", "base_target_filena...
Gets the base filename and extension of the target file. :param target_file: the complete path of the target file :returns: base filename and extension
[ "Gets", "the", "base", "filename", "and", "extension", "of", "the", "target", "file", "." ]
python
train
42.888889
mdgoldberg/sportsref
sportsref/nba/seasons.py
https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nba/seasons.py#L99-L142
def schedule(self, kind='R'): """Returns a list of BoxScore IDs for every game in the season. Only needs to handle 'R' or 'P' options because decorator handles 'B'. :param kind: 'R' for regular season, 'P' for playoffs, 'B' for both. Defaults to 'R'. :returns: DataFrame of s...
[ "def", "schedule", "(", "self", ",", "kind", "=", "'R'", ")", ":", "kind", "=", "kind", ".", "upper", "(", ")", "[", "0", "]", "dfs", "=", "[", "]", "# get games from each month", "for", "month", "in", "(", "'october'", ",", "'november'", ",", "'dece...
Returns a list of BoxScore IDs for every game in the season. Only needs to handle 'R' or 'P' options because decorator handles 'B'. :param kind: 'R' for regular season, 'P' for playoffs, 'B' for both. Defaults to 'R'. :returns: DataFrame of schedule information. :rtype: pd.D...
[ "Returns", "a", "list", "of", "BoxScore", "IDs", "for", "every", "game", "in", "the", "season", ".", "Only", "needs", "to", "handle", "R", "or", "P", "options", "because", "decorator", "handles", "B", "." ]
python
test
34.568182
LonamiWebs/Telethon
telethon/network/mtprotosender.py
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/network/mtprotosender.py#L282-L332
async def _reconnect(self, last_error): """ Cleanly disconnects and then reconnects. """ self._log.debug('Closing current connection...') await self._connection.disconnect() await helpers._cancel( self._log, send_loop_handle=self._send_loop_handle...
[ "async", "def", "_reconnect", "(", "self", ",", "last_error", ")", ":", "self", ".", "_log", ".", "debug", "(", "'Closing current connection...'", ")", "await", "self", ".", "_connection", ".", "disconnect", "(", ")", "await", "helpers", ".", "_cancel", "(",...
Cleanly disconnects and then reconnects.
[ "Cleanly", "disconnects", "and", "then", "reconnects", "." ]
python
train
38.058824
PredixDev/predixpy
predix/admin/service.py
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/service.py#L36-L45
def _get_config_path(self): """ Return a sensible configuration path for caching config settings. """ org = self.service.space.org.name space = self.service.space.name name = self.name return "~/.predix/%s/%s/%s.json" % (org, space, name)
[ "def", "_get_config_path", "(", "self", ")", ":", "org", "=", "self", ".", "service", ".", "space", ".", "org", ".", "name", "space", "=", "self", ".", "service", ".", "space", ".", "name", "name", "=", "self", ".", "name", "return", "\"~/.predix/%s/%s...
Return a sensible configuration path for caching config settings.
[ "Return", "a", "sensible", "configuration", "path", "for", "caching", "config", "settings", "." ]
python
train
29.4
juju/charm-helpers
charmhelpers/contrib/openstack/audits/__init__.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/__init__.py#L60-L72
def is_audit_type(*args): """This audit is included in the specified kinds of audits. :param *args: List of AuditTypes to include this audit in :type args: List[AuditType] :rtype: Callable[Dict] """ def _is_audit_type(audit_options): if audit_options.get('audit_type') in args: ...
[ "def", "is_audit_type", "(", "*", "args", ")", ":", "def", "_is_audit_type", "(", "audit_options", ")", ":", "if", "audit_options", ".", "get", "(", "'audit_type'", ")", "in", "args", ":", "return", "True", "else", ":", "return", "False", "return", "_is_au...
This audit is included in the specified kinds of audits. :param *args: List of AuditTypes to include this audit in :type args: List[AuditType] :rtype: Callable[Dict]
[ "This", "audit", "is", "included", "in", "the", "specified", "kinds", "of", "audits", "." ]
python
train
29.769231
aganezov/bg
bg/breakpoint_graph.py
https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/breakpoint_graph.py#L844-L855
def to_json(self, schema_info=True): """ JSON serialization method that account for all information-wise important part of breakpoint graph """ genomes = set() result = {} result["edges"] = [] for bgedge in self.edges(): genomes |= bgedge.multicolor.colors ...
[ "def", "to_json", "(", "self", ",", "schema_info", "=", "True", ")", ":", "genomes", "=", "set", "(", ")", "result", "=", "{", "}", "result", "[", "\"edges\"", "]", "=", "[", "]", "for", "bgedge", "in", "self", ".", "edges", "(", ")", ":", "genom...
JSON serialization method that account for all information-wise important part of breakpoint graph
[ "JSON", "serialization", "method", "that", "account", "for", "all", "information", "-", "wise", "important", "part", "of", "breakpoint", "graph" ]
python
train
50.083333
klmitch/framer
framer/framers.py
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/framers.py#L363-L400
def to_frame(self, data, state): """ Extract a single frame from the data buffer. The consumed data should be removed from the buffer. If no complete frame can be read, must raise a ``NoFrames`` exception. :param data: A ``bytearray`` instance containing the data so ...
[ "def", "to_frame", "(", "self", ",", "data", ",", "state", ")", ":", "# Find the next newline", "data_len", "=", "data", ".", "find", "(", "b'\\n'", ")", "if", "data_len", "<", "0", ":", "# No line to extract", "raise", "exc", ".", "NoFrames", "(", ")", ...
Extract a single frame from the data buffer. The consumed data should be removed from the buffer. If no complete frame can be read, must raise a ``NoFrames`` exception. :param data: A ``bytearray`` instance containing the data so far read. :param state: An instanc...
[ "Extract", "a", "single", "frame", "from", "the", "data", "buffer", ".", "The", "consumed", "data", "should", "be", "removed", "from", "the", "buffer", ".", "If", "no", "complete", "frame", "can", "be", "read", "must", "raise", "a", "NoFrames", "exception"...
python
train
32.947368
Unidata/siphon
siphon/radarserver.py
https://github.com/Unidata/siphon/blob/53fb0d84fbce1c18c8e81c9e68bc81620ee0a6ac/siphon/radarserver.py#L101-L127
def validate_query(self, query): """Validate a query. Determines whether `query` is well-formed. This includes checking for all required parameters, as well as checking parameters for valid values. Parameters ---------- query : RadarQuery The query to valida...
[ "def", "validate_query", "(", "self", ",", "query", ")", ":", "valid", "=", "True", "# Make sure all stations are in the table", "if", "'stn'", "in", "query", ".", "spatial_query", ":", "valid", "=", "valid", "and", "all", "(", "stid", "in", "self", ".", "st...
Validate a query. Determines whether `query` is well-formed. This includes checking for all required parameters, as well as checking parameters for valid values. Parameters ---------- query : RadarQuery The query to validate Returns ------- ...
[ "Validate", "a", "query", "." ]
python
train
28.37037
limodou/uliweb
uliweb/orm/__init__.py
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L916-L932
def set_model_config(model_name, config, replace=False): """ This function should be only used in initialization phrase :param model_name: model name it's should be string :param config: config should be dict. e.g. {'__mapping_only__', '__tablename__', '__ext_model__'} :param replace: if Tru...
[ "def", "set_model_config", "(", "model_name", ",", "config", ",", "replace", "=", "False", ")", ":", "assert", "isinstance", "(", "model_name", ",", "str", ")", "assert", "isinstance", "(", "config", ",", "dict", ")", "d", "=", "__models__", ".", "setdefau...
This function should be only used in initialization phrase :param model_name: model name it's should be string :param config: config should be dict. e.g. {'__mapping_only__', '__tablename__', '__ext_model__'} :param replace: if True, then replace original config, False will update
[ "This", "function", "should", "be", "only", "used", "in", "initialization", "phrase", ":", "param", "model_name", ":", "model", "name", "it", "s", "should", "be", "string", ":", "param", "config", ":", "config", "should", "be", "dict", ".", "e", ".", "g"...
python
train
35.705882
rm-hull/luma.core
luma/core/ansi_color.py
https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/ansi_color.py#L41-L74
def parse_str(text): """ Given a string of characters, for each normal ASCII character, yields a directive consisting of a 'putch' instruction followed by the character itself. If a valid ANSI escape sequence is detected within the string, the supported codes are translated into directives. For...
[ "def", "parse_str", "(", "text", ")", ":", "prog", "=", "re", ".", "compile", "(", "r'^\\033\\[(\\d+(;\\d+)*)m'", ",", "re", ".", "UNICODE", ")", "while", "text", "!=", "\"\"", ":", "result", "=", "prog", ".", "match", "(", "text", ")", "if", "result",...
Given a string of characters, for each normal ASCII character, yields a directive consisting of a 'putch' instruction followed by the character itself. If a valid ANSI escape sequence is detected within the string, the supported codes are translated into directives. For example ``\\033[42m`` would ...
[ "Given", "a", "string", "of", "characters", "for", "each", "normal", "ASCII", "character", "yields", "a", "directive", "consisting", "of", "a", "putch", "instruction", "followed", "by", "the", "character", "itself", "." ]
python
train
35.794118
iotile/coretools
iotileship/iotile/ship/recipe_manager.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/recipe_manager.py#L98-L112
def get_recipe(self, recipe_name): """Get a recipe by name. Args: recipe_name (str): The name of the recipe to fetch. Can be either the yaml file name or the name of the recipe. """ if recipe_name.endswith('.yaml'): recipe = self._recipes.get(Reci...
[ "def", "get_recipe", "(", "self", ",", "recipe_name", ")", ":", "if", "recipe_name", ".", "endswith", "(", "'.yaml'", ")", ":", "recipe", "=", "self", ".", "_recipes", ".", "get", "(", "RecipeObject", ".", "FromFile", "(", "recipe_name", ",", "self", "."...
Get a recipe by name. Args: recipe_name (str): The name of the recipe to fetch. Can be either the yaml file name or the name of the recipe.
[ "Get", "a", "recipe", "by", "name", "." ]
python
train
42.733333
baruwa-enterprise/BaruwaAPI
BaruwaAPI/resource.py
https://github.com/baruwa-enterprise/BaruwaAPI/blob/53335b377ccfd388e42f4f240f181eed72f51180/BaruwaAPI/resource.py#L471-L475
def get_org_smarthost(self, orgid, serverid): """Get an organization smarthost""" return self.api_call( ENDPOINTS['orgsmarthosts']['get'], dict(orgid=orgid, serverid=serverid))
[ "def", "get_org_smarthost", "(", "self", ",", "orgid", ",", "serverid", ")", ":", "return", "self", ".", "api_call", "(", "ENDPOINTS", "[", "'orgsmarthosts'", "]", "[", "'get'", "]", ",", "dict", "(", "orgid", "=", "orgid", ",", "serverid", "=", "serveri...
Get an organization smarthost
[ "Get", "an", "organization", "smarthost" ]
python
train
42.4
watson-developer-cloud/python-sdk
ibm_watson/discovery_v1.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L10234-L10247
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'scope') and self.scope is not None: _dict['scope'] = self.scope if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status i...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'scope'", ")", "and", "self", ".", "scope", "is", "not", "None", ":", "_dict", "[", "'scope'", "]", "=", "self", ".", "scope", "if", "hasattr", ...
Return a json dictionary representing this model.
[ "Return", "a", "json", "dictionary", "representing", "this", "model", "." ]
python
train
45.357143
bwesterb/displays
src/main.py
https://github.com/bwesterb/displays/blob/37764a3ce1be5e7b3c3bee8e4853554ed0417a82/src/main.py#L23-L31
def our_IsUsableForDesktopGUI(m): """ A more leniant version of CGDisplayModeIsUsableForDesktopGUI """ if guess_bitDepth(Q.CGDisplayModeCopyPixelEncoding(m)) != 24: return False if Q.CGDisplayModeGetWidth(m) < 640: return False if Q.CGDisplayModeGetHeight(...
[ "def", "our_IsUsableForDesktopGUI", "(", "m", ")", ":", "if", "guess_bitDepth", "(", "Q", ".", "CGDisplayModeCopyPixelEncoding", "(", "m", ")", ")", "!=", "24", ":", "return", "False", "if", "Q", ".", "CGDisplayModeGetWidth", "(", "m", ")", "<", "640", ":"...
A more leniant version of CGDisplayModeIsUsableForDesktopGUI
[ "A", "more", "leniant", "version", "of", "CGDisplayModeIsUsableForDesktopGUI" ]
python
train
41.111111
troeger/opensubmit
web/opensubmit/admin/submissionfile.py
https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/web/opensubmit/admin/submissionfile.py#L22-L28
def get_queryset(self, request): ''' Restrict the listed submission files for the current user.''' qs = super(SubmissionFileAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: return qs.filter(Q(submissions__assignment__course__tutors_...
[ "def", "get_queryset", "(", "self", ",", "request", ")", ":", "qs", "=", "super", "(", "SubmissionFileAdmin", ",", "self", ")", ".", "get_queryset", "(", "request", ")", "if", "request", ".", "user", ".", "is_superuser", ":", "return", "qs", "else", ":",...
Restrict the listed submission files for the current user.
[ "Restrict", "the", "listed", "submission", "files", "for", "the", "current", "user", "." ]
python
train
57.571429
google/grr
grr/server/grr_response_server/gui/api_plugins/vfs.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_plugins/vfs.py#L714-L731
def _Aff4Read(aff4_obj, offset, length): """Reads contents of given AFF4 file. Args: aff4_obj: An AFF4 stream instance to retrieve contents for. offset: An offset to start the reading from. length: A number of bytes to read. Reads the whole file if 0. Returns: Contents of specified AFF4 stream. ...
[ "def", "_Aff4Read", "(", "aff4_obj", ",", "offset", ",", "length", ")", ":", "length", "=", "length", "or", "(", "_Aff4Size", "(", "aff4_obj", ")", "-", "offset", ")", "aff4_obj", ".", "Seek", "(", "offset", ")", "return", "aff4_obj", ".", "Read", "(",...
Reads contents of given AFF4 file. Args: aff4_obj: An AFF4 stream instance to retrieve contents for. offset: An offset to start the reading from. length: A number of bytes to read. Reads the whole file if 0. Returns: Contents of specified AFF4 stream. Raises: TypeError: If `aff4_obj` is not...
[ "Reads", "contents", "of", "given", "AFF4", "file", "." ]
python
train
27.277778
awslabs/sockeye
sockeye/score.py
https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/score.py#L47-L85
def get_data_iters_and_vocabs(args: argparse.Namespace, model_folder: Optional[str]) -> Tuple['data_io.BaseParallelSampleIter', List[vocab.Vocab], vocab.Vocab, model.ModelConfig]: """ Loads the data iterators and v...
[ "def", "get_data_iters_and_vocabs", "(", "args", ":", "argparse", ".", "Namespace", ",", "model_folder", ":", "Optional", "[", "str", "]", ")", "->", "Tuple", "[", "'data_io.BaseParallelSampleIter'", ",", "List", "[", "vocab", ".", "Vocab", "]", ",", "vocab", ...
Loads the data iterators and vocabularies. :param args: Arguments as returned by argparse. :param model_folder: Output folder. :return: The scoring data iterator as well as the source and target vocabularies.
[ "Loads", "the", "data", "iterators", "and", "vocabularies", "." ]
python
train
42.769231
mitsei/dlkit
dlkit/handcar/learning/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/learning/sessions.py#L1539-L1568
def remove_child_objectives(self, objective_id=None): """Removes all children from an objective. arg: objective_id (osid.id.Id): the Id of an objective raise: NotFound - objective_id not found raise: NullArgument - objective_id is null raise: OperationFailed - unable to co...
[ "def", "remove_child_objectives", "(", "self", ",", "objective_id", "=", "None", ")", ":", "if", "objective_id", "is", "None", ":", "raise", "NullArgument", "(", ")", "ols", "=", "ObjectiveLookupSession", "(", "self", ".", "_objective_bank_id", ",", "runtime", ...
Removes all children from an objective. arg: objective_id (osid.id.Id): the Id of an objective raise: NotFound - objective_id not found raise: NullArgument - objective_id is null raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization f...
[ "Removes", "all", "children", "from", "an", "objective", "." ]
python
train
40
hyperledger/indy-plenum
plenum/common/config_util.py
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/config_util.py#L68-L95
def _getConfig(general_config_dir: str = None): """ Reads a file called config.py in the project directory :raises: FileNotFoundError :return: the configuration as a python object """ stp_config = STPConfig() plenum_config = import_module("plenum.config") config = stp_config config....
[ "def", "_getConfig", "(", "general_config_dir", ":", "str", "=", "None", ")", ":", "stp_config", "=", "STPConfig", "(", ")", "plenum_config", "=", "import_module", "(", "\"plenum.config\"", ")", "config", "=", "stp_config", "config", ".", "__dict__", ".", "upd...
Reads a file called config.py in the project directory :raises: FileNotFoundError :return: the configuration as a python object
[ "Reads", "a", "file", "called", "config", ".", "py", "in", "the", "project", "directory" ]
python
train
35.714286
dw/mitogen
mitogen/service.py
https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/service.py#L948-L1002
def fetch(self, path, sender, msg): """ Start a transfer for a registered path. :param str path: File path. :param mitogen.core.Sender sender: Sender to receive file data. :returns: Dict containing the file metadata: * ``size``: F...
[ "def", "fetch", "(", "self", ",", "path", ",", "sender", ",", "msg", ")", ":", "if", "path", "not", "in", "self", ".", "_paths", "and", "not", "self", ".", "_prefix_is_authorized", "(", "path", ")", ":", "msg", ".", "reply", "(", "mitogen", ".", "c...
Start a transfer for a registered path. :param str path: File path. :param mitogen.core.Sender sender: Sender to receive file data. :returns: Dict containing the file metadata: * ``size``: File size in bytes. * ``mode``: Integer file ...
[ "Start", "a", "transfer", "for", "a", "registered", "path", "." ]
python
train
35.381818
FutunnOpen/futuquant
futuquant/examples/learn/max_sub.py
https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/examples/learn/max_sub.py#L27-L53
def allStockQoutation(self): ''' 订阅多只股票的行情数据 :return: ''' logger = Logs().getNewLogger('allStockQoutation', QoutationAsynPush.dir) markets= [Market.HK,Market.US,Market.SH,Market.SZ] #,Market.HK_FUTURE,Market.US_OPTION stockTypes = [SecurityType.STOCK,SecurityType....
[ "def", "allStockQoutation", "(", "self", ")", ":", "logger", "=", "Logs", "(", ")", ".", "getNewLogger", "(", "'allStockQoutation'", ",", "QoutationAsynPush", ".", "dir", ")", "markets", "=", "[", "Market", ".", "HK", ",", "Market", ".", "US", ",", "Mark...
订阅多只股票的行情数据 :return:
[ "订阅多只股票的行情数据", ":", "return", ":" ]
python
train
49.074074
inasafe/inasafe
safe/gui/tools/help/impact_report_help.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/impact_report_help.py#L49-L136
def content(): """Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.message.Message """ message = m.Message() ...
[ "def", "content", "(", ")", ":", "message", "=", "m", ".", "Message", "(", ")", "message", ".", "add", "(", "m", ".", "Paragraph", "(", "tr", "(", "'To start report generation you need to click on the Print '", "'button in the buttons area. This will open the Impact rep...
Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.message.Message
[ "Helper", "method", "that", "returns", "just", "the", "content", "." ]
python
train
37.306818
roboogle/gtkmvc3
gtkmvco/gtkmvc3/controller.py
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/controller.py#L229-L281
def setup_column(self, widget, column=0, attribute=None, renderer=None, property=None, from_python=None, to_python=None, model=None): # Maybe this is too overloaded. """ Set up a :class:`TreeView` to display attributes of Python objects stored in its :class:`TreeModel`. ...
[ "def", "setup_column", "(", "self", ",", "widget", ",", "column", "=", "0", ",", "attribute", "=", "None", ",", "renderer", "=", "None", ",", "property", "=", "None", ",", "from_python", "=", "None", ",", "to_python", "=", "None", ",", "model", "=", ...
Set up a :class:`TreeView` to display attributes of Python objects stored in its :class:`TreeModel`. This assumes that :class:`TreeViewColumn` instances have already been added and :class:`CellRenderer` instances packed into them. Both can be done in Glade. *model* is the insta...
[ "Set", "up", "a", ":", "class", ":", "TreeView", "to", "display", "attributes", "of", "Python", "objects", "stored", "in", "its", ":", "class", ":", "TreeModel", "." ]
python
train
44.150943
JinnLynn/genpac
genpac/pysocks/socks.py
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L740-L821
def connect(self, dest_pair): """ Connects to the specified destination through a proxy. Uses the same API as socket's connect(). To select the proxy server, use set_proxy(). dest_pair - 2-tuple of (IP/hostname, port). """ if len(dest_pair) != 2 or dest_pair[0].s...
[ "def", "connect", "(", "self", ",", "dest_pair", ")", ":", "if", "len", "(", "dest_pair", ")", "!=", "2", "or", "dest_pair", "[", "0", "]", ".", "startswith", "(", "\"[\"", ")", ":", "# Probably IPv6, not supported -- raise an error, and hope", "# Happy Eyeballs...
Connects to the specified destination through a proxy. Uses the same API as socket's connect(). To select the proxy server, use set_proxy(). dest_pair - 2-tuple of (IP/hostname, port).
[ "Connects", "to", "the", "specified", "destination", "through", "a", "proxy", ".", "Uses", "the", "same", "API", "as", "socket", "s", "connect", "()", ".", "To", "select", "the", "proxy", "server", "use", "set_proxy", "()", "." ]
python
train
38.634146
emirozer/fake2db
fake2db/couchdb_handler.py
https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/couchdb_handler.py#L73-L93
def data_filler_simple_registration(self, number_of_rows, db): '''creates and fills the table with simple regis. information ''' try: simple_registration = db for i in range(0, number_of_rows): post_simple_reg = { "id": rnd_id_generat...
[ "def", "data_filler_simple_registration", "(", "self", ",", "number_of_rows", ",", "db", ")", ":", "try", ":", "simple_registration", "=", "db", "for", "i", "in", "range", "(", "0", ",", "number_of_rows", ")", ":", "post_simple_reg", "=", "{", "\"id\"", ":",...
creates and fills the table with simple regis. information
[ "creates", "and", "fills", "the", "table", "with", "simple", "regis", ".", "information" ]
python
train
33.619048
gwastro/pycbc
pycbc/events/coinc.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L1081-L1095
def backout_last(self, updated_singles, num_coincs): """Remove the recently added singles and coincs Parameters ---------- updated_singles: dict of numpy.ndarrays Array of indices that have been just updated in the internal buffers of single detector triggers. ...
[ "def", "backout_last", "(", "self", ",", "updated_singles", ",", "num_coincs", ")", ":", "for", "ifo", "in", "updated_singles", ":", "self", ".", "singles", "[", "ifo", "]", ".", "discard_last", "(", "updated_singles", "[", "ifo", "]", ")", "self", ".", ...
Remove the recently added singles and coincs Parameters ---------- updated_singles: dict of numpy.ndarrays Array of indices that have been just updated in the internal buffers of single detector triggers. num_coincs: int The number of coincs that were...
[ "Remove", "the", "recently", "added", "singles", "and", "coincs" ]
python
train
39.4
jonathanj/txspinneret
txspinneret/route.py
https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/route.py#L277-L285
def _forObject(self, obj): """ Create a new `Router` instance, with it's own set of routes, for ``obj``. """ router = type(self)() router._routes = list(self._routes) router._self = obj return router
[ "def", "_forObject", "(", "self", ",", "obj", ")", ":", "router", "=", "type", "(", "self", ")", "(", ")", "router", ".", "_routes", "=", "list", "(", "self", ".", "_routes", ")", "router", ".", "_self", "=", "obj", "return", "router" ]
Create a new `Router` instance, with it's own set of routes, for ``obj``.
[ "Create", "a", "new", "Router", "instance", "with", "it", "s", "own", "set", "of", "routes", "for", "obj", "." ]
python
valid
28.333333
limodou/uliweb
uliweb/i18n/pygettext.py
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/i18n/pygettext.py#L285-L312
def _visit_pyfiles(list, dirname, names): """Helper for getFilesForName().""" # get extension for python source files if not globals().has_key('_py_ext'): global _py_ext # _py_ext = [triple[0] for triple in imp.get_suffixes() # if triple[2] == imp.PY_SOURCE][0] _py_e...
[ "def", "_visit_pyfiles", "(", "list", ",", "dirname", ",", "names", ")", ":", "# get extension for python source files", "if", "not", "globals", "(", ")", ".", "has_key", "(", "'_py_ext'", ")", ":", "global", "_py_ext", "# _py_ext = [triple[0] for triple in imp...
Helper for getFilesForName().
[ "Helper", "for", "getFilesForName", "()", "." ]
python
train
29.571429
materialsproject/pymatgen
pymatgen/phonon/dos.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/phonon/dos.py#L122-L129
def ind_zero_freq(self): """ Index of the first point for which the freqencies are equal or greater than zero. """ ind = np.searchsorted(self.frequencies, 0) if ind >= len(self.frequencies): raise ValueError("No positive frequencies found") return ind
[ "def", "ind_zero_freq", "(", "self", ")", ":", "ind", "=", "np", ".", "searchsorted", "(", "self", ".", "frequencies", ",", "0", ")", "if", "ind", ">=", "len", "(", "self", ".", "frequencies", ")", ":", "raise", "ValueError", "(", "\"No positive frequenc...
Index of the first point for which the freqencies are equal or greater than zero.
[ "Index", "of", "the", "first", "point", "for", "which", "the", "freqencies", "are", "equal", "or", "greater", "than", "zero", "." ]
python
train
38
SmokinCaterpillar/pypet
pypet/trajectory.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/trajectory.py#L3591-L3614
def f_get_results(self, fast_access=False, copy=True): """ Returns a dictionary containing the full result names as keys and the corresponding result objects or result data items as values. :param fast_access: Determines whether the result objects or their values are returned ...
[ "def", "f_get_results", "(", "self", ",", "fast_access", "=", "False", ",", "copy", "=", "True", ")", ":", "return", "self", ".", "_return_item_dictionary", "(", "self", ".", "_results", ",", "fast_access", ",", "copy", ")" ]
Returns a dictionary containing the full result names as keys and the corresponding result objects or result data items as values. :param fast_access: Determines whether the result objects or their values are returned in the dictionary. Works only for results if they contain a...
[ "Returns", "a", "dictionary", "containing", "the", "full", "result", "names", "as", "keys", "and", "the", "corresponding", "result", "objects", "or", "result", "data", "items", "as", "values", "." ]
python
test
37.625
saltstack/salt
salt/modules/elasticsearch.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L330-L349
def alias_exists(aliases, indices=None, hosts=None, profile=None): ''' Return a boolean indicating whether given alias exists indices Single or multiple indices separated by comma, use _all to perform the operation on all indices. aliases Alias names separated by comma CLI example:...
[ "def", "alias_exists", "(", "aliases", ",", "indices", "=", "None", ",", "hosts", "=", "None", ",", "profile", "=", "None", ")", ":", "es", "=", "_get_instance", "(", "hosts", ",", "profile", ")", "try", ":", "return", "es", ".", "indices", ".", "exi...
Return a boolean indicating whether given alias exists indices Single or multiple indices separated by comma, use _all to perform the operation on all indices. aliases Alias names separated by comma CLI example:: salt myminion elasticsearch.alias_exists None testindex
[ "Return", "a", "boolean", "indicating", "whether", "given", "alias", "exists" ]
python
train
38.7
riga/law
law/patches.py
https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/patches.py#L92-L103
def patch_worker_factory(): """ Patches the ``luigi.interface._WorkerSchedulerFactory`` to include sandboxing information when create a worker instance. """ def create_worker(self, scheduler, worker_processes, assistant=False): worker = luigi.worker.Worker(scheduler=scheduler, worker_process...
[ "def", "patch_worker_factory", "(", ")", ":", "def", "create_worker", "(", "self", ",", "scheduler", ",", "worker_processes", ",", "assistant", "=", "False", ")", ":", "worker", "=", "luigi", ".", "worker", ".", "Worker", "(", "scheduler", "=", "scheduler", ...
Patches the ``luigi.interface._WorkerSchedulerFactory`` to include sandboxing information when create a worker instance.
[ "Patches", "the", "luigi", ".", "interface", ".", "_WorkerSchedulerFactory", "to", "include", "sandboxing", "information", "when", "create", "a", "worker", "instance", "." ]
python
train
47.583333
boppreh/keyboard
keyboard/_darwinkeyboard.py
https://github.com/boppreh/keyboard/blob/dbb73dfff484f733d5fed8dbc53301af5b6c7f50/keyboard/_darwinkeyboard.py#L239-L284
def press(self, key_code): """ Sends a 'down' event for the specified scan code """ if key_code >= 128: # Media key ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( 14, # type (0, 0), # loc...
[ "def", "press", "(", "self", ",", "key_code", ")", ":", "if", "key_code", ">=", "128", ":", "# Media key", "ev", "=", "NSEvent", ".", "otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_", "(", "14", ",", "# type", "(", "0", ...
Sends a 'down' event for the specified scan code
[ "Sends", "a", "down", "event", "for", "the", "specified", "scan", "code" ]
python
train
44.043478
blaklites/fb
fb/graph.py
https://github.com/blaklites/fb/blob/4ddba4dae204463ed24f473872215c5a26370a81/fb/graph.py#L15-L22
def publish(self, cat, **kwargs): """ This method is used for creating objects in the facebook graph. The first paramter is "cat", the category of publish. In addition to "cat" "id" must also be passed and is catched by "kwargs" """ ...
[ "def", "publish", "(", "self", ",", "cat", ",", "*", "*", "kwargs", ")", ":", "res", "=", "request", ".", "publish_cat1", "(", "\"POST\"", ",", "self", ".", "con", ",", "self", ".", "token", ",", "cat", ",", "kwargs", ")", "return", "res" ]
This method is used for creating objects in the facebook graph. The first paramter is "cat", the category of publish. In addition to "cat" "id" must also be passed and is catched by "kwargs"
[ "This", "method", "is", "used", "for", "creating", "objects", "in", "the", "facebook", "graph", ".", "The", "first", "paramter", "is", "cat", "the", "category", "of", "publish", ".", "In", "addition", "to", "cat", "id", "must", "also", "be", "passed", "a...
python
train
52.75
svenevs/exhale
exhale/graph.py
https://github.com/svenevs/exhale/blob/fe7644829057af622e467bb529db6c03a830da99/exhale/graph.py#L424-L437
def findNestedDirectories(self, lst): ''' Recursive helper function for finding nested directories. If this node is a directory node, it is appended to ``lst``. Each node also calls each of its child ``findNestedDirectories`` with the same list. :Parameters: ``lst`...
[ "def", "findNestedDirectories", "(", "self", ",", "lst", ")", ":", "if", "self", ".", "kind", "==", "\"dir\"", ":", "lst", ".", "append", "(", "self", ")", "for", "c", "in", "self", ".", "children", ":", "c", ".", "findNestedDirectories", "(", "lst", ...
Recursive helper function for finding nested directories. If this node is a directory node, it is appended to ``lst``. Each node also calls each of its child ``findNestedDirectories`` with the same list. :Parameters: ``lst`` (list) The list each directory node is t...
[ "Recursive", "helper", "function", "for", "finding", "nested", "directories", ".", "If", "this", "node", "is", "a", "directory", "node", "it", "is", "appended", "to", "lst", ".", "Each", "node", "also", "calls", "each", "of", "its", "child", "findNestedDirec...
python
train
37.642857
log2timeline/dfvfs
dfvfs/resolver/cache.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/cache.py#L149-L170
def GrabObject(self, identifier): """Grabs a cached object based on the identifier. This method increments the cache value reference count. Args: identifier (str): VFS object identifier. Raises: KeyError: if the VFS object is not found in the cache. RuntimeError: if the cache value ...
[ "def", "GrabObject", "(", "self", ",", "identifier", ")", ":", "if", "identifier", "not", "in", "self", ".", "_values", ":", "raise", "KeyError", "(", "'Missing cached object for identifier: {0:s}'", ".", "format", "(", "identifier", ")", ")", "cache_value", "="...
Grabs a cached object based on the identifier. This method increments the cache value reference count. Args: identifier (str): VFS object identifier. Raises: KeyError: if the VFS object is not found in the cache. RuntimeError: if the cache value is missing.
[ "Grabs", "a", "cached", "object", "based", "on", "the", "identifier", "." ]
python
train
30.272727
zinic/pynsive
pynsive/reflection.py
https://github.com/zinic/pynsive/blob/15bc8b35a91be5817979eb327427b6235b1b411e/pynsive/reflection.py#L220-L240
def rlist_classes(module, cls_filter=None): """ Attempts to list all of the classes within a given module namespace. This method, unlike list_classes, will recurse into discovered submodules. If a type filter is set, it will be called with each class as its parameter. This filter's return value...
[ "def", "rlist_classes", "(", "module", ",", "cls_filter", "=", "None", ")", ":", "found", "=", "list", "(", ")", "mnames", "=", "rlist_modules", "(", "module", ")", "for", "mname", "in", "mnames", ":", "[", "found", ".", "append", "(", "c", ")", "for...
Attempts to list all of the classes within a given module namespace. This method, unlike list_classes, will recurse into discovered submodules. If a type filter is set, it will be called with each class as its parameter. This filter's return value must be interpretable as a boolean. Results that ev...
[ "Attempts", "to", "list", "all", "of", "the", "classes", "within", "a", "given", "module", "namespace", ".", "This", "method", "unlike", "list_classes", "will", "recurse", "into", "discovered", "submodules", "." ]
python
test
40.142857
LasLabs/python-five9
five9/models/base_model.py
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/models/base_model.py#L150-L158
def _get_non_empty_list(cls, iter): """Return a list of the input, excluding all ``None`` values.""" res = [] for value in iter: if hasattr(value, 'items'): value = cls._get_non_empty_dict(value) or None if value is not None: res.append(val...
[ "def", "_get_non_empty_list", "(", "cls", ",", "iter", ")", ":", "res", "=", "[", "]", "for", "value", "in", "iter", ":", "if", "hasattr", "(", "value", ",", "'items'", ")", ":", "value", "=", "cls", ".", "_get_non_empty_dict", "(", "value", ")", "or...
Return a list of the input, excluding all ``None`` values.
[ "Return", "a", "list", "of", "the", "input", "excluding", "all", "None", "values", "." ]
python
train
37.111111
moonso/loqusdb
loqusdb/plugins/mongo/adapter.py
https://github.com/moonso/loqusdb/blob/792dcd0d461aff5adc703c49eebf58964913a513/loqusdb/plugins/mongo/adapter.py#L55-L70
def ensure_indexes(self): """Update the indexes""" for collection_name in INDEXES: existing_indexes = self.indexes(collection_name) indexes = INDEXES[collection_name] for index in indexes: index_name = index.document.get('name') if inde...
[ "def", "ensure_indexes", "(", "self", ")", ":", "for", "collection_name", "in", "INDEXES", ":", "existing_indexes", "=", "self", ".", "indexes", "(", "collection_name", ")", "indexes", "=", "INDEXES", "[", "collection_name", "]", "for", "index", "in", "indexes...
Update the indexes
[ "Update", "the", "indexes" ]
python
train
46.5625
svinota/mdns
mdns/zeroconf.py
https://github.com/svinota/mdns/blob/295f6407132616a0ff7401124b9057d89555f91d/mdns/zeroconf.py#L624-L629
def set_property(self, key, value): """ Update only one property in the dict """ self.properties[key] = value self.sync_properties()
[ "def", "set_property", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "properties", "[", "key", "]", "=", "value", "self", ".", "sync_properties", "(", ")" ]
Update only one property in the dict
[ "Update", "only", "one", "property", "in", "the", "dict" ]
python
train
27.833333
mardix/Mocha
mocha/contrib/app_data.py
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/app_data.py#L32-L56
def set(key, value={}, reset=False, init=False): """ Set data :param key: A unique to set, best to use __name__ :param value: dict - the value to save :param reset: bool - If true, it will reset the value to the current one. if False, it will just update the stored value with the c...
[ "def", "set", "(", "key", ",", "value", "=", "{", "}", ",", "reset", "=", "False", ",", "init", "=", "False", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"App Data value must be a dict\"", ")"...
Set data :param key: A unique to set, best to use __name__ :param value: dict - the value to save :param reset: bool - If true, it will reset the value to the current one. if False, it will just update the stored value with the current one :param init: bool - If True, ...
[ "Set", "data", ":", "param", "key", ":", "A", "unique", "to", "set", "best", "to", "use", "__name__", ":", "param", "value", ":", "dict", "-", "the", "value", "to", "save", ":", "param", "reset", ":", "bool", "-", "If", "true", "it", "will", "reset...
python
train
36.4
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/ASLUAV.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/ASLUAV.py#L7597-L7607
def sens_power_send(self, adc121_vspb_volt, adc121_cspb_amp, adc121_cs1_amp, adc121_cs2_amp, force_mavlink1=False): ''' Voltage and current sensor data adc121_vspb_volt : Power board voltage sensor reading in volts (float) adc121_cspb_amp ...
[ "def", "sens_power_send", "(", "self", ",", "adc121_vspb_volt", ",", "adc121_cspb_amp", ",", "adc121_cs1_amp", ",", "adc121_cs2_amp", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "sens_power_encode", "(", "adc12...
Voltage and current sensor data adc121_vspb_volt : Power board voltage sensor reading in volts (float) adc121_cspb_amp : Power board current sensor reading in amps (float) adc121_cs1_amp : Board current sensor 1 reading in amps (float) ...
[ "Voltage", "and", "current", "sensor", "data" ]
python
train
65.727273
rodluger/everest
everest/masksolve.py
https://github.com/rodluger/everest/blob/6779591f9f8b3556847e2fbf761bdfac7520eaea/everest/masksolve.py#L105-L132
def MaskSolveSlow(A, b, w=5, progress=True, niter=None): ''' Identical to `MaskSolve`, but computes the solution the brute-force way. ''' # Number of data points N = b.shape[0] # How many iterations? Default is to go through # the entire dataset if niter is None: ...
[ "def", "MaskSolveSlow", "(", "A", ",", "b", ",", "w", "=", "5", ",", "progress", "=", "True", ",", "niter", "=", "None", ")", ":", "# Number of data points\r", "N", "=", "b", ".", "shape", "[", "0", "]", "# How many iterations? Default is to go through\r", ...
Identical to `MaskSolve`, but computes the solution the brute-force way.
[ "Identical", "to", "MaskSolve", "but", "computes", "the", "solution", "the", "brute", "-", "force", "way", "." ]
python
train
26.107143
jameslyons/python_speech_features
python_speech_features/base.py
https://github.com/jameslyons/python_speech_features/blob/40c590269b57c64a8c1f1ddaaff2162008d1850c/python_speech_features/base.py#L8-L23
def calculate_nfft(samplerate, winlen): """Calculates the FFT size as a power of two greater than or equal to the number of samples in a single window length. Having an FFT less than the window length loses precision by dropping many of the samples; a longer FFT than the window allows zero-padding ...
[ "def", "calculate_nfft", "(", "samplerate", ",", "winlen", ")", ":", "window_length_samples", "=", "winlen", "*", "samplerate", "nfft", "=", "1", "while", "nfft", "<", "window_length_samples", ":", "nfft", "*=", "2", "return", "nfft" ]
Calculates the FFT size as a power of two greater than or equal to the number of samples in a single window length. Having an FFT less than the window length loses precision by dropping many of the samples; a longer FFT than the window allows zero-padding of the FFT buffer which is neutral in terms...
[ "Calculates", "the", "FFT", "size", "as", "a", "power", "of", "two", "greater", "than", "or", "equal", "to", "the", "number", "of", "samples", "in", "a", "single", "window", "length", ".", "Having", "an", "FFT", "less", "than", "the", "window", "length",...
python
train
42.125
csparpa/pyowm
pyowm/weatherapi25/observation.py
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/observation.py#L72-L81
def to_JSON(self): """Dumps object fields into a JSON formatted string :returns: the JSON string """ return json.dumps({"reception_time": self._reception_time, "Location": json.loads(self._location.to_JSON()), "Weather": json.loads...
[ "def", "to_JSON", "(", "self", ")", ":", "return", "json", ".", "dumps", "(", "{", "\"reception_time\"", ":", "self", ".", "_reception_time", ",", "\"Location\"", ":", "json", ".", "loads", "(", "self", ".", "_location", ".", "to_JSON", "(", ")", ")", ...
Dumps object fields into a JSON formatted string :returns: the JSON string
[ "Dumps", "object", "fields", "into", "a", "JSON", "formatted", "string" ]
python
train
36.6
bcbio/bcbio-nextgen
bcbio/bed/__init__.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bed/__init__.py#L20-L44
def concat(bed_files, catted=None): """ recursively concat a set of BED files, returning a sorted bedtools object of the result """ bed_files = [x for x in bed_files if x] if len(bed_files) == 0: if catted: # move to a .bed extension for downstream tools if not already ...
[ "def", "concat", "(", "bed_files", ",", "catted", "=", "None", ")", ":", "bed_files", "=", "[", "x", "for", "x", "in", "bed_files", "if", "x", "]", "if", "len", "(", "bed_files", ")", "==", "0", ":", "if", "catted", ":", "# move to a .bed extension for...
recursively concat a set of BED files, returning a sorted bedtools object of the result
[ "recursively", "concat", "a", "set", "of", "BED", "files", "returning", "a", "sorted", "bedtools", "object", "of", "the", "result" ]
python
train
31.88
apache/spark
python/pyspark/sql/readwriter.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/readwriter.py#L761-L786
def saveAsTable(self, name, format=None, mode=None, partitionBy=None, **options): """Saves the content of the :class:`DataFrame` as the specified table. In the case the table already exists, behavior of this function depends on the save mode, specified by the `mode` function (default to throwin...
[ "def", "saveAsTable", "(", "self", ",", "name", ",", "format", "=", "None", ",", "mode", "=", "None", ",", "partitionBy", "=", "None", ",", "*", "*", "options", ")", ":", "self", ".", "mode", "(", "mode", ")", ".", "options", "(", "*", "*", "opti...
Saves the content of the :class:`DataFrame` as the specified table. In the case the table already exists, behavior of this function depends on the save mode, specified by the `mode` function (default to throwing an exception). When `mode` is `Overwrite`, the schema of the :class:`DataFrame` doe...
[ "Saves", "the", "content", "of", "the", ":", "class", ":", "DataFrame", "as", "the", "specified", "table", "." ]
python
train
49.615385
google/importlab
importlab/resolve.py
https://github.com/google/importlab/blob/92090a0b4421137d1369c2ed952eda6bb4c7a155/importlab/resolve.py#L235-L244
def resolve_all(self, import_items): """Resolves a list of imports. Yields filenames. """ for import_item in import_items: try: yield self.resolve_import(import_item) except ImportException as err: logging.info('unknown module %s',...
[ "def", "resolve_all", "(", "self", ",", "import_items", ")", ":", "for", "import_item", "in", "import_items", ":", "try", ":", "yield", "self", ".", "resolve_import", "(", "import_item", ")", "except", "ImportException", "as", "err", ":", "logging", ".", "in...
Resolves a list of imports. Yields filenames.
[ "Resolves", "a", "list", "of", "imports", "." ]
python
train
32.8
assemblerflow/flowcraft
flowcraft/generator/inspect.py
https://github.com/assemblerflow/flowcraft/blob/fc3f4bddded1efc76006600016dc71a06dd908c0/flowcraft/generator/inspect.py#L893-L935
def trace_parser(self): """Method that parses the trace file once and updates the :attr:`status_info` attribute with the new entries. """ # Check the timestamp of the tracefile. Only proceed with the parsing # if it changed from the previous time. size_stamp = os.path.ge...
[ "def", "trace_parser", "(", "self", ")", ":", "# Check the timestamp of the tracefile. Only proceed with the parsing", "# if it changed from the previous time.", "size_stamp", "=", "os", ".", "path", ".", "getsize", "(", "self", ".", "trace_file", ")", "self", ".", "trace...
Method that parses the trace file once and updates the :attr:`status_info` attribute with the new entries.
[ "Method", "that", "parses", "the", "trace", "file", "once", "and", "updates", "the", ":", "attr", ":", "status_info", "attribute", "with", "the", "new", "entries", "." ]
python
test
33.325581
JarryShaw/PyPCAPKit
src/const/http/error_code.py
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/http/error_code.py#L28-L34
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return ErrorCode(key) if key not in ErrorCode._member_map_: extend_enum(ErrorCode, key, default) return ErrorCode[key]
[ "def", "get", "(", "key", ",", "default", "=", "-", "1", ")", ":", "if", "isinstance", "(", "key", ",", "int", ")", ":", "return", "ErrorCode", "(", "key", ")", "if", "key", "not", "in", "ErrorCode", ".", "_member_map_", ":", "extend_enum", "(", "E...
Backport support for original codes.
[ "Backport", "support", "for", "original", "codes", "." ]
python
train
37.428571
jplusplus/statscraper
statscraper/scrapers/SMHIScraper.py
https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/scrapers/SMHIScraper.py#L237-L250
def _get_example_csv(self): """For dimension parsing """ station_key = self.json["station"][0]["key"] period = "corrected-archive" url = self.url\ .replace(".json", "/station/{}/period/{}/data.csv"\ .format(station_key, period)) r = re...
[ "def", "_get_example_csv", "(", "self", ")", ":", "station_key", "=", "self", ".", "json", "[", "\"station\"", "]", "[", "0", "]", "[", "\"key\"", "]", "period", "=", "\"corrected-archive\"", "url", "=", "self", ".", "url", ".", "replace", "(", "\".json\...
For dimension parsing
[ "For", "dimension", "parsing" ]
python
train
34
Erotemic/ubelt
ubelt/util_func.py
https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_func.py#L25-L58
def inject_method(self, func, name=None): """ Injects a function into an object instance as a bound method The main use case of this function is for monkey patching. While monkey patching is sometimes necessary it should generally be avoided. Thus, we simply remind the developer that there might be...
[ "def", "inject_method", "(", "self", ",", "func", ",", "name", "=", "None", ")", ":", "# TODO: if func is a bound method we should probably unbind it", "new_method", "=", "func", ".", "__get__", "(", "self", ",", "self", ".", "__class__", ")", "if", "name", "is"...
Injects a function into an object instance as a bound method The main use case of this function is for monkey patching. While monkey patching is sometimes necessary it should generally be avoided. Thus, we simply remind the developer that there might be a better way. Args: self (object): insta...
[ "Injects", "a", "function", "into", "an", "object", "instance", "as", "a", "bound", "method" ]
python
valid
37.676471
coreGreenberet/homematicip-rest-api
homematicip/home.py
https://github.com/coreGreenberet/homematicip-rest-api/blob/d4c8df53281577e01709f75cacb78b1a5a1d00db/homematicip/home.py#L403-L415
def search_device_by_id(self, deviceID) -> Device: """ searches a device by given id Args: deviceID(str): the device to search for Returns the Device object or None if it couldn't find a device """ for d in self.devices: ...
[ "def", "search_device_by_id", "(", "self", ",", "deviceID", ")", "->", "Device", ":", "for", "d", "in", "self", ".", "devices", ":", "if", "d", ".", "id", "==", "deviceID", ":", "return", "d", "return", "None" ]
searches a device by given id Args: deviceID(str): the device to search for Returns the Device object or None if it couldn't find a device
[ "searches", "a", "device", "by", "given", "id", "Args", ":", "deviceID", "(", "str", ")", ":", "the", "device", "to", "search", "for", "Returns", "the", "Device", "object", "or", "None", "if", "it", "couldn", "t", "find", "a", "device" ]
python
train
29.076923
Nic30/hwt
hwt/serializer/generic/serializer.py
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/generic/serializer.py#L120-L148
def serializationDecision(cls, obj, serializedClasses, serializedConfiguredUnits): """ Decide if this unit should be serialized or not eventually fix name to fit same already serialized unit :param obj: object to serialize :param serializedClasses: ...
[ "def", "serializationDecision", "(", "cls", ",", "obj", ",", "serializedClasses", ",", "serializedConfiguredUnits", ")", ":", "isDeclaration", "=", "isinstance", "(", "obj", ",", "Entity", ")", "isDefinition", "=", "isinstance", "(", "obj", ",", "Architecture", ...
Decide if this unit should be serialized or not eventually fix name to fit same already serialized unit :param obj: object to serialize :param serializedClasses: dict {unitCls : unitobj} :param serializedConfiguredUnits: (unitCls, paramsValues) : unitObj where paramsValues a...
[ "Decide", "if", "this", "unit", "should", "be", "serialized", "or", "not", "eventually", "fix", "name", "to", "fit", "same", "already", "serialized", "unit" ]
python
test
37.448276
Jajcus/pyxmpp2
pyxmpp2/xmppserializer.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppserializer.py#L327-L344
def emit_stanza(self, element): """"Serialize a stanza. Must be called after `emit_head`. :Parameters: - `element`: the element to serialize :Types: - `element`: :etree:`ElementTree.Element` :Return: serialized element :Returntype: `unicode` ...
[ "def", "emit_stanza", "(", "self", ",", "element", ")", ":", "if", "not", "self", ".", "_head_emitted", ":", "raise", "RuntimeError", "(", "\".emit_head() must be called first.\"", ")", "string", "=", "self", ".", "_emit_element", "(", "element", ",", "level", ...
Serialize a stanza. Must be called after `emit_head`. :Parameters: - `element`: the element to serialize :Types: - `element`: :etree:`ElementTree.Element` :Return: serialized element :Returntype: `unicode`
[ "Serialize", "a", "stanza", "." ]
python
valid
33