text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _createStatsDict(self, headers, rows): """Utility method that returns database stats as a nested dictionary. @param headers: List of columns in query result. @param rows: List of rows in query result. @return: Nested dictionary of values. Fi...
[ "def", "_createStatsDict", "(", "self", ",", "headers", ",", "rows", ")", ":", "dbstats", "=", "{", "}", "for", "row", "in", "rows", ":", "dbstats", "[", "row", "[", "0", "]", "]", "=", "dict", "(", "zip", "(", "headers", "[", "1", ":", "]", ",...
40.571429
0.012048
def compare(left: Optional[L], right: Optional[R]) -> 'Comparison[L, R]': """ Calculate the comparison of two entities. | left | right | Return Type | |===========|===========|=========================| | file | file | FileComparison | ...
[ "def", "compare", "(", "left", ":", "Optional", "[", "L", "]", ",", "right", ":", "Optional", "[", "R", "]", ")", "->", "'Comparison[L, R]'", ":", "if", "isinstance", "(", "left", ",", "File", ")", "and", "isinstance", "(", "right", ",", "Directory", ...
44.727273
0.001326
def read(self, source = None, **options): ''' Reads and optionally parses a single message. :Parameters: - `source` - optional data buffer to be read, if not specified data is read from the wrapped stream :Options: - `raw` (`boolean`) - indicates wh...
[ "def", "read", "(", "self", ",", "source", "=", "None", ",", "*", "*", "options", ")", ":", "message", "=", "self", ".", "read_header", "(", "source", ")", "message", ".", "data", "=", "self", ".", "read_data", "(", "message", ".", "size", ",", "me...
42.565217
0.011988
def _build_regex(self): """ Performs a reverse lookup on a named view and generates a list of regexes that match that object. It generates regexes with the domain name included, using sites provided by the get_sites() method. >>> regex = provider.regex >...
[ "def", "_build_regex", "(", "self", ")", ":", "# get the regexes from the urlconf", "url_patterns", "=", "resolver", ".", "reverse_dict", ".", "get", "(", "self", ".", "_meta", ".", "named_view", ")", "try", ":", "regex", "=", "url_patterns", "[", "1", "]", ...
36.294118
0.008682
def decode_from_file(estimator, filename, hparams, decode_hp, decode_to_file=None, checkpoint_path=None): """Compute predictions on entries in filename and write them out.""" if not decode_hp.batch_size: dec...
[ "def", "decode_from_file", "(", "estimator", ",", "filename", ",", "hparams", ",", "decode_hp", ",", "decode_to_file", "=", "None", ",", "checkpoint_path", "=", "None", ")", ":", "if", "not", "decode_hp", ".", "batch_size", ":", "decode_hp", ".", "batch_size",...
37.289157
0.011959
def iter_repos(self, type='', number=-1, etag=None): """Iterate over repos for this organization. :param str type: (optional), accepted values: ('all', 'public', 'member', 'private', 'forks', 'sources'), API default: 'all' :param int number: (optional), number of members...
[ "def", "iter_repos", "(", "self", ",", "type", "=", "''", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "url", "=", "self", ".", "_build_url", "(", "'repos'", ",", "base_url", "=", "self", ".", "_api", ")", "params", "=", "{",...
48.058824
0.002401
def reorder(args): """ %prog reorder tabfile 1,2,4,3 > newtabfile Reorder columns in tab-delimited files. The above syntax will print out a new file with col-1,2,4,3 from the old file. """ import csv p = OptionParser(reorder.__doc__) p.set_sep() opts, args = p.parse_args(args) ...
[ "def", "reorder", "(", "args", ")", ":", "import", "csv", "p", "=", "OptionParser", "(", "reorder", ".", "__doc__", ")", "p", ".", "set_sep", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ...
27.333333
0.001473
def delete(no_logs, config_file): """Delete the project.""" config = _load_config(config_file) s3 = boto3.client('s3') cfn = boto3.client('cloudformation') logs = boto3.client('logs') try: stack = cfn.describe_stacks(StackName=config['name'])['Stacks'][0] except botocore.exceptions...
[ "def", "delete", "(", "no_logs", ",", "config_file", ")", ":", "config", "=", "_load_config", "(", "config_file", ")", "s3", "=", "boto3", ".", "client", "(", "'s3'", ")", "cfn", "=", "boto3", ".", "client", "(", "'cloudformation'", ")", "logs", "=", "...
38.809524
0.000598
def get_volume_id(connection, volume): """ Get Volume ID from the given volume. Input can be volume id or its Name tag. :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type volume: str :param volume: Volume ID or Volume Name :returns: Volume...
[ "def", "get_volume_id", "(", "connection", ",", "volume", ")", ":", "# Regular expression to check whether input is a volume id", "volume_id_pattern", "=", "re", ".", "compile", "(", "'vol-\\w{8}'", ")", "if", "volume_id_pattern", ".", "match", "(", "volume", ")", ":"...
34.828571
0.001596
def _make_class(cls, **kwargs): """Return a custom Visual class with given parameters.""" kwargs = {k: (v if v is not None else getattr(cls, k, None)) for k, v in kwargs.items()} # The class name contains a hash of the custom parameters. name = cls.__name__ + '_' + _hash(kwargs) if nam...
[ "def", "_make_class", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "{", "k", ":", "(", "v", "if", "v", "is", "not", "None", "else", "getattr", "(", "cls", ",", "k", ",", "None", ")", ")", "for", "k", ",", "v", "in", "kwargs",...
43.909091
0.002028
def get_ignorer(path, additional_exclusions=None): """Create ignorer with directory gitignore file.""" ignorefile = zgitignore.ZgitIgnore() gitignore_file = os.path.join(path, '.gitignore') if os.path.isfile(gitignore_file): with open(gitignore_file, 'r') as fileobj: ignorefile.add_p...
[ "def", "get_ignorer", "(", "path", ",", "additional_exclusions", "=", "None", ")", ":", "ignorefile", "=", "zgitignore", ".", "ZgitIgnore", "(", ")", "gitignore_file", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'.gitignore'", ")", "if", "os", ...
38.833333
0.002096
def _load_bboxes(csv_path, csv_positions, prefix): """Returns bounded boxes listed within given CSV file.""" logging.info('Loading CSVs %s from positions %s with prefix %s', csv_path, csv_positions, prefix) boxes = collections.defaultdict(list) with tf.io.gfile.GFile(csv_path) as csv_f: if cs...
[ "def", "_load_bboxes", "(", "csv_path", ",", "csv_positions", ",", "prefix", ")", ":", "logging", ".", "info", "(", "'Loading CSVs %s from positions %s with prefix %s'", ",", "csv_path", ",", "csv_positions", ",", "prefix", ")", "boxes", "=", "collections", ".", "...
41.846154
0.014376
def get_min(self,*args,**kwargs): """ Returns the minimum of a Dimension TODO: conversion is not implemented yet but should be """ if len(args) == 1: return self.spike_times.get_label(args[0]).min return [self.spike_times.get_label(a).max for a in arg...
[ "def", "get_min", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "return", "self", ".", "spike_times", ".", "get_label", "(", "args", "[", "0", "]", ")", ".", "min", "return", "[...
34.888889
0.012422
def voice_message_create(self, recipients, body, params=None): """Create a new voice message.""" if params is None: params = {} if type(recipients) == list: recipients = ','.join(recipients) params.update({'recipients': recipients, 'body': body}) return VoiceMessage(...
[ "def", "voice_message_create", "(", "self", ",", "recipients", ",", "body", ",", "params", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "{", "}", "if", "type", "(", "recipients", ")", "==", "list", ":", "recipients", "=", ...
45.75
0.010724
def _process_image_file(fobj, session, filename): """Process image files from the dataset.""" # We need to read the image files and convert them to JPEG, since some files # actually contain GIF, PNG or BMP data (despite having a .jpg extension) and # some encoding options that will make TF crash in general. i...
[ "def", "_process_image_file", "(", "fobj", ",", "session", ",", "filename", ")", ":", "# We need to read the image files and convert them to JPEG, since some files", "# actually contain GIF, PNG or BMP data (despite having a .jpg extension) and", "# some encoding options that will make TF cr...
56.714286
0.01737
def mcs_to_rate(mcs, bw=20, long_gi=True): """Convert MCS index to rate in Mbps. See http://mcsindex.com/ Args: mcs (int): MCS index bw (int): bandwidth, 20, 40, 80, ... long_gi(bool): True if long GI is used. Returns: rate (float): bitrate in Mbps >>> mcs_to_rat...
[ "def", "mcs_to_rate", "(", "mcs", ",", "bw", "=", "20", ",", "long_gi", "=", "True", ")", ":", "if", "bw", "not", "in", "[", "20", ",", "40", ",", "80", ",", "160", "]", ":", "raise", "Exception", "(", "\"Unknown bandwidth: %d MHz\"", "%", "(", "bw...
22.142857
0.001236
def parse_exchange(exchange_def, default_compartment): """Parse a structured exchange definition as obtained from a YAML file. Returns in iterator of compound, reaction, lower and upper bounds. """ default_compartment = exchange_def.get('compartment', default_compartment) for compound_def in exch...
[ "def", "parse_exchange", "(", "exchange_def", ",", "default_compartment", ")", ":", "default_compartment", "=", "exchange_def", ".", "get", "(", "'compartment'", ",", "default_compartment", ")", "for", "compound_def", "in", "exchange_def", ".", "get", "(", "'compoun...
44.857143
0.00156
def _map_response(response, decode=False): """Maps a urllib3 response to a httplib/httplib2 Response.""" # This causes weird deepcopy errors, so it's commented out for now. # item._urllib3_response = response item = httplib2.Response(response.getheaders()) item.status = response.status item['sta...
[ "def", "_map_response", "(", "response", ",", "decode", "=", "False", ")", ":", "# This causes weird deepcopy errors, so it's commented out for now.", "# item._urllib3_response = response", "item", "=", "httplib2", ".", "Response", "(", "response", ".", "getheaders", "(", ...
44.222222
0.00123
def _validate(self): """ Ensure that our expression string has variables of the form x_0, x_1, ... x_(N - 1), where N is the length of our inputs. """ variable_names, _unused = getExprNames(self._expr, {}) expr_indices = [] for name in variable_names: ...
[ "def", "_validate", "(", "self", ")", ":", "variable_names", ",", "_unused", "=", "getExprNames", "(", "self", ".", "_expr", ",", "{", "}", ")", "expr_indices", "=", "[", "]", "for", "name", "in", "variable_names", ":", "if", "name", "==", "'inf'", ":"...
37.833333
0.002148
def _properties_table(obj, columns=None, exclude_columns=None): """ Construct a `~astropy.table.QTable` of source properties from a `SourceProperties` or `SourceCatalog` object. Parameters ---------- obj : `SourceProperties` or `SourceCatalog` instance The object containing the source p...
[ "def", "_properties_table", "(", "obj", ",", "columns", "=", "None", ",", "exclude_columns", "=", "None", ")", ":", "# default properties", "columns_all", "=", "[", "'id'", ",", "'xcentroid'", ",", "'ycentroid'", ",", "'sky_centroid'", ",", "'sky_centroid_icrs'", ...
38.923077
0.000386
def parse_duration_with_start(start, duration): """ Attepmt to parse an ISO8601 formatted duration based on a start datetime. Accepts a ``duration`` and a start ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object. """ elements = _parse_du...
[ "def", "parse_duration_with_start", "(", "start", ",", "duration", ")", ":", "elements", "=", "_parse_duration_string", "(", "_clean", "(", "duration", ")", ")", "year", ",", "month", "=", "_year_month_delta_from_elements", "(", "elements", ")", "end", "=", "sta...
26.913043
0.00156
def get_subsequencesinsertion(cls, subsequences, indent) -> str: """Return the insertion string required for the given group of sequences. >>> from hydpy.auxs.xmltools import XSDWriter >>> from hydpy import prepare_model >>> model = prepare_model('hland_v1') >>> print(XS...
[ "def", "get_subsequencesinsertion", "(", "cls", ",", "subsequences", ",", "indent", ")", "->", "str", ":", "blanks", "=", "' '", "*", "(", "indent", "*", "4", ")", "lines", "=", "[", "f'{blanks}<element name=\"{subsequences.name}\"'", ",", "f'{blanks} minO...
38.948718
0.001285
def merge_close_vertices(verts, faces, close_epsilon=1e-5): """ Will merge vertices that are closer than close_epsilon. Warning, this has a O(n^2) memory usage because we compute the full vert-to-vert distance matrix. If you have a large mesh, might want to use some kind of spatial search structure...
[ "def", "merge_close_vertices", "(", "verts", ",", "faces", ",", "close_epsilon", "=", "1e-5", ")", ":", "# Pairwise distance between verts", "if", "USE_SCIPY", ":", "D", "=", "spdist", ".", "cdist", "(", "verts", ",", "verts", ")", "else", ":", "D", "=", "...
36.666667
0.000633
def delete_customer(self, handle): """Delete a customer.""" self.request(E.deleteCustomerRequest(E.handle(handle))) return True
[ "def", "delete_customer", "(", "self", ",", "handle", ")", ":", "self", ".", "request", "(", "E", ".", "deleteCustomerRequest", "(", "E", ".", "handle", "(", "handle", ")", ")", ")", "return", "True" ]
24.666667
0.013072
def getTrackedDeviceIndexForControllerRole(self, unDeviceType): """Returns the device index associated with a specific role, for example the left hand or the right hand. This function is deprecated in favor of the new IVRInput system.""" fn = self.function_table.getTrackedDeviceIndexForControllerRole ...
[ "def", "getTrackedDeviceIndexForControllerRole", "(", "self", ",", "unDeviceType", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getTrackedDeviceIndexForControllerRole", "result", "=", "fn", "(", "unDeviceType", ")", "return", "result" ]
61.5
0.008021
def to_half(b:Collection[Tensor])->Collection[Tensor]: "Recursively map lists of tensors in `b ` to FP16." if is_listy(b): return [to_half(o) for o in b] return b.half() if b.dtype not in [torch.int64, torch.int32, torch.int16] else b
[ "def", "to_half", "(", "b", ":", "Collection", "[", "Tensor", "]", ")", "->", "Collection", "[", "Tensor", "]", ":", "if", "is_listy", "(", "b", ")", ":", "return", "[", "to_half", "(", "o", ")", "for", "o", "in", "b", "]", "return", "b", ".", ...
60.75
0.020325
def get_summary(self, key, start, end, tz=None): """Get a summary for the series from *start* to *end*. The summary is a map containing keys *count*, *min*, *max*, *mean*, *sum*, and *stddev*. :param string key: the series key to use :param start: the start time for the data po...
[ "def", "get_summary", "(", "self", ",", "key", ",", "start", ",", "end", ",", "tz", "=", "None", ")", ":", "url", "=", "make_series_url", "(", "key", ")", "url", "=", "urlparse", ".", "urljoin", "(", "url", "+", "'/'", ",", "'summary'", ")", "vstar...
37.785714
0.001843
def iter(self, columnnames, order='', sort=True): """Return a tableiter object. :class:`tableiter` lets one iterate over a table by returning in each iteration step a reference table containing equal values for the given columns. By default a sort is done on the given columns to...
[ "def", "iter", "(", "self", ",", "columnnames", ",", "order", "=", "''", ",", "sort", "=", "True", ")", ":", "from", ".", "tableiter", "import", "tableiter", "return", "tableiter", "(", "self", ",", "columnnames", ",", "order", ",", "sort", ")" ]
35.541667
0.002283
def load_new_labware(container_name): """ Load a labware in the new schema into a placeable. :raises KeyError: If the labware name is not found """ defn = new_labware.load_definition_by_name(container_name) labware_id = defn['otId'] saved_offset = _look_up_offsets(labware_id) container = Co...
[ "def", "load_new_labware", "(", "container_name", ")", ":", "defn", "=", "new_labware", ".", "load_definition_by_name", "(", "container_name", ")", "labware_id", "=", "defn", "[", "'otId'", "]", "saved_offset", "=", "_look_up_offsets", "(", "labware_id", ")", "con...
40
0.001221
def list_basebackups_http(self, arg): """List available basebackups from a HTTP source""" self.storage = HTTPRestore(arg.host, arg.port, arg.site) self.storage.show_basebackup_list(verbose=arg.verbose)
[ "def", "list_basebackups_http", "(", "self", ",", "arg", ")", ":", "self", ".", "storage", "=", "HTTPRestore", "(", "arg", ".", "host", ",", "arg", ".", "port", ",", "arg", ".", "site", ")", "self", ".", "storage", ".", "show_basebackup_list", "(", "ve...
55.5
0.008889
def stop_task(self, task_tag, stop_dependent=True, stop_requirements=False): """ Stop task with the given task tag. If task already stopped, then nothing happens. :param task_tag: task to stop :param stop_dependent: if True, then every task, that require the given task as dependency, will be \ stopped before. ...
[ "def", "stop_task", "(", "self", ",", "task_tag", ",", "stop_dependent", "=", "True", ",", "stop_requirements", "=", "False", ")", ":", "# TODO: \"coverage\" requires more tests", "task", "=", "self", ".", "started_tasks", "(", "task_registry_id", "=", "task_tag", ...
32.357895
0.026199
def collapse_phenotypes(self,input_phenotype_labels,output_phenotype_label,verbose=True): """ Rename one or more input phenotypes to a single output phenotype Args: input_phenotype_labels (list): A str name or list of names to combine output_phenotype_label (list): A str...
[ "def", "collapse_phenotypes", "(", "self", ",", "input_phenotype_labels", ",", "output_phenotype_label", ",", "verbose", "=", "True", ")", ":", "if", "isinstance", "(", "input_phenotype_labels", ",", "str", ")", ":", "input_phenotype_labels", "=", "[", "input_phenot...
49.885714
0.019663
def set_power_capping(self, power_capping_state, power_cap=None, wait_for_completion=True, operation_timeout=None): """ Set the power capping settings of this CPC. The power capping settings of a CPC define whether or not the power consumption of the CPC is limi...
[ "def", "set_power_capping", "(", "self", ",", "power_capping_state", ",", "power_cap", "=", "None", ",", "wait_for_completion", "=", "True", ",", "operation_timeout", "=", "None", ")", ":", "body", "=", "{", "'power-capping-state'", ":", "power_capping_state", "}"...
44.227723
0.000657
def prep_for_deserialize(model, record, using, init_list=None): # pylint:disable=unused-argument """ Convert a record from SFDC (decoded JSON) to dict(model string, pk, fields) If fixes fields of some types. If names of required fields `init_list `are specified, then only these fields are processed. ...
[ "def", "prep_for_deserialize", "(", "model", ",", "record", ",", "using", ",", "init_list", "=", "None", ")", ":", "# pylint:disable=unused-argument", "# TODO the parameter 'using' is not currently important.", "attribs", "=", "record", ".", "pop", "(", "'attributes'", ...
40.352941
0.002135
def solver(A, config): """Generate an SA solver given matrix A and a configuration. Parameters ---------- A : array, matrix, csr_matrix, bsr_matrix Matrix to invert, CSR or BSR format preferred for efficiency config : dict A dictionary of solver configuration parameters that is used...
[ "def", "solver", "(", "A", ",", "config", ")", ":", "# Convert A to acceptable format", "A", "=", "make_csr", "(", "A", ")", "# Generate smoothed aggregation solver", "try", ":", "return", "smoothed_aggregation_solver", "(", "A", ",", "B", "=", "config", "[", "'...
38.461538
0.000488
def indentation(logical_line, previous_logical, indent_char, indent_level, previous_indent_level): """ Use 4 spaces per indentation level. For really old code that you don't want to mess up, you can continue to use 8-space tabs. """ if indent_char == ' ' and indent_level % 4: ...
[ "def", "indentation", "(", "logical_line", ",", "previous_logical", ",", "indent_char", ",", "indent_level", ",", "previous_indent_level", ")", ":", "if", "indent_char", "==", "' '", "and", "indent_level", "%", "4", ":", "return", "0", ",", "\"E111 indentation is ...
43.2
0.001511
def get_postalcodes_around_radius(self, pc, radius): postalcodes = self.get(pc) if postalcodes is None: raise PostalCodeNotFoundException("Could not find postal code you're searching for.") else: pc = postalcodes[0] radius = float(radius) ...
[ "def", "get_postalcodes_around_radius", "(", "self", ",", "pc", ",", "radius", ")", ":", "postalcodes", "=", "self", ".", "get", "(", "pc", ")", "if", "postalcodes", "is", "None", ":", "raise", "PostalCodeNotFoundException", "(", "\"Could not find postal code you'...
35.586207
0.011321
def save_tensorflow(self, inputs, path, byte_order="little_endian", data_format="nhwc"): """ Save a model to protobuf files so that it can be used in tensorflow inference. When saving the model, placeholders will be added to the tf model as input nodes. So you need to pass in the names ...
[ "def", "save_tensorflow", "(", "self", ",", "inputs", ",", "path", ",", "byte_order", "=", "\"little_endian\"", ",", "data_format", "=", "\"nhwc\"", ")", ":", "callBigDlFunc", "(", "self", ".", "bigdl_type", ",", "\"saveTF\"", ",", "self", ".", "value", ",",...
63
0.010428
def _getTypename(self, defn): """ Returns the SQL typename required to store the given FieldDefinition """ return 'REAL' if defn.type.float or 'TIME' in defn.type.name or defn.dntoeu else 'INTEGER'
[ "def", "_getTypename", "(", "self", ",", "defn", ")", ":", "return", "'REAL'", "if", "defn", ".", "type", ".", "float", "or", "'TIME'", "in", "defn", ".", "type", ".", "name", "or", "defn", ".", "dntoeu", "else", "'INTEGER'" ]
70.333333
0.018779
def sel(self, indexers=None, method=None, tolerance=None, drop=False, **indexers_kwargs): """Returns a new dataset with each array indexed by tick labels along the specified dimension(s). In contrast to `Dataset.isel`, indexers for this method should use labels instead of in...
[ "def", "sel", "(", "self", ",", "indexers", "=", "None", ",", "method", "=", "None", ",", "tolerance", "=", "None", ",", "drop", "=", "False", ",", "*", "*", "indexers_kwargs", ")", ":", "indexers", "=", "either_dict_or_kwargs", "(", "indexers", ",", "...
48.434783
0.00088
def IsTemplateParameterList(clean_lines, linenum, column): """Check if the token ending on (linenum, column) is the end of template<>. Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True...
[ "def", "IsTemplateParameterList", "(", "clean_lines", ",", "linenum", ",", "column", ")", ":", "(", "_", ",", "startline", ",", "startpos", ")", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "column", ")", "if", "(", "startpos", ">"...
37.5
0.009756
def copy(self): """ Returns a "T" (tee) copy of the given stream, allowing the calling stream to continue being used. """ a, b = it.tee(self._data) # 2 generators, not thread-safe self._data = a return Stream(b)
[ "def", "copy", "(", "self", ")", ":", "a", ",", "b", "=", "it", ".", "tee", "(", "self", ".", "_data", ")", "# 2 generators, not thread-safe", "self", ".", "_data", "=", "a", "return", "Stream", "(", "b", ")" ]
29
0.008368
def delete(self, full_path): """Delete a file in full_path >>> nd.delete('/Picture/flower.png') :param full_path: The full path to delete the file to, *including the file name*. :return: ``True`` if success to delete the file or ``False`` """ now = datetime.datetim...
[ "def", "delete", "(", "self", ",", "full_path", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "isoformat", "(", ")", "url", "=", "nurls", "[", "'delete'", "]", "+", "full_path", "headers", "=", "{", "'userid'", ":", ...
32.03125
0.00947
def impulse(dur=None, one=1., zero=0.): """ Impulse stream generator. Parameters ---------- dur : Duration, in number of samples; endless if not given. Returns ------- Stream that repeats "0.0" during a given time duration (if any) or endlessly, but starts with one (and only one) "1.0". """ ...
[ "def", "impulse", "(", "dur", "=", "None", ",", "one", "=", "1.", ",", "zero", "=", "0.", ")", ":", "if", "dur", "is", "None", "or", "(", "isinf", "(", "dur", ")", "and", "dur", ">", "0", ")", ":", "yield", "one", "while", "True", ":", "yield...
20.958333
0.011407
def _Httplib2Debuglevel(http_request, level, http=None): """Temporarily change the value of httplib2.debuglevel, if necessary. If http_request has a `loggable_body` distinct from `body`, then we need to prevent httplib2 from logging the full body. This sets httplib2.debuglevel for the duration of the `...
[ "def", "_Httplib2Debuglevel", "(", "http_request", ",", "level", ",", "http", "=", "None", ")", ":", "if", "http_request", ".", "loggable_body", "is", "None", ":", "yield", "return", "old_level", "=", "httplib2", ".", "debuglevel", "http_levels", "=", "{", "...
41.219512
0.000578
def _wrap_in_place(func): # noqa: D202 """Take a function that doesn't return the graph and returns the graph.""" @wraps(func) def wrapper(graph, *args, **kwargs): """Apply the enclosed function and returns the graph.""" func(graph, *args, **kwargs) return g...
[ "def", "_wrap_in_place", "(", "func", ")", ":", "# noqa: D202", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "graph", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Apply the enclosed function and returns the graph.\"\"\"", "func", "(", ...
33.9
0.008621
def set_env(user, name, value=None): ''' Set up an environment variable in the crontab. CLI Example: .. code-block:: bash salt '*' cron.set_env root MAILTO user@example.com ''' lst = list_tab(user) for env in lst['env']: if name == env['name']: if value != env[...
[ "def", "set_env", "(", "user", ",", "name", ",", "value", "=", "None", ")", ":", "lst", "=", "list_tab", "(", "user", ")", "for", "env", "in", "lst", "[", "'env'", "]", ":", "if", "name", "==", "env", "[", "'name'", "]", ":", "if", "value", "!=...
28
0.001233
def load_commands(self): """ Load cli commands from submodules. """ command_folder = os.path.join(os.path.dirname(__file__), '..', 'commands') command_dirs = { 'gandi.cli': command_folder } if 'GANDICLI_PATH' in os.environ: ...
[ "def", "load_commands", "(", "self", ")", ":", "command_folder", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'..'", ",", "'commands'", ")", "command_dirs", "=", "{", "'gandi.cli'", ":", "comm...
47.190476
0.001978
def pick_coda_from_decimal(decimal): """Picks only a coda from a decimal.""" decimal = Decimal(decimal) __, digits, exp = decimal.as_tuple() if exp < 0: return DIGIT_CODAS[digits[-1]] __, digits, exp = decimal.normalize().as_tuple() index = bisect_right(EXP_INDICES, exp) - 1 if index...
[ "def", "pick_coda_from_decimal", "(", "decimal", ")", ":", "decimal", "=", "Decimal", "(", "decimal", ")", "__", ",", "digits", ",", "exp", "=", "decimal", ".", "as_tuple", "(", ")", "if", "exp", "<", "0", ":", "return", "DIGIT_CODAS", "[", "digits", "...
34
0.002387
def show_lbaas_l7rule(self, l7rule, l7policy, **_params): """Fetches information of a certain L7 policy's rule.""" return self.get(self.lbaas_l7rule_path % (l7policy, l7rule), params=_params)
[ "def", "show_lbaas_l7rule", "(", "self", ",", "l7rule", ",", "l7policy", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "self", ".", "lbaas_l7rule_path", "%", "(", "l7policy", ",", "l7rule", ")", ",", "params", "=", "_params", "...
57
0.008658
def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors): """Decode a single field from a pax record. """ try: return value.decode(encoding, "strict") except UnicodeDecodeError: return value.decode(fallback_encoding, fallback_errors)
[ "def", "_decode_pax_field", "(", "self", ",", "value", ",", "encoding", ",", "fallback_encoding", ",", "fallback_errors", ")", ":", "try", ":", "return", "value", ".", "decode", "(", "encoding", ",", "\"strict\"", ")", "except", "UnicodeDecodeError", ":", "ret...
43.857143
0.009585
def zap(target=None, **kwargs): ''' Destroy the partition table and content of a given disk. .. code-block:: bash salt '*' ceph.osd_prepare 'dev'='/dev/vdc' \\ 'cluster_name'='ceph' \\ 'cluster_uuid'='cluster_uuid' dev The block device to format. c...
[ "def", "zap", "(", "target", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "target", "is", "not", "None", ":", "log", ".", "warning", "(", "\"Depricated use of function, use kwargs\"", ")", "target", "=", "kwargs", ".", "get", "(", "\"dev\"", ","...
26.75
0.001504
def error_response(self, error, mimetype='application/json', status=400, **kwargs): """ Return an error response to the client with default status code of *400* stating the error as outlined in :rfc:`5.2`. """ return HttpResponse(json.dumps(error), mimetype=mimetype, ...
[ "def", "error_response", "(", "self", ",", "error", ",", "mimetype", "=", "'application/json'", ",", "status", "=", "400", ",", "*", "*", "kwargs", ")", ":", "return", "HttpResponse", "(", "json", ".", "dumps", "(", "error", ")", ",", "mimetype", "=", ...
44.125
0.011111
def to_dict(self): '''A representation of that publication data that matches the schema we use in our databases.''' if not self.record_type == 'journal': # todo: it may be worthwhile creating subclasses for each entry type (journal, conference, etc.) with a common # API e.g. to_j...
[ "def", "to_dict", "(", "self", ")", ":", "if", "not", "self", ".", "record_type", "==", "'journal'", ":", "# todo: it may be worthwhile creating subclasses for each entry type (journal, conference, etc.) with a common", "# API e.g. to_json which creates output appropriately", "raise"...
41.727273
0.023417
def tail_field(field): """ RETURN THE FIRST STEP IN PATH, ALONG WITH THE REMAINING TAIL """ if field == "." or field==None: return ".", "." elif "." in field: if "\\." in field: return tuple(k.replace("\a", ".") for k in field.replace("\\.", "\a").split(".", 1)) e...
[ "def", "tail_field", "(", "field", ")", ":", "if", "field", "==", "\".\"", "or", "field", "==", "None", ":", "return", "\".\"", ",", "\".\"", "elif", "\".\"", "in", "field", ":", "if", "\"\\\\.\"", "in", "field", ":", "return", "tuple", "(", "k", "."...
29.769231
0.010025
def _generateFileFromProb(filename, numRecords, categoryList, initProb, firstOrderProb, secondOrderProb, seqLen, numNoise=0, resetsEvery=None): """ Generate a set of records reflecting a set of probabilities. Parameters: ---------------------------------------------------------------- filename: ...
[ "def", "_generateFileFromProb", "(", "filename", ",", "numRecords", ",", "categoryList", ",", "initProb", ",", "firstOrderProb", ",", "secondOrderProb", ",", "seqLen", ",", "numNoise", "=", "0", ",", "resetsEvery", "=", "None", ")", ":", "# Create the file", "pr...
38.892857
0.014327
def set_exception(self, exception): """Sets the exception of a ``Future.``""" self.set_exc_info( (exception.__class__, exception, getattr(exception, '__traceback__', None)))
[ "def", "set_exception", "(", "self", ",", "exception", ")", ":", "self", ".", "set_exc_info", "(", "(", "exception", ".", "__class__", ",", "exception", ",", "getattr", "(", "exception", ",", "'__traceback__'", ",", "None", ")", ")", ")" ]
37
0.008811
def register_class(klass, alias=None): """ Registers a class to be used in the data streaming. This is the equivalent to the C{[RemoteClass(alias="foobar")]} AS3 metatag. @return: The registered L{ClassAlias} instance. @see: L{unregister_class} """ meta = util.get_class_meta(klass) if ...
[ "def", "register_class", "(", "klass", ",", "alias", "=", "None", ")", ":", "meta", "=", "util", ".", "get_class_meta", "(", "klass", ")", "if", "alias", "is", "not", "None", ":", "meta", "[", "'alias'", "]", "=", "alias", "alias_klass", "=", "util", ...
24.130435
0.001733
def names(self): """ Returns the player's name and real name. Returns two empty strings if the player is unknown. AI real name is always an empty string. """ if self.name == self.UNKNOWN_HUMAN_PLAYER: return "", "" if not self.is_ai and " " in self.name: return "", self.name return self.name, ""
[ "def", "names", "(", "self", ")", ":", "if", "self", ".", "name", "==", "self", ".", "UNKNOWN_HUMAN_PLAYER", ":", "return", "\"\"", ",", "\"\"", "if", "not", "self", ".", "is_ai", "and", "\" \"", "in", "self", ".", "name", ":", "return", "\"\"", ",",...
23.692308
0.0375
def execute_all(self): """ Execute all workflows """ for workflow_id in self.workflows: if self.workflows[workflow_id].online: for interval in self.workflows[workflow_id].requested_intervals: logging.info("Executing workflow {} over interva...
[ "def", "execute_all", "(", "self", ")", ":", "for", "workflow_id", "in", "self", ".", "workflows", ":", "if", "self", ".", "workflows", "[", "workflow_id", "]", ".", "online", ":", "for", "interval", "in", "self", ".", "workflows", "[", "workflow_id", "]...
46
0.009479
def _iter_module_subclasses(package, module_name, base_cls): """inspect all modules in this directory for subclasses of inherit from ``base_cls``. inpiration from http://stackoverflow.com/q/1796180/564709 """ module = importlib.import_module('.' + module_name, package) for name, obj in inspect.getme...
[ "def", "_iter_module_subclasses", "(", "package", ",", "module_name", ",", "base_cls", ")", ":", "module", "=", "importlib", ".", "import_module", "(", "'.'", "+", "module_name", ",", "package", ")", "for", "name", ",", "obj", "in", "inspect", ".", "getmembe...
51.5
0.002387
def setup_hfb_pars(self): """setup non-mult parameters for hfb (yuck!) """ if self.m.hfb6 is None: self.logger.lraise("couldn't find hfb pak") tpl_file,df = pyemu.gw_utils.write_hfb_template(self.m) self.in_files.append(os.path.split(tpl_file.replace(".tpl",""))[-1]...
[ "def", "setup_hfb_pars", "(", "self", ")", ":", "if", "self", ".", "m", ".", "hfb6", "is", "None", ":", "self", ".", "logger", ".", "lraise", "(", "\"couldn't find hfb pak\"", ")", "tpl_file", ",", "df", "=", "pyemu", ".", "gw_utils", ".", "write_hfb_tem...
36.636364
0.009685
def get_all_blockstack_ops_at( self, block_number, offset=None, count=None, include_history=None, restore_history=None ): """ Get all name, namespace, and account records affected at a particular block, in the state they were at the given block number. Paginate if offset, count ...
[ "def", "get_all_blockstack_ops_at", "(", "self", ",", "block_number", ",", "offset", "=", "None", ",", "count", "=", "None", ",", "include_history", "=", "None", ",", "restore_history", "=", "None", ")", ":", "if", "include_history", "is", "not", "None", ":"...
39.909091
0.013348
def tail(environment, zappa_settings): """ Stolen verbatim from django-zappa: https://github.com/Miserlou/django-zappa/blob/master/django_zappa/management/commands/tail.py """ def print_logs(logs): for log in logs: timestamp = log['timestamp'] message = log['messag...
[ "def", "tail", "(", "environment", ",", "zappa_settings", ")", ":", "def", "print_logs", "(", "logs", ")", ":", "for", "log", "in", "logs", ":", "timestamp", "=", "log", "[", "'timestamp'", "]", "message", "=", "log", "[", "'message'", "]", "if", "\"ST...
29.690476
0.001553
def vreckon(Lat1: float, Lon1: float, Rng: float, Azim: float, ell: Ellipsoid = None) -> Tuple[float, float, float]: """ This is the Vincenty "forward" solution. Computes points at a specified azimuth and range in an ellipsoidal earth. Using the reference ellipsoid, travel a given distance ...
[ "def", "vreckon", "(", "Lat1", ":", "float", ",", "Lon1", ":", "float", ",", "Rng", ":", "float", ",", "Azim", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "lat1"...
41.817143
0.002269
def conform_query(cls, query): """Converts the query string from a target uri, uses cls.allowed_kwargs, and cls.filter_kwargs to drive logic. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls...
[ "def", "conform_query", "(", "cls", ",", "query", ")", ":", "query", "=", "parse_qs", "(", "query", ",", "keep_blank_values", "=", "True", ")", "# Remove any unexpected keywords from the query string.", "if", "cls", ".", "filter_kwargs", ":", "query", "=", "{", ...
37.814815
0.00191
def get_final_from_initial(mass1, mass2, spin1x=0., spin1y=0., spin1z=0., spin2x=0., spin2y=0., spin2z=0., approximant='SEOBNRv4'): """Estimates the final mass and spin from the given initial parameters. This uses the fits used by the EOBNR models for conve...
[ "def", "get_final_from_initial", "(", "mass1", ",", "mass2", ",", "spin1x", "=", "0.", ",", "spin1y", "=", "0.", ",", "spin1z", "=", "0.", ",", "spin2x", "=", "0.", ",", "spin2y", "=", "0.", ",", "spin2z", "=", "0.", ",", "approximant", "=", "'SEOBNR...
41.316667
0.000394
def close(self): """ Clean up NetworkTables listeners """ NetworkTables.removeGlobalListener(self._nt_on_change) NetworkTables.removeConnectionListener(self._nt_connected)
[ "def", "close", "(", "self", ")", ":", "NetworkTables", ".", "removeGlobalListener", "(", "self", ".", "_nt_on_change", ")", "NetworkTables", ".", "removeConnectionListener", "(", "self", ".", "_nt_connected", ")" ]
34.333333
0.009479
def _ssweek_info(ssweek_year, ssweek_week): "Give all the ssweek info we need from one calculation" prev_year_start = _ssweek_year_start(ssweek_year-1) year_start = _ssweek_year_start(ssweek_year) next_year_start = _ssweek_year_start(ssweek_year+1) first_day = year_start + dt.timedelta(weeks=ssweek_...
[ "def", "_ssweek_info", "(", "ssweek_year", ",", "ssweek_week", ")", ":", "prev_year_start", "=", "_ssweek_year_start", "(", "ssweek_year", "-", "1", ")", "year_start", "=", "_ssweek_year_start", "(", "ssweek_year", ")", "next_year_start", "=", "_ssweek_year_start", ...
56.9
0.00173
def clone(self, *, method: str=sentinel, rel_url: StrOrURL=sentinel, headers: LooseHeaders=sentinel, scheme: str=sentinel, host: str=sentinel, remote: str=sentinel) -> 'BaseRequest': """Clone itself with replacement some attributes. Creates and returns a new in...
[ "def", "clone", "(", "self", ",", "*", ",", "method", ":", "str", "=", "sentinel", ",", "rel_url", ":", "StrOrURL", "=", "sentinel", ",", "headers", ":", "LooseHeaders", "=", "sentinel", ",", "scheme", ":", "str", "=", "sentinel", ",", "host", ":", "...
35.306122
0.009561
def defrise_ellipses(ndim, nellipses=8, alternating=False): """Ellipses for the standard Defrise phantom in 2 or 3 dimensions. Parameters ---------- ndim : {2, 3} Dimension of the space for the ellipses/ellipsoids. nellipses : int, optional Number of ellipses. If more ellipses are u...
[ "def", "defrise_ellipses", "(", "ndim", ",", "nellipses", "=", "8", ",", "alternating", "=", "False", ")", ":", "ellipses", "=", "[", "]", "if", "ndim", "==", "2", ":", "for", "i", "in", "range", "(", "nellipses", ")", ":", "if", "alternating", ":", ...
32.444444
0.000554
def set_temperature(self, temperature): """ Initializes the velocities based on Maxwell-Boltzmann distribution. Removes linear, but not angular drift (same as VASP) Scales the energies to the exact temperature (microcanonical ensemble) Velocities are given in A/fs. This is the v...
[ "def", "set_temperature", "(", "self", ",", "temperature", ")", ":", "# mean 0 variance 1", "velocities", "=", "np", ".", "random", ".", "randn", "(", "len", "(", "self", ".", "structure", ")", ",", "3", ")", "# in AMU, (N,1) array", "atomic_masses", "=", "n...
36.788462
0.001018
def Upload(self,directory,filename): """Uploads/Updates/Replaces files""" db = self._loadDB(directory) logger.debug("wp: Attempting upload of %s"%(filename)) # See if this already exists in our DB if db.has_key(filename): pid=db[filename] logger.debug('...
[ "def", "Upload", "(", "self", ",", "directory", ",", "filename", ")", ":", "db", "=", "self", ".", "_loadDB", "(", "directory", ")", "logger", ".", "debug", "(", "\"wp: Attempting upload of %s\"", "%", "(", "filename", ")", ")", "# See if this already exists i...
29.644444
0.017417
def _dissect_msg(self, match): """ Split messages into bytes and return a tuple of bytes. """ recvfrom = match.group(1) frame = bytes.fromhex(match.group(2)) if recvfrom == 'E': _LOGGER.warning("Received erroneous message, ignoring: %s", frame) ret...
[ "def", "_dissect_msg", "(", "self", ",", "match", ")", ":", "recvfrom", "=", "match", ".", "group", "(", "1", ")", "frame", "=", "bytes", ".", "fromhex", "(", "match", ".", "group", "(", "2", ")", ")", "if", "recvfrom", "==", "'E'", ":", "_LOGGER",...
45.315789
0.002275
def use_isolated_family_view(self): """Pass through to provider RelationshipLookupSession.use_isolated_family_view""" self._family_view = ISOLATED # self._get_provider_session('relationship_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(...
[ "def", "use_isolated_family_view", "(", "self", ")", ":", "self", ".", "_family_view", "=", "ISOLATED", "# self._get_provider_session('relationship_lookup_session') # To make sure the session is tracked", "for", "session", "in", "self", ".", "_get_provider_sessions", "(", ")", ...
48.666667
0.008969
def html(self): """ Render this test case as HTML :return: """ failure = "" skipped = None stdout = tag.text(self.stdout) stderr = tag.text(self.stderr) if self.skipped: skipped = """ <hr size="1"/> <div class="...
[ "def", "html", "(", "self", ")", ":", "failure", "=", "\"\"", "skipped", "=", "None", "stdout", "=", "tag", ".", "text", "(", "self", ".", "stdout", ")", "stderr", "=", "tag", ".", "text", "(", "self", ".", "stderr", ")", "if", "self", ".", "skip...
31.982759
0.001046
def validate(self, fixerrors=True): """ Validates that the geometry is correctly formatted according to the geometry type. Parameters: - **fixerrors** (optional): Attempts to fix minor errors without raising exceptions (defaults to True) Returns: - True if th...
[ "def", "validate", "(", "self", ",", "fixerrors", "=", "True", ")", ":", "# validate nullgeometry or has type and coordinates keys", "if", "not", "self", ".", "_data", ":", "# null geometry, no further checking needed", "return", "True", "elif", "\"type\"", "not", "in",...
46.181818
0.011243
def git_static_file(filename, mimetype='auto', download=False, charset='UTF-8'): """ This method is derived from bottle.static_file: Open [a file] and return :exc:`HTTPResponse` with status code 200, 305, 403 or 404. The ``Content-Type``, ...
[ "def", "git_static_file", "(", "filename", ",", "mimetype", "=", "'auto'", ",", "download", "=", "False", ",", "charset", "=", "'UTF-8'", ")", ":", "# root = os.path.abspath(root) + os.sep", "# filename = os.path.abspath(pathjoin(root, filename.strip('/\\\\')))", "filename", ...
42.024096
0.00028
def locate(self, point, _verify=True): r"""Find a point on the current surface. Solves for :math:`s` and :math:`t` in :math:`B(s, t) = p`. This method acts as a (partial) inverse to :meth:`evaluate_cartesian`. .. warning:: A unique solution is only guaranteed if the curren...
[ "def", "locate", "(", "self", ",", "point", ",", "_verify", "=", "True", ")", ":", "if", "_verify", ":", "if", "self", ".", "_dimension", "!=", "2", ":", "raise", "NotImplementedError", "(", "\"Only 2D surfaces supported.\"", ")", "if", "point", ".", "shap...
35.228571
0.000789
def get_all_specs(self): """Returns a dict mapping kernel names and resource directories. """ # This is new in 4.1 -> https://github.com/jupyter/jupyter_client/pull/93 specs = self.get_all_kernel_specs_for_envs() specs.update(super(EnvironmentKernelSpecManager, self).get_all_spec...
[ "def", "get_all_specs", "(", "self", ")", ":", "# This is new in 4.1 -> https://github.com/jupyter/jupyter_client/pull/93", "specs", "=", "self", ".", "get_all_kernel_specs_for_envs", "(", ")", "specs", ".", "update", "(", "super", "(", "EnvironmentKernelSpecManager", ",", ...
48.428571
0.008696
def Sens_m_sample(poly, dist, samples, rule="R"): """ First order sensitivity indices estimated using Saltelli's method. Args: poly (chaospy.Poly): If provided, evaluated samples through polynomials before returned. dist (chaopy.Dist): distribution to sample from. ...
[ "def", "Sens_m_sample", "(", "poly", ",", "dist", ",", "samples", ",", "rule", "=", "\"R\"", ")", ":", "dim", "=", "len", "(", "dist", ")", "generator", "=", "Saltelli", "(", "dist", ",", "samples", ",", "poly", ",", "rule", "=", "rule", ")", "zero...
29.442308
0.001264
def get_signed_in_token(self): """GetSignedInToken. [Preview API] :rtype: :class:`<AccessTokenResult> <azure.devops.v5_0.identity.models.AccessTokenResult>` """ response = self._send(http_method='GET', location_id='6074ff18-aaad-4abb-a41e-5c75f617805...
[ "def", "get_signed_in_token", "(", "self", ")", ":", "response", "=", "self", ".", "_send", "(", "http_method", "=", "'GET'", ",", "location_id", "=", "'6074ff18-aaad-4abb-a41e-5c75f6178057'", ",", "version", "=", "'5.0-preview.1'", ")", "return", "self", ".", "...
48.222222
0.00905
def transform(self, X, mean=None, lenscale=None): """ Apply the spectral mixture component basis to X. Parameters ---------- X: ndarray (N, d) array of observations where N is the number of samples, and d is the dimensionality of X. mean: ndarray,...
[ "def", "transform", "(", "self", ",", "X", ",", "mean", "=", "None", ",", "lenscale", "=", "None", ")", ":", "mean", "=", "self", ".", "_check_dim", "(", "X", ".", "shape", "[", "1", "]", ",", "mean", ",", "paramind", "=", "0", ")", "lenscale", ...
38.4375
0.001586
def authenticate(self, me, state=None, next_url=None): """Authenticate a user via IndieAuth. Args: me (string): the authing user's URL. if it does not begin with https?://, http:// will be prepended. state (string, optional): passed through the whole auth process, ...
[ "def", "authenticate", "(", "self", ",", "me", ",", "state", "=", "None", ",", "next_url", "=", "None", ")", ":", "redirect_url", "=", "flask", ".", "url_for", "(", "self", ".", "flask_endpoint_for_function", "(", "self", ".", "_authenticated_handler", ")", ...
46.95
0.002088
def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, ...
[ "def", "session_info", "(", "consul_url", "=", "None", ",", "token", "=", "None", ",", "session", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "if", "not", "consul_url", ":", "consul_url", "=", "_get_config", "(", ")", "if", ...
29.35
0.001649
def _need_subquery(arg, attributes, named_attributes): """ Decide whether the projection argument needs to be wrapped in a subquery """ if arg.heading.expressions or arg.distinct: # argument has any renamed (computed) attributes return True restricting_attributes = a...
[ "def", "_need_subquery", "(", "arg", ",", "attributes", ",", "named_attributes", ")", ":", "if", "arg", ".", "heading", ".", "expressions", "or", "arg", ".", "distinct", ":", "# argument has any renamed (computed) attributes", "return", "True", "restricting_attributes...
61.555556
0.010676
def delete_customer(self, customer_id): """Deletes an existing customer.""" request = self._delete("customers/" + str(customer_id)) return self.responder(request)
[ "def", "delete_customer", "(", "self", ",", "customer_id", ")", ":", "request", "=", "self", ".", "_delete", "(", "\"customers/\"", "+", "str", "(", "customer_id", ")", ")", "return", "self", ".", "responder", "(", "request", ")" ]
45.75
0.010753
def single_qubit_op_to_framed_phase_form( mat: np.ndarray) -> Tuple[np.ndarray, complex, complex]: """Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g). U translates the rotation axis of M to the Z axis. g fixes a global phase factor difference caused by the translation. r's ph...
[ "def", "single_qubit_op_to_framed_phase_form", "(", "mat", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "complex", ",", "complex", "]", ":", "vals", ",", "vecs", "=", "np", ".", "linalg", ".", "eig", "(", "mat", ")", ...
40.269231
0.000933
def stop(self): """ Stop the interface :rtype: None """ self.debug("()") try: self.unjoin() time.sleep(2) except: self.exception("Failed to leave audience") super(SensorClient, self).stop()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "debug", "(", "\"()\"", ")", "try", ":", "self", ".", "unjoin", "(", ")", "time", ".", "sleep", "(", "2", ")", "except", ":", "self", ".", "exception", "(", "\"Failed to leave audience\"", ")", "supe...
21.384615
0.010345
def _constrain_L2_grad(op, grad): """Gradient for constrained optimization on an L2 unit ball. This function projects the gradient onto the ball if you are on the boundary (or outside!), but leaves it untouched if you are inside the ball. Args: op: the tensorflow op we're computing the gradient for. g...
[ "def", "_constrain_L2_grad", "(", "op", ",", "grad", ")", ":", "inp", "=", "op", ".", "inputs", "[", "0", "]", "inp_norm", "=", "tf", ".", "norm", "(", "inp", ")", "unit_inp", "=", "inp", "/", "inp_norm", "grad_projection", "=", "dot", "(", "unit_inp...
30.071429
0.01496
def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm na...
[ "def", "migrate_non_shared", "(", "vm_", ",", "target", ",", "ssh", "=", "False", ")", ":", "cmd", "=", "_get_migrate_command", "(", ")", "+", "' --copy-storage-all '", "+", "vm_", "+", "_get_target", "(", "target", ",", "ssh", ")", "stdout", "=", "subproc...
27.78125
0.001087
def _getUsername(self): """ Return a localpart@domain style string naming the owner of our store. @rtype: C{unicode} """ for (l, d) in getAccountNames(self.store): return l + u'@' + d
[ "def", "_getUsername", "(", "self", ")", ":", "for", "(", "l", ",", "d", ")", "in", "getAccountNames", "(", "self", ".", "store", ")", ":", "return", "l", "+", "u'@'", "+", "d" ]
28.625
0.008475
def __match_signature_tree(self, signature_tree, data, depth = 0): """Recursive function to find matches along the signature tree. signature_tree is the part of the tree left to walk data is the data being checked against the signature tree depth keeps track of how far we have gon...
[ "def", "__match_signature_tree", "(", "self", ",", "signature_tree", ",", "data", ",", "depth", "=", "0", ")", ":", "matched_names", "=", "list", "(", ")", "match", "=", "signature_tree", "# Walk the bytes in the data and match them", "# against the signature", "#", ...
34.169014
0.008013
def upgrade(refresh=True, dist_upgrade=False, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done t...
[ "def", "upgrade", "(", "refresh", "=", "True", ",", "dist_upgrade", "=", "False", ",", "*", "*", "kwargs", ")", ":", "cache_valid_time", "=", "kwargs", ".", "pop", "(", "'cache_valid_time'", ",", "0", ")", "if", "salt", ".", "utils", ".", "data", ".", ...
33.413793
0.001671
def character(prompt=None, empty=False): """Prompt a single character. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- str or None A str if the user entered a single-characte...
[ "def", "character", "(", "prompt", "=", "None", ",", "empty", "=", "False", ")", ":", "s", "=", "_prompt_input", "(", "prompt", ")", "if", "empty", "and", "not", "s", ":", "return", "None", "elif", "len", "(", "s", ")", "==", "1", ":", "return", ...
23.75
0.001686
def promote(self, name): """Promote to a PartitionName by combining with a bundle Name.""" return PartitionName(**dict(list(name.dict.items()) + list(self.dict.items())))
[ "def", "promote", "(", "self", ",", "name", ")", ":", "return", "PartitionName", "(", "*", "*", "dict", "(", "list", "(", "name", ".", "dict", ".", "items", "(", ")", ")", "+", "list", "(", "self", ".", "dict", ".", "items", "(", ")", ")", ")",...
61.333333
0.016129
def _get_fields_by_mro(klass, field_class, ordered=False): """Collect fields from a class, following its method resolution order. The class itself is excluded from the search; only its parents are checked. Get fields from ``_declared_fields`` if available, else use ``__dict__``. :param type klass: Clas...
[ "def", "_get_fields_by_mro", "(", "klass", ",", "field_class", ",", "ordered", "=", "False", ")", ":", "mro", "=", "inspect", ".", "getmro", "(", "klass", ")", "# Loop over mro in reverse to maintain correct order of fields", "return", "sum", "(", "(", "_get_fields"...
35.047619
0.001323
def _has_valid_positional_setitem_indexer(self, indexer): """ validate that an positional indexer cannot enlarge its target will raise if needed, does not modify the indexer externally """ if isinstance(indexer, dict): raise IndexError("{0} cannot enlarge its target object" ...
[ "def", "_has_valid_positional_setitem_indexer", "(", "self", ",", "indexer", ")", ":", "if", "isinstance", "(", "indexer", ",", "dict", ")", ":", "raise", "IndexError", "(", "\"{0} cannot enlarge its target object\"", ".", "format", "(", "self", ".", "name", ")", ...
45.038462
0.001672
def add_resource(self, text, mimetype, placement=None): """ Add a resource needed by this Fragment. Other helpers, such as :func:`add_css` or :func:`add_javascript` are more convenient for those common types of resource. `text`: the actual text of this resource, as a unicode st...
[ "def", "add_resource", "(", "self", ",", "text", ",", "mimetype", ",", "placement", "=", "None", ")", ":", "if", "not", "placement", ":", "placement", "=", "self", ".", "_default_placement", "(", "mimetype", ")", "res", "=", "FragmentResource", "(", "'text...
34.12
0.002281
def run_class(class_name, args=None, properties=None, classpath=None, hadoop_conf_dir=None, logger=None, keep_streams=True): """ Run a Java class with Hadoop (equivalent of running ``hadoop <class_name>`` from the command line). Additional ``HADOOP_CLASSPATH`` elements can be provided via...
[ "def", "run_class", "(", "class_name", ",", "args", "=", "None", ",", "properties", "=", "None", ",", "classpath", "=", "None", ",", "hadoop_conf_dir", "=", "None", ",", "logger", "=", "None", ",", "keep_streams", "=", "True", ")", ":", "if", "logger", ...
40.319149
0.000515