repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
mdiener/grace
grace/py27/slimit/parser.py
https://github.com/mdiener/grace/blob/2dab13a2cf636da5da989904c5885166fc94d36d/grace/py27/slimit/parser.py#L440-L448
def p_postfix_expr(self, p): """postfix_expr : left_hand_side_expr | left_hand_side_expr PLUSPLUS | left_hand_side_expr MINUSMINUS """ if len(p) == 2: p[0] = p[1] else: p[0] = ast.UnaryOp(op=p[2], value=p[1], postfix...
[ "def", "p_postfix_expr", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "else", ":", "p", "[", "0", "]", "=", "ast", ".", "UnaryOp", "(", "op", "=", "p", "[", "2...
postfix_expr : left_hand_side_expr | left_hand_side_expr PLUSPLUS | left_hand_side_expr MINUSMINUS
[ "postfix_expr", ":", "left_hand_side_expr", "|", "left_hand_side_expr", "PLUSPLUS", "|", "left_hand_side_expr", "MINUSMINUS" ]
python
train
alorence/pysvg-py3
pysvg/shape.py
https://github.com/alorence/pysvg-py3/blob/ce217a4da3ada44a71d3e2f391d37c67d95c724e/pysvg/shape.py#L152-L157
def getBottomRight(self): """ Retrieves a tuple with the x,y coordinates of the lower right point of the circle. Requires the radius and the coordinates to be numbers """ return (float(self.get_cx()) + float(self.get_r()), float(self.get_cy()) - float(self.get_r()))
[ "def", "getBottomRight", "(", "self", ")", ":", "return", "(", "float", "(", "self", ".", "get_cx", "(", ")", ")", "+", "float", "(", "self", ".", "get_r", "(", ")", ")", ",", "float", "(", "self", ".", "get_cy", "(", ")", ")", "-", "float", "(...
Retrieves a tuple with the x,y coordinates of the lower right point of the circle. Requires the radius and the coordinates to be numbers
[ "Retrieves", "a", "tuple", "with", "the", "x", "y", "coordinates", "of", "the", "lower", "right", "point", "of", "the", "circle", ".", "Requires", "the", "radius", "and", "the", "coordinates", "to", "be", "numbers" ]
python
train
Microsoft/knack
knack/arguments.py
https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/arguments.py#L359-L376
def enum_choice_list(data): """ Creates the argparse choices and type kwargs for a supplied enum type or list of strings """ # transform enum types, otherwise assume list of string choices if not data: return {} try: choices = [x.value for x in data] except AttributeError: c...
[ "def", "enum_choice_list", "(", "data", ")", ":", "# transform enum types, otherwise assume list of string choices", "if", "not", "data", ":", "return", "{", "}", "try", ":", "choices", "=", "[", "x", ".", "value", "for", "x", "in", "data", "]", "except", "Att...
Creates the argparse choices and type kwargs for a supplied enum type or list of strings
[ "Creates", "the", "argparse", "choices", "and", "type", "kwargs", "for", "a", "supplied", "enum", "type", "or", "list", "of", "strings" ]
python
train
sony/nnabla
python/src/nnabla/parametric_functions.py
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L2026-L2132
def pow2_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, with_zero_w=False, n_w=8, m_w=2, ste_fine_grained_w=True,...
[ "def", "pow2_quantized_affine", "(", "inp", ",", "n_outmaps", ",", "base_axis", "=", "1", ",", "w_init", "=", "None", ",", "b_init", "=", "None", ",", "fix_parameters", "=", "False", ",", "rng", "=", "None", ",", "with_bias", "=", "True", ",", "quantize_...
Pow2 Quantized Affine. Pow2 Quantized Affine is the affine function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_j = \sum_{i} Q(w_{ji}) x_i, where :math:`Q(w_{ji})` is the power-of-2 quantization function. ...
[ "Pow2", "Quantized", "Affine", "." ]
python
train
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_0/npm/npm_client.py
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/npm/npm_client.py#L335-L360
def update_scoped_package(self, package_version_details, feed_id, package_scope, unscoped_package_name, package_version): """UpdateScopedPackage. [Preview API] :param :class:`<PackageVersionDetails> <azure.devops.v5_0.npm.models.PackageVersionDetails>` package_version_details: :param str...
[ "def", "update_scoped_package", "(", "self", ",", "package_version_details", ",", "feed_id", ",", "package_scope", ",", "unscoped_package_name", ",", "package_version", ")", ":", "route_values", "=", "{", "}", "if", "feed_id", "is", "not", "None", ":", "route_valu...
UpdateScopedPackage. [Preview API] :param :class:`<PackageVersionDetails> <azure.devops.v5_0.npm.models.PackageVersionDetails>` package_version_details: :param str feed_id: :param str package_scope: :param str unscoped_package_name: :param str package_version: :rt...
[ "UpdateScopedPackage", ".", "[", "Preview", "API", "]", ":", "param", ":", "class", ":", "<PackageVersionDetails", ">", "<azure", ".", "devops", ".", "v5_0", ".", "npm", ".", "models", ".", "PackageVersionDetails", ">", "package_version_details", ":", ":", "pa...
python
train
echinopsii/net.echinopsii.ariane.community.cli.python3
ariane_clip3/directory.py
https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L1631-L1645
def json_2_nic(json_obj): """ transform JSON obj coming from Ariane to ariane_clip3 object :param json_obj: the JSON obj coming from Ariane :return: ariane_clip3 NIC object """ LOGGER.debug("NIC.json_2_nic") return NIC(nic_id=json_obj['nicID'], ...
[ "def", "json_2_nic", "(", "json_obj", ")", ":", "LOGGER", ".", "debug", "(", "\"NIC.json_2_nic\"", ")", "return", "NIC", "(", "nic_id", "=", "json_obj", "[", "'nicID'", "]", ",", "mac_address", "=", "json_obj", "[", "'nicMacAddress'", "]", ",", "name", "="...
transform JSON obj coming from Ariane to ariane_clip3 object :param json_obj: the JSON obj coming from Ariane :return: ariane_clip3 NIC object
[ "transform", "JSON", "obj", "coming", "from", "Ariane", "to", "ariane_clip3", "object", ":", "param", "json_obj", ":", "the", "JSON", "obj", "coming", "from", "Ariane", ":", "return", ":", "ariane_clip3", "NIC", "object" ]
python
train
vowatchka/palindromus
palindromus/__init__.py
https://github.com/vowatchka/palindromus/blob/2fdac9259d7ba515d27cfde48c6d2be721594d66/palindromus/__init__.py#L318-L366
def checksuper(sometext, interchange = ALL): """ Checks that some text is superpalindrome. Checking performs case-insensitive :param str sometext: It is some string that will be checked for superpalindrome as text. What is the text see at help(palindromus.istext) The text can be multil...
[ "def", "checksuper", "(", "sometext", ",", "interchange", "=", "ALL", ")", ":", "def", "text_by_columns", "(", "text", ",", "columns", ")", ":", "column_idx", "=", "0", "result_text", "=", "\"\"", "while", "column_idx", "+", "1", "<=", "columns", ":", "f...
Checks that some text is superpalindrome. Checking performs case-insensitive :param str sometext: It is some string that will be checked for superpalindrome as text. What is the text see at help(palindromus.istext) The text can be multiline. :keyword dict interchange: It is di...
[ "Checks", "that", "some", "text", "is", "superpalindrome", ".", "Checking", "performs", "case", "-", "insensitive", ":", "param", "str", "sometext", ":", "It", "is", "some", "string", "that", "will", "be", "checked", "for", "superpalindrome", "as", "text", "...
python
train
chrisspen/weka
weka/arff.py
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L592-L601
def define_attribute(self, name, atype, data=None): """ Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'. For nominal attributes, pass the possible values as data. For date attributes, pass the format as data. """ ...
[ "def", "define_attribute", "(", "self", ",", "name", ",", "atype", ",", "data", "=", "None", ")", ":", "self", ".", "attributes", ".", "append", "(", "name", ")", "assert", "atype", "in", "TYPES", ",", "\"Unknown type '%s'. Must be one of: %s\"", "%", "(", ...
Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'. For nominal attributes, pass the possible values as data. For date attributes, pass the format as data.
[ "Define", "a", "new", "attribute", ".", "atype", "has", "to", "be", "one", "of", "integer", "real", "numeric", "string", "date", "or", "nominal", ".", "For", "nominal", "attributes", "pass", "the", "possible", "values", "as", "data", ".", "For", "date", ...
python
train
gbiggs/rtsprofile
rtsprofile/exec_context.py
https://github.com/gbiggs/rtsprofile/blob/fded6eddcb0b25fe9808b1b12336a4413ea00905/rtsprofile/exec_context.py#L263-L282
def to_dict(self): '''Save this execution context into a dictionary.''' d = {'id': self.id, 'kind': self.kind} if self.rate != 0.0: d['rate'] = self.rate participants = [] for p in self.participants: participants.append(p.to_dict()) ...
[ "def", "to_dict", "(", "self", ")", ":", "d", "=", "{", "'id'", ":", "self", ".", "id", ",", "'kind'", ":", "self", ".", "kind", "}", "if", "self", ".", "rate", "!=", "0.0", ":", "d", "[", "'rate'", "]", "=", "self", ".", "rate", "participants"...
Save this execution context into a dictionary.
[ "Save", "this", "execution", "context", "into", "a", "dictionary", "." ]
python
train
basho/riak-python-client
riak/transports/tcp/transport.py
https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/transports/tcp/transport.py#L231-L238
def get_keys(self, bucket, timeout=None): """ Lists all keys within a bucket. """ msg_code = riak.pb.messages.MSG_CODE_LIST_KEYS_REQ codec = self._get_codec(msg_code) stream = self.stream_keys(bucket, timeout=timeout) return codec.decode_get_keys(stream)
[ "def", "get_keys", "(", "self", ",", "bucket", ",", "timeout", "=", "None", ")", ":", "msg_code", "=", "riak", ".", "pb", ".", "messages", ".", "MSG_CODE_LIST_KEYS_REQ", "codec", "=", "self", ".", "_get_codec", "(", "msg_code", ")", "stream", "=", "self"...
Lists all keys within a bucket.
[ "Lists", "all", "keys", "within", "a", "bucket", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/nose/util.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L139-L147
def file_like(name): """A name is file-like if it is a path that exists, or it has a directory part, or it ends in .py, or it isn't a legal python identifier. """ return (os.path.exists(name) or os.path.dirname(name) or name.endswith('.py') or not ident_re.match(o...
[ "def", "file_like", "(", "name", ")", ":", "return", "(", "os", ".", "path", ".", "exists", "(", "name", ")", "or", "os", ".", "path", ".", "dirname", "(", "name", ")", "or", "name", ".", "endswith", "(", "'.py'", ")", "or", "not", "ident_re", "....
A name is file-like if it is a path that exists, or it has a directory part, or it ends in .py, or it isn't a legal python identifier.
[ "A", "name", "is", "file", "-", "like", "if", "it", "is", "a", "path", "that", "exists", "or", "it", "has", "a", "directory", "part", "or", "it", "ends", "in", ".", "py", "or", "it", "isn", "t", "a", "legal", "python", "identifier", "." ]
python
test
CxAalto/gtfspy
gtfspy/routing/journey_data_analyzer.py
https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/journey_data_analyzer.py#L26-L73
def get_journey_legs_to_target(self, target, fastest_path=True, min_boardings=False, all_leg_sections=True, ignore_walk=False, diff_threshold=None, diff_path=None): """ Returns a dataframe of aggregated sections from source nodes to target. The returned...
[ "def", "get_journey_legs_to_target", "(", "self", ",", "target", ",", "fastest_path", "=", "True", ",", "min_boardings", "=", "False", ",", "all_leg_sections", "=", "True", ",", "ignore_walk", "=", "False", ",", "diff_threshold", "=", "None", ",", "diff_path", ...
Returns a dataframe of aggregated sections from source nodes to target. The returned sections are either transfer point to transfer point or stop to stop. In a before after setting, the results can be filtered based on values in a difference db. :param target: :param fastest_path: ...
[ "Returns", "a", "dataframe", "of", "aggregated", "sections", "from", "source", "nodes", "to", "target", ".", "The", "returned", "sections", "are", "either", "transfer", "point", "to", "transfer", "point", "or", "stop", "to", "stop", ".", "In", "a", "before",...
python
valid
Stewori/pytypes
pytypes/typechecker.py
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typechecker.py#L373-L549
def override(func, auto = False): """Decorator applicable to methods only. For a version applicable also to classes or modules use auto_override. Asserts that for the decorated method a parent method exists in its mro. If both the decorated method and its parent method are type annotated, the decora...
[ "def", "override", "(", "func", ",", "auto", "=", "False", ")", ":", "if", "not", "pytypes", ".", "checking_enabled", ":", "return", "func", "# notes:", "# - don't use @override on __init__ (raise warning? Error for now!),", "# because __init__ is not intended to be called ...
Decorator applicable to methods only. For a version applicable also to classes or modules use auto_override. Asserts that for the decorated method a parent method exists in its mro. If both the decorated method and its parent method are type annotated, the decorator additionally asserts compatibility of...
[ "Decorator", "applicable", "to", "methods", "only", ".", "For", "a", "version", "applicable", "also", "to", "classes", "or", "modules", "use", "auto_override", ".", "Asserts", "that", "for", "the", "decorated", "method", "a", "parent", "method", "exists", "in"...
python
train
fhcrc/nestly
nestly/scons.py
https://github.com/fhcrc/nestly/blob/4d7818b5950f405d2067a6b8577d5afb7527c9ff/nestly/scons.py#L136-L155
def add_target(self, name=None): """ Add an SCons target to this nest. The function decorated will be immediately called with each of the output directories and current control dictionaries. Each result will be added to the respective control dictionary for later nests to ...
[ "def", "add_target", "(", "self", ",", "name", "=", "None", ")", ":", "def", "deco", "(", "func", ")", ":", "def", "nestfunc", "(", "control", ")", ":", "destdir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dest_dir", ",", "control", ...
Add an SCons target to this nest. The function decorated will be immediately called with each of the output directories and current control dictionaries. Each result will be added to the respective control dictionary for later nests to access. :param name: Name for the target i...
[ "Add", "an", "SCons", "target", "to", "this", "nest", "." ]
python
train
sdispater/cleo
cleo/commands/command.py
https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L71-L83
def _configure_using_fluent_definition(self): """ Configure the console command using a fluent definition. """ definition = Parser.parse(self.signature) self._config.set_name(definition["name"]) for name, flags, description, default in definition["arguments"]: ...
[ "def", "_configure_using_fluent_definition", "(", "self", ")", ":", "definition", "=", "Parser", ".", "parse", "(", "self", ".", "signature", ")", "self", ".", "_config", ".", "set_name", "(", "definition", "[", "\"name\"", "]", ")", "for", "name", ",", "f...
Configure the console command using a fluent definition.
[ "Configure", "the", "console", "command", "using", "a", "fluent", "definition", "." ]
python
train
tchellomello/python-arlo
pyarlo/camera.py
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/camera.py#L224-L230
def _get_camera_properties(self): """Lookup camera properties from base station.""" if self.base_station and self.base_station.camera_properties: for cam in self.base_station.camera_properties: if cam["serialNumber"] == self.device_id: return cam r...
[ "def", "_get_camera_properties", "(", "self", ")", ":", "if", "self", ".", "base_station", "and", "self", ".", "base_station", ".", "camera_properties", ":", "for", "cam", "in", "self", ".", "base_station", ".", "camera_properties", ":", "if", "cam", "[", "\...
Lookup camera properties from base station.
[ "Lookup", "camera", "properties", "from", "base", "station", "." ]
python
train
Azure/azure-sdk-for-python
azure-mgmt-keyvault/azure/mgmt/keyvault/key_vault_management_client.py
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-mgmt-keyvault/azure/mgmt/keyvault/key_vault_management_client.py#L100-L112
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2016-10-01: :mod:`v2016_10_01.models<azure.mgmt.keyvault.v2016_10_01.models>` * 2018-02-14: :mod:`v2018_02_14.models<azure.mgmt.keyvault.v2018_02_14.models>` """ if api_version == '20...
[ "def", "models", "(", "cls", ",", "api_version", "=", "DEFAULT_API_VERSION", ")", ":", "if", "api_version", "==", "'2016-10-01'", ":", "from", ".", "v2016_10_01", "import", "models", "return", "models", "elif", "api_version", "==", "'2018-02-14'", ":", "from", ...
Module depends on the API version: * 2016-10-01: :mod:`v2016_10_01.models<azure.mgmt.keyvault.v2016_10_01.models>` * 2018-02-14: :mod:`v2018_02_14.models<azure.mgmt.keyvault.v2018_02_14.models>`
[ "Module", "depends", "on", "the", "API", "version", ":" ]
python
test
google-research/batch-ppo
agents/parts/iterate_sequences.py
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/parts/iterate_sequences.py#L26-L74
def iterate_sequences( consumer_fn, output_template, sequences, length, chunk_length=None, batch_size=None, num_epochs=1, padding_value=0): """Iterate over batches of chunks of sequences for multiple epochs. The batch dimension of the length tensor must be set because it is used to infer buffer sizes. ...
[ "def", "iterate_sequences", "(", "consumer_fn", ",", "output_template", ",", "sequences", ",", "length", ",", "chunk_length", "=", "None", ",", "batch_size", "=", "None", ",", "num_epochs", "=", "1", ",", "padding_value", "=", "0", ")", ":", "if", "not", "...
Iterate over batches of chunks of sequences for multiple epochs. The batch dimension of the length tensor must be set because it is used to infer buffer sizes. Args: consumer_fn: Function creating the operation to process the data. output_template: Nested tensors of same shape and dtype as outputs. ...
[ "Iterate", "over", "batches", "of", "chunks", "of", "sequences", "for", "multiple", "epochs", "." ]
python
train
KnowledgeLinks/rdfframework
rdfframework/connections/connmanager.py
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L106-L132
def set_conn(self, **kwargs): """ takes a connection and creates the connection """ # log = logging.getLogger("%s.%s" % (self.log, inspect.stack()[0][3])) log.setLevel(kwargs.get('log_level',self.log_level)) conn_name = kwargs.get("name") if not conn_name: raise Nam...
[ "def", "set_conn", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# log = logging.getLogger(\"%s.%s\" % (self.log, inspect.stack()[0][3]))", "log", ".", "setLevel", "(", "kwargs", ".", "get", "(", "'log_level'", ",", "self", ".", "log_level", ")", ")", "conn_nam...
takes a connection and creates the connection
[ "takes", "a", "connection", "and", "creates", "the", "connection" ]
python
train
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/python_breakpoint.py
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/python_breakpoint.py#L240-L250
def GetExpirationTime(self): """Computes the timestamp at which this breakpoint will expire.""" # TODO(emrekultursay): Move this to a common method. if '.' not in self.definition['createTime']: fmt = '%Y-%m-%dT%H:%M:%S%Z' else: fmt = '%Y-%m-%dT%H:%M:%S.%f%Z' create_datetime = datetime.s...
[ "def", "GetExpirationTime", "(", "self", ")", ":", "# TODO(emrekultursay): Move this to a common method.", "if", "'.'", "not", "in", "self", ".", "definition", "[", "'createTime'", "]", ":", "fmt", "=", "'%Y-%m-%dT%H:%M:%S%Z'", "else", ":", "fmt", "=", "'%Y-%m-%dT%H...
Computes the timestamp at which this breakpoint will expire.
[ "Computes", "the", "timestamp", "at", "which", "this", "breakpoint", "will", "expire", "." ]
python
train
rigetti/pyquil
pyquil/operator_estimation.py
https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/operator_estimation.py#L580-L628
def _max_tpb_overlap(tomo_expt: TomographyExperiment): """ Given an input TomographyExperiment, provide a dictionary indicating which ExperimentSettings share a tensor product basis :param tomo_expt: TomographyExperiment, from which to group ExperimentSettings that share a tpb and can be run to...
[ "def", "_max_tpb_overlap", "(", "tomo_expt", ":", "TomographyExperiment", ")", ":", "# initialize empty dictionary", "diagonal_sets", "=", "{", "}", "# loop through ExperimentSettings of the TomographyExperiment", "for", "expt_setting", "in", "tomo_expt", ":", "# no need to gro...
Given an input TomographyExperiment, provide a dictionary indicating which ExperimentSettings share a tensor product basis :param tomo_expt: TomographyExperiment, from which to group ExperimentSettings that share a tpb and can be run together :return: dictionary keyed with ExperimentSetting (specif...
[ "Given", "an", "input", "TomographyExperiment", "provide", "a", "dictionary", "indicating", "which", "ExperimentSettings", "share", "a", "tensor", "product", "basis" ]
python
train
owncloud/pyocclient
owncloud/owncloud.py
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1632-L1641
def _normalize_path(path): """Makes sure the path starts with a "/" """ if isinstance(path, FileInfo): path = path.path if len(path) == 0: return '/' if not path.startswith('/'): path = '/' + path return path
[ "def", "_normalize_path", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "FileInfo", ")", ":", "path", "=", "path", ".", "path", "if", "len", "(", "path", ")", "==", "0", ":", "return", "'/'", "if", "not", "path", ".", "startswith", "...
Makes sure the path starts with a "/"
[ "Makes", "sure", "the", "path", "starts", "with", "a", "/" ]
python
train
HttpRunner/HttpRunner
httprunner/utils.py
https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/utils.py#L28-L33
def unset_os_environ(variables_mapping): """ set variables mapping to os.environ """ for variable in variables_mapping: os.environ.pop(variable) logger.log_debug("Unset OS environment variable: {}".format(variable))
[ "def", "unset_os_environ", "(", "variables_mapping", ")", ":", "for", "variable", "in", "variables_mapping", ":", "os", ".", "environ", ".", "pop", "(", "variable", ")", "logger", ".", "log_debug", "(", "\"Unset OS environment variable: {}\"", ".", "format", "(", ...
set variables mapping to os.environ
[ "set", "variables", "mapping", "to", "os", ".", "environ" ]
python
train
Fantomas42/django-blog-zinnia
zinnia/comparison.py
https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/comparison.py#L53-L62
def get_related(self, instance, number): """ Return a list of the most related objects to instance. """ related_pks = self.compute_related(instance.pk)[:number] related_pks = [pk for pk, score in related_pks] related_objects = sorted( self.queryset.model.objec...
[ "def", "get_related", "(", "self", ",", "instance", ",", "number", ")", ":", "related_pks", "=", "self", ".", "compute_related", "(", "instance", ".", "pk", ")", "[", ":", "number", "]", "related_pks", "=", "[", "pk", "for", "pk", ",", "score", "in", ...
Return a list of the most related objects to instance.
[ "Return", "a", "list", "of", "the", "most", "related", "objects", "to", "instance", "." ]
python
train
blockstack/virtualchain
virtualchain/lib/ecdsalib.py
https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/ecdsalib.py#L380-L392
def sign_raw_data(raw_data, privatekey_hex): """ Sign a string of data. Returns signature as a base64 string """ if not isinstance(raw_data, (str, unicode)): raise ValueError("Data is not a string") raw_data = str(raw_data) si = ECSigner(privatekey_hex) si.update(raw_data) ...
[ "def", "sign_raw_data", "(", "raw_data", ",", "privatekey_hex", ")", ":", "if", "not", "isinstance", "(", "raw_data", ",", "(", "str", ",", "unicode", ")", ")", ":", "raise", "ValueError", "(", "\"Data is not a string\"", ")", "raw_data", "=", "str", "(", ...
Sign a string of data. Returns signature as a base64 string
[ "Sign", "a", "string", "of", "data", ".", "Returns", "signature", "as", "a", "base64", "string" ]
python
train
yyuu/botornado
boto/s3/key.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/s3/key.py#L1171-L1226
def get_contents_to_file(self, fp, headers=None, cb=None, num_cb=10, torrent=False, version_id=None, res_download_handler=None, response_headers=None): """ Ret...
[ "def", "get_contents_to_file", "(", "self", ",", "fp", ",", "headers", "=", "None", ",", "cb", "=", "None", ",", "num_cb", "=", "10", ",", "torrent", "=", "False", ",", "version_id", "=", "None", ",", "res_download_handler", "=", "None", ",", "response_h...
Retrieve an object from S3 using the name of the Key object as the key in S3. Write the contents of the object to the file pointed to by 'fp'. :type fp: File -like object :param fp: :type headers: dict :param headers: additional HTTP headers that will be sent with ...
[ "Retrieve", "an", "object", "from", "S3", "using", "the", "name", "of", "the", "Key", "object", "as", "the", "key", "in", "S3", ".", "Write", "the", "contents", "of", "the", "object", "to", "the", "file", "pointed", "to", "by", "fp", "." ]
python
train
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L3798-L3808
def xpathNextDescendant(self, ctxt): """Traversal function for the "descendant" direction the descendant axis contains the descendants of the context node in document order; a descendant is a child or a child of a child and so on. """ if ctxt is None: ctxt__o = None ...
[ "def", "xpathNextDescendant", "(", "self", ",", "ctxt", ")", ":", "if", "ctxt", "is", "None", ":", "ctxt__o", "=", "None", "else", ":", "ctxt__o", "=", "ctxt", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlXPathNextDescendant", "(", "ctxt__o", ",", "self...
Traversal function for the "descendant" direction the descendant axis contains the descendants of the context node in document order; a descendant is a child or a child of a child and so on.
[ "Traversal", "function", "for", "the", "descendant", "direction", "the", "descendant", "axis", "contains", "the", "descendants", "of", "the", "context", "node", "in", "document", "order", ";", "a", "descendant", "is", "a", "child", "or", "a", "child", "of", ...
python
train
Blueqat/Blueqat
blueqat/vqe.py
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L36-L52
def get_energy(self, circuit, sampler): """Calculate energy from circuit and sampler.""" val = 0.0 for meas in self.hamiltonian: c = circuit.copy() for op in meas.ops: if op.op == "X": c.h[op.n] elif op.op == "Y": ...
[ "def", "get_energy", "(", "self", ",", "circuit", ",", "sampler", ")", ":", "val", "=", "0.0", "for", "meas", "in", "self", ".", "hamiltonian", ":", "c", "=", "circuit", ".", "copy", "(", ")", "for", "op", "in", "meas", ".", "ops", ":", "if", "op...
Calculate energy from circuit and sampler.
[ "Calculate", "energy", "from", "circuit", "and", "sampler", "." ]
python
train
horazont/aioxmpp
aioxmpp/dispatcher.py
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/dispatcher.py#L338-L373
def message_handler(type_, from_): """ Register the decorated function as message handler. :param type_: Message type to listen for :type type_: :class:`~.MessageType` :param from_: Sender JIDs to listen for :type from_: :class:`aioxmpp.JID` or :data:`None` :raise TypeError: if the decorate...
[ "def", "message_handler", "(", "type_", ",", "from_", ")", ":", "def", "decorator", "(", "f", ")", ":", "if", "asyncio", ".", "iscoroutinefunction", "(", "f", ")", ":", "raise", "TypeError", "(", "\"message_handler must not be a coroutine function\"", ")", "aiox...
Register the decorated function as message handler. :param type_: Message type to listen for :type type_: :class:`~.MessageType` :param from_: Sender JIDs to listen for :type from_: :class:`aioxmpp.JID` or :data:`None` :raise TypeError: if the decorated object is a coroutine function .. seeals...
[ "Register", "the", "decorated", "function", "as", "message", "handler", "." ]
python
train
ARMmbed/icetea
icetea_lib/tools/GenericProcess.py
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GenericProcess.py#L219-L238
def stop(self): """ Stop the reader """ # print('stopping NonBlockingStreamReader..') # print('acquire..') NonBlockingStreamReader._stream_mtx.acquire() # print('acquire..ok') NonBlockingStreamReader._streams.remove(self._descriptor) if not NonBloc...
[ "def", "stop", "(", "self", ")", ":", "# print('stopping NonBlockingStreamReader..')", "# print('acquire..')", "NonBlockingStreamReader", ".", "_stream_mtx", ".", "acquire", "(", ")", "# print('acquire..ok')", "NonBlockingStreamReader", ".", "_streams", ".", "remove", "(", ...
Stop the reader
[ "Stop", "the", "reader" ]
python
train
redhat-cip/python-dciclient
dciclient/v1/shell_commands/remoteci.py
https://github.com/redhat-cip/python-dciclient/blob/a4aa5899062802bbe4c30a075d8447f8d222d214/dciclient/v1/shell_commands/remoteci.py#L359-L377
def attach_rconfiguration(context, id, name, topic_id, component_types, data): """attach_rconfiguration(context, name, topic_id, component_types, data): Attach an rconfiguration to a Remote CI >>> dcictl remoteci-attach-rconfiguration ID [OPTIONS] :param string id: id of the remoteci :param strin...
[ "def", "attach_rconfiguration", "(", "context", ",", "id", ",", "name", ",", "topic_id", ",", "component_types", ",", "data", ")", ":", "result", "=", "remoteci", ".", "add_rconfiguration", "(", "context", ",", "id", ",", "name", ",", "topic_id", ",", "com...
attach_rconfiguration(context, name, topic_id, component_types, data): Attach an rconfiguration to a Remote CI >>> dcictl remoteci-attach-rconfiguration ID [OPTIONS] :param string id: id of the remoteci :param string name: name of the rconfiguration [required] :param string topic_id: ID of the to...
[ "attach_rconfiguration", "(", "context", "name", "topic_id", "component_types", "data", ")", ":" ]
python
train
F-Secure/see
see/context/resources/network.py
https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/network.py#L198-L206
def address_lookup(hypervisor, address_pool): """Retrieves a valid and available network IP address.""" address_pool = set(address_pool) active_addresses = set(active_network_addresses(hypervisor)) try: return random.choice(tuple(address_pool - active_addresses)) except IndexError: ...
[ "def", "address_lookup", "(", "hypervisor", ",", "address_pool", ")", ":", "address_pool", "=", "set", "(", "address_pool", ")", "active_addresses", "=", "set", "(", "active_network_addresses", "(", "hypervisor", ")", ")", "try", ":", "return", "random", ".", ...
Retrieves a valid and available network IP address.
[ "Retrieves", "a", "valid", "and", "available", "network", "IP", "address", "." ]
python
train
mozilla/socorrolib
socorrolib/lib/transform_rules.py
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L87-L109
def action(self, *args, **kwargs): """the default action for Support Classifiers invokes any derivied _action function, trapping any exceptions raised in the process. We are obligated to catch these exceptions to give subsequent rules the opportunity to act and perhaps mitigate the erro...
[ "def", "action", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "self", ".", "_action", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "KeyError", ",", "x", ":", "self", ".", "config", ".", "l...
the default action for Support Classifiers invokes any derivied _action function, trapping any exceptions raised in the process. We are obligated to catch these exceptions to give subsequent rules the opportunity to act and perhaps mitigate the error. An error during the action applica...
[ "the", "default", "action", "for", "Support", "Classifiers", "invokes", "any", "derivied", "_action", "function", "trapping", "any", "exceptions", "raised", "in", "the", "process", ".", "We", "are", "obligated", "to", "catch", "these", "exceptions", "to", "give"...
python
train
sryza/spark-timeseries
python/sparkts/models/_model.py
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/models/_model.py#L7-L19
def remove_time_dependent_effects(self, ts): """ Given a timeseries, apply inverse operations to obtain the original series of underlying errors. Parameters ---------- ts: Time series of observations with this model's characteristics as a Numpy array ...
[ "def", "remove_time_dependent_effects", "(", "self", ",", "ts", ")", ":", "destts", "=", "Vectors", ".", "dense", "(", "np", ".", "array", "(", "[", "0", "]", "*", "len", "(", "ts", ")", ")", ")", "result", "=", "self", ".", "_jmodel", ".", "remove...
Given a timeseries, apply inverse operations to obtain the original series of underlying errors. Parameters ---------- ts: Time series of observations with this model's characteristics as a Numpy array returns the time series with removed time-dependent effects as a ...
[ "Given", "a", "timeseries", "apply", "inverse", "operations", "to", "obtain", "the", "original", "series", "of", "underlying", "errors", ".", "Parameters", "----------", "ts", ":", "Time", "series", "of", "observations", "with", "this", "model", "s", "characteri...
python
train
ljcooke/see
see/tools.py
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/tools.py#L47-L52
def filter_wildcard(names, pattern): """ Return a tuple of strings that match a shell-style wildcard pattern. """ return tuple(name for name in names if fnmatch.fnmatch(name, pattern))
[ "def", "filter_wildcard", "(", "names", ",", "pattern", ")", ":", "return", "tuple", "(", "name", "for", "name", "in", "names", "if", "fnmatch", ".", "fnmatch", "(", "name", ",", "pattern", ")", ")" ]
Return a tuple of strings that match a shell-style wildcard pattern.
[ "Return", "a", "tuple", "of", "strings", "that", "match", "a", "shell", "-", "style", "wildcard", "pattern", "." ]
python
train
lacava/few
few/evaluation.py
https://github.com/lacava/few/blob/5c72044425e9a5d73b8dc2cbb9b96e873dcb5b4a/few/evaluation.py#L232-L247
def inertia(X,y,samples=False): """ return the within-class squared distance from the centroid""" # pdb.set_trace() if samples: # return within-class distance for each sample inertia = np.zeros(y.shape) for label in np.unique(y): inertia[y==label] = (X[y==label] - np.mean...
[ "def", "inertia", "(", "X", ",", "y", ",", "samples", "=", "False", ")", ":", "# pdb.set_trace()", "if", "samples", ":", "# return within-class distance for each sample", "inertia", "=", "np", ".", "zeros", "(", "y", ".", "shape", ")", "for", "label", "in", ...
return the within-class squared distance from the centroid
[ "return", "the", "within", "-", "class", "squared", "distance", "from", "the", "centroid" ]
python
train
bsmurphy/PyKrige
pykrige/variogram_models.py
https://github.com/bsmurphy/PyKrige/blob/a4db3003b0b5688658c12faeb95a5a8b2b14b433/pykrige/variogram_models.py#L37-L42
def power_variogram_model(m, d): """Power model, m is [scale, exponent, nugget]""" scale = float(m[0]) exponent = float(m[1]) nugget = float(m[2]) return scale * d**exponent + nugget
[ "def", "power_variogram_model", "(", "m", ",", "d", ")", ":", "scale", "=", "float", "(", "m", "[", "0", "]", ")", "exponent", "=", "float", "(", "m", "[", "1", "]", ")", "nugget", "=", "float", "(", "m", "[", "2", "]", ")", "return", "scale", ...
Power model, m is [scale, exponent, nugget]
[ "Power", "model", "m", "is", "[", "scale", "exponent", "nugget", "]" ]
python
train
zabertech/python-izaber
izaber/zconfig.py
https://github.com/zabertech/python-izaber/blob/729bf9ef637e084c8ab3cc16c34cf659d3a79ee4/izaber/zconfig.py#L210-L299
def config_amend_(self,config_amend): """ This will take a YAML or dict configuration and load it into the configuration file for furthur usage. The good part about this method is that it doesn't clobber, only appends when keys are missing. This should provide a ...
[ "def", "config_amend_", "(", "self", ",", "config_amend", ")", ":", "if", "not", "isinstance", "(", "config_amend", ",", "dict", ")", ":", "config_amend", "=", "yaml", ".", "load", "(", "config_amend", ")", "def", "merge_dicts", "(", "source", ",", "target...
This will take a YAML or dict configuration and load it into the configuration file for furthur usage. The good part about this method is that it doesn't clobber, only appends when keys are missing. This should provide a value in dictionary format like: { ...
[ "This", "will", "take", "a", "YAML", "or", "dict", "configuration", "and", "load", "it", "into", "the", "configuration", "file", "for", "furthur", "usage", ".", "The", "good", "part", "about", "this", "method", "is", "that", "it", "doesn", "t", "clobber", ...
python
train
loli/medpy
bin/medpy_zoom_image.py
https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/bin/medpy_zoom_image.py#L80-L111
def zoom(image, factor, dimension, hdr = False, order = 3): """ Zooms the provided image by the supplied factor in the supplied dimension. The factor is an integer determining how many slices should be put between each existing pair. If an image header (hdr) is supplied, its voxel spacing gets updat...
[ "def", "zoom", "(", "image", ",", "factor", ",", "dimension", ",", "hdr", "=", "False", ",", "order", "=", "3", ")", ":", "# check if supplied dimension is valid", "if", "dimension", ">=", "image", ".", "ndim", ":", "raise", "argparse", ".", "ArgumentError",...
Zooms the provided image by the supplied factor in the supplied dimension. The factor is an integer determining how many slices should be put between each existing pair. If an image header (hdr) is supplied, its voxel spacing gets updated. Returns the image and the updated header or false.
[ "Zooms", "the", "provided", "image", "by", "the", "supplied", "factor", "in", "the", "supplied", "dimension", ".", "The", "factor", "is", "an", "integer", "determining", "how", "many", "slices", "should", "be", "put", "between", "each", "existing", "pair", "...
python
train
vmware/pyvmomi
pyVmomi/VmomiSupport.py
https://github.com/vmware/pyvmomi/blob/3ffcb23bf77d757175c0d5216ba9a25345d824cd/pyVmomi/VmomiSupport.py#L1285-L1305
def GetServiceVersions(namespace): """ Get all the versions for the service with specified namespace (partially) ordered by compatibility (i.e. any version in the list that is compatible with some version v in the list will preceed v) """ def compare(a, b): if a == b: return 0 if ...
[ "def", "GetServiceVersions", "(", "namespace", ")", ":", "def", "compare", "(", "a", ",", "b", ")", ":", "if", "a", "==", "b", ":", "return", "0", "if", "b", "in", "parentMap", "[", "a", "]", ":", "return", "-", "1", "if", "a", "in", "parentMap",...
Get all the versions for the service with specified namespace (partially) ordered by compatibility (i.e. any version in the list that is compatible with some version v in the list will preceed v)
[ "Get", "all", "the", "versions", "for", "the", "service", "with", "specified", "namespace", "(", "partially", ")", "ordered", "by", "compatibility", "(", "i", ".", "e", ".", "any", "version", "in", "the", "list", "that", "is", "compatible", "with", "some",...
python
train
google/grr
grr/server/grr_response_server/export.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/export.py#L1520-L1537
def Convert(self, metadata, yara_match, token=None): """Convert a single YaraProcessScanMatch.""" conv = ProcessToExportedProcessConverter(options=self.options) process = list( conv.Convert(ExportedMetadata(), yara_match.process, token=token))[0] seen_rules = set() for m in yara_match.matc...
[ "def", "Convert", "(", "self", ",", "metadata", ",", "yara_match", ",", "token", "=", "None", ")", ":", "conv", "=", "ProcessToExportedProcessConverter", "(", "options", "=", "self", ".", "options", ")", "process", "=", "list", "(", "conv", ".", "Convert",...
Convert a single YaraProcessScanMatch.
[ "Convert", "a", "single", "YaraProcessScanMatch", "." ]
python
train
atarashansky/self-assembling-manifold
SAM.py
https://github.com/atarashansky/self-assembling-manifold/blob/4db4793f65af62047492327716932ba81a67f679/SAM.py#L588-L610
def regress_genes(self, PCs): """Regress out the principal components in 'PCs' from the filtered expression data ('SAM.D'). Assumes 'calculate_regression_PCs' has been previously called. Parameters ---------- PCs - int, numpy.array, list The principal compone...
[ "def", "regress_genes", "(", "self", ",", "PCs", ")", ":", "ind", "=", "[", "PCs", "]", "ind", "=", "np", ".", "array", "(", "ind", ")", ".", "flatten", "(", ")", "try", ":", "y", "=", "self", ".", "adata", ".", "X", ".", "toarray", "(", ")",...
Regress out the principal components in 'PCs' from the filtered expression data ('SAM.D'). Assumes 'calculate_regression_PCs' has been previously called. Parameters ---------- PCs - int, numpy.array, list The principal components to regress out of the expression data...
[ "Regress", "out", "the", "principal", "components", "in", "PCs", "from", "the", "filtered", "expression", "data", "(", "SAM", ".", "D", ")", ".", "Assumes", "calculate_regression_PCs", "has", "been", "previously", "called", "." ]
python
train
genialis/resolwe
resolwe/flow/models/entity.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/entity.py#L74-L110
def duplicate(self, contributor=None, inherit_collections=False): """Duplicate (make a copy).""" duplicate = Entity.objects.get(id=self.id) duplicate.pk = None duplicate.slug = None duplicate.name = 'Copy of {}'.format(self.name) duplicate.duplicated = now() if co...
[ "def", "duplicate", "(", "self", ",", "contributor", "=", "None", ",", "inherit_collections", "=", "False", ")", ":", "duplicate", "=", "Entity", ".", "objects", ".", "get", "(", "id", "=", "self", ".", "id", ")", "duplicate", ".", "pk", "=", "None", ...
Duplicate (make a copy).
[ "Duplicate", "(", "make", "a", "copy", ")", "." ]
python
train
saltstack/salt
salt/modules/mysql.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1863-L1949
def grant_exists(grant, database, user, host='localhost', grant_option=False, escape=True, **connection_args): ''' Checks to see if a grant exists in the database CLI Example: .. code-block:: bash ...
[ "def", "grant_exists", "(", "grant", ",", "database", ",", "user", ",", "host", "=", "'localhost'", ",", "grant_option", "=", "False", ",", "escape", "=", "True", ",", "*", "*", "connection_args", ")", ":", "server_version", "=", "salt", ".", "utils", "....
Checks to see if a grant exists in the database CLI Example: .. code-block:: bash salt '*' mysql.grant_exists \ 'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
[ "Checks", "to", "see", "if", "a", "grant", "exists", "in", "the", "database" ]
python
train
pycontribs/python-crowd
crowd.py
https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L534-L551
def send_password_reset_link(self, username): """Sends the user a password reset link (by email) Args: username: The account username. Returns: True: Succeeded False: If unsuccessful """ response = self._post(self.rest_url + "/user/mail/pass...
[ "def", "send_password_reset_link", "(", "self", ",", "username", ")", ":", "response", "=", "self", ".", "_post", "(", "self", ".", "rest_url", "+", "\"/user/mail/password\"", ",", "params", "=", "{", "\"username\"", ":", "username", "}", ")", "if", "respons...
Sends the user a password reset link (by email) Args: username: The account username. Returns: True: Succeeded False: If unsuccessful
[ "Sends", "the", "user", "a", "password", "reset", "link", "(", "by", "email", ")" ]
python
train
erikrose/peep
peep.py
https://github.com/erikrose/peep/blob/c16f08c7f61e2f2afecb7cd1c93752bdd96c4968/peep.py#L321-L333
def memoize(func): """Memoize a method that should return the same result every time on a given instance. """ @wraps(func) def memoizer(self): if not hasattr(self, '_cache'): self._cache = {} if func.__name__ not in self._cache: self._cache[func.__name__] = f...
[ "def", "memoize", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "memoizer", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_cache'", ")", ":", "self", ".", "_cache", "=", "{", "}", "if", "func", ".", "__name__"...
Memoize a method that should return the same result every time on a given instance.
[ "Memoize", "a", "method", "that", "should", "return", "the", "same", "result", "every", "time", "on", "a", "given", "instance", "." ]
python
train
nicolargo/glances
glances/plugins/glances_gpu.py
https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/plugins/glances_gpu.py#L239-L248
def exit(self): """Overwrite the exit method to close the GPU API.""" if self.nvml_ready: try: pynvml.nvmlShutdown() except Exception as e: logger.debug("pynvml failed to shutdown correctly ({})".format(e)) # Call the father exit method ...
[ "def", "exit", "(", "self", ")", ":", "if", "self", ".", "nvml_ready", ":", "try", ":", "pynvml", ".", "nvmlShutdown", "(", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "\"pynvml failed to shutdown correctly ({})\"", ".", "format"...
Overwrite the exit method to close the GPU API.
[ "Overwrite", "the", "exit", "method", "to", "close", "the", "GPU", "API", "." ]
python
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L1366-L1433
def _parse_country_file(self, cty_file, country_mapping_filename=None): """ Parse the content of a PLIST file from country-files.com return the parsed values in dictionaries. Country-files.com provides Prefixes and Exceptions """ import plistlib cty_list = None...
[ "def", "_parse_country_file", "(", "self", ",", "cty_file", ",", "country_mapping_filename", "=", "None", ")", ":", "import", "plistlib", "cty_list", "=", "None", "entities", "=", "{", "}", "exceptions", "=", "{", "}", "prefixes", "=", "{", "}", "exceptions_...
Parse the content of a PLIST file from country-files.com return the parsed values in dictionaries. Country-files.com provides Prefixes and Exceptions
[ "Parse", "the", "content", "of", "a", "PLIST", "file", "from", "country", "-", "files", ".", "com", "return", "the", "parsed", "values", "in", "dictionaries", ".", "Country", "-", "files", ".", "com", "provides", "Prefixes", "and", "Exceptions" ]
python
train
log2timeline/plaso
plaso/output/shared_elastic.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/output/shared_elastic.py#L268-L278
def SetServerInformation(self, server, port): """Set the server information. Args: server (str): IP address or hostname of the server. port (int): Port number of the server. """ self._host = server self._port = port logger.debug('Elasticsearch server: {0!s} port: {1:d}'.format( ...
[ "def", "SetServerInformation", "(", "self", ",", "server", ",", "port", ")", ":", "self", ".", "_host", "=", "server", "self", ".", "_port", "=", "port", "logger", ".", "debug", "(", "'Elasticsearch server: {0!s} port: {1:d}'", ".", "format", "(", "server", ...
Set the server information. Args: server (str): IP address or hostname of the server. port (int): Port number of the server.
[ "Set", "the", "server", "information", "." ]
python
train
iotile/coretools
iotilecore/iotile/core/hw/reports/utc_assigner.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L125-L135
def anchor_stream(self, stream_id, converter="rtc"): """Mark a stream as containing anchor points.""" if isinstance(converter, str): converter = self._known_converters.get(converter) if converter is None: raise ArgumentError("Unknown anchor converter string: %s"...
[ "def", "anchor_stream", "(", "self", ",", "stream_id", ",", "converter", "=", "\"rtc\"", ")", ":", "if", "isinstance", "(", "converter", ",", "str", ")", ":", "converter", "=", "self", ".", "_known_converters", ".", "get", "(", "converter", ")", "if", "c...
Mark a stream as containing anchor points.
[ "Mark", "a", "stream", "as", "containing", "anchor", "points", "." ]
python
train
annoviko/pyclustering
pyclustering/container/cftree.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/container/cftree.py#L1186-L1216
def __split_leaf_node(self, node): """! @brief Performs splitting of the specified leaf node. @param[in] node (leaf_node): Leaf node that should be splitted. @return (list) New pair of leaf nodes [leaf_node1, leaf_node2]. @warning Splitted node ...
[ "def", "__split_leaf_node", "(", "self", ",", "node", ")", ":", "# search farthest pair of entries\r", "[", "farthest_entity1", ",", "farthest_entity2", "]", "=", "node", ".", "get_farthest_entries", "(", "self", ".", "__type_measurement", ")", "# create new nodes\r", ...
! @brief Performs splitting of the specified leaf node. @param[in] node (leaf_node): Leaf node that should be splitted. @return (list) New pair of leaf nodes [leaf_node1, leaf_node2]. @warning Splitted node is transformed to non_leaf.
[ "!" ]
python
valid
theislab/scvelo
scvelo/read_load.py
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/read_load.py#L35-L99
def clean_obs_names(data, base='[AGTCBDHKMNRSVWY]', ID_length=12, copy=False): """Cleans up the obs_names and identifies sample names. For example an obs_name 'samlple1_AGTCdate' is changed to 'AGTC' of the sample 'sample1_date'. The sample name is then saved in obs['sample_batch']. The genetic codes ar...
[ "def", "clean_obs_names", "(", "data", ",", "base", "=", "'[AGTCBDHKMNRSVWY]'", ",", "ID_length", "=", "12", ",", "copy", "=", "False", ")", ":", "def", "get_base_list", "(", "name", ",", "base", ")", ":", "base_list", "=", "base", "while", "re", ".", ...
Cleans up the obs_names and identifies sample names. For example an obs_name 'samlple1_AGTCdate' is changed to 'AGTC' of the sample 'sample1_date'. The sample name is then saved in obs['sample_batch']. The genetic codes are identified according to according to https://www.neb.com/tools-and-resources/usage-g...
[ "Cleans", "up", "the", "obs_names", "and", "identifies", "sample", "names", ".", "For", "example", "an", "obs_name", "samlple1_AGTCdate", "is", "changed", "to", "AGTC", "of", "the", "sample", "sample1_date", ".", "The", "sample", "name", "is", "then", "saved",...
python
train
aparo/pyes
pyes/es.py
https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L909-L921
def delete(self, index, doc_type, id, bulk=False, **query_params): """ Delete a typed JSON document from a specific index based on its id. If bulk is True, the delete operation is put in bulk mode. """ if bulk: cmd = {"delete": {"_index": index, "_type": doc_type, ...
[ "def", "delete", "(", "self", ",", "index", ",", "doc_type", ",", "id", ",", "bulk", "=", "False", ",", "*", "*", "query_params", ")", ":", "if", "bulk", ":", "cmd", "=", "{", "\"delete\"", ":", "{", "\"_index\"", ":", "index", ",", "\"_type\"", ":...
Delete a typed JSON document from a specific index based on its id. If bulk is True, the delete operation is put in bulk mode.
[ "Delete", "a", "typed", "JSON", "document", "from", "a", "specific", "index", "based", "on", "its", "id", ".", "If", "bulk", "is", "True", "the", "delete", "operation", "is", "put", "in", "bulk", "mode", "." ]
python
train
wright-group/WrightTools
WrightTools/kit/_path.py
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_path.py#L20-L44
def get_path_matching(name): """Get path matching a name. Parameters ---------- name : string Name to search for. Returns ------- string Full filepath. """ # first try looking in the user folder p = os.path.join(os.path.expanduser("~"), name) # then try expa...
[ "def", "get_path_matching", "(", "name", ")", ":", "# first try looking in the user folder", "p", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", ",", "name", ")", "# then try expanding upwards from cwd", "if", ...
Get path matching a name. Parameters ---------- name : string Name to search for. Returns ------- string Full filepath.
[ "Get", "path", "matching", "a", "name", "." ]
python
train
PedalPi/PluginsManager
pluginsmanager/jack/jack_client.py
https://github.com/PedalPi/PluginsManager/blob/2dcc9f6a79b48e9c9be82efffd855352fa15c5c7/pluginsmanager/jack/jack_client.py#L87-L91
def midi_outputs(self): """ :return: A list of MIDI output :class:`Ports`. """ return self.client.get_ports(is_midi=True, is_physical=True, is_output=True)
[ "def", "midi_outputs", "(", "self", ")", ":", "return", "self", ".", "client", ".", "get_ports", "(", "is_midi", "=", "True", ",", "is_physical", "=", "True", ",", "is_output", "=", "True", ")" ]
:return: A list of MIDI output :class:`Ports`.
[ ":", "return", ":", "A", "list", "of", "MIDI", "output", ":", "class", ":", "Ports", "." ]
python
train
log2timeline/dftimewolf
dftimewolf/lib/collectors/grr_hosts.py
https://github.com/log2timeline/dftimewolf/blob/45f898476a288d73c4256ae8e3836a2a4848c0d7/dftimewolf/lib/collectors/grr_hosts.py#L178-L209
def _download_files(self, client, flow_id): """Download files from the specified flow. Args: client: GRR Client object to which to download flow data from. flow_id: GRR flow ID. Returns: str: path of downloaded files. """ output_file_path = os.path.join( self.output_path,...
[ "def", "_download_files", "(", "self", ",", "client", ",", "flow_id", ")", ":", "output_file_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "output_path", ",", "'.'", ".", "join", "(", "(", "flow_id", ",", "'zip'", ")", ")", ")", "if",...
Download files from the specified flow. Args: client: GRR Client object to which to download flow data from. flow_id: GRR flow ID. Returns: str: path of downloaded files.
[ "Download", "files", "from", "the", "specified", "flow", "." ]
python
train
balloob/voluptuous-serialize
voluptuous_serialize/__init__.py
https://github.com/balloob/voluptuous-serialize/blob/02992eb3128063d065048cdcbfb907efe0a53b99/voluptuous_serialize/__init__.py#L15-L97
def convert(schema): """Convert a voluptuous schema to a dictionary.""" # pylint: disable=too-many-return-statements,too-many-branches if isinstance(schema, vol.Schema): schema = schema.schema if isinstance(schema, Mapping): val = [] for key, value in schema.items(): ...
[ "def", "convert", "(", "schema", ")", ":", "# pylint: disable=too-many-return-statements,too-many-branches", "if", "isinstance", "(", "schema", ",", "vol", ".", "Schema", ")", ":", "schema", "=", "schema", ".", "schema", "if", "isinstance", "(", "schema", ",", "...
Convert a voluptuous schema to a dictionary.
[ "Convert", "a", "voluptuous", "schema", "to", "a", "dictionary", "." ]
python
train
lepture/captcha
captcha/audio.py
https://github.com/lepture/captcha/blob/fb6238e741c7e264eba117b27fa911c25c76c527/captcha/audio.py#L124-L136
def mix_wave(src, dst): """Mix two wave body into one.""" if len(src) > len(dst): # output should be longer dst, src = src, dst for i, sv in enumerate(src): dv = dst[i] if sv < 128 and dv < 128: dst[i] = int(sv * dv / 128) else: dst[i] = int(2...
[ "def", "mix_wave", "(", "src", ",", "dst", ")", ":", "if", "len", "(", "src", ")", ">", "len", "(", "dst", ")", ":", "# output should be longer", "dst", ",", "src", "=", "src", ",", "dst", "for", "i", ",", "sv", "in", "enumerate", "(", "src", ")"...
Mix two wave body into one.
[ "Mix", "two", "wave", "body", "into", "one", "." ]
python
train
glormph/msstitch
src/app/readers/tsv.py
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/tsv.py#L74-L82
def get_proteins_from_psm(line): """From a line, return list of proteins reported by Mzid2TSV. When unrolled lines are given, this returns the single protein from the line.""" proteins = line[mzidtsvdata.HEADER_PROTEIN].split(';') outproteins = [] for protein in proteins: prepost_protein = r...
[ "def", "get_proteins_from_psm", "(", "line", ")", ":", "proteins", "=", "line", "[", "mzidtsvdata", ".", "HEADER_PROTEIN", "]", ".", "split", "(", "';'", ")", "outproteins", "=", "[", "]", "for", "protein", "in", "proteins", ":", "prepost_protein", "=", "r...
From a line, return list of proteins reported by Mzid2TSV. When unrolled lines are given, this returns the single protein from the line.
[ "From", "a", "line", "return", "list", "of", "proteins", "reported", "by", "Mzid2TSV", ".", "When", "unrolled", "lines", "are", "given", "this", "returns", "the", "single", "protein", "from", "the", "line", "." ]
python
train
nion-software/nionswift
nion/swift/FilterPanel.py
https://github.com/nion-software/nionswift/blob/d43693eaf057b8683b9638e575000f055fede452/nion/swift/FilterPanel.py#L121-L133
def __display_for_tree_node(self, tree_node): """ Return the text display for the given tree node. Based on number of keys associated with tree node. """ keys = tree_node.keys if len(keys) == 1: return "{0} ({1})".format(tree_node.keys[-1], tree_node.count) elif len(keys) == ...
[ "def", "__display_for_tree_node", "(", "self", ",", "tree_node", ")", ":", "keys", "=", "tree_node", ".", "keys", "if", "len", "(", "keys", ")", "==", "1", ":", "return", "\"{0} ({1})\"", ".", "format", "(", "tree_node", ".", "keys", "[", "-", "1", "]"...
Return the text display for the given tree node. Based on number of keys associated with tree node.
[ "Return", "the", "text", "display", "for", "the", "given", "tree", "node", ".", "Based", "on", "number", "of", "keys", "associated", "with", "tree", "node", "." ]
python
train
Robpol86/sphinxcontrib-imgur
sphinxcontrib/imgur/imgur_api.py
https://github.com/Robpol86/sphinxcontrib-imgur/blob/5c178481d645147d10acb096793eda41c12c57af/sphinxcontrib/imgur/imgur_api.py#L31-L74
def query_api(app, client_id, imgur_id, is_album): """Query the Imgur API. :raise APIError: When Imgur responds with errors or unexpected data. :param sphinx.application.Sphinx app: Sphinx application object. :param str client_id: Imgur API client ID to use. https://api.imgur.com/oauth2 :param str...
[ "def", "query_api", "(", "app", ",", "client_id", ",", "imgur_id", ",", "is_album", ")", ":", "url", "=", "API_URL", ".", "format", "(", "type", "=", "'album'", "if", "is_album", "else", "'image'", ",", "id", "=", "imgur_id", ")", "headers", "=", "{", ...
Query the Imgur API. :raise APIError: When Imgur responds with errors or unexpected data. :param sphinx.application.Sphinx app: Sphinx application object. :param str client_id: Imgur API client ID to use. https://api.imgur.com/oauth2 :param str imgur_id: The Imgur ID to query. :param bool is_album...
[ "Query", "the", "Imgur", "API", "." ]
python
train
newville/asteval
asteval/asteval.py
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L442-L452
def on_name(self, node): # ('id', 'ctx') """Name node.""" ctx = node.ctx.__class__ if ctx in (ast.Param, ast.Del): return str(node.id) else: if node.id in self.symtable: return self.symtable[node.id] else: msg = "name...
[ "def", "on_name", "(", "self", ",", "node", ")", ":", "# ('id', 'ctx')", "ctx", "=", "node", ".", "ctx", ".", "__class__", "if", "ctx", "in", "(", "ast", ".", "Param", ",", "ast", ".", "Del", ")", ":", "return", "str", "(", "node", ".", "id", ")"...
Name node.
[ "Name", "node", "." ]
python
train
tnkteja/myhelp
virtualEnvironment/lib/python2.7/site-packages/coverage/codeunit.py
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/codeunit.py#L9-L34
def code_unit_factory(morfs, file_locator): """Construct a list of CodeUnits from polymorphic inputs. `morfs` is a module or a filename, or a list of same. `file_locator` is a FileLocator that can help resolve filenames. Returns a list of CodeUnit objects. """ # Be sure we have a list. i...
[ "def", "code_unit_factory", "(", "morfs", ",", "file_locator", ")", ":", "# Be sure we have a list.", "if", "not", "isinstance", "(", "morfs", ",", "(", "list", ",", "tuple", ")", ")", ":", "morfs", "=", "[", "morfs", "]", "# On Windows, the shell doesn't expand...
Construct a list of CodeUnits from polymorphic inputs. `morfs` is a module or a filename, or a list of same. `file_locator` is a FileLocator that can help resolve filenames. Returns a list of CodeUnit objects.
[ "Construct", "a", "list", "of", "CodeUnits", "from", "polymorphic", "inputs", "." ]
python
test
CityOfZion/neo-python
neo/Settings.py
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Settings.py#L291-L309
def set_logfile(self, filename, max_bytes=0, backup_count=0): """ Setup logging to a (rotating) logfile. Args: filename (str): Logfile. If filename is None, disable file logging max_bytes (int): Maximum number of bytes per logfile. If used together with backup_count, ...
[ "def", "set_logfile", "(", "self", ",", "filename", ",", "max_bytes", "=", "0", ",", "backup_count", "=", "0", ")", ":", "_logger", "=", "logging", ".", "getLogger", "(", "\"neo-python\"", ")", "if", "not", "filename", "and", "not", "self", ".", "rotatin...
Setup logging to a (rotating) logfile. Args: filename (str): Logfile. If filename is None, disable file logging max_bytes (int): Maximum number of bytes per logfile. If used together with backup_count, logfile will be rotated when it reaches this amount of b...
[ "Setup", "logging", "to", "a", "(", "rotating", ")", "logfile", "." ]
python
train
codelv/enaml-native
src/enamlnative/android/android_fragment.py
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_fragment.py#L117-L131
def on_create_view(self): """ Trigger the click """ d = self.declaration changed = not d.condition if changed: d.condition = True view = self.get_view() if changed: self.ready.set_result(True) return view
[ "def", "on_create_view", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "changed", "=", "not", "d", ".", "condition", "if", "changed", ":", "d", ".", "condition", "=", "True", "view", "=", "self", ".", "get_view", "(", ")", "if", "chang...
Trigger the click
[ "Trigger", "the", "click" ]
python
train
cjdrake/pyeda
pyeda/boolalg/bdd.py
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L166-L178
def upoint2bddpoint(upoint): """Convert an untyped point into a BDD point. .. seealso:: For definitions of points and untyped points, see the :mod:`pyeda.boolalg.boolfunc` module. """ point = dict() for uniqid in upoint[0]: point[_VARS[uniqid]] = 0 for uniqid in upoint[1]:...
[ "def", "upoint2bddpoint", "(", "upoint", ")", ":", "point", "=", "dict", "(", ")", "for", "uniqid", "in", "upoint", "[", "0", "]", ":", "point", "[", "_VARS", "[", "uniqid", "]", "]", "=", "0", "for", "uniqid", "in", "upoint", "[", "1", "]", ":",...
Convert an untyped point into a BDD point. .. seealso:: For definitions of points and untyped points, see the :mod:`pyeda.boolalg.boolfunc` module.
[ "Convert", "an", "untyped", "point", "into", "a", "BDD", "point", "." ]
python
train
graphql-python/graphql-core-next
graphql/validation/rules/fields_on_correct_type.py
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/fields_on_correct_type.py#L71-L106
def get_suggested_type_names( schema: GraphQLSchema, type_: GraphQLOutputType, field_name: str ) -> List[str]: """ Get a list of suggested type names. Go through all of the implementations of type, as well as the interfaces that they implement. If any of those types include the provided field, ...
[ "def", "get_suggested_type_names", "(", "schema", ":", "GraphQLSchema", ",", "type_", ":", "GraphQLOutputType", ",", "field_name", ":", "str", ")", "->", "List", "[", "str", "]", ":", "if", "is_abstract_type", "(", "type_", ")", ":", "type_", "=", "cast", ...
Get a list of suggested type names. Go through all of the implementations of type, as well as the interfaces that they implement. If any of those types include the provided field, suggest them, sorted by how often the type is referenced, starting with Interfaces.
[ "Get", "a", "list", "of", "suggested", "type", "names", "." ]
python
train
StellarCN/py-stellar-base
stellar_base/stellarxdr/xdrgen.py
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/stellarxdr/xdrgen.py#L1075-L1096
def xdrbody(self, prefix=''): """Return xdr code for the body (part between braces) of big 3 types""" body = '' prefix += indent if self.type == 'enum': body = ''.join( ["%s,\n" % l.xdrout(prefix) for l in self.body[:-1]]) body += "%s\n" % self.bod...
[ "def", "xdrbody", "(", "self", ",", "prefix", "=", "''", ")", ":", "body", "=", "''", "prefix", "+=", "indent", "if", "self", ".", "type", "==", "'enum'", ":", "body", "=", "''", ".", "join", "(", "[", "\"%s,\\n\"", "%", "l", ".", "xdrout", "(", ...
Return xdr code for the body (part between braces) of big 3 types
[ "Return", "xdr", "code", "for", "the", "body", "(", "part", "between", "braces", ")", "of", "big", "3", "types" ]
python
train
GibbsConsulting/django-plotly-dash
django_plotly_dash/models.py
https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/models.py#L184-L189
def populate_values(self): ''' Add values from the underlying dash layout configuration ''' obj = self._get_base_state() self.base_state = json.dumps(obj)
[ "def", "populate_values", "(", "self", ")", ":", "obj", "=", "self", ".", "_get_base_state", "(", ")", "self", ".", "base_state", "=", "json", ".", "dumps", "(", "obj", ")" ]
Add values from the underlying dash layout configuration
[ "Add", "values", "from", "the", "underlying", "dash", "layout", "configuration" ]
python
train
joestump/python-oauth2
oauth2/__init__.py
https://github.com/joestump/python-oauth2/blob/b94f69b1ad195513547924e380d9265133e995fa/oauth2/__init__.py#L269-L282
def to_string(self): """Returns this token as a plain string, suitable for storage. The resulting string includes the token's secret, so you should never send or store this string where a third party can read it. """ items = [ ('oauth_token', self.key), ...
[ "def", "to_string", "(", "self", ")", ":", "items", "=", "[", "(", "'oauth_token'", ",", "self", ".", "key", ")", ",", "(", "'oauth_token_secret'", ",", "self", ".", "secret", ")", ",", "]", "if", "self", ".", "callback_confirmed", "is", "not", "None",...
Returns this token as a plain string, suitable for storage. The resulting string includes the token's secret, so you should never send or store this string where a third party can read it.
[ "Returns", "this", "token", "as", "a", "plain", "string", "suitable", "for", "storage", ".", "The", "resulting", "string", "includes", "the", "token", "s", "secret", "so", "you", "should", "never", "send", "or", "store", "this", "string", "where", "a", "th...
python
train
kamikaze/webdav
src/webdav/client.py
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L393-L417
def download_file(self, remote_path, local_path, progress=None): """Downloads file from WebDAV server and save it locally. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: the path to remote file for downloading. :param local...
[ "def", "download_file", "(", "self", ",", "remote_path", ",", "local_path", ",", "progress", "=", "None", ")", ":", "urn", "=", "Urn", "(", "remote_path", ")", "if", "self", ".", "is_dir", "(", "urn", ".", "path", "(", ")", ")", ":", "raise", "Option...
Downloads file from WebDAV server and save it locally. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: the path to remote file for downloading. :param local_path: the path to save file locally. :param progress: progress func...
[ "Downloads", "file", "from", "WebDAV", "server", "and", "save", "it", "locally", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#rfc", ".", "section", ".", ...
python
train
iotile/coretools
iotilecore/iotile/core/utilities/async_tools/operation_manager.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L216-L227
def clear(self): """Clear all waiters. This method will remove any current scheduled waiter with an asyncio.CancelledError exception. """ for _, waiter in self.waiters(): if isinstance(waiter, asyncio.Future) and not waiter.done(): waiter.set_excepti...
[ "def", "clear", "(", "self", ")", ":", "for", "_", ",", "waiter", "in", "self", ".", "waiters", "(", ")", ":", "if", "isinstance", "(", "waiter", ",", "asyncio", ".", "Future", ")", "and", "not", "waiter", ".", "done", "(", ")", ":", "waiter", "....
Clear all waiters. This method will remove any current scheduled waiter with an asyncio.CancelledError exception.
[ "Clear", "all", "waiters", "." ]
python
train
TeamHG-Memex/eli5
eli5/xgboost.py
https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/xgboost.py#L89-L217
def explain_prediction_xgboost( xgb, doc, vec=None, top=None, top_targets=None, target_names=None, targets=None, feature_names=None, feature_re=None, # type: Pattern[str] feature_filter=None, vectorized=False, # type: bool is_regr...
[ "def", "explain_prediction_xgboost", "(", "xgb", ",", "doc", ",", "vec", "=", "None", ",", "top", "=", "None", ",", "top_targets", "=", "None", ",", "target_names", "=", "None", ",", "targets", "=", "None", ",", "feature_names", "=", "None", ",", "featur...
Return an explanation of XGBoost prediction (via scikit-learn wrapper XGBClassifier or XGBRegressor, or via xgboost.Booster) as feature weights. See :func:`eli5.explain_prediction` for description of ``top``, ``top_targets``, ``target_names``, ``targets``, ``feature_names``, ``feature_re`` and ``featur...
[ "Return", "an", "explanation", "of", "XGBoost", "prediction", "(", "via", "scikit", "-", "learn", "wrapper", "XGBClassifier", "or", "XGBRegressor", "or", "via", "xgboost", ".", "Booster", ")", "as", "feature", "weights", "." ]
python
train
pypa/bandersnatch
src/bandersnatch/utils.py
https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/utils.py#L121-L145
def update_safe(filename: str, **kw: Any) -> Generator[IO, None, None]: """Rewrite a file atomically. Clients are allowed to delete the tmpfile to signal that they don't want to have it updated. """ with tempfile.NamedTemporaryFile( dir=os.path.dirname(filename), delete=False, ...
[ "def", "update_safe", "(", "filename", ":", "str", ",", "*", "*", "kw", ":", "Any", ")", "->", "Generator", "[", "IO", ",", "None", ",", "None", "]", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "dir", "=", "os", ".", "path", ".", "dirn...
Rewrite a file atomically. Clients are allowed to delete the tmpfile to signal that they don't want to have it updated.
[ "Rewrite", "a", "file", "atomically", "." ]
python
train
Azure/azure-cli-extensions
src/express-route-cross-connection/azext_expressroutecrossconnection/vendored_sdks/network_management_client.py
https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/express-route-cross-connection/azext_expressroutecrossconnection/vendored_sdks/network_management_client.py#L168-L220
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2015-06-15: :mod:`v2015_06_15.models<azure.mgmt.network.v2015_06_15.models>` * 2016-09-01: :mod:`v2016_09_01.models<azure.mgmt.network.v2016_09_01.models>` * 2016-12-01: :mod:`v2016_12_01....
[ "def", "models", "(", "cls", ",", "api_version", "=", "DEFAULT_API_VERSION", ")", ":", "if", "api_version", "==", "'2015-06-15'", ":", "from", ".", "v2015_06_15", "import", "models", "return", "models", "elif", "api_version", "==", "'2016-09-01'", ":", "from", ...
Module depends on the API version: * 2015-06-15: :mod:`v2015_06_15.models<azure.mgmt.network.v2015_06_15.models>` * 2016-09-01: :mod:`v2016_09_01.models<azure.mgmt.network.v2016_09_01.models>` * 2016-12-01: :mod:`v2016_12_01.models<azure.mgmt.network.v2016_12_01.models>` * 2...
[ "Module", "depends", "on", "the", "API", "version", ":" ]
python
train
cablehead/vanilla
vanilla/message.py
https://github.com/cablehead/vanilla/blob/c9f5b86f45720a30e8840fb68b1429b919c4ca66/vanilla/message.py#L243-L254
def send(self, item, timeout=-1): """ Send an *item* on this pair. This will block unless our Rever is ready, either forever or until *timeout* milliseconds. """ if not self.ready: self.pause(timeout=timeout) if isinstance(item, Exception): return...
[ "def", "send", "(", "self", ",", "item", ",", "timeout", "=", "-", "1", ")", ":", "if", "not", "self", ".", "ready", ":", "self", ".", "pause", "(", "timeout", "=", "timeout", ")", "if", "isinstance", "(", "item", ",", "Exception", ")", ":", "ret...
Send an *item* on this pair. This will block unless our Rever is ready, either forever or until *timeout* milliseconds.
[ "Send", "an", "*", "item", "*", "on", "this", "pair", ".", "This", "will", "block", "unless", "our", "Rever", "is", "ready", "either", "forever", "or", "until", "*", "timeout", "*", "milliseconds", "." ]
python
train
nugget/python-insteonplm
insteonplm/plm.py
https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L381-L385
def _get_plm_info(self): """Request PLM Info.""" _LOGGER.info('Requesting Insteon Modem Info') msg = GetImInfo() self.send_msg(msg, wait_nak=True, wait_timeout=.5)
[ "def", "_get_plm_info", "(", "self", ")", ":", "_LOGGER", ".", "info", "(", "'Requesting Insteon Modem Info'", ")", "msg", "=", "GetImInfo", "(", ")", "self", ".", "send_msg", "(", "msg", ",", "wait_nak", "=", "True", ",", "wait_timeout", "=", ".5", ")" ]
Request PLM Info.
[ "Request", "PLM", "Info", "." ]
python
train
Esri/ArcREST
src/arcrest/common/general.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/general.py#L237-L244
def geometryType(self): """ returns the feature's geometry type """ if self._geomType is None: if self.geometry is not None: self._geomType = self.geometry.type else: self._geomType = "Table" return self._geomType
[ "def", "geometryType", "(", "self", ")", ":", "if", "self", ".", "_geomType", "is", "None", ":", "if", "self", ".", "geometry", "is", "not", "None", ":", "self", ".", "_geomType", "=", "self", ".", "geometry", ".", "type", "else", ":", "self", ".", ...
returns the feature's geometry type
[ "returns", "the", "feature", "s", "geometry", "type" ]
python
train
rflamary/POT
ot/datasets.py
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/datasets.py#L83-L85
def get_2D_samples_gauss(n, m, sigma, random_state=None): """ Deprecated see make_2D_samples_gauss """ return make_2D_samples_gauss(n, m, sigma, random_state=None)
[ "def", "get_2D_samples_gauss", "(", "n", ",", "m", ",", "sigma", ",", "random_state", "=", "None", ")", ":", "return", "make_2D_samples_gauss", "(", "n", ",", "m", ",", "sigma", ",", "random_state", "=", "None", ")" ]
Deprecated see make_2D_samples_gauss
[ "Deprecated", "see", "make_2D_samples_gauss" ]
python
train
saltstack/salt
salt/cloud/clouds/azurearm.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/azurearm.py#L192-L213
def get_resource_by_id(resource_id, api_version, extract_value=None): ''' Get an AzureARM resource by id ''' ret = {} try: resconn = get_conn(client_type='resource') resource_query = resconn.resources.get_by_id( resource_id=resource_id, api_version=api_versio...
[ "def", "get_resource_by_id", "(", "resource_id", ",", "api_version", ",", "extract_value", "=", "None", ")", ":", "ret", "=", "{", "}", "try", ":", "resconn", "=", "get_conn", "(", "client_type", "=", "'resource'", ")", "resource_query", "=", "resconn", ".",...
Get an AzureARM resource by id
[ "Get", "an", "AzureARM", "resource", "by", "id" ]
python
train
agabrown/PyGaia
pygaia/errors/astrometric.py
https://github.com/agabrown/PyGaia/blob/ae972b0622a15f713ffae471f925eac25ccdae47/pygaia/errors/astrometric.py#L203-L228
def positionErrorSkyAvg(G, vmini, extension=0.0): """ Calculate the sky averaged position errors from G and (V-I). NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR SIMULATED ASTROMETRY IS ALSO ON THE ICRS. Parameters ---------- G - Value(s) of ...
[ "def", "positionErrorSkyAvg", "(", "G", ",", "vmini", ",", "extension", "=", "0.0", ")", ":", "parallaxError", "=", "parallaxErrorSkyAvg", "(", "G", ",", "vmini", ",", "extension", "=", "extension", ")", "return", "_scalingForPositions", "[", "'AlphaStar'", "]...
Calculate the sky averaged position errors from G and (V-I). NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR SIMULATED ASTROMETRY IS ALSO ON THE ICRS. Parameters ---------- G - Value(s) of G-band magnitude. vmini - Value(s) of (V-I) colour. K...
[ "Calculate", "the", "sky", "averaged", "position", "errors", "from", "G", "and", "(", "V", "-", "I", ")", "." ]
python
test
nickmckay/LiPD-utilities
Python/lipd/lpd_noaa.py
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L221-L241
def __convert_keys_2(header, d): """ Convert lpd to noaa keys for this one section :param str header: Section header :param dict d: Metadata :return dict: Metadata w/ converted keys """ d_out = {} try: for k, v in d.items(): tr...
[ "def", "__convert_keys_2", "(", "header", ",", "d", ")", ":", "d_out", "=", "{", "}", "try", ":", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "try", ":", "noaa_key", "=", "LIPD_NOAA_MAP_BY_SECTION", "[", "header", "]", "[", "k", ...
Convert lpd to noaa keys for this one section :param str header: Section header :param dict d: Metadata :return dict: Metadata w/ converted keys
[ "Convert", "lpd", "to", "noaa", "keys", "for", "this", "one", "section", ":", "param", "str", "header", ":", "Section", "header", ":", "param", "dict", "d", ":", "Metadata", ":", "return", "dict", ":", "Metadata", "w", "/", "converted", "keys" ]
python
train
Radi85/Comment
comment/templatetags/comment_tags.py
https://github.com/Radi85/Comment/blob/c3c46afe51228cd7ee4e04f5e6164fff1be3a5bc/comment/templatetags/comment_tags.py#L48-L65
def img_url(obj, profile_app_name, profile_model_name): """ returns url of profile image of a user """ try: content_type = ContentType.objects.get( app_label=profile_app_name, model=profile_model_name.lower() ) except ContentType.DoesNotExist: return "" ex...
[ "def", "img_url", "(", "obj", ",", "profile_app_name", ",", "profile_model_name", ")", ":", "try", ":", "content_type", "=", "ContentType", ".", "objects", ".", "get", "(", "app_label", "=", "profile_app_name", ",", "model", "=", "profile_model_name", ".", "lo...
returns url of profile image of a user
[ "returns", "url", "of", "profile", "image", "of", "a", "user" ]
python
train
fuzeman/plex.py
plex/request.py
https://github.com/fuzeman/plex.py/blob/f1155f94bce1a695a569b56ac8ba5bb6da00a07f/plex/request.py#L34-L56
def construct_url(self): """Construct a full plex request URI, with `params`.""" path = [self.path] path.extend([str(x) for x in self.params]) url = self.client.base_url + '/'.join(x for x in path if x) query = self.kwargs.get('query') if query: # Dict -> Li...
[ "def", "construct_url", "(", "self", ")", ":", "path", "=", "[", "self", ".", "path", "]", "path", ".", "extend", "(", "[", "str", "(", "x", ")", "for", "x", "in", "self", ".", "params", "]", ")", "url", "=", "self", ".", "client", ".", "base_u...
Construct a full plex request URI, with `params`.
[ "Construct", "a", "full", "plex", "request", "URI", "with", "params", "." ]
python
train
noahbenson/neuropythy
neuropythy/util/core.py
https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/util/core.py#L1465-L1477
def dirpath_to_list(p): ''' dirpath_to_list(path) yields a list of directories contained in the given path specification. A path may be either a single directory name (==> [path]), a :-separated list of directories (==> path.split(':')), a list of directory names (==> path), or None (==> []). Note that...
[ "def", "dirpath_to_list", "(", "p", ")", ":", "if", "p", "is", "None", ":", "p", "=", "[", "]", "elif", "pimms", ".", "is_str", "(", "p", ")", ":", "p", "=", "p", ".", "split", "(", "':'", ")", "if", "len", "(", "p", ")", ">", "0", "and", ...
dirpath_to_list(path) yields a list of directories contained in the given path specification. A path may be either a single directory name (==> [path]), a :-separated list of directories (==> path.split(':')), a list of directory names (==> path), or None (==> []). Note that the return value filters out pa...
[ "dirpath_to_list", "(", "path", ")", "yields", "a", "list", "of", "directories", "contained", "in", "the", "given", "path", "specification", "." ]
python
train
ssalentin/plip
plip/modules/report.py
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L75-L87
def construct_txt_file(self): """Construct the header of the txt file""" textlines = ['Prediction of noncovalent interactions for PDB structure %s' % self.mol.pymol_name.upper(), ] textlines.append("=" * len(textlines[0])) textlines.append('Created on %s using PLIP v%s\n' % (time.strftim...
[ "def", "construct_txt_file", "(", "self", ")", ":", "textlines", "=", "[", "'Prediction of noncovalent interactions for PDB structure %s'", "%", "self", ".", "mol", ".", "pymol_name", ".", "upper", "(", ")", ",", "]", "textlines", ".", "append", "(", "\"=\"", "*...
Construct the header of the txt file
[ "Construct", "the", "header", "of", "the", "txt", "file" ]
python
train
dswah/pyGAM
pygam/pygam.py
https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1929-L2044
def sample(self, X, y, quantity='y', sample_at_X=None, weights=None, n_draws=100, n_bootstraps=5, objective='auto'): """Simulate from the posterior of the coefficients and smoothing params. Samples are drawn from the posterior of the coefficients and smoothing parameters given th...
[ "def", "sample", "(", "self", ",", "X", ",", "y", ",", "quantity", "=", "'y'", ",", "sample_at_X", "=", "None", ",", "weights", "=", "None", ",", "n_draws", "=", "100", ",", "n_bootstraps", "=", "5", ",", "objective", "=", "'auto'", ")", ":", "if",...
Simulate from the posterior of the coefficients and smoothing params. Samples are drawn from the posterior of the coefficients and smoothing parameters given the response in an approximate way. The GAM must already be fitted before calling this method; if the model has not been fitted, ...
[ "Simulate", "from", "the", "posterior", "of", "the", "coefficients", "and", "smoothing", "params", "." ]
python
train
saulpw/visidata
visidata/vdtui.py
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2301-L2307
def ColumnAttr(name='', attr=None, **kwargs): 'Column using getattr/setattr of given attr.' return Column(name, expr=attr if attr is not None else name, getter=lambda col,row: getattrdeep(row, col.expr), setter=lambda col,row,val: setattrdeep(row, col.expr, ...
[ "def", "ColumnAttr", "(", "name", "=", "''", ",", "attr", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Column", "(", "name", ",", "expr", "=", "attr", "if", "attr", "is", "not", "None", "else", "name", ",", "getter", "=", "lambda", ...
Column using getattr/setattr of given attr.
[ "Column", "using", "getattr", "/", "setattr", "of", "given", "attr", "." ]
python
train
Fantomas42/django-blog-zinnia
zinnia/views/random.py
https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/views/random.py#L14-L20
def get_redirect_url(self, **kwargs): """ Get entry corresponding to 'pk' and return the get_absolute_url of the entry. """ entry = Entry.published.all().order_by('?')[0] return entry.get_absolute_url()
[ "def", "get_redirect_url", "(", "self", ",", "*", "*", "kwargs", ")", ":", "entry", "=", "Entry", ".", "published", ".", "all", "(", ")", ".", "order_by", "(", "'?'", ")", "[", "0", "]", "return", "entry", ".", "get_absolute_url", "(", ")" ]
Get entry corresponding to 'pk' and return the get_absolute_url of the entry.
[ "Get", "entry", "corresponding", "to", "pk", "and", "return", "the", "get_absolute_url", "of", "the", "entry", "." ]
python
train
PGower/PyCanvas
pycanvas/apis/grade_change_log.py
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/grade_change_log.py#L19-L44
def query_by_assignment(self, assignment_id, end_time=None, start_time=None): """ Query by assignment. List grade change events for a given assignment. """ path = {} data = {} params = {} # REQUIRED - PATH - assignment_id """ID""" ...
[ "def", "query_by_assignment", "(", "self", ",", "assignment_id", ",", "end_time", "=", "None", ",", "start_time", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - assignment_id\r", "\"\"\"ID\"...
Query by assignment. List grade change events for a given assignment.
[ "Query", "by", "assignment", ".", "List", "grade", "change", "events", "for", "a", "given", "assignment", "." ]
python
train
tjcsl/ion
intranet/apps/eighth/models.py
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L579-L582
def num_no_signups(self): """How many people have not signed up?""" signup_users_count = User.objects.get_students().count() return signup_users_count - self.num_signups()
[ "def", "num_no_signups", "(", "self", ")", ":", "signup_users_count", "=", "User", ".", "objects", ".", "get_students", "(", ")", ".", "count", "(", ")", "return", "signup_users_count", "-", "self", ".", "num_signups", "(", ")" ]
How many people have not signed up?
[ "How", "many", "people", "have", "not", "signed", "up?" ]
python
train
sbarham/dsrt
build/lib/dsrt/config/ConfigurationLoader.py
https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/build/lib/dsrt/config/ConfigurationLoader.py#L24-L54
def load_config(self, path): '''Load a configuration file; eventually, support dicts, .yaml, .csv, etc.''' # if no path was provided, resort to defaults if path == None: print("Path to config was null; using defaults.") return if not os.path.exists(path): ...
[ "def", "load_config", "(", "self", ",", "path", ")", ":", "# if no path was provided, resort to defaults", "if", "path", "==", "None", ":", "print", "(", "\"Path to config was null; using defaults.\"", ")", "return", "if", "not", "os", ".", "path", ".", "exists", ...
Load a configuration file; eventually, support dicts, .yaml, .csv, etc.
[ "Load", "a", "configuration", "file", ";", "eventually", "support", "dicts", ".", "yaml", ".", "csv", "etc", "." ]
python
train
autokey/autokey
lib/autokey/scripting_highlevel.py
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting_highlevel.py#L114-L124
def acknowledge_gnome_notification(): """ Moves mouse pointer to the bottom center of the screen and clicks on it. """ x0, y0 = mouse_pos() mouse_move(10000, 10000) # TODO: What if the screen is larger? Loop until mouse position does not change anymore? x, y = mouse_pos() mouse_rmove(-x/2, ...
[ "def", "acknowledge_gnome_notification", "(", ")", ":", "x0", ",", "y0", "=", "mouse_pos", "(", ")", "mouse_move", "(", "10000", ",", "10000", ")", "# TODO: What if the screen is larger? Loop until mouse position does not change anymore?", "x", ",", "y", "=", "mouse_pos...
Moves mouse pointer to the bottom center of the screen and clicks on it.
[ "Moves", "mouse", "pointer", "to", "the", "bottom", "center", "of", "the", "screen", "and", "clicks", "on", "it", "." ]
python
train
saltstack/salt
salt/modules/boto_iam.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L408-L440
def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=p...
[ "def", "get_group_members", "(", "group_name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",",...
Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup
[ "Get", "group", "information", "." ]
python
train
Gandi/gandi.cli
gandi/cli/commands/ip.py
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/ip.py#L220-L231
def detach(gandi, resource, background, force): """Detach an ip from it's currently attached vm. resource can be an ip id or ip. """ if not force: proceed = click.confirm('Are you sure you want to detach ip %s?' % resource) if not proceed: ret...
[ "def", "detach", "(", "gandi", ",", "resource", ",", "background", ",", "force", ")", ":", "if", "not", "force", ":", "proceed", "=", "click", ".", "confirm", "(", "'Are you sure you want to detach ip %s?'", "%", "resource", ")", "if", "not", "proceed", ":",...
Detach an ip from it's currently attached vm. resource can be an ip id or ip.
[ "Detach", "an", "ip", "from", "it", "s", "currently", "attached", "vm", "." ]
python
train
inveniosoftware/invenio-communities
invenio_communities/cli.py
https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/cli.py#L81-L93
def request(community_id, record_id, accept): """Request a record acceptance to a community.""" c = Community.get(community_id) assert c is not None record = Record.get_record(record_id) if accept: c.add_record(record) record.commit() else: InclusionRequest.create(communi...
[ "def", "request", "(", "community_id", ",", "record_id", ",", "accept", ")", ":", "c", "=", "Community", ".", "get", "(", "community_id", ")", "assert", "c", "is", "not", "None", "record", "=", "Record", ".", "get_record", "(", "record_id", ")", "if", ...
Request a record acceptance to a community.
[ "Request", "a", "record", "acceptance", "to", "a", "community", "." ]
python
train
NLeSC/noodles
noodles/lib/streams.py
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/lib/streams.py#L212-L226
def broadcast(*sinks_): """The |broadcast| decorator creates a |push| object that receives a message by ``yield`` and then sends this message on to all the given sinks. .. |broadcast| replace:: :py:func:`broadcast` """ @push def bc(): sinks = [s() for s in sinks_] while True: ...
[ "def", "broadcast", "(", "*", "sinks_", ")", ":", "@", "push", "def", "bc", "(", ")", ":", "sinks", "=", "[", "s", "(", ")", "for", "s", "in", "sinks_", "]", "while", "True", ":", "msg", "=", "yield", "for", "s", "in", "sinks", ":", "s", ".",...
The |broadcast| decorator creates a |push| object that receives a message by ``yield`` and then sends this message on to all the given sinks. .. |broadcast| replace:: :py:func:`broadcast`
[ "The", "|broadcast|", "decorator", "creates", "a", "|push|", "object", "that", "receives", "a", "message", "by", "yield", "and", "then", "sends", "this", "message", "on", "to", "all", "the", "given", "sinks", "." ]
python
train
limpyd/redis-limpyd
limpyd/indexes.py
https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/indexes.py#L1314-L1322
def store(self, key, pk, value): """Store the value/pk in the sorted set index For the parameters, see BaseRangeIndex.store We simple store the pk as a member of the sorted set with the value being the score """ self.connection.zadd(key, value, pk)
[ "def", "store", "(", "self", ",", "key", ",", "pk", ",", "value", ")", ":", "self", ".", "connection", ".", "zadd", "(", "key", ",", "value", ",", "pk", ")" ]
Store the value/pk in the sorted set index For the parameters, see BaseRangeIndex.store We simple store the pk as a member of the sorted set with the value being the score
[ "Store", "the", "value", "/", "pk", "in", "the", "sorted", "set", "index" ]
python
train
yougov/librarypaste
librarypaste/datastore.py
https://github.com/yougov/librarypaste/blob/740fafcb260f493ca5bbd24afd59d49444c2b2ae/librarypaste/datastore.py#L13-L26
def short_key(): """ Generate a short key. >>> key = short_key() >>> len(key) 5 """ firstlast = list(ascii_letters + digits) middle = firstlast + list('-_') return ''.join(( choice(firstlast), choice(middle), choice(middle), choice(middle), choice(firstlast), ))
[ "def", "short_key", "(", ")", ":", "firstlast", "=", "list", "(", "ascii_letters", "+", "digits", ")", "middle", "=", "firstlast", "+", "list", "(", "'-_'", ")", "return", "''", ".", "join", "(", "(", "choice", "(", "firstlast", ")", ",", "choice", "...
Generate a short key. >>> key = short_key() >>> len(key) 5
[ "Generate", "a", "short", "key", "." ]
python
train
Erotemic/utool
utool/_internal/win32_send_keys.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/win32_send_keys.py#L638-L688
def main(): "Send some test strings" actions = """ {LWIN} {PAUSE .25} r {PAUSE .25} Notepad.exe{ENTER} {PAUSE 1} Hello{SPACE}World! {PAUSE 1} %{F4} {PAUSE .25} n """ SendKeys(actions, pause = .1) keys = par...
[ "def", "main", "(", ")", ":", "actions", "=", "\"\"\"\n {LWIN}\n {PAUSE .25}\n r\n {PAUSE .25}\n Notepad.exe{ENTER}\n {PAUSE 1}\n Hello{SPACE}World!\n {PAUSE 1}\n %{F4}\n {PAUSE .25}\n n\n \"\"\"", "SendKeys", "(",...
Send some test strings
[ "Send", "some", "test", "strings" ]
python
train