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
pjuren/pyokit
src/pyokit/io/genomeAlignment.py
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/genomeAlignment.py#L63-L72
def __trim_extensions_dot(exts): """trim leading dots from extensions and drop any empty strings.""" if exts is None: return None res = [] for i in range(0, len(exts)): if exts[i] == "": continue res.append(__trim_extension_dot(exts[i])) return res
[ "def", "__trim_extensions_dot", "(", "exts", ")", ":", "if", "exts", "is", "None", ":", "return", "None", "res", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "exts", ")", ")", ":", "if", "exts", "[", "i", "]", "==", "\"\...
trim leading dots from extensions and drop any empty strings.
[ "trim", "leading", "dots", "from", "extensions", "and", "drop", "any", "empty", "strings", "." ]
python
train
pybel/pybel
src/pybel/io/nodelink.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/nodelink.py#L77-L80
def from_json_file(file: TextIO, check_version=True) -> BELGraph: """Build a graph from the Node-Link JSON contained in the given file.""" graph_json_dict = json.load(file) return from_json(graph_json_dict, check_version=check_version)
[ "def", "from_json_file", "(", "file", ":", "TextIO", ",", "check_version", "=", "True", ")", "->", "BELGraph", ":", "graph_json_dict", "=", "json", ".", "load", "(", "file", ")", "return", "from_json", "(", "graph_json_dict", ",", "check_version", "=", "chec...
Build a graph from the Node-Link JSON contained in the given file.
[ "Build", "a", "graph", "from", "the", "Node", "-", "Link", "JSON", "contained", "in", "the", "given", "file", "." ]
python
train
wavycloud/pyboto3
pyboto3/cloudwatch.py
https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/cloudwatch.py#L571-L778
def put_metric_alarm(AlarmName=None, AlarmDescription=None, ActionsEnabled=None, OKActions=None, AlarmActions=None, InsufficientDataActions=None, MetricName=None, Namespace=None, Statistic=None, ExtendedStatistic=None, Dimensions=None, Period=None, Unit=None, EvaluationPeriods=None, Threshold=None, ComparisonOperator=N...
[ "def", "put_metric_alarm", "(", "AlarmName", "=", "None", ",", "AlarmDescription", "=", "None", ",", "ActionsEnabled", "=", "None", ",", "OKActions", "=", "None", ",", "AlarmActions", "=", "None", ",", "InsufficientDataActions", "=", "None", ",", "MetricName", ...
Creates or updates an alarm and associates it with the specified metric. Optionally, this operation can associate one or more Amazon SNS resources with the alarm. When this operation creates an alarm, the alarm state is immediately set to INSUFFICIENT_DATA . The alarm is evaluated and its state is set appropriately...
[ "Creates", "or", "updates", "an", "alarm", "and", "associates", "it", "with", "the", "specified", "metric", ".", "Optionally", "this", "operation", "can", "associate", "one", "or", "more", "Amazon", "SNS", "resources", "with", "the", "alarm", ".", "When", "t...
python
train
jeremymcrae/denovonear
denovonear/ensembl_requester.py
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/ensembl_requester.py#L324-L344
def get_exon_ranges_for_transcript(self, transcript_id): """ obtain the sequence for a transcript from ensembl """ headers = {"content-type": "application/json"} self.attempt = 0 ext = "/overlap/id/{}?feature=exon".format(transcript_id) r = self.ensembl_...
[ "def", "get_exon_ranges_for_transcript", "(", "self", ",", "transcript_id", ")", ":", "headers", "=", "{", "\"content-type\"", ":", "\"application/json\"", "}", "self", ".", "attempt", "=", "0", "ext", "=", "\"/overlap/id/{}?feature=exon\"", ".", "format", "(", "t...
obtain the sequence for a transcript from ensembl
[ "obtain", "the", "sequence", "for", "a", "transcript", "from", "ensembl" ]
python
train
scoutapp/scout_apm_python
src/scout_apm/core/config.py
https://github.com/scoutapp/scout_apm_python/blob/e5539ee23b8129be9b75d5007c88b6158b51294f/src/scout_apm/core/config.py#L91-L98
def set(cls, **kwargs): """ Sets a configuration value for the Scout agent. Values set here will not override values set in ENV. """ global SCOUT_PYTHON_VALUES for key, value in kwargs.items(): SCOUT_PYTHON_VALUES[key] = value
[ "def", "set", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "global", "SCOUT_PYTHON_VALUES", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "SCOUT_PYTHON_VALUES", "[", "key", "]", "=", "value" ]
Sets a configuration value for the Scout agent. Values set here will not override values set in ENV.
[ "Sets", "a", "configuration", "value", "for", "the", "Scout", "agent", ".", "Values", "set", "here", "will", "not", "override", "values", "set", "in", "ENV", "." ]
python
train
arne-cl/discoursegraphs
src/discoursegraphs/readwrite/exmaralda.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/exmaralda.py#L127-L158
def __add_annotation_tier(self, docgraph, body, annotation_layer): """ adds a span-based annotation layer as a <tier> to the Exmaralda <body>. Parameter --------- docgraph : DiscourseDocumentGraph the document graph from which the chains will be extracted bod...
[ "def", "__add_annotation_tier", "(", "self", ",", "docgraph", ",", "body", ",", "annotation_layer", ")", ":", "layer_cat", "=", "annotation_layer", ".", "split", "(", "':'", ")", "[", "-", "1", "]", "temp_tier", "=", "self", ".", "E", "(", "'tier'", ",",...
adds a span-based annotation layer as a <tier> to the Exmaralda <body>. Parameter --------- docgraph : DiscourseDocumentGraph the document graph from which the chains will be extracted body : etree._Element an etree representation of the <basic_body> element (and...
[ "adds", "a", "span", "-", "based", "annotation", "layer", "as", "a", "<tier", ">", "to", "the", "Exmaralda", "<body", ">", "." ]
python
train
MonashBI/arcana
arcana/data/input.py
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/data/input.py#L135-L141
def pipeline_getter(self): "For duck-typing with *Spec types" if not self.derivable: raise ArcanaUsageError( "There is no pipeline getter for {} because it doesn't " "fallback to a derived spec".format(self)) return self._fallback.pipeline_getter
[ "def", "pipeline_getter", "(", "self", ")", ":", "if", "not", "self", ".", "derivable", ":", "raise", "ArcanaUsageError", "(", "\"There is no pipeline getter for {} because it doesn't \"", "\"fallback to a derived spec\"", ".", "format", "(", "self", ")", ")", "return",...
For duck-typing with *Spec types
[ "For", "duck", "-", "typing", "with", "*", "Spec", "types" ]
python
train
ubernostrum/django-registration
src/django_registration/validators.py
https://github.com/ubernostrum/django-registration/blob/cf10b13423669346a1f4cfaa31aae0b42856b416/src/django_registration/validators.py#L253-L269
def validate_confusables_email(value): """ Validator which disallows 'dangerous' email addresses likely to represent homograph attacks. An email address is 'dangerous' if either the local-part or the domain, considered on their own, are mixed-script and contain one or more characters appearing ...
[ "def", "validate_confusables_email", "(", "value", ")", ":", "if", "'@'", "not", "in", "value", ":", "return", "local_part", ",", "domain", "=", "value", ".", "split", "(", "'@'", ")", "if", "confusables", ".", "is_dangerous", "(", "local_part", ")", "or",...
Validator which disallows 'dangerous' email addresses likely to represent homograph attacks. An email address is 'dangerous' if either the local-part or the domain, considered on their own, are mixed-script and contain one or more characters appearing in the Unicode Visually Confusable Characters f...
[ "Validator", "which", "disallows", "dangerous", "email", "addresses", "likely", "to", "represent", "homograph", "attacks", "." ]
python
train
bcb/jsonrpcserver
jsonrpcserver/methods.py
https://github.com/bcb/jsonrpcserver/blob/26bb70e868f81691816cabfc4b60a83428842b2f/jsonrpcserver/methods.py#L16-L31
def validate_args(func: Method, *args: Any, **kwargs: Any) -> Method: """ Check if the request's arguments match a function's signature. Raises TypeError exception if arguments cannot be passed to a function. Args: func: The function to check. args: Positional arguments. kwargs...
[ "def", "validate_args", "(", "func", ":", "Method", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Method", ":", "signature", "(", "func", ")", ".", "bind", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return",...
Check if the request's arguments match a function's signature. Raises TypeError exception if arguments cannot be passed to a function. Args: func: The function to check. args: Positional arguments. kwargs: Keyword arguments. Raises: TypeError: If the arguments cannot be pa...
[ "Check", "if", "the", "request", "s", "arguments", "match", "a", "function", "s", "signature", "." ]
python
train
fedora-infra/fedmsg
fedmsg/crypto/gpg.py
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/crypto/gpg.py#L56-L87
def verify(self, data, signature=None, keyrings=None, homedir=None): ''' `data` <string> the data to verify. `signature` <string> The signature, if detached from the data. `keyrings` <list of string> Additional keyrings to search in. `homedir` <string> Override the configured hom...
[ "def", "verify", "(", "self", ",", "data", ",", "signature", "=", "None", ",", "keyrings", "=", "None", ",", "homedir", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", ":", "data", "=", "data", ".", "encod...
`data` <string> the data to verify. `signature` <string> The signature, if detached from the data. `keyrings` <list of string> Additional keyrings to search in. `homedir` <string> Override the configured homedir.
[ "data", "<string", ">", "the", "data", "to", "verify", ".", "signature", "<string", ">", "The", "signature", "if", "detached", "from", "the", "data", ".", "keyrings", "<list", "of", "string", ">", "Additional", "keyrings", "to", "search", "in", ".", "homed...
python
train
greenbender/pynntp
nntp/nntp.py
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L364-L382
def info_gen(self, code, message, compressed=False): """Dispatcher for the info generators. Determines which __info_*_gen() should be used based on the supplied parameters. Args: code: The status code for the command response. message: The status message for the...
[ "def", "info_gen", "(", "self", ",", "code", ",", "message", ",", "compressed", "=", "False", ")", ":", "if", "\"COMPRESS=GZIP\"", "in", "message", ":", "return", "self", ".", "__info_gzip_gen", "(", ")", "if", "compressed", ":", "return", "self", ".", "...
Dispatcher for the info generators. Determines which __info_*_gen() should be used based on the supplied parameters. Args: code: The status code for the command response. message: The status message for the command reponse. compressed: Force decompression. U...
[ "Dispatcher", "for", "the", "info", "generators", "." ]
python
test
mitsei/dlkit
dlkit/json_/utilities.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/utilities.py#L105-L135
def clean_up_datetime(obj_map): """convert datetime objects to dictionaries for storage""" clean_map = {} for key, value in obj_map.items(): if isinstance(value, datetime.datetime): clean_map[key] = { 'year': value.year, 'month': value.month, ...
[ "def", "clean_up_datetime", "(", "obj_map", ")", ":", "clean_map", "=", "{", "}", "for", "key", ",", "value", "in", "obj_map", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "clean_map", "[", ...
convert datetime objects to dictionaries for storage
[ "convert", "datetime", "objects", "to", "dictionaries", "for", "storage" ]
python
train
williamFalcon/test-tube
examples/hpc_cpu_example.py
https://github.com/williamFalcon/test-tube/blob/db5a47067a854f76d89f8066582023c1e184bccb/examples/hpc_cpu_example.py#L5-L31
def train(hparams, *args): """Train your awesome model. :param hparams: The arguments to run the model with. """ # Initialize experiments and track all the hyperparameters exp = Experiment( name=hparams.test_tube_exp_name, # Location to save the metrics. save_dir=hparams.log...
[ "def", "train", "(", "hparams", ",", "*", "args", ")", ":", "# Initialize experiments and track all the hyperparameters", "exp", "=", "Experiment", "(", "name", "=", "hparams", ".", "test_tube_exp_name", ",", "# Location to save the metrics.", "save_dir", "=", "hparams"...
Train your awesome model. :param hparams: The arguments to run the model with.
[ "Train", "your", "awesome", "model", "." ]
python
test
sbusard/wagoner
wagoner/tree.py
https://github.com/sbusard/wagoner/blob/7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b/wagoner/tree.py#L33-L70
def from_table(cls, table, length, prefix=0, flatten=False): """ Extract from the given table a tree for word length, taking only prefixes of prefix length (if greater than 0) into account to compute successors. :param table: the table to extract the tree from; :...
[ "def", "from_table", "(", "cls", ",", "table", ",", "length", ",", "prefix", "=", "0", ",", "flatten", "=", "False", ")", ":", "# Build the expanded tree with necessary suffix and length", "tree", "=", "defaultdict", "(", "dict", ")", "# The tree", "pending", "=...
Extract from the given table a tree for word length, taking only prefixes of prefix length (if greater than 0) into account to compute successors. :param table: the table to extract the tree from; :param length: the length of words generated by the extracted tree; ...
[ "Extract", "from", "the", "given", "table", "a", "tree", "for", "word", "length", "taking", "only", "prefixes", "of", "prefix", "length", "(", "if", "greater", "than", "0", ")", "into", "account", "to", "compute", "successors", ".", ":", "param", "table", ...
python
train
pypa/pipenv
pipenv/vendor/requirementslib/utils.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/utils.py#L148-L160
def is_vcs(pipfile_entry): # type: (PipfileType) -> bool """Determine if dictionary entry from Pipfile is for a vcs dependency.""" if isinstance(pipfile_entry, Mapping): return any(key for key in pipfile_entry.keys() if key in VCS_LIST) elif isinstance(pipfile_entry, six.string_types): ...
[ "def", "is_vcs", "(", "pipfile_entry", ")", ":", "# type: (PipfileType) -> bool", "if", "isinstance", "(", "pipfile_entry", ",", "Mapping", ")", ":", "return", "any", "(", "key", "for", "key", "in", "pipfile_entry", ".", "keys", "(", ")", "if", "key", "in", ...
Determine if dictionary entry from Pipfile is for a vcs dependency.
[ "Determine", "if", "dictionary", "entry", "from", "Pipfile", "is", "for", "a", "vcs", "dependency", "." ]
python
train
bethgelab/foolbox
foolbox/attacks/adef_attack.py
https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/attacks/adef_attack.py#L76-L117
def _compose(image, vec_field, color_axis): """Calculate the composition of the function image with the vector field vec_field by interpolation. new_func = compose(image, vec_field) In: image: numpy.ndarray of shape C x h x w with C = 3 or C = 1 (color channels), h, w >= 2, and [type...
[ "def", "_compose", "(", "image", ",", "vec_field", ",", "color_axis", ")", ":", "if", "color_axis", "==", "2", ":", "image", "=", "_transpose_image", "(", "image", ")", "c", ",", "h", ",", "w", "=", "image", ".", "shape", "# colors, height, width", "hran...
Calculate the composition of the function image with the vector field vec_field by interpolation. new_func = compose(image, vec_field) In: image: numpy.ndarray of shape C x h x w with C = 3 or C = 1 (color channels), h, w >= 2, and [type] = 'Float' or 'Double'. Contains the value...
[ "Calculate", "the", "composition", "of", "the", "function", "image", "with", "the", "vector", "field", "vec_field", "by", "interpolation", ".", "new_func", "=", "compose", "(", "image", "vec_field", ")", "In", ":", "image", ":", "numpy", ".", "ndarray", "of"...
python
valid
keenlabs/KeenClient-Python
keen/api.py
https://github.com/keenlabs/KeenClient-Python/blob/266387c3376d1e000d117e17c45045ae3439d43f/keen/api.py#L184-L207
def query(self, analysis_type, params, all_keys=False): """ Performs a query using the Keen IO analysis API. A read key must be set first. """ if not self._order_by_is_valid_or_none(params): raise ValueError("order_by given is invalid or is missing required group_by.") ...
[ "def", "query", "(", "self", ",", "analysis_type", ",", "params", ",", "all_keys", "=", "False", ")", ":", "if", "not", "self", ".", "_order_by_is_valid_or_none", "(", "params", ")", ":", "raise", "ValueError", "(", "\"order_by given is invalid or is missing requi...
Performs a query using the Keen IO analysis API. A read key must be set first.
[ "Performs", "a", "query", "using", "the", "Keen", "IO", "analysis", "API", ".", "A", "read", "key", "must", "be", "set", "first", "." ]
python
train
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_metrics.py
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_metrics.py#L179-L191
def TNE_metric(bpmn_graph): """ Returns the value of the TNE metric (Total Number of Events of the Model) for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. """ events_counts = get_events_counts(bpmn_graph) return sum( [c...
[ "def", "TNE_metric", "(", "bpmn_graph", ")", ":", "events_counts", "=", "get_events_counts", "(", "bpmn_graph", ")", "return", "sum", "(", "[", "count", "for", "_", ",", "count", "in", "events_counts", ".", "items", "(", ")", "]", ")" ]
Returns the value of the TNE metric (Total Number of Events of the Model) for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model.
[ "Returns", "the", "value", "of", "the", "TNE", "metric", "(", "Total", "Number", "of", "Events", "of", "the", "Model", ")", "for", "the", "BPMNDiagramGraph", "instance", "." ]
python
train
saltstack/salt
salt/modules/vsphere.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L5150-L5278
def _apply_cluster_dict(cluster_spec, cluster_dict, vsan_spec=None, vsan_61=True): ''' Applies the values of cluster_dict dictionary to a cluster spec (vim.ClusterConfigSpecEx). All vsan values (cluster_dict['vsan']) will be applied to vsan_spec (vim.vsan.cluster.ConfigInfoE...
[ "def", "_apply_cluster_dict", "(", "cluster_spec", ",", "cluster_dict", ",", "vsan_spec", "=", "None", ",", "vsan_61", "=", "True", ")", ":", "log", ".", "trace", "(", "'Applying cluster dict %s'", ",", "cluster_dict", ")", "if", "cluster_dict", ".", "get", "(...
Applies the values of cluster_dict dictionary to a cluster spec (vim.ClusterConfigSpecEx). All vsan values (cluster_dict['vsan']) will be applied to vsan_spec (vim.vsan.cluster.ConfigInfoEx). Can be not omitted if not required. VSAN 6.1 config needs to be applied differently than the post VSAN 6.1...
[ "Applies", "the", "values", "of", "cluster_dict", "dictionary", "to", "a", "cluster", "spec", "(", "vim", ".", "ClusterConfigSpecEx", ")", "." ]
python
train
ChrisCummins/labm8
modules.py
https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/modules.py#L28-L68
def import_foreign(name, custom_name=None): """ Import a module with a custom name. NOTE this is only needed for Python2. For Python3, import the module using the "as" keyword to declare the custom name. For implementation details, see: http://stackoverflow.com/a/6032023 Example: T...
[ "def", "import_foreign", "(", "name", ",", "custom_name", "=", "None", ")", ":", "if", "lab", ".", "is_python3", "(", ")", ":", "io", ".", "error", "(", "(", "\"Ignoring attempt to import foreign module '{mod}' \"", "\"using python version {major}.{minor}\"", ".", "...
Import a module with a custom name. NOTE this is only needed for Python2. For Python3, import the module using the "as" keyword to declare the custom name. For implementation details, see: http://stackoverflow.com/a/6032023 Example: To import the standard module "math" as "std_math": ...
[ "Import", "a", "module", "with", "a", "custom", "name", "." ]
python
train
apache/incubator-mxnet
tools/caffe_translator/scripts/convert_caffe_model.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/caffe_translator/scripts/convert_caffe_model.py#L33-L36
def add_param(self, param_name, layer_index, blob_index): """Add a param to the .params file""" blobs = self.layers[layer_index].blobs self.dict_param[param_name] = mx.nd.array(caffe.io.blobproto_to_array(blobs[blob_index]))
[ "def", "add_param", "(", "self", ",", "param_name", ",", "layer_index", ",", "blob_index", ")", ":", "blobs", "=", "self", ".", "layers", "[", "layer_index", "]", ".", "blobs", "self", ".", "dict_param", "[", "param_name", "]", "=", "mx", ".", "nd", "....
Add a param to the .params file
[ "Add", "a", "param", "to", "the", ".", "params", "file" ]
python
train
sentinel-hub/sentinelhub-py
sentinelhub/areas.py
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L181-L184
def _reduce_sizes(self, bbox_list): """Reduces sizes of bounding boxes """ return [BBox(self._intersection_area(bbox).bounds, self.crs).transform(bbox.crs) for bbox in bbox_list]
[ "def", "_reduce_sizes", "(", "self", ",", "bbox_list", ")", ":", "return", "[", "BBox", "(", "self", ".", "_intersection_area", "(", "bbox", ")", ".", "bounds", ",", "self", ".", "crs", ")", ".", "transform", "(", "bbox", ".", "crs", ")", "for", "bbo...
Reduces sizes of bounding boxes
[ "Reduces", "sizes", "of", "bounding", "boxes" ]
python
train
saltstack/salt
salt/cloud/clouds/ec2.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/ec2.py#L3792-L3809
def _toggle_term_protect(name, value): ''' Enable or Disable termination protection on a node ''' instance_id = _get_node(name)['instanceId'] params = {'Action': 'ModifyInstanceAttribute', 'InstanceId': instance_id, 'DisableApiTermination.Value': value} result = aws...
[ "def", "_toggle_term_protect", "(", "name", ",", "value", ")", ":", "instance_id", "=", "_get_node", "(", "name", ")", "[", "'instanceId'", "]", "params", "=", "{", "'Action'", ":", "'ModifyInstanceAttribute'", ",", "'InstanceId'", ":", "instance_id", ",", "'D...
Enable or Disable termination protection on a node
[ "Enable", "or", "Disable", "termination", "protection", "on", "a", "node" ]
python
train
ghukill/pyfc4
pyfc4/models.py
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/models.py#L1085-L1106
def _build_rdf(self, data=None): ''' Parse incoming rdf as self.rdf.orig_graph, create copy at self.rdf.graph Args: data (): payload from GET request, expected RDF content in various serialization formats Returns: None ''' # recreate rdf data self.rdf = SimpleNamespace() self.rdf.data = data ...
[ "def", "_build_rdf", "(", "self", ",", "data", "=", "None", ")", ":", "# recreate rdf data", "self", ".", "rdf", "=", "SimpleNamespace", "(", ")", "self", ".", "rdf", ".", "data", "=", "data", "self", ".", "rdf", ".", "prefixes", "=", "SimpleNamespace", ...
Parse incoming rdf as self.rdf.orig_graph, create copy at self.rdf.graph Args: data (): payload from GET request, expected RDF content in various serialization formats Returns: None
[ "Parse", "incoming", "rdf", "as", "self", ".", "rdf", ".", "orig_graph", "create", "copy", "at", "self", ".", "rdf", ".", "graph" ]
python
train
zagaran/mongolia
mongolia/database_object.py
https://github.com/zagaran/mongolia/blob/82c499345f0a8610c7289545e19f5f633e8a81c0/mongolia/database_object.py#L454-L492
def json_update(self, json_str, exclude=[], ignore_non_defaults=True): """ Updates a database object based on a json object. The intent of this method is to allow passing json to an interface which then subsequently manipulates the object and then sends back an update. ...
[ "def", "json_update", "(", "self", ",", "json_str", ",", "exclude", "=", "[", "]", ",", "ignore_non_defaults", "=", "True", ")", ":", "update_dict", "=", "json", ".", "loads", "(", "json_str", ",", "cls", "=", "MongoliaJSONDecoder", ",", "encoding", "=", ...
Updates a database object based on a json object. The intent of this method is to allow passing json to an interface which then subsequently manipulates the object and then sends back an update. Mongolia will also automatically convert any json values that were initially conver...
[ "Updates", "a", "database", "object", "based", "on", "a", "json", "object", ".", "The", "intent", "of", "this", "method", "is", "to", "allow", "passing", "json", "to", "an", "interface", "which", "then", "subsequently", "manipulates", "the", "object", "and",...
python
train
saltstack/salt
salt/grains/core.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L538-L563
def _aix_memdata(): ''' Return the memory information for AIX systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = salt.utils.path.which('prtconf') if prtconf: for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = [x for x in line.strip...
[ "def", "_aix_memdata", "(", ")", ":", "grains", "=", "{", "'mem_total'", ":", "0", ",", "'swap_total'", ":", "0", "}", "prtconf", "=", "salt", ".", "utils", ".", "path", ".", "which", "(", "'prtconf'", ")", "if", "prtconf", ":", "for", "line", "in", ...
Return the memory information for AIX systems
[ "Return", "the", "memory", "information", "for", "AIX", "systems" ]
python
train
squaresLab/BugZoo
bugzoo/mgr/container.py
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L364-L379
def coverage(self, container: Container, tests: Optional[Iterable[TestCase]] = None, *, instrument: bool = True ) -> TestSuiteCoverage: """ Computes line coverage information over a provided set of tests for the...
[ "def", "coverage", "(", "self", ",", "container", ":", "Container", ",", "tests", ":", "Optional", "[", "Iterable", "[", "TestCase", "]", "]", "=", "None", ",", "*", ",", "instrument", ":", "bool", "=", "True", ")", "->", "TestSuiteCoverage", ":", "ext...
Computes line coverage information over a provided set of tests for the program inside a given container.
[ "Computes", "line", "coverage", "information", "over", "a", "provided", "set", "of", "tests", "for", "the", "program", "inside", "a", "given", "container", "." ]
python
train
juju/charm-helpers
charmhelpers/contrib/hardening/utils.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/utils.py#L63-L84
def _get_user_provided_overrides(modules): """Load user-provided config overrides. :param modules: stack modules to lookup in user overrides yaml file. :returns: overrides dictionary. """ overrides = os.path.join(os.environ['JUJU_CHARM_DIR'], 'hardening.yaml') if os...
[ "def", "_get_user_provided_overrides", "(", "modules", ")", ":", "overrides", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'JUJU_CHARM_DIR'", "]", ",", "'hardening.yaml'", ")", "if", "os", ".", "path", ".", "exists", "(", "override...
Load user-provided config overrides. :param modules: stack modules to lookup in user overrides yaml file. :returns: overrides dictionary.
[ "Load", "user", "-", "provided", "config", "overrides", "." ]
python
train
lemieuxl/pyGenClean
pyGenClean/Ethnicity/check_ethnicity.py
https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/Ethnicity/check_ethnicity.py#L303-L327
def compute_eigenvalues(in_prefix, out_prefix): """Computes the Eigenvalues using smartpca from Eigensoft. :param in_prefix: the prefix of the input files. :param out_prefix: the prefix of the output files. :type in_prefix: str :type out_prefix: str Creates a "parameter file" used by smartpca...
[ "def", "compute_eigenvalues", "(", "in_prefix", ",", "out_prefix", ")", ":", "# First, we create the parameter file", "with", "open", "(", "out_prefix", "+", "\".parameters\"", ",", "\"w\"", ")", "as", "o_file", ":", "print", ">>", "o_file", ",", "\"genotypename: ...
Computes the Eigenvalues using smartpca from Eigensoft. :param in_prefix: the prefix of the input files. :param out_prefix: the prefix of the output files. :type in_prefix: str :type out_prefix: str Creates a "parameter file" used by smartpca and runs it.
[ "Computes", "the", "Eigenvalues", "using", "smartpca", "from", "Eigensoft", "." ]
python
train
mardix/Yass
yass/yass.py
https://github.com/mardix/Yass/blob/32f804c1a916f5b0a13d13fa750e52be3b6d666d/yass/yass.py#L398-L471
def create_page(self, build_dir, filepath, context={}, content=None, template=None, markup=None, layout=None): """ To dynamically create a page and save it in the build_dir :param build_dir: (path) The base directory that will hold the created page :param filepath: (string) the name of t...
[ "def", "create_page", "(", "self", ",", "build_dir", ",", "filepath", ",", "context", "=", "{", "}", ",", "content", "=", "None", ",", "template", "=", "None", ",", "markup", "=", "None", ",", "layout", "=", "None", ")", ":", "build_dir", "=", "build...
To dynamically create a page and save it in the build_dir :param build_dir: (path) The base directory that will hold the created page :param filepath: (string) the name of the file to create. May contain slash to indicate directory It will also create the url based on that name ...
[ "To", "dynamically", "create", "a", "page", "and", "save", "it", "in", "the", "build_dir", ":", "param", "build_dir", ":", "(", "path", ")", "The", "base", "directory", "that", "will", "hold", "the", "created", "page", ":", "param", "filepath", ":", "(",...
python
train
briandilley/ebs-deploy
ebs_deploy/__init__.py
https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L326-L334
def environment_exists(self, env_name): """ Returns whether or not the given environment exists """ response = self.ebs.describe_environments(application_name=self.app_name, environment_names=[env_name], include_deleted=False) ret...
[ "def", "environment_exists", "(", "self", ",", "env_name", ")", ":", "response", "=", "self", ".", "ebs", ".", "describe_environments", "(", "application_name", "=", "self", ".", "app_name", ",", "environment_names", "=", "[", "env_name", "]", ",", "include_de...
Returns whether or not the given environment exists
[ "Returns", "whether", "or", "not", "the", "given", "environment", "exists" ]
python
valid
Ex-Mente/auxi.0
auxi/tools/transportphenomena/dimensionlessquantities.py
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/transportphenomena/dimensionlessquantities.py#L66-L77
def Re(L: float, v: float, nu: float) -> float: """ Calculate the Reynolds number. :param L: [m] surface characteristic length. :param v: [m/s] fluid velocity relative to the object. :param nu: [m2/s] fluid kinematic viscosity. :returns: float """ return v * L / nu
[ "def", "Re", "(", "L", ":", "float", ",", "v", ":", "float", ",", "nu", ":", "float", ")", "->", "float", ":", "return", "v", "*", "L", "/", "nu" ]
Calculate the Reynolds number. :param L: [m] surface characteristic length. :param v: [m/s] fluid velocity relative to the object. :param nu: [m2/s] fluid kinematic viscosity. :returns: float
[ "Calculate", "the", "Reynolds", "number", "." ]
python
valid
fp12/achallonge
challonge/tournament.py
https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/tournament.py#L713-L737
async def process_check_ins(self): """ finalize the check in phase |methcoro| Warning: |unstable| Note: |from_api| This should be invoked after a tournament's check-in window closes before the tournament is started. 1. Marks participants who have no...
[ "async", "def", "process_check_ins", "(", "self", ")", ":", "params", "=", "{", "'include_participants'", ":", "1", ",", "# forced to 1 since we need to update the Participant instances", "'include_matches'", ":", "1", "if", "AUTO_GET_MATCHES", "else", "0", "}", "res", ...
finalize the check in phase |methcoro| Warning: |unstable| Note: |from_api| This should be invoked after a tournament's check-in window closes before the tournament is started. 1. Marks participants who have not checked in as inactive. 2. Moves ...
[ "finalize", "the", "check", "in", "phase" ]
python
train
n8henrie/pycookiecheat
src/pycookiecheat/pycookiecheat.py
https://github.com/n8henrie/pycookiecheat/blob/1e0ba783da31689f5b37f9706205ff366d72f03d/src/pycookiecheat/pycookiecheat.py#L150-L244
def chrome_cookies( url: str, cookie_file: str = None, browser: str = "Chrome", curl_cookie_file: str = None, ) -> dict: """Retrieve cookies from Chrome/Chromium on OSX or Linux. Args: url: Domain from which to retrieve cookies, starting with http(s) cook...
[ "def", "chrome_cookies", "(", "url", ":", "str", ",", "cookie_file", ":", "str", "=", "None", ",", "browser", ":", "str", "=", "\"Chrome\"", ",", "curl_cookie_file", ":", "str", "=", "None", ",", ")", "->", "dict", ":", "# If running Chrome on OSX", "if", ...
Retrieve cookies from Chrome/Chromium on OSX or Linux. Args: url: Domain from which to retrieve cookies, starting with http(s) cookie_file: Path to alternate file to search for cookies browser: Name of the browser's cookies to read ('Chrome' or 'Chromium') curl_cookie_file: Path to ...
[ "Retrieve", "cookies", "from", "Chrome", "/", "Chromium", "on", "OSX", "or", "Linux", "." ]
python
train
timkpaine/pyEX
pyEX/marketdata/http.py
https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/marketdata/http.py#L85-L106
def deep(symbol=None, token='', version=''): '''DEEP is used to receive real-time depth of book quotations direct from IEX. The depth of book quotations received via DEEP provide an aggregated size of resting displayed orders at a price and side, and do not indicate the size or number of individual orders a...
[ "def", "deep", "(", "symbol", "=", "None", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "_raiseIfNotStr", "(", "symbol", ")", "if", "symbol", ":", "return", "_getJson", "(", "'deep?symbols='", "+", "symbol", ",", "token", ",", "version...
DEEP is used to receive real-time depth of book quotations direct from IEX. The depth of book quotations received via DEEP provide an aggregated size of resting displayed orders at a price and side, and do not indicate the size or number of individual orders at any price level. Non-displayed orders and non-...
[ "DEEP", "is", "used", "to", "receive", "real", "-", "time", "depth", "of", "book", "quotations", "direct", "from", "IEX", ".", "The", "depth", "of", "book", "quotations", "received", "via", "DEEP", "provide", "an", "aggregated", "size", "of", "resting", "d...
python
valid
astropy/astropy-healpix
astropy_healpix/core.py
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L529-L558
def interpolate_bilinear_lonlat(lon, lat, values, order='ring'): """ Interpolate values at specific longitudes/latitudes using bilinear interpolation Parameters ---------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude values as :class:`~astropy.units.Quantity` insta...
[ "def", "interpolate_bilinear_lonlat", "(", "lon", ",", "lat", ",", "values", ",", "order", "=", "'ring'", ")", ":", "nside", "=", "npix_to_nside", "(", "values", ".", "shape", "[", "0", "]", ")", "indices", ",", "weights", "=", "bilinear_interpolation_weight...
Interpolate values at specific longitudes/latitudes using bilinear interpolation Parameters ---------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude values as :class:`~astropy.units.Quantity` instances with angle units. values : `~numpy.ndarray` Array wi...
[ "Interpolate", "values", "at", "specific", "longitudes", "/", "latitudes", "using", "bilinear", "interpolation" ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L8826-L8835
def param_request_list_send(self, target_system, target_component, force_mavlink1=False): ''' Request all parameters of this component. After this request, all parameters are emitted. target_system : System ID (uint8_t) target_...
[ "def", "param_request_list_send", "(", "self", ",", "target_system", ",", "target_component", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "param_request_list_encode", "(", "target_system", ",", "target_component", ...
Request all parameters of this component. After this request, all parameters are emitted. target_system : System ID (uint8_t) target_component : Component ID (uint8_t)
[ "Request", "all", "parameters", "of", "this", "component", ".", "After", "this", "request", "all", "parameters", "are", "emitted", "." ]
python
train
vals/umis
umis/umis.py
https://github.com/vals/umis/blob/e8adb8486d9e9134ab8a6cad9811a7e74dcc4a2c/umis/umis.py#L959-L985
def cb_histogram(fastq, umi_histogram): ''' Counts the number of reads for each cellular barcode Expects formatted fastq files. ''' annotations = detect_fastq_annotations(fastq) re_string = construct_transformed_regex(annotations) parser_re = re.compile(re_string) cb_counter = collections....
[ "def", "cb_histogram", "(", "fastq", ",", "umi_histogram", ")", ":", "annotations", "=", "detect_fastq_annotations", "(", "fastq", ")", "re_string", "=", "construct_transformed_regex", "(", "annotations", ")", "parser_re", "=", "re", ".", "compile", "(", "re_strin...
Counts the number of reads for each cellular barcode Expects formatted fastq files.
[ "Counts", "the", "number", "of", "reads", "for", "each", "cellular", "barcode" ]
python
train
digidotcom/python-wvalib
wva/cli.py
https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/cli.py#L110-L123
def cli(ctx, hostname, username, password, config_dir, https): """Command-line interface for interacting with a WVA device""" ctx.is_root = True ctx.user_values_entered = False ctx.config_dir = os.path.abspath(os.path.expanduser(config_dir)) ctx.config = load_config(ctx) ctx.hostname = hostname ...
[ "def", "cli", "(", "ctx", ",", "hostname", ",", "username", ",", "password", ",", "config_dir", ",", "https", ")", ":", "ctx", ".", "is_root", "=", "True", "ctx", ".", "user_values_entered", "=", "False", "ctx", ".", "config_dir", "=", "os", ".", "path...
Command-line interface for interacting with a WVA device
[ "Command", "-", "line", "interface", "for", "interacting", "with", "a", "WVA", "device" ]
python
train
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/guerilla/guerillamgmt.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2176-L2191
def dep_add_prj(self, *args, **kwargs): """Add projects to the current department :returns: None :rtype: None :raises: None """ if not self.cur_dep: return dialog = ProjectAdderDialog(department=self.cur_dep) dialog.exec_() prjs = dia...
[ "def", "dep_add_prj", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "cur_dep", ":", "return", "dialog", "=", "ProjectAdderDialog", "(", "department", "=", "self", ".", "cur_dep", ")", "dialog", ".", "exec_"...
Add projects to the current department :returns: None :rtype: None :raises: None
[ "Add", "projects", "to", "the", "current", "department" ]
python
train
SheffieldML/GPy
GPy/likelihoods/likelihood.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/likelihoods/likelihood.py#L413-L438
def predictive_mean(self, mu, variance, Y_metadata=None): """ Quadrature calculation of the predictive mean: E(Y_star|Y) = E( E(Y_star|f_star, Y) ) :param mu: mean of posterior :param sigma: standard deviation of posterior """ #conditional_mean: the edpected value of y ...
[ "def", "predictive_mean", "(", "self", ",", "mu", ",", "variance", ",", "Y_metadata", "=", "None", ")", ":", "#conditional_mean: the edpected value of y given some f, under this likelihood", "fmin", "=", "-", "np", ".", "inf", "fmax", "=", "np", ".", "inf", "def",...
Quadrature calculation of the predictive mean: E(Y_star|Y) = E( E(Y_star|f_star, Y) ) :param mu: mean of posterior :param sigma: standard deviation of posterior
[ "Quadrature", "calculation", "of", "the", "predictive", "mean", ":", "E", "(", "Y_star|Y", ")", "=", "E", "(", "E", "(", "Y_star|f_star", "Y", ")", ")" ]
python
train
qacafe/cdrouter.py
cdrouter/results.py
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L623-L636
def updates(self, id, update_id=None): # pylint: disable=invalid-name,redefined-builtin """Get updates of a running result via long-polling. If no updates are available, CDRouter waits up to 10 seconds before sending an empty response. :param id: Result ID as an int. :param update_id: (optiona...
[ "def", "updates", "(", "self", ",", "id", ",", "update_id", "=", "None", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "if", "update_id", "is", "None", ":", "update_id", "=", "-", "1", "schema", "=", "UpdateSchema", "(", ")", "resp", "=", "se...
Get updates of a running result via long-polling. If no updates are available, CDRouter waits up to 10 seconds before sending an empty response. :param id: Result ID as an int. :param update_id: (optional) Update ID as an int. :return: :class:`results.Update <results.Update>` object :r...
[ "Get", "updates", "of", "a", "running", "result", "via", "long", "-", "polling", ".", "If", "no", "updates", "are", "available", "CDRouter", "waits", "up", "to", "10", "seconds", "before", "sending", "an", "empty", "response", "." ]
python
train
Qiskit/qiskit-terra
qiskit/visualization/text.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L935-L944
def set_cl_multibox(self, creg, label, top_connect='┴'): """ Sets the multi clbit box. Args: creg (string): The affected classical register. label (string): The label for the multi clbit box. top_connect (char): The char to connect the box on the top. ...
[ "def", "set_cl_multibox", "(", "self", ",", "creg", ",", "label", ",", "top_connect", "=", "'┴'):", "", "", "clbit", "=", "[", "bit", "for", "bit", "in", "self", ".", "cregs", "if", "bit", "[", "0", "]", "==", "creg", "]", "self", ".", "_set_multib...
Sets the multi clbit box. Args: creg (string): The affected classical register. label (string): The label for the multi clbit box. top_connect (char): The char to connect the box on the top.
[ "Sets", "the", "multi", "clbit", "box", ".", "Args", ":", "creg", "(", "string", ")", ":", "The", "affected", "classical", "register", ".", "label", "(", "string", ")", ":", "The", "label", "for", "the", "multi", "clbit", "box", ".", "top_connect", "("...
python
test
arista-eosplus/pyeapi
pyeapi/api/mlag.py
https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/api/mlag.py#L227-L239
def set_peer_address(self, value=None, default=False, disable=False): """Configures the mlag peer-address value Args: value (str): The value to configure the peer-address default (bool): Configures the peer-address using the default keyword disable (b...
[ "def", "set_peer_address", "(", "self", ",", "value", "=", "None", ",", "default", "=", "False", ",", "disable", "=", "False", ")", ":", "return", "self", ".", "_configure_mlag", "(", "'peer-address'", ",", "value", ",", "default", ",", "disable", ")" ]
Configures the mlag peer-address value Args: value (str): The value to configure the peer-address default (bool): Configures the peer-address using the default keyword disable (bool): Negates the peer-address using the no keyword Returns: ...
[ "Configures", "the", "mlag", "peer", "-", "address", "value" ]
python
train
Gorialis/jishaku
jishaku/cog.py
https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L446-L477
async def jsk_curl(self, ctx: commands.Context, url: str): """ Download and display a text file from the internet. This command is similar to jsk cat, but accepts a URL. """ # remove embed maskers if present url = url.lstrip("<").rstrip(">") async with ReplResp...
[ "async", "def", "jsk_curl", "(", "self", ",", "ctx", ":", "commands", ".", "Context", ",", "url", ":", "str", ")", ":", "# remove embed maskers if present", "url", "=", "url", ".", "lstrip", "(", "\"<\"", ")", ".", "rstrip", "(", "\">\"", ")", "async", ...
Download and display a text file from the internet. This command is similar to jsk cat, but accepts a URL.
[ "Download", "and", "display", "a", "text", "file", "from", "the", "internet", "." ]
python
train
wavefrontHQ/python-client
wavefront_api_client/models/chart.py
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart.py#L323-L338
def summarization(self, summarization): """Sets the summarization of this Chart. Summarization strategy for the chart. MEAN is default # noqa: E501 :param summarization: The summarization of this Chart. # noqa: E501 :type: str """ allowed_values = ["MEAN", "MEDIAN", ...
[ "def", "summarization", "(", "self", ",", "summarization", ")", ":", "allowed_values", "=", "[", "\"MEAN\"", ",", "\"MEDIAN\"", ",", "\"MIN\"", ",", "\"MAX\"", ",", "\"SUM\"", ",", "\"COUNT\"", ",", "\"LAST\"", ",", "\"FIRST\"", "]", "# noqa: E501", "if", "s...
Sets the summarization of this Chart. Summarization strategy for the chart. MEAN is default # noqa: E501 :param summarization: The summarization of this Chart. # noqa: E501 :type: str
[ "Sets", "the", "summarization", "of", "this", "Chart", "." ]
python
train
SHDShim/pytheos
pytheos/eqn_hugoniot.py
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_hugoniot.py#L146-L163
def hugoniot_rho_single(p, rho0, c0, s, min_strain=0.01): """ calculate density in g/cm^3 from a hugoniot curve :param p: pressure in GPa :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :param min_strain: defining minimum v...
[ "def", "hugoniot_rho_single", "(", "p", ",", "rho0", ",", "c0", ",", "s", ",", "min_strain", "=", "0.01", ")", ":", "if", "p", "<=", "1.e-5", ":", "return", "rho0", "def", "f_diff", "(", "rho", ")", ":", "return", "hugoniot_p", "(", "rho", ",", "rh...
calculate density in g/cm^3 from a hugoniot curve :param p: pressure in GPa :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :param min_strain: defining minimum v/v0 value to search volume for :return: density in g/cm^3
[ "calculate", "density", "in", "g", "/", "cm^3", "from", "a", "hugoniot", "curve" ]
python
train
pandas-dev/pandas
pandas/core/generic.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L6899-L7067
def asof(self, where, subset=None): """ Return the last row(s) without any NaNs before `where`. The last row (for each element in `where`, if list) without any NaN is taken. In case of a :class:`~pandas.DataFrame`, the last row without NaN considering only the subset of ...
[ "def", "asof", "(", "self", ",", "where", ",", "subset", "=", "None", ")", ":", "if", "isinstance", "(", "where", ",", "str", ")", ":", "from", "pandas", "import", "to_datetime", "where", "=", "to_datetime", "(", "where", ")", "if", "not", "self", "....
Return the last row(s) without any NaNs before `where`. The last row (for each element in `where`, if list) without any NaN is taken. In case of a :class:`~pandas.DataFrame`, the last row without NaN considering only the subset of columns (if not `None`) .. versionadded:: 0.19....
[ "Return", "the", "last", "row", "(", "s", ")", "without", "any", "NaNs", "before", "where", "." ]
python
train
librosa/librosa
librosa/feature/spectral.py
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L1631-L1744
def melspectrogram(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', power=2.0, **kwargs): """Compute a mel-scaled spectrogram. If a spectrogram input `S` is provided, then it is mapped directly onto ...
[ "def", "melspectrogram", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "S", "=", "None", ",", "n_fft", "=", "2048", ",", "hop_length", "=", "512", ",", "win_length", "=", "None", ",", "window", "=", "'hann'", ",", "center", "=", "True", ",",...
Compute a mel-scaled spectrogram. If a spectrogram input `S` is provided, then it is mapped directly onto the mel basis `mel_f` by `mel_f.dot(S)`. If a time-series input `y, sr` is provided, then its magnitude spectrogram `S` is first computed, and then mapped onto the mel scale by `mel_f.dot(S**p...
[ "Compute", "a", "mel", "-", "scaled", "spectrogram", "." ]
python
test
google/openhtf
openhtf/util/conf.py
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L368-L397
def load_from_file(self, yamlfile, _override=True, _allow_undeclared=False): """Loads the configuration from a file. Parsed contents must be a single dict mapping config key to value. Args: yamlfile: The opened file object to load configuration from. See load_from_dict() for other args' descri...
[ "def", "load_from_file", "(", "self", ",", "yamlfile", ",", "_override", "=", "True", ",", "_allow_undeclared", "=", "False", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Loading configuration from file: %s'", ",", "yamlfile", ")", "try", ":", "parsed...
Loads the configuration from a file. Parsed contents must be a single dict mapping config key to value. Args: yamlfile: The opened file object to load configuration from. See load_from_dict() for other args' descriptions. Raises: ConfigurationInvalidError: If configuration file can't be...
[ "Loads", "the", "configuration", "from", "a", "file", "." ]
python
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L723-L810
async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sen...
[ "async", "def", "sendmail", "(", "self", ",", "sender", ",", "recipients", ",", "message", ",", "mail_options", "=", "None", ",", "rcpt_options", "=", "None", ")", ":", "# Make sure `recipients` is a list:", "if", "isinstance", "(", "recipients", ",", "str", "...
Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while...
[ "Performs", "an", "entire", "e", "-", "mail", "transaction", "." ]
python
train
saltstack/salt
salt/modules/network.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L1250-L1376
def mod_hostname(hostname): ''' Modify hostname .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) CLI Example: .. code-block:: bash salt '*' network.mod_hostname master.saltstack.com ''' # # SunOS tested on SmartOS and OmniOS (Solaris...
[ "def", "mod_hostname", "(", "hostname", ")", ":", "#", "# SunOS tested on SmartOS and OmniOS (Solaris 10 compatible)", "# Oracle Solaris 11 uses smf, currently not supported", "#", "# /etc/nodename is the hostname only, not fqdn", "# /etc/defaultdomain is the domain", "# /etc/hosts should ha...
Modify hostname .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) CLI Example: .. code-block:: bash salt '*' network.mod_hostname master.saltstack.com
[ "Modify", "hostname" ]
python
train
dstufft/crust
crust/query.py
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L382-L389
def create(self, **kwargs): """ Creates a new object with the given kwargs, saving it to the api and returning the created object. """ obj = self.resource(**kwargs) obj.save(force_insert=True) return obj
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "self", ".", "resource", "(", "*", "*", "kwargs", ")", "obj", ".", "save", "(", "force_insert", "=", "True", ")", "return", "obj" ]
Creates a new object with the given kwargs, saving it to the api and returning the created object.
[ "Creates", "a", "new", "object", "with", "the", "given", "kwargs", "saving", "it", "to", "the", "api", "and", "returning", "the", "created", "object", "." ]
python
train
wummel/linkchecker
third_party/miniboa-r42/miniboa/telnet.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/miniboa-r42/miniboa/telnet.py#L185-L191
def send_wrapped(self, text): """ Send text padded and wrapped to the user's screen width. """ lines = word_wrap(text, self.columns) for line in lines: self.send_cc(line + '\n')
[ "def", "send_wrapped", "(", "self", ",", "text", ")", ":", "lines", "=", "word_wrap", "(", "text", ",", "self", ".", "columns", ")", "for", "line", "in", "lines", ":", "self", ".", "send_cc", "(", "line", "+", "'\\n'", ")" ]
Send text padded and wrapped to the user's screen width.
[ "Send", "text", "padded", "and", "wrapped", "to", "the", "user", "s", "screen", "width", "." ]
python
train
mrstephenneal/mysql-toolkit
mysql/toolkit/commands/dump.py
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/commands/dump.py#L20-L39
def set_dump_directory(base=None, sub_dir=None): """Create directory for dumping SQL commands.""" # Set current timestamp timestamp = datetime.fromtimestamp(time()).strftime('%Y-%m-%d %H-%M-%S') # Clean sub_dir if sub_dir and '.' in sub_dir: sub_dir = sub_dir.rsplit('.', 1)[0] # Create...
[ "def", "set_dump_directory", "(", "base", "=", "None", ",", "sub_dir", "=", "None", ")", ":", "# Set current timestamp", "timestamp", "=", "datetime", ".", "fromtimestamp", "(", "time", "(", ")", ")", ".", "strftime", "(", "'%Y-%m-%d %H-%M-%S'", ")", "# Clean ...
Create directory for dumping SQL commands.
[ "Create", "directory", "for", "dumping", "SQL", "commands", "." ]
python
train
faroit/stempeg
stempeg/write.py
https://github.com/faroit/stempeg/blob/ebbaec87ea440fcbb06423d708e7847749e63d38/stempeg/write.py#L10-L35
def check_available_aac_encoders(): """Returns the available AAC encoders Returns ---------- codecs : list(str) List of available encoder codecs """ cmd = [ 'ffmpeg', '-v', 'error', '-codecs' ] output = sp.check_output(cmd) aac_codecs = [ x ...
[ "def", "check_available_aac_encoders", "(", ")", ":", "cmd", "=", "[", "'ffmpeg'", ",", "'-v'", ",", "'error'", ",", "'-codecs'", "]", "output", "=", "sp", ".", "check_output", "(", "cmd", ")", "aac_codecs", "=", "[", "x", "for", "x", "in", "output", "...
Returns the available AAC encoders Returns ---------- codecs : list(str) List of available encoder codecs
[ "Returns", "the", "available", "AAC", "encoders" ]
python
train
delph-in/pydelphin
delphin/tdl.py
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/tdl.py#L1872-L1906
def format(obj, indent=0): """ Serialize TDL objects to strings. Args: obj: instance of :class:`Term`, :class:`Conjunction`, or :class:`TypeDefinition` classes or subclasses indent (int): number of spaces to indent the formatted object Returns: str: serialized form o...
[ "def", "format", "(", "obj", ",", "indent", "=", "0", ")", ":", "if", "isinstance", "(", "obj", ",", "TypeDefinition", ")", ":", "return", "_format_typedef", "(", "obj", ",", "indent", ")", "elif", "isinstance", "(", "obj", ",", "Conjunction", ")", ":"...
Serialize TDL objects to strings. Args: obj: instance of :class:`Term`, :class:`Conjunction`, or :class:`TypeDefinition` classes or subclasses indent (int): number of spaces to indent the formatted object Returns: str: serialized form of *obj* Example: >>> conj =...
[ "Serialize", "TDL", "objects", "to", "strings", "." ]
python
train
proycon/pynlpl
pynlpl/formats/folia.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L3336-L3341
def xml(self, attribs = None,elements = None, skipchildren = False): """See :meth:`AbstractElement.xml`""" if not attribs: attribs = {} if self.idref: attribs['id'] = self.idref return super(AbstractTextMarkup,self).xml(attribs,elements, skipchildren)
[ "def", "xml", "(", "self", ",", "attribs", "=", "None", ",", "elements", "=", "None", ",", "skipchildren", "=", "False", ")", ":", "if", "not", "attribs", ":", "attribs", "=", "{", "}", "if", "self", ".", "idref", ":", "attribs", "[", "'id'", "]", ...
See :meth:`AbstractElement.xml`
[ "See", ":", "meth", ":", "AbstractElement", ".", "xml" ]
python
train
datacamp/pythonwhat
pythonwhat/checks/check_logic.py
https://github.com/datacamp/pythonwhat/blob/ffbf7f8436a51f77c22f3bed75ba3bc37a5c666f/pythonwhat/checks/check_logic.py#L233-L271
def set_env(state, **kwargs): """Update/set environemnt variables for student and solution environments. When ``has_equal_x()`` is used after this, the variables specified through this function will be available in the student and solution process. Note that you will not see these variables in the stud...
[ "def", "set_env", "(", "state", ",", "*", "*", "kwargs", ")", ":", "stu_crnt", "=", "state", ".", "student_env", ".", "context", "sol_crnt", "=", "state", ".", "solution_env", ".", "context", "stu_new", "=", "stu_crnt", ".", "update", "(", "kwargs", ")",...
Update/set environemnt variables for student and solution environments. When ``has_equal_x()`` is used after this, the variables specified through this function will be available in the student and solution process. Note that you will not see these variables in the student process of the state produced by ...
[ "Update", "/", "set", "environemnt", "variables", "for", "student", "and", "solution", "environments", "." ]
python
test
amanusk/s-tui
s_tui/s_tui.py
https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/s_tui.py#L387-L452
def _generate_graph_controls(self): """ Display sidebar controls. i.e. buttons, and controls""" # setup mode radio buttons stress_modes = self.controller.stress_conroller.get_modes() group = [] for mode in stress_modes: self.mode_buttons.append(radio_button(group, mod...
[ "def", "_generate_graph_controls", "(", "self", ")", ":", "# setup mode radio buttons", "stress_modes", "=", "self", ".", "controller", ".", "stress_conroller", ".", "get_modes", "(", ")", "group", "=", "[", "]", "for", "mode", "in", "stress_modes", ":", "self",...
Display sidebar controls. i.e. buttons, and controls
[ "Display", "sidebar", "controls", ".", "i", ".", "e", ".", "buttons", "and", "controls" ]
python
train
pyroscope/pyrocore
src/pyrocore/util/osmagic.py
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/osmagic.py#L41-L67
def check_process(pidfile): """ Read pid file and check process status. Return (running, pid). """ # Check pid file try: handle = open(pidfile, 'r') except IOError as exc: if exc.errno == errno.ENOENT: # pid file disappeared return False, 0 rai...
[ "def", "check_process", "(", "pidfile", ")", ":", "# Check pid file", "try", ":", "handle", "=", "open", "(", "pidfile", ",", "'r'", ")", "except", "IOError", "as", "exc", ":", "if", "exc", ".", "errno", "==", "errno", ".", "ENOENT", ":", "# pid file dis...
Read pid file and check process status. Return (running, pid).
[ "Read", "pid", "file", "and", "check", "process", "status", ".", "Return", "(", "running", "pid", ")", "." ]
python
train
ff0000/scarlet
scarlet/versioning/fields.py
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/versioning/fields.py#L42-L71
def update_rel_to(self, klass): """ If we have a string for a model, see if we know about it yet, if so use it directly otherwise take the lazy approach. This check is needed because this is called before the main M2M field contribute to class is called. """ if i...
[ "def", "update_rel_to", "(", "self", ",", "klass", ")", ":", "if", "isinstance", "(", "self", ".", "remote_field", ".", "to", ",", "basestring", ")", ":", "relation", "=", "self", ".", "remote_field", ".", "to", "try", ":", "app_label", ",", "model_name"...
If we have a string for a model, see if we know about it yet, if so use it directly otherwise take the lazy approach. This check is needed because this is called before the main M2M field contribute to class is called.
[ "If", "we", "have", "a", "string", "for", "a", "model", "see", "if", "we", "know", "about", "it", "yet", "if", "so", "use", "it", "directly", "otherwise", "take", "the", "lazy", "approach", ".", "This", "check", "is", "needed", "because", "this", "is",...
python
train
lesscpy/lesscpy
lesscpy/lessc/utility.py
https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/utility.py#L234-L243
def split_unit(value): """ Split a number from its unit 1px -> (q, 'px') Args: value (str): input returns: tuple """ r = re.search('^(\-?[\d\.]+)(.*)$', str(value)) return r.groups() if r else ('', '')
[ "def", "split_unit", "(", "value", ")", ":", "r", "=", "re", ".", "search", "(", "'^(\\-?[\\d\\.]+)(.*)$'", ",", "str", "(", "value", ")", ")", "return", "r", ".", "groups", "(", ")", "if", "r", "else", "(", "''", ",", "''", ")" ]
Split a number from its unit 1px -> (q, 'px') Args: value (str): input returns: tuple
[ "Split", "a", "number", "from", "its", "unit", "1px", "-", ">", "(", "q", "px", ")", "Args", ":", "value", "(", "str", ")", ":", "input", "returns", ":", "tuple" ]
python
valid
pantsbuild/pex
pex/vendor/_vendored/wheel/wheel/bdist_wheel.py
https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/vendor/_vendored/wheel/wheel/bdist_wheel.py#L318-L375
def egg2dist(self, egginfo_path, distinfo_path): """Convert an .egg-info directory into a .dist-info directory""" def adios(p): """Appropriately delete directory, file or link.""" if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p): shutil.rmtree(p...
[ "def", "egg2dist", "(", "self", ",", "egginfo_path", ",", "distinfo_path", ")", ":", "def", "adios", "(", "p", ")", ":", "\"\"\"Appropriately delete directory, file or link.\"\"\"", "if", "os", ".", "path", ".", "exists", "(", "p", ")", "and", "not", "os", "...
Convert an .egg-info directory into a .dist-info directory
[ "Convert", "an", ".", "egg", "-", "info", "directory", "into", "a", ".", "dist", "-", "info", "directory" ]
python
train
tBaxter/python-card-me
card_me/icalendar.py
https://github.com/tBaxter/python-card-me/blob/ffebc7fed44f83983b7438e57263dcda67207664/card_me/icalendar.py#L361-L471
def getrruleset(self, addRDate=False): """ Get an rruleset created from self. If addRDate is True, add an RDATE for dtstart if it's not included in an RRULE, and count is decremented if it exists. Note that for rules which don't match DTSTART, DTSTART may not appear in ...
[ "def", "getrruleset", "(", "self", ",", "addRDate", "=", "False", ")", ":", "rruleset", "=", "None", "for", "name", "in", "DATESANDRULES", ":", "addfunc", "=", "None", "for", "line", "in", "self", ".", "contents", ".", "get", "(", "name", ",", "(", "...
Get an rruleset created from self. If addRDate is True, add an RDATE for dtstart if it's not included in an RRULE, and count is decremented if it exists. Note that for rules which don't match DTSTART, DTSTART may not appear in list(rruleset), although it should. By default, an RDATE i...
[ "Get", "an", "rruleset", "created", "from", "self", "." ]
python
train
kejbaly2/metrique
metrique/utils.py
https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/utils.py#L197-L227
def clear_stale_pids(pids, pid_dir='/tmp', prefix='', multi=False): 'check for and remove any pids which have no corresponding process' if isinstance(pids, (int, float, long)): pids = [pids] pids = str2list(pids, map_=unicode) procs = map(unicode, os.listdir('/proc')) running = [pid for pid ...
[ "def", "clear_stale_pids", "(", "pids", ",", "pid_dir", "=", "'/tmp'", ",", "prefix", "=", "''", ",", "multi", "=", "False", ")", ":", "if", "isinstance", "(", "pids", ",", "(", "int", ",", "float", ",", "long", ")", ")", ":", "pids", "=", "[", "...
check for and remove any pids which have no corresponding process
[ "check", "for", "and", "remove", "any", "pids", "which", "have", "no", "corresponding", "process" ]
python
train
apple/turicreate
src/external/xgboost/python-package/xgboost/core.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L688-L710
def boost(self, dtrain, grad, hess): """ Boost the booster for one iteration, with customized gradient statistics. Parameters ---------- dtrain : DMatrix The training DMatrix. grad : list The first order of gradient. hess : list ...
[ "def", "boost", "(", "self", ",", "dtrain", ",", "grad", ",", "hess", ")", ":", "if", "len", "(", "grad", ")", "!=", "len", "(", "hess", ")", ":", "raise", "ValueError", "(", "'grad / hess length mismatch: {} / {}'", ".", "format", "(", "len", "(", "gr...
Boost the booster for one iteration, with customized gradient statistics. Parameters ---------- dtrain : DMatrix The training DMatrix. grad : list The first order of gradient. hess : list The second order of gradient.
[ "Boost", "the", "booster", "for", "one", "iteration", "with", "customized", "gradient", "statistics", "." ]
python
train
ecell/ecell4
ecell4/extra/azure_batch.py
https://github.com/ecell/ecell4/blob/a4a1229661c39b2059adbbacae9090e5ba664e01/ecell4/extra/azure_batch.py#L254-L302
def add_tasks(batch_service_client, job_id, loads, output_container_name, output_container_sas_token, task_file, acount_name): """Adds a task for each input file in the collection to the specified job. :param batch_service_client: A Batch service client. :type batch_service_clie...
[ "def", "add_tasks", "(", "batch_service_client", ",", "job_id", ",", "loads", ",", "output_container_name", ",", "output_container_sas_token", ",", "task_file", ",", "acount_name", ")", ":", "_log", ".", "info", "(", "'Adding {} tasks to job [{}]...'", ".", "format", ...
Adds a task for each input file in the collection to the specified job. :param batch_service_client: A Batch service client. :type batch_service_client: `azure.batch.BatchServiceClient` :param str job_id: The ID of the job to which to add the tasks. :param list input_files: A collection of input files....
[ "Adds", "a", "task", "for", "each", "input", "file", "in", "the", "collection", "to", "the", "specified", "job", "." ]
python
train
viatoriche/microservices
examples/http/basic.py
https://github.com/viatoriche/microservices/blob/3510563edd15dc6131b8a948d6062856cd904ac7/examples/http/basic.py#L51-L59
def second_params_two(test, two): """Second resource * POST: return [test, two, request data] * GET: return [test, two] """ if request.method == 'POST': return [test, two, request.data] return {'result': [test, two]}
[ "def", "second_params_two", "(", "test", ",", "two", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "return", "[", "test", ",", "two", ",", "request", ".", "data", "]", "return", "{", "'result'", ":", "[", "test", ",", "two", "]", "...
Second resource * POST: return [test, two, request data] * GET: return [test, two]
[ "Second", "resource" ]
python
train
pantsbuild/pants
src/python/pants/option/parser.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/parser.py#L300-L331
def register(self, *args, **kwargs): """Register an option.""" if self._frozen: raise FrozenRegistration(self.scope, args[0]) # Prevent further registration in enclosing scopes. ancestor = self._parent_parser while ancestor: ancestor._freeze() ancestor = ancestor._parent_parser ...
[ "def", "register", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_frozen", ":", "raise", "FrozenRegistration", "(", "self", ".", "scope", ",", "args", "[", "0", "]", ")", "# Prevent further registration in enclosing ...
Register an option.
[ "Register", "an", "option", "." ]
python
train
LonamiWebs/Telethon
telethon/helpers.py
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/helpers.py#L11-L13
def generate_random_long(signed=True): """Generates a random long integer (8 bytes), which is optionally signed""" return int.from_bytes(os.urandom(8), signed=signed, byteorder='little')
[ "def", "generate_random_long", "(", "signed", "=", "True", ")", ":", "return", "int", ".", "from_bytes", "(", "os", ".", "urandom", "(", "8", ")", ",", "signed", "=", "signed", ",", "byteorder", "=", "'little'", ")" ]
Generates a random long integer (8 bytes), which is optionally signed
[ "Generates", "a", "random", "long", "integer", "(", "8", "bytes", ")", "which", "is", "optionally", "signed" ]
python
train
qiniu/python-sdk
qiniu/auth.py
https://github.com/qiniu/python-sdk/blob/a69fbef4e3e6ea1ebe09f4610a5b18bb2c17de59/qiniu/auth.py#L127-L160
def upload_token( self, bucket, key=None, expires=3600, policy=None, strict_policy=True): """生成上传凭证 Args: bucket: 上传的空间名 key: 上传的文件名,默认为空 expires: 上传凭证的过期时间,默认为3600s policy: 上传策...
[ "def", "upload_token", "(", "self", ",", "bucket", ",", "key", "=", "None", ",", "expires", "=", "3600", ",", "policy", "=", "None", ",", "strict_policy", "=", "True", ")", ":", "if", "bucket", "is", "None", "or", "bucket", "==", "''", ":", "raise", ...
生成上传凭证 Args: bucket: 上传的空间名 key: 上传的文件名,默认为空 expires: 上传凭证的过期时间,默认为3600s policy: 上传策略,默认为空 Returns: 上传凭证
[ "生成上传凭证" ]
python
train
romanz/trezor-agent
libagent/gpg/__init__.py
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/__init__.py#L279-L324
def main(device_type): """Parse command-line arguments.""" epilog = ('See https://github.com/romanz/trezor-agent/blob/master/' 'doc/README-GPG.md for usage examples.') parser = argparse.ArgumentParser(epilog=epilog) agent_package = device_type.package_name() resources_map = {r.key: r ...
[ "def", "main", "(", "device_type", ")", ":", "epilog", "=", "(", "'See https://github.com/romanz/trezor-agent/blob/master/'", "'doc/README-GPG.md for usage examples.'", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "epilog", "=", "epilog", ")", "agent_packag...
Parse command-line arguments.
[ "Parse", "command", "-", "line", "arguments", "." ]
python
train
erdewit/ib_insync
ib_insync/ib.py
https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/ib.py#L1193-L1207
def cancelTickByTickData(self, contract: Contract, tickType: str): """ Unsubscribe from tick-by-tick data Args: contract: The exact contract object that was used to subscribe with. """ ticker = self.ticker(contract) reqId = self.wrapper.endTic...
[ "def", "cancelTickByTickData", "(", "self", ",", "contract", ":", "Contract", ",", "tickType", ":", "str", ")", ":", "ticker", "=", "self", ".", "ticker", "(", "contract", ")", "reqId", "=", "self", ".", "wrapper", ".", "endTicker", "(", "ticker", ",", ...
Unsubscribe from tick-by-tick data Args: contract: The exact contract object that was used to subscribe with.
[ "Unsubscribe", "from", "tick", "-", "by", "-", "tick", "data" ]
python
train
mlperf/training
reinforcement/tensorflow/minigo/oneoffs/heatmap.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/heatmap.py#L45-L85
def eval_policy(eval_positions): """Evaluate all positions with all models save the policy heatmaps as CSVs CSV name is "heatmap-<position_name>-<model-index>.csv" CSV format is: model number, value network output, policy network outputs position_name is taken from the SGF file Policy network outp...
[ "def", "eval_policy", "(", "eval_positions", ")", ":", "model_paths", "=", "oneoff_utils", ".", "get_model_paths", "(", "fsdb", ".", "models_dir", "(", ")", ")", "idx_start", "=", "FLAGS", ".", "idx_start", "eval_every", "=", "FLAGS", ".", "eval_every", "print...
Evaluate all positions with all models save the policy heatmaps as CSVs CSV name is "heatmap-<position_name>-<model-index>.csv" CSV format is: model number, value network output, policy network outputs position_name is taken from the SGF file Policy network outputs (19x19) are saved in flat order (see...
[ "Evaluate", "all", "positions", "with", "all", "models", "save", "the", "policy", "heatmaps", "as", "CSVs" ]
python
train
KeithSSmith/switcheo-python
switcheo/neo/signatures.py
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/neo/signatures.py#L200-L230
def sign_create_withdrawal(withdrawal_params, key_pair): """ Function to create the withdrawal request by signing the parameters necessary for withdrawal. Execution of this function is as follows:: sign_create_withdrawal(withdrawal_params=signable_params, private_key=eth_private_key) The expec...
[ "def", "sign_create_withdrawal", "(", "withdrawal_params", ",", "key_pair", ")", ":", "encoded_message", "=", "encode_message", "(", "withdrawal_params", ")", "create_params", "=", "withdrawal_params", ".", "copy", "(", ")", "create_params", "[", "'address'", "]", "...
Function to create the withdrawal request by signing the parameters necessary for withdrawal. Execution of this function is as follows:: sign_create_withdrawal(withdrawal_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { ...
[ "Function", "to", "create", "the", "withdrawal", "request", "by", "signing", "the", "parameters", "necessary", "for", "withdrawal", ".", "Execution", "of", "this", "function", "is", "as", "follows", "::" ]
python
train
thespacedoctor/frankenstein
frankenstein/electric.py
https://github.com/thespacedoctor/frankenstein/blob/48d943d9757e92dfa9ea7407628fa2d633c840fb/frankenstein/electric.py#L135-L158
def _join_all_filenames_and_text( self): """ *join all file names, driectory names and text content together* """ self.log.info('starting the ``_join_all_filenames_and_text`` method') contentString = u"" for i in self.directoryContents: contentStr...
[ "def", "_join_all_filenames_and_text", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``_join_all_filenames_and_text`` method'", ")", "contentString", "=", "u\"\"", "for", "i", "in", "self", ".", "directoryContents", ":", "contentString", ...
*join all file names, driectory names and text content together*
[ "*", "join", "all", "file", "names", "driectory", "names", "and", "text", "content", "together", "*" ]
python
train
python-diamond/Diamond
src/collectors/ipvs/ipvs.py
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/ipvs/ipvs.py#L45-L56
def get_default_config(self): """ Returns the default collector settings """ config = super(IPVSCollector, self).get_default_config() config.update({ 'bin': '/usr/sbin/ipvsadm', 'use_sudo': True, 'sudo_cmd': '/usr/b...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "IPVSCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'bin'", ":", "'/usr/sbin/ipvsadm'", ",", "'use_sudo'", ":", "True", ...
Returns the default collector settings
[ "Returns", "the", "default", "collector", "settings" ]
python
train
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/__init__.py
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/__init__.py#L325-L359
def _gitinfo(): ''' returns a string containing git branch, commit id and commit date ''' result = None repo_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', '.git') if os.path.exists(repo_path): # Check if the .git is a file. If it is a file, it means that we are in a submodule...
[ "def", "_gitinfo", "(", ")", ":", "result", "=", "None", "repo_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'..'", ",", "'..'", ",", "'..'", ",", "'.git'", ")", "if", "os", ".", ...
returns a string containing git branch, commit id and commit date
[ "returns", "a", "string", "containing", "git", "branch", "commit", "id", "and", "commit", "date" ]
python
train
edx/edx-drf-extensions
edx_rest_framework_extensions/middleware.py
https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/middleware.py#L78-L102
def _set_request_auth_type_metric(self, request): """ Add metric 'request_auth_type' for the authentication type used. NOTE: This is a best guess at this point. Possible values include: no-user unauthenticated jwt/bearer/other-token-type session-...
[ "def", "_set_request_auth_type_metric", "(", "self", ",", "request", ")", ":", "if", "'HTTP_AUTHORIZATION'", "in", "request", ".", "META", "and", "request", ".", "META", "[", "'HTTP_AUTHORIZATION'", "]", ":", "token_parts", "=", "request", ".", "META", "[", "'...
Add metric 'request_auth_type' for the authentication type used. NOTE: This is a best guess at this point. Possible values include: no-user unauthenticated jwt/bearer/other-token-type session-or-unknown (catch all)
[ "Add", "metric", "request_auth_type", "for", "the", "authentication", "type", "used", "." ]
python
train
solocompt/plugs-mail
plugs_mail/mail.py
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/mail.py#L33-L45
def validate_context(self): """ Make sure there are no duplicate context objects or we might end up with switched data Converting the tuple to a set gets rid of the eventual duplicate objects, comparing the length of the original tuple and set tells us if we have...
[ "def", "validate_context", "(", "self", ")", ":", "if", "self", ".", "context", "and", "len", "(", "self", ".", "context", ")", "!=", "len", "(", "set", "(", "self", ".", "context", ")", ")", ":", "LOGGER", ".", "error", "(", "'Cannot have duplicated c...
Make sure there are no duplicate context objects or we might end up with switched data Converting the tuple to a set gets rid of the eventual duplicate objects, comparing the length of the original tuple and set tells us if we have duplicates in the tuple or not
[ "Make", "sure", "there", "are", "no", "duplicate", "context", "objects", "or", "we", "might", "end", "up", "with", "switched", "data" ]
python
train
markovmodel/msmtools
msmtools/estimation/api.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/estimation/api.py#L402-L455
def connected_sets(C, directed=True): r"""Compute connected sets of microstates. Connected components for a directed graph with edge-weights given by the count matrix. Parameters ---------- C : scipy.sparse matrix Count matrix specifying edge weights. directed : bool, optional ...
[ "def", "connected_sets", "(", "C", ",", "directed", "=", "True", ")", ":", "if", "isdense", "(", "C", ")", ":", "return", "sparse", ".", "connectivity", ".", "connected_sets", "(", "csr_matrix", "(", "C", ")", ",", "directed", "=", "directed", ")", "el...
r"""Compute connected sets of microstates. Connected components for a directed graph with edge-weights given by the count matrix. Parameters ---------- C : scipy.sparse matrix Count matrix specifying edge weights. directed : bool, optional Whether to compute connected components...
[ "r", "Compute", "connected", "sets", "of", "microstates", "." ]
python
train
aliyun/aliyun-log-python-sdk
aliyun/log/logclient.py
https://github.com/aliyun/aliyun-log-python-sdk/blob/ac383db0a16abf1e5ef7df36074374184b43516e/aliyun/log/logclient.py#L2106-L2123
def list_consumer_group(self, project, logstore): """ List consumer group :type project: string :param project: project name :type logstore: string :param logstore: logstore name :return: ListConsumerGroupResponse """ resource = "/logstores...
[ "def", "list_consumer_group", "(", "self", ",", "project", ",", "logstore", ")", ":", "resource", "=", "\"/logstores/\"", "+", "logstore", "+", "\"/consumergroups\"", "params", "=", "{", "}", "headers", "=", "{", "}", "(", "resp", ",", "header", ")", "=", ...
List consumer group :type project: string :param project: project name :type logstore: string :param logstore: logstore name :return: ListConsumerGroupResponse
[ "List", "consumer", "group", ":", "type", "project", ":", "string", ":", "param", "project", ":", "project", "name", ":", "type", "logstore", ":", "string", ":", "param", "logstore", ":", "logstore", "name", ":", "return", ":", "ListConsumerGroupResponse" ]
python
train
quantumlib/Cirq
cirq/sim/wave_function.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/wave_function.py#L118-L138
def bloch_vector_of(self, qubit: ops.Qid) -> np.ndarray: """Returns the bloch vector of a qubit in the state. Calculates the bloch vector of the given qubit in the state given by self.state_vector(), given that self.state_vector() follows the standard Kronecker convention of num...
[ "def", "bloch_vector_of", "(", "self", ",", "qubit", ":", "ops", ".", "Qid", ")", "->", "np", ".", "ndarray", ":", "return", "bloch_vector_from_state_vector", "(", "self", ".", "state_vector", "(", ")", ",", "self", ".", "qubit_map", "[", "qubit", "]", "...
Returns the bloch vector of a qubit in the state. Calculates the bloch vector of the given qubit in the state given by self.state_vector(), given that self.state_vector() follows the standard Kronecker convention of numpy.kron. Args: qubit: qubit who's bloch vector ...
[ "Returns", "the", "bloch", "vector", "of", "a", "qubit", "in", "the", "state", "." ]
python
train
aws/sagemaker-python-sdk
src/sagemaker/model.py
https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/model.py#L97-L118
def _create_sagemaker_model(self, instance_type, accelerator_type=None, tags=None): """Create a SageMaker Model Entity Args: instance_type (str): The EC2 instance type that this Model will be used for, this is only used to determine if the image needs GPU support or not. ...
[ "def", "_create_sagemaker_model", "(", "self", ",", "instance_type", ",", "accelerator_type", "=", "None", ",", "tags", "=", "None", ")", ":", "container_def", "=", "self", ".", "prepare_container_def", "(", "instance_type", ",", "accelerator_type", "=", "accelera...
Create a SageMaker Model Entity Args: instance_type (str): The EC2 instance type that this Model will be used for, this is only used to determine if the image needs GPU support or not. accelerator_type (str): Type of Elastic Inference accelerator to attach to an endpoint...
[ "Create", "a", "SageMaker", "Model", "Entity" ]
python
train
hyperledger/indy-plenum
plenum/server/node.py
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L2423-L2435
def applyReq(self, request: Request, cons_time: int): """ Apply request to appropriate ledger and state. `cons_time` is the UTC epoch at which consensus was reached. """ self.execute_hook(NodeHooks.PRE_REQUEST_APPLICATION, request=request, cons_time=cons...
[ "def", "applyReq", "(", "self", ",", "request", ":", "Request", ",", "cons_time", ":", "int", ")", ":", "self", ".", "execute_hook", "(", "NodeHooks", ".", "PRE_REQUEST_APPLICATION", ",", "request", "=", "request", ",", "cons_time", "=", "cons_time", ")", ...
Apply request to appropriate ledger and state. `cons_time` is the UTC epoch at which consensus was reached.
[ "Apply", "request", "to", "appropriate", "ledger", "and", "state", ".", "cons_time", "is", "the", "UTC", "epoch", "at", "which", "consensus", "was", "reached", "." ]
python
train
PyCQA/astroid
astroid/node_classes.py
https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L638-L658
def _fixed_source_line(self): """Attempt to find the line that this node appears on. We need this method since not all nodes have :attr:`lineno` set. :returns: The line number of this node, or None if this could not be determined. :rtype: int or None """ lin...
[ "def", "_fixed_source_line", "(", "self", ")", ":", "line", "=", "self", ".", "lineno", "_node", "=", "self", "try", ":", "while", "line", "is", "None", ":", "_node", "=", "next", "(", "_node", ".", "get_children", "(", ")", ")", "line", "=", "_node"...
Attempt to find the line that this node appears on. We need this method since not all nodes have :attr:`lineno` set. :returns: The line number of this node, or None if this could not be determined. :rtype: int or None
[ "Attempt", "to", "find", "the", "line", "that", "this", "node", "appears", "on", "." ]
python
train
raamana/hiwenet
hiwenet/pairwise_dist.py
https://github.com/raamana/hiwenet/blob/b12699b3722fd0a6a835e7d7ca4baf58fb181809/hiwenet/pairwise_dist.py#L90-L307
def extract(features, groups, weight_method=default_weight_method, num_bins=default_num_bins, edge_range=default_edge_range, trim_outliers=default_trim_behaviour, trim_percentile=default_trim_percentile, use_original_distribution=False, ...
[ "def", "extract", "(", "features", ",", "groups", ",", "weight_method", "=", "default_weight_method", ",", "num_bins", "=", "default_num_bins", ",", "edge_range", "=", "default_edge_range", ",", "trim_outliers", "=", "default_trim_behaviour", ",", "trim_percentile", "...
Extracts the histogram-distance weighted adjacency matrix. Parameters ---------- features : ndarray or str 1d array of scalar values, either provided directly as a 1d numpy array, or as a path to a file containing these values groups : ndarray or str Membership array of same le...
[ "Extracts", "the", "histogram", "-", "distance", "weighted", "adjacency", "matrix", "." ]
python
train
alpha-xone/xbbg
xbbg/blp.py
https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/blp.py#L260-L347
def bdib(ticker, dt, typ='TRADE', **kwargs) -> pd.DataFrame: """ Bloomberg intraday bar data Args: ticker: ticker name dt: date to download typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK] **kwargs: batch: whether is batch process to download data ...
[ "def", "bdib", "(", "ticker", ",", "dt", ",", "typ", "=", "'TRADE'", ",", "*", "*", "kwargs", ")", "->", "pd", ".", "DataFrame", ":", "from", "xbbg", ".", "core", "import", "missing", "logger", "=", "logs", ".", "get_logger", "(", "bdib", ",", "lev...
Bloomberg intraday bar data Args: ticker: ticker name dt: date to download typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK] **kwargs: batch: whether is batch process to download data log: level of logs Returns: pd.DataFrame
[ "Bloomberg", "intraday", "bar", "data" ]
python
valid
Synerty/peek-plugin-base
peek_plugin_base/client/PeekPlatformDesktopHttpHookABC.py
https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/client/PeekPlatformDesktopHttpHookABC.py#L31-L42
def addDesktopResource(self, pluginSubPath: bytes, resource: BasicResource) -> None: """ Add Site Resource Add a cusotom implementation of a served http resource. :param pluginSubPath: The resource path where you want to serve this resource. :param resource: The resource to serve. ...
[ "def", "addDesktopResource", "(", "self", ",", "pluginSubPath", ":", "bytes", ",", "resource", ":", "BasicResource", ")", "->", "None", ":", "pluginSubPath", "=", "pluginSubPath", ".", "strip", "(", "b'/'", ")", "self", ".", "__rootDesktopResource", ".", "putC...
Add Site Resource Add a cusotom implementation of a served http resource. :param pluginSubPath: The resource path where you want to serve this resource. :param resource: The resource to serve. :return: None
[ "Add", "Site", "Resource" ]
python
train
crs4/pydoop
pydoop/hadut.py
https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/hadut.py#L194-L227
def get_task_trackers(properties=None, hadoop_conf_dir=None, offline=False): """ Get the list of task trackers in the Hadoop cluster. Each element in the returned list is in the ``(host, port)`` format. All arguments are passed to :func:`run_class`. If ``offline`` is :obj:`True`, try getting the l...
[ "def", "get_task_trackers", "(", "properties", "=", "None", ",", "hadoop_conf_dir", "=", "None", ",", "offline", "=", "False", ")", ":", "if", "offline", ":", "if", "not", "hadoop_conf_dir", ":", "hadoop_conf_dir", "=", "pydoop", ".", "hadoop_conf", "(", ")"...
Get the list of task trackers in the Hadoop cluster. Each element in the returned list is in the ``(host, port)`` format. All arguments are passed to :func:`run_class`. If ``offline`` is :obj:`True`, try getting the list of task trackers from the ``slaves`` file in Hadoop's configuration directory (no...
[ "Get", "the", "list", "of", "task", "trackers", "in", "the", "Hadoop", "cluster", "." ]
python
train
ReFirmLabs/binwalk
src/binwalk/plugins/unpfs.py
https://github.com/ReFirmLabs/binwalk/blob/a0c5315fd2bae167e5c3d8469ce95d5defc743c2/src/binwalk/plugins/unpfs.py#L42-L45
def _get_node(self): """Reads a chunk of meta data from file and returns a PFSNode.""" data = self.meta.read(self.node_size) return PFSNode(data, self.endianness)
[ "def", "_get_node", "(", "self", ")", ":", "data", "=", "self", ".", "meta", ".", "read", "(", "self", ".", "node_size", ")", "return", "PFSNode", "(", "data", ",", "self", ".", "endianness", ")" ]
Reads a chunk of meta data from file and returns a PFSNode.
[ "Reads", "a", "chunk", "of", "meta", "data", "from", "file", "and", "returns", "a", "PFSNode", "." ]
python
train
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L3873-L3885
def freeze(self): """ Freeze (disable) all settings """ for fields in zip(self.xsll, self.xsul, self.xslr, self.xsur, self.ys, self.nx, self.ny): for field in fields: field.disable() self.nquad.disable() self.xbin.disa...
[ "def", "freeze", "(", "self", ")", ":", "for", "fields", "in", "zip", "(", "self", ".", "xsll", ",", "self", ".", "xsul", ",", "self", ".", "xslr", ",", "self", ".", "xsur", ",", "self", ".", "ys", ",", "self", ".", "nx", ",", "self", ".", "n...
Freeze (disable) all settings
[ "Freeze", "(", "disable", ")", "all", "settings" ]
python
train
tensorflow/probability
tensorflow_probability/python/vi/csiszar_divergence.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/vi/csiszar_divergence.py#L360-L389
def pearson(logu, name=None): """The Pearson Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Pearson Csiszar-function is: ```none f(u) = (u - 1)**2 ``` Warning: this function makes non-log-space calculations and may therefore be ...
[ "def", "pearson", "(", "logu", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "name", ",", "\"pearson\"", ",", "[", "logu", "]", ")", ":", "logu", "=", "tf", ".", "convert_to_tensor", "(", "value...
The Pearson Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Pearson Csiszar-function is: ```none f(u) = (u - 1)**2 ``` Warning: this function makes non-log-space calculations and may therefore be numerically unstable for `|logu| >...
[ "The", "Pearson", "Csiszar", "-", "function", "in", "log", "-", "space", "." ]
python
test
developersociety/django-glitter
glitter/templatetags/glitter.py
https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/templatetags/glitter.py#L25-L49
def glitter_startbody(context): """ Template tag which renders the glitter overlay and sidebar. This is only shown to users with permission to edit the page. """ user = context.get('user') path_body = 'glitter/include/startbody.html' path_plus = 'glitter/include/startbody_%s_%s.html' ren...
[ "def", "glitter_startbody", "(", "context", ")", ":", "user", "=", "context", ".", "get", "(", "'user'", ")", "path_body", "=", "'glitter/include/startbody.html'", "path_plus", "=", "'glitter/include/startbody_%s_%s.html'", "rendered", "=", "''", "if", "user", "is",...
Template tag which renders the glitter overlay and sidebar. This is only shown to users with permission to edit the page.
[ "Template", "tag", "which", "renders", "the", "glitter", "overlay", "and", "sidebar", ".", "This", "is", "only", "shown", "to", "users", "with", "permission", "to", "edit", "the", "page", "." ]
python
train
zyga/python-glibc
tempfile_ext.py
https://github.com/zyga/python-glibc/blob/d6fdb306b123a995471584a5201155c60a34448a/tempfile_ext.py#L333-L355
def _mkstemp_inner(dir, pre, suf, flags): """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" names = _get_candidate_names() for seq in range(TMP_MAX): name = next(names) file = _os.path.join(dir, pre + name + suf) try: fd = _os.open(file, flags, 0o600)...
[ "def", "_mkstemp_inner", "(", "dir", ",", "pre", ",", "suf", ",", "flags", ")", ":", "names", "=", "_get_candidate_names", "(", ")", "for", "seq", "in", "range", "(", "TMP_MAX", ")", ":", "name", "=", "next", "(", "names", ")", "file", "=", "_os", ...
Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.
[ "Code", "common", "to", "mkstemp", "TemporaryFile", "and", "NamedTemporaryFile", "." ]
python
train
evansde77/dockerstache
src/dockerstache/__main__.py
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/__main__.py#L68-L86
def main(): """ _main_ Create a CLI parser and use that to run the template rendering process """ options = build_parser() try: run(**options) except RuntimeError as ex: msg = ( "An error occurred running dockerstache: {} " "please see logging in...
[ "def", "main", "(", ")", ":", "options", "=", "build_parser", "(", ")", "try", ":", "run", "(", "*", "*", "options", ")", "except", "RuntimeError", "as", "ex", ":", "msg", "=", "(", "\"An error occurred running dockerstache: {} \"", "\"please see logging info ab...
_main_ Create a CLI parser and use that to run the template rendering process
[ "_main_" ]
python
train
ixc/django-model-settings
model_settings/templatetags/model_settings_tags.py
https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/templatetags/model_settings_tags.py#L102-L113
def render_tag(self, context, name, nodelist): """ Returns the value of the named setting. """ # Use `try` and `except` instead of `setdefault()` so we can skip # rendering the nodelist when the setting already exists. settings = self.setting_model.objects.filter(name=nam...
[ "def", "render_tag", "(", "self", ",", "context", ",", "name", ",", "nodelist", ")", ":", "# Use `try` and `except` instead of `setdefault()` so we can skip", "# rendering the nodelist when the setting already exists.", "settings", "=", "self", ".", "setting_model", ".", "obj...
Returns the value of the named setting.
[ "Returns", "the", "value", "of", "the", "named", "setting", "." ]
python
valid
aiogram/aiogram
aiogram/dispatcher/dispatcher.py
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/dispatcher.py#L655-L677
def chosen_inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs): """ Decorator for chosen inline query handler Example: .. code-block:: python3 @dp.chosen_inline_handler(lambda chosen_inline_query: True) async def some_chosen_inline_handle...
[ "def", "chosen_inline_handler", "(", "self", ",", "*", "custom_filters", ",", "state", "=", "None", ",", "run_task", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "callback", ")", ":", "self", ".", "register_chosen_inline_handler",...
Decorator for chosen inline query handler Example: .. code-block:: python3 @dp.chosen_inline_handler(lambda chosen_inline_query: True) async def some_chosen_inline_handler(chosen_inline_query: types.ChosenInlineResult) :param state: :param custom_filters: ...
[ "Decorator", "for", "chosen", "inline", "query", "handler" ]
python
train
datastax/python-driver
cassandra/policies.py
https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/policies.py#L998-L1011
def translate(self, addr): """ Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which will point to the private IP address within the same datacenter. """ # get family of this address so we translate to the same family = sock...
[ "def", "translate", "(", "self", ",", "addr", ")", ":", "# get family of this address so we translate to the same", "family", "=", "socket", ".", "getaddrinfo", "(", "addr", ",", "0", ",", "socket", ".", "AF_UNSPEC", ",", "socket", ".", "SOCK_STREAM", ")", "[", ...
Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which will point to the private IP address within the same datacenter.
[ "Reverse", "DNS", "the", "public", "broadcast_address", "then", "lookup", "that", "hostname", "to", "get", "the", "AWS", "-", "resolved", "IP", "which", "will", "point", "to", "the", "private", "IP", "address", "within", "the", "same", "datacenter", "." ]
python
train