text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _appendArgs(url, args): """Append some arguments to an HTTP query. """ # to be merged with oidutil.appendArgs when we combine the projects. if hasattr(args, 'items'): args = list(args.items()) args.sort() if len(args) == 0: return url # According to XRI Resolution s...
[ "def", "_appendArgs", "(", "url", ",", "args", ")", ":", "# to be merged with oidutil.appendArgs when we combine the projects.", "if", "hasattr", "(", "args", ",", "'items'", ")", ":", "args", "=", "list", "(", "args", ".", "items", "(", ")", ")", "args", ".",...
30.5
0.001325
def read(file): """Read in a file and create a data strucuture that is a hash with members 'header' and 'data'. The 'header' is a hash of header keywords, the data is a hash of columns. To get to the nth element of column NAME use hdu[data][NAME][n]. To get the header information use hdu[header][KEYW...
[ "def", "read", "(", "file", ")", ":", "f", "=", "open", "(", "file", ",", "'r'", ")", "lines", "=", "f", ".", "readlines", "(", ")", "f", ".", "close", "(", ")", "import", "re", ",", "string", "keywords", "=", "[", "]", "values", "=", "[", "]...
37.213333
0.023386
def update_job(name, config): ''' Update the specified job with the given configuration. CLI Example: .. code-block:: bash salt chronos-minion-id chronos.update_job my-job '<config yaml>' ''' if 'name' not in config: config['name'] = name data = salt.utils.json.dumps(confi...
[ "def", "update_job", "(", "name", ",", "config", ")", ":", "if", "'name'", "not", "in", "config", ":", "config", "[", "'name'", "]", "=", "name", "data", "=", "salt", ".", "utils", ".", "json", ".", "dumps", "(", "config", ")", "try", ":", "respons...
27.741935
0.001124
def slurp(file, binary=False, expand=False): r"""Read in a complete file `file` as a string Parameters: - `file`: a file handle or a string (`str` or `unicode`). - `binary`: whether to read in the file in binary mode (default: False). """ mode = "r" + ["b",""][not binary] file = _normaliz...
[ "def", "slurp", "(", "file", ",", "binary", "=", "False", ",", "expand", "=", "False", ")", ":", "mode", "=", "\"r\"", "+", "[", "\"b\"", ",", "\"\"", "]", "[", "not", "binary", "]", "file", "=", "_normalizeToFile", "(", "file", ",", "mode", "=", ...
36.636364
0.009685
def logprob(self, actions, action_logits): """ Logarithm of probability of given sample """ neg_log_prob = F.nll_loss(action_logits, actions, reduction='none') return -neg_log_prob
[ "def", "logprob", "(", "self", ",", "actions", ",", "action_logits", ")", ":", "neg_log_prob", "=", "F", ".", "nll_loss", "(", "action_logits", ",", "actions", ",", "reduction", "=", "'none'", ")", "return", "-", "neg_log_prob" ]
50.25
0.009804
def valueRepr(self): """ Transform the representation of the value according to the behavior, if any. """ v = self.value if self.behavior: v = self.behavior.valueRepr(self) return v
[ "def", "valueRepr", "(", "self", ")", ":", "v", "=", "self", ".", "value", "if", "self", ".", "behavior", ":", "v", "=", "self", ".", "behavior", ".", "valueRepr", "(", "self", ")", "return", "v" ]
26.777778
0.008032
def get_data_generator_by_id(hardware_source_id, sync=True): """ Return a generator for data. :param bool sync: whether to wait for current frame to finish then collect next frame NOTE: a new ndarray is created for each call. """ hardware_source = HardwareSourceManager().get_hardwa...
[ "def", "get_data_generator_by_id", "(", "hardware_source_id", ",", "sync", "=", "True", ")", ":", "hardware_source", "=", "HardwareSourceManager", "(", ")", ".", "get_hardware_source_for_hardware_source_id", "(", "hardware_source_id", ")", "def", "get_last_data", "(", "...
40.333333
0.008081
def _ReadRecordSchemaAttributes(self, tables, file_object, record_offset): """Reads a schema attributes (CSSM_DL_DB_SCHEMA_ATTRIBUTES) record. Args: tables (dict[int, KeychainDatabaseTable]): tables per identifier. file_object (file): file-like object. record_offset (int): offset of the recor...
[ "def", "_ReadRecordSchemaAttributes", "(", "self", ",", "tables", ",", "file_object", ",", "record_offset", ")", ":", "record_header", "=", "self", ".", "_ReadRecordHeader", "(", "file_object", ",", "record_offset", ")", "attribute_value_offsets", "=", "self", ".", ...
38.753247
0.002288
def unzoom_all(self,event=None,panel=None): """zoom out full data range """ if panel is None: panel = self.current_panel self.panels[panel].unzoom_all(event=event)
[ "def", "unzoom_all", "(", "self", ",", "event", "=", "None", ",", "panel", "=", "None", ")", ":", "if", "panel", "is", "None", ":", "panel", "=", "self", ".", "current_panel", "self", ".", "panels", "[", "panel", "]", ".", "unzoom_all", "(", "event",...
46
0.026738
def assert_raises_regex(exception, regex, msg_fmt="{msg}"): """Fail unless an exception with a message that matches a regular expression is raised within the context. The regular expression can be a regular expression string or object. >>> with assert_raises_regex(ValueError, r"\\d+"): ... ra...
[ "def", "assert_raises_regex", "(", "exception", ",", "regex", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "def", "test", "(", "exc", ")", ":", "compiled", "=", "re", ".", "compile", "(", "regex", ")", "if", "not", "exc", ".", "args", ":", "msg", "=",...
33.415094
0.000549
def lazy_module(modname, error_strings=None, lazy_mod_class=LazyModule, level='leaf'): """Function allowing lazy importing of a module into the namespace. A lazy module object is created, registered in `sys.modules`, and returned. This is a hollow module; actual loading, and `ImportErrors...
[ "def", "lazy_module", "(", "modname", ",", "error_strings", "=", "None", ",", "lazy_mod_class", "=", "LazyModule", ",", "level", "=", "'leaf'", ")", ":", "if", "error_strings", "is", "None", ":", "error_strings", "=", "{", "}", "_set_default_errornames", "(", ...
43.176471
0.001776
def get(key, default='', delimiter=DEFAULT_TARGET_DELIM, ordered=True): ''' Attempt to retrieve the named value from grains, if the named value is not available return the passed default. The default return is an empty string. The value can also represent a value in a nested dict using a ":" delimiter ...
[ "def", "get", "(", "key", ",", "default", "=", "''", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ",", "ordered", "=", "True", ")", ":", "if", "ordered", "is", "True", ":", "grains", "=", "__grains__", "else", ":", "grains", "=", "salt", ".", "utils"...
28.909091
0.00076
def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" if not msg_id in self._records: raise KeyError("No such msg_id %r"%(msg_id)) return copy(self._records[msg_id])
[ "def", "get_record", "(", "self", ",", "msg_id", ")", ":", "if", "not", "msg_id", "in", "self", ".", "_records", ":", "raise", "KeyError", "(", "\"No such msg_id %r\"", "%", "(", "msg_id", ")", ")", "return", "copy", "(", "self", ".", "_records", "[", ...
43.6
0.018018
def _storage_list_keys(bucket, pattern): """ List all storage keys in a specified bucket that match a pattern. """ data = [{'Name': item.metadata.name, 'Type': item.metadata.content_type, 'Size': item.metadata.size, 'Updated': item.metadata.updated_on} for item in _storage...
[ "def", "_storage_list_keys", "(", "bucket", ",", "pattern", ")", ":", "data", "=", "[", "{", "'Name'", ":", "item", ".", "metadata", ".", "name", ",", "'Type'", ":", "item", ".", "metadata", ".", "content_type", ",", "'Size'", ":", "item", ".", "metada...
54.125
0.011364
def open_document(self, path, encoding=None, replace_tabs_by_spaces=True, clean_trailing_whitespaces=True, safe_save=True, restore_cursor_position=True, preferred_eol=0, autodetect_eol=True, show_whitespaces=False, **kwargs): """ Opens a ...
[ "def", "open_document", "(", "self", ",", "path", ",", "encoding", "=", "None", ",", "replace_tabs_by_spaces", "=", "True", ",", "clean_trailing_whitespaces", "=", "True", ",", "safe_save", "=", "True", ",", "restore_cursor_position", "=", "True", ",", "preferre...
44.264151
0.001042
def url_replace_param(url, name, value): """ Replace a GET parameter in an URL """ url_components = urlparse(force_str(url)) query_params = parse_qs(url_components.query) query_params[name] = value query = urlencode(query_params, doseq=True) return force_text( urlunparse( ...
[ "def", "url_replace_param", "(", "url", ",", "name", ",", "value", ")", ":", "url_components", "=", "urlparse", "(", "force_str", "(", "url", ")", ")", "query_params", "=", "parse_qs", "(", "url_components", ".", "query", ")", "query_params", "[", "name", ...
27.75
0.001742
def can_user_approve_this_page(self, user): """Check if a user can approve this page.""" self.ensure_one() # if it's not required, anyone can approve if not self.is_approval_required: return True # if user belongs to 'Knowledge / Manager', he can approve anything ...
[ "def", "can_user_approve_this_page", "(", "self", ",", "user", ")", ":", "self", ".", "ensure_one", "(", ")", "# if it's not required, anyone can approve", "if", "not", "self", ".", "is_approval_required", ":", "return", "True", "# if user belongs to 'Knowledge / Manager'...
46.666667
0.002334
def matching_key_for(self, key): """ Given a key, return the actual key stored in self that matches. Raise KeyError if the key isn't found. """ try: return next(e_key for e_key in self.keys() if e_key == key) except StopIteration: raise KeyError(key)
[ "def", "matching_key_for", "(", "self", ",", "key", ")", ":", "try", ":", "return", "next", "(", "e_key", "for", "e_key", "in", "self", ".", "keys", "(", ")", "if", "e_key", "==", "key", ")", "except", "StopIteration", ":", "raise", "KeyError", "(", ...
28.888889
0.037313
async def guessImageMetadataFromHttpData(response): """ Identify an image format and size from the beginning of its HTTP data. """ metadata = None img_data = bytearray() while len(img_data) < CoverSourceResult.MAX_FILE_METADATA_PEEK_SIZE: new_img_data = await response.content.read(__class__.METAD...
[ "async", "def", "guessImageMetadataFromHttpData", "(", "response", ")", ":", "metadata", "=", "None", "img_data", "=", "bytearray", "(", ")", "while", "len", "(", "img_data", ")", "<", "CoverSourceResult", ".", "MAX_FILE_METADATA_PEEK_SIZE", ":", "new_img_data", "...
35.4375
0.013746
def _addMethod(self, effect, verb, resource, conditions): """Adds a method to the internal lists of allowed or denied methods. Each object in the internal list contains a resource ARN and a condition statement. The condition statement can be null.""" if verb != "*" and not hasattr(HttpVe...
[ "def", "_addMethod", "(", "self", ",", "effect", ",", "verb", ",", "resource", ",", "conditions", ")", ":", "if", "verb", "!=", "\"*\"", "and", "not", "hasattr", "(", "HttpVerb", ",", "verb", ")", ":", "raise", "NameError", "(", "\"Invalid HTTP verb \"", ...
40.774194
0.012365
def scenario_damage(riskinputs, riskmodel, param, monitor): """ Core function for a damage computation. :param riskinputs: :class:`openquake.risklib.riskinput.RiskInput` objects :param riskmodel: a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance :param monitor: ...
[ "def", "scenario_damage", "(", "riskinputs", ",", "riskmodel", ",", "param", ",", "monitor", ")", ":", "L", "=", "len", "(", "riskmodel", ".", "loss_types", ")", "D", "=", "len", "(", "riskmodel", ".", "damage_states", ")", "E", "=", "param", "[", "'nu...
46.363636
0.00096
def call(method, *args, **kwargs): ''' Calls an arbitrary netmiko method. ''' kwargs = clean_kwargs(**kwargs) if not netmiko_device['always_alive']: connection = ConnectHandler(**netmiko_device['args']) ret = getattr(connection, method)(*args, **kwargs) connection.disconnect(...
[ "def", "call", "(", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "clean_kwargs", "(", "*", "*", "kwargs", ")", "if", "not", "netmiko_device", "[", "'always_alive'", "]", ":", "connection", "=", "ConnectHandler", "(", "*...
36.727273
0.002415
def get_arg_parse(): """Parses the Command Line Arguments using argparse.""" # Create parser object: objParser = argparse.ArgumentParser() # Add argument to namespace -strCsvPrf results file path: objParser.add_argument('-strCsvPrf', required=True, metavar='/path/to/my_pr...
[ "def", "get_arg_parse", "(", ")", ":", "# Create parser object:", "objParser", "=", "argparse", ".", "ArgumentParser", "(", ")", "# Add argument to namespace -strCsvPrf results file path:", "objParser", ".", "add_argument", "(", "'-strCsvPrf'", ",", "required", "=", "True...
44.536585
0.000536
def headerData(self, index, orientation, role): """ QHeaderView respects the following item data roles: TextAlignmentRole, DisplayRole, FontRole, DecorationRole, ForegroundRole, BackgroundRole. """ ...
[ "def", "headerData", "(", "self", ",", "index", ",", "orientation", ",", "role", ")", ":", "d", "=", "self", ".", "declaration", "if", "orientation", "==", "Qt", ".", "Horizontal", "and", "role", "==", "Qt", ".", "DisplayRole", ":", "try", ":", "return...
36.695652
0.009238
def is_empty(self): ''' Returns: bool: Check if the index is empty. ''' return all(all(index[r].is_empty() for r in index) for index in self.indexes)
[ "def", "is_empty", "(", "self", ")", ":", "return", "all", "(", "all", "(", "index", "[", "r", "]", ".", "is_empty", "(", ")", "for", "r", "in", "index", ")", "for", "index", "in", "self", ".", "indexes", ")" ]
29.428571
0.009434
def _download_images(self): """ Downloads the images from the retrieved image URLs and stores in the specified destination folder. Multiprocessing is being used to minimize the download time """ print('\nDownloading Images for the Query: ' + self._imageQuery) tr...
[ "def", "_download_images", "(", "self", ")", ":", "print", "(", "'\\nDownloading Images for the Query: '", "+", "self", ".", "_imageQuery", ")", "try", ":", "self", ".", "_initialize_progress_bar", "(", ")", "# Initialize and assign work to the threads in the threadpool", ...
33.615385
0.002225
def by_name(self, name): """ In many cases you want to access directory not by it's ID, but by it's name. This method implements red-black search method, which internally uses CFB format. Also this method has internal name cache to speed up 2nd+ named accesses. """ ...
[ "def", "by_name", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_name_cache", ":", "return", "self", "[", "self", ".", "_name_cache", "[", "name", "]", "]", "if", "self", ".", "source", ".", "root", ".", "name", "==", "name"...
34.185185
0.002107
def flexbar_barplot (self): """ Make the HighCharts HTML to plot the flexbar rates """ # Specify the order of the different possible categories keys = OrderedDict() keys['remaining_reads'] = { 'color': '#437bb1', 'name': 'Remaining reads' } keys['skipped_due_to_un...
[ "def", "flexbar_barplot", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'remaining_reads'", "]", "=", "{", "'color'", ":", "'#437bb1'", ",", "'name'", ":", "'Remaining reads'", ...
47.9
0.023541
def write_file(filepath, encoding, gzipped, data): """ Write the data to file either as a gzip file or text based on the gzipped parameter Args: filepath (str): The filename to open encoding (str): The file encoding to use gzipped (bool): Whether the file should ...
[ "def", "write_file", "(", "filepath", ",", "encoding", ",", "gzipped", ",", "data", ")", ":", "if", "gzipped", ":", "with", "gzip", ".", "open", "(", "filepath", ",", "\"wt\"", ")", "as", "fobj", ":", "fobj", ".", "write", "(", "data", ")", "else", ...
36.611111
0.001479
def get_name_curr(self, name): """Get current name of symbol. """ self._register_name(name) return self._var_name_mappers[name].get_current()
[ "def", "get_name_curr", "(", "self", ",", "name", ")", ":", "self", ".", "_register_name", "(", "name", ")", "return", "self", ".", "_var_name_mappers", "[", "name", "]", ".", "get_current", "(", ")" ]
28.166667
0.011494
def _get_descending_key(gettime=time.time): """Returns a key name lexically ordered by time descending. This lets us have a key name for use with Datastore entities which returns rows in time descending order when it is scanned in lexically ascending order, allowing us to bypass index building for descending i...
[ "def", "_get_descending_key", "(", "gettime", "=", "time", ".", "time", ")", ":", "now_descending", "=", "int", "(", "(", "_FUTURE_TIME", "-", "gettime", "(", ")", ")", "*", "100", ")", "request_id_hash", "=", "os", ".", "environ", ".", "get", "(", "\"...
36
0.010526
def release(self): """ Wraps Lock.release """ self._lock.release() with self._stat_lock: self._locked = False self._last_released = datetime.now()
[ "def", "release", "(", "self", ")", ":", "self", ".", "_lock", ".", "release", "(", ")", "with", "self", ".", "_stat_lock", ":", "self", ".", "_locked", "=", "False", "self", ".", "_last_released", "=", "datetime", ".", "now", "(", ")" ]
27
0.010256
def save(self, **kwargs): """Returns a buffer to the image for saving, supports the following optional keyword arguments: format - The format to save as: see Image.FORMATS optimize - The image file size should be optimized preserve_exif - Preserve the Exif information in JPEGs ...
[ "def", "save", "(", "self", ",", "*", "*", "kwargs", ")", ":", "opts", "=", "Image", ".", "_normalize_options", "(", "kwargs", ")", "outfile", "=", "BytesIO", "(", ")", "if", "opts", "[", "\"pil\"", "]", "[", "\"format\"", "]", ":", "fmt", "=", "op...
35.233333
0.00092
def unique(values): """ Hash table-based unique. Uniques are returned in order of appearance. This does NOT sort. Significantly faster than numpy.unique. Includes NA values. Parameters ---------- values : 1d array-like Returns ------- numpy.ndarray or ExtensionArray T...
[ "def", "unique", "(", "values", ")", ":", "values", "=", "_ensure_arraylike", "(", "values", ")", "if", "is_extension_array_dtype", "(", "values", ")", ":", "# Dispatch to extension dtype's unique.", "return", "values", ".", "unique", "(", ")", "original", "=", ...
28.967391
0.000363
def validate_equal(value): """ Validate the field value is equal to the given value. Should work with anything that supports '==' operator. :param value: Value to compare. :raises: ``ValidationError('equal')`` """ def equal_validator(field, data): if field.value is None: ...
[ "def", "validate_equal", "(", "value", ")", ":", "def", "equal_validator", "(", "field", ",", "data", ")", ":", "if", "field", ".", "value", "is", "None", ":", "return", "if", "not", "(", "field", ".", "value", "==", "value", ")", ":", "raise", "Vali...
31.142857
0.002227
def get_current_info(self, symbolList, columns=None): """get_current_info() uses the yahoo.finance.quotes datatable to get all of the stock information presented in the main table on a typical stock page and a bunch of data from the key statistics page. """ response = self.select('yahoo...
[ "def", "get_current_info", "(", "self", ",", "symbolList", ",", "columns", "=", "None", ")", ":", "response", "=", "self", ".", "select", "(", "'yahoo.finance.quotes'", ",", "columns", ")", ".", "where", "(", "[", "'symbol'", ",", "'in'", ",", "symbolList"...
66.333333
0.019851
def _get_enabled_disabled(enabled_prop="true"): ''' DRY: Get all service FMRIs and their enabled property ''' ret = set() cmd = '/usr/bin/svcprop -c -p general/enabled "*"' lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines() for line in lines: comps = line.split(...
[ "def", "_get_enabled_disabled", "(", "enabled_prop", "=", "\"true\"", ")", ":", "ret", "=", "set", "(", ")", "cmd", "=", "'/usr/bin/svcprop -c -p general/enabled \"*\"'", "lines", "=", "__salt__", "[", "'cmd.run_stdout'", "]", "(", "cmd", ",", "python_shell", "=",...
33.285714
0.002088
def pip(usr_pswd=None): """ This updates one package at a time. Could do all at once: pip list --outdated | cut -d' ' -f1 | xargs pip install --upgrade """ # see if pip is installed try: cmd('which pip') except: return print('-[pip]----------') p = cmd('pip list --outdated') if not p: return pkgs = get...
[ "def", "pip", "(", "usr_pswd", "=", "None", ")", ":", "# see if pip is installed", "try", ":", "cmd", "(", "'which pip'", ")", "except", ":", "return", "print", "(", "'-[pip]----------'", ")", "p", "=", "cmd", "(", "'pip list --outdated'", ")", "if", "not", ...
22.730769
0.040584
def dphi_fc(fdata): """Apply phi derivative in the Fourier domain.""" nrows = fdata.shape[0] ncols = fdata.shape[1] B = int(ncols / 2) # As always, we assume nrows and ncols are even a = list(range(0, int(B))) ap = list(range(-int(B), 0)) a.extend(ap) dphi = np.zeros...
[ "def", "dphi_fc", "(", "fdata", ")", ":", "nrows", "=", "fdata", ".", "shape", "[", "0", "]", "ncols", "=", "fdata", ".", "shape", "[", "1", "]", "B", "=", "int", "(", "ncols", "/", "2", ")", "# As always, we assume nrows and ncols are even", "a", "=",...
24.333333
0.015385
def on_message(self, opcode, message): """ The primary dispatch function to handle incoming WebSocket messages. :param int opcode: The opcode of the message that was received. :param bytes message: The data contained within the message. """ self.logger.debug("processing {0} (opcode: 0x{1:02x}) message".for...
[ "def", "on_message", "(", "self", ",", "opcode", ",", "message", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"processing {0} (opcode: 0x{1:02x}) message\"", ".", "format", "(", "self", ".", "_opcode_names", ".", "get", "(", "opcode", ",", "'UNKNOWN'"...
33.78125
0.031475
def get_valences(self, structure): """ Returns a list of valences for the structure. This currently works only for ordered structures only. Args: structure: Structure to analyze Returns: A list of valences for each site in the structure (for an ordered ...
[ "def", "get_valences", "(", "self", ",", "structure", ")", ":", "els", "=", "[", "Element", "(", "el", ".", "symbol", ")", "for", "el", "in", "structure", ".", "composition", ".", "elements", "]", "if", "not", "set", "(", "els", ")", ".", "issubset",...
39.094017
0.00032
def version_to_int(value): """ Convert version info to integer :param value: the version received from system/info, e.g. "2.28" :return: integer from version, e.g. 28, None if it couldn't be parsed """ # remove '-SNAPSHOT' value = value.replace('-SNAPSHOT', '') # remove '-RCx' if '-R...
[ "def", "version_to_int", "(", "value", ")", ":", "# remove '-SNAPSHOT'", "value", "=", "value", ".", "replace", "(", "'-SNAPSHOT'", ",", "''", ")", "# remove '-RCx'", "if", "'-RC'", "in", "value", ":", "value", "=", "value", ".", "split", "(", "'-RC'", ","...
30.666667
0.00211
def get_edges_by_hashes(self, edge_hashes: List[str]) -> List[Edge]: """Look up several edges by hashes of their PyBEL edge data dictionaries.""" return self.session.query(Edge).filter(Edge.sha512.in_(edge_hashes)).all()
[ "def", "get_edges_by_hashes", "(", "self", ",", "edge_hashes", ":", "List", "[", "str", "]", ")", "->", "List", "[", "Edge", "]", ":", "return", "self", ".", "session", ".", "query", "(", "Edge", ")", ".", "filter", "(", "Edge", ".", "sha512", ".", ...
78
0.016949
def readable_time_delta(seconds): """ Convert a number of seconds into readable days, hours, and minutes """ days = seconds // 86400 seconds -= days * 86400 hours = seconds // 3600 seconds -= hours * 3600 minutes = seconds // 60 m_suffix = 's' if minutes != 1 else '' h_suffix = ...
[ "def", "readable_time_delta", "(", "seconds", ")", ":", "days", "=", "seconds", "//", "86400", "seconds", "-=", "days", "*", "86400", "hours", "=", "seconds", "//", "3600", "seconds", "-=", "hours", "*", "3600", "minutes", "=", "seconds", "//", "60", "m_...
26.826087
0.001565
def provide_data(self): """The name and shape of data provided by this iterator""" return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.data]
[ "def", "provide_data", "(", "self", ")", ":", "return", "[", "(", "k", ",", "tuple", "(", "[", "self", ".", "batch_size", "]", "+", "list", "(", "v", ".", "shape", "[", "1", ":", "]", ")", ")", ")", "for", "k", ",", "v", "in", "self", ".", ...
59
0.01676
def mod_data(fsclient): ''' Generate the module arguments for the shim data ''' # TODO, change out for a fileserver backend sync_refs = [ 'modules', 'states', 'grains', 'renderers', 'returners', ] ret = {} envs = fsclien...
[ "def", "mod_data", "(", "fsclient", ")", ":", "# TODO, change out for a fileserver backend", "sync_refs", "=", "[", "'modules'", ",", "'states'", ",", "'grains'", ",", "'renderers'", ",", "'returners'", ",", "]", "ret", "=", "{", "}", "envs", "=", "fsclient", ...
32.423729
0.000507
def load(self, filename=None, refresh=False): """ Try to load the data from a pre existing data file if it exists. If the data file does not exist, refresh the data and save it in the data file for future use. The data file is a json file. :param filename: The filename t...
[ "def", "load", "(", "self", ",", "filename", "=", "None", ",", "refresh", "=", "False", ")", ":", "filename", "=", "filename", "or", "self", ".", "data_file", "(", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "if", ...
32.944444
0.001638
def refresh_keyspace_metadata(self, keyspace, max_schema_agreement_wait=None): """ Synchronously refresh keyspace metadata. This applies to keyspace-level information such as replication and durability settings. It does not refresh tables, types, etc. contained in the keyspace. See :met...
[ "def", "refresh_keyspace_metadata", "(", "self", ",", "keyspace", ",", "max_schema_agreement_wait", "=", "None", ")", ":", "if", "not", "self", ".", "control_connection", ".", "refresh_schema", "(", "target_type", "=", "SchemaTargetType", ".", "KEYSPACE", ",", "ke...
74.1
0.010667
def deref_const(self, index): """ returns the dereferenced value from the const pool. For simple types, this will be a single value indicating the constant. For more complex types, such as fieldref, methodref, etc, this will return a tuple. """ if not index: ...
[ "def", "deref_const", "(", "self", ",", "index", ")", ":", "if", "not", "index", ":", "raise", "IndexError", "(", "\"Requested const 0\"", ")", "t", ",", "v", "=", "self", ".", "consts", "[", "index", "]", "if", "t", "in", "(", "CONST_Utf8", ",", "CO...
33.185185
0.002169
def get_resource_value(self, device_id, _resource_path, **kwargs): # noqa: E501 """Read from a resource # noqa: E501 Requests the resource value and when the response is available, an `AsyncIDResponse` json object is received in the notification channel. The preferred way to get resource values is to...
[ "def", "get_resource_value", "(", "self", ",", "device_id", ",", "_resource_path", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "r...
115.291667
0.000717
def MAP_ADD(self, instr): key = self.ast_stack.pop() value = self.ast_stack.pop() self.ast_stack.append((key, value)) 'NOP'
[ "def", "MAP_ADD", "(", "self", ",", "instr", ")", ":", "key", "=", "self", ".", "ast_stack", ".", "pop", "(", ")", "value", "=", "self", ".", "ast_stack", ".", "pop", "(", ")", "self", ".", "ast_stack", ".", "append", "(", "(", "key", ",", "value...
25.166667
0.012821
def div_filter(key: str, value: list, format: str, meta: Any) -> Optional[list]: """Filter the JSON ``value`` for alert divs. Arguments --------- key Key of the structure value Values in the structure format Output format of the processing meta Meta informati...
[ "def", "div_filter", "(", "key", ":", "str", ",", "value", ":", "list", ",", "format", ":", "str", ",", "meta", ":", "Any", ")", "->", "Optional", "[", "list", "]", ":", "if", "key", "!=", "\"Div\"", "or", "format", "!=", "\"latex\"", ":", "return"...
26.666667
0.002413
def _request(self, url, method='GET', params=None, api_call=None, json_encoded=False): """Internal request method""" method = method.lower() params = params or {} func = getattr(self.client, method) if isinstance(params, dict) and json_encoded is False: params, files...
[ "def", "_request", "(", "self", ",", "url", ",", "method", "=", "'GET'", ",", "params", "=", "None", ",", "api_call", "=", "None", ",", "json_encoded", "=", "False", ")", ":", "method", "=", "method", ".", "lower", "(", ")", "params", "=", "params", ...
36.632911
0.001009
def _dirint_bins(times, kt_prime, zenith, w, delta_kt_prime): """ Determine the bins for the DIRINT coefficients. Parameters ---------- times : pd.DatetimeIndex kt_prime : Zenith-independent clearness index zenith : Solar zenith angle w : precipitable water estimated from surface dew-po...
[ "def", "_dirint_bins", "(", "times", ",", "kt_prime", ",", "zenith", ",", "w", ",", "delta_kt_prime", ")", ":", "# @wholmgren: the following bin assignments use MATLAB's 1-indexing.", "# Later, we'll subtract 1 to conform to Python's 0-indexing.", "# Create kt_prime bins", "kt_prim...
41.280702
0.000415
def activity_changed(self, selection, model): """ enables and disables action buttons depending on selected item """ (model, iter) = selection.get_selected() # treat any selected case unsorted_selected = self._get_selected_category() == -1 self.get_widget('activity_edit').set_se...
[ "def", "activity_changed", "(", "self", ",", "selection", ",", "model", ")", ":", "(", "model", ",", "iter", ")", "=", "selection", ".", "get_selected", "(", ")", "# treat any selected case", "unsorted_selected", "=", "self", ".", "_get_selected_category", "(", ...
50.625
0.009709
def DueToRun(self): """Called periodically by the cron daemon, if True Run() will be called. Returns: True if it is time to run based on the specified frequency. """ if self.Get(self.Schema.DISABLED): return False cron_args = self.Get(self.Schema.CRON_ARGS) last_run_time = self.G...
[ "def", "DueToRun", "(", "self", ")", ":", "if", "self", ".", "Get", "(", "self", ".", "Schema", ".", "DISABLED", ")", ":", "return", "False", "cron_args", "=", "self", ".", "Get", "(", "self", ".", "Schema", ".", "CRON_ARGS", ")", "last_run_time", "=...
26.366667
0.010976
def _choices(text, randomized=True): """ Return all the possible choices from the following format: {a|b|c} @type text: str @param text: Text written used spin syntax @type randomized: bool @param text: Specifies if the choices will be given in random order or not. @return: A generator th...
[ "def", "_choices", "(", "text", ",", "randomized", "=", "True", ")", ":", "if", "text", ":", "# regex pattern that will be used for splitting", "pattern", "=", "r'{0}|{1}|{2}'", ".", "format", "(", "re", ".", "escape", "(", "char_opening", ")", ",", "re", ".",...
29.44
0.001316
def set_change_request_state(change_id, state='approved'): ''' Set the approval state of a change request/record :param change_id: The ID of the change request, e.g. CHG123545 :type change_id: ``str`` :param state: The target state, e.g. approved :type state: ``str`` CLI Example: ....
[ "def", "set_change_request_state", "(", "change_id", ",", "state", "=", "'approved'", ")", ":", "client", "=", "_get_client", "(", ")", "client", ".", "table", "=", "'change_request'", "# Get the change record first", "record", "=", "client", ".", "get", "(", "{...
32
0.001083
def send(self, command, sender, target, args, kwargs): """Used by the server to send messages to the client. Returns a future. """ command = get_command(command) data = {'command': command.__name__, 'id': create_aid(), 'sender': actor_identity(send...
[ "def", "send", "(", "self", ",", "command", ",", "sender", ",", "target", ",", "args", ",", "kwargs", ")", ":", "command", "=", "get_command", "(", "command", ")", "data", "=", "{", "'command'", ":", "command", ".", "__name__", ",", "'id'", ":", "cre...
32.896552
0.002037
def free(self, *args, **kwargs): """ Turns a constant into a parameter. As arguments, parameters must be strings. As keyword arguments, they can be set at the same time. """ # first set all the keyword argument values self.set(**kwargs) # get everything into one ...
[ "def", "free", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# first set all the keyword argument values", "self", ".", "set", "(", "*", "*", "kwargs", ")", "# get everything into one big list", "cnames", "=", "list", "(", "args", ")", "...
38.15625
0.015176
def _GetRelPath(self, filename): """Get relative path of a file according to the current directory, given its logical path in the repo.""" assert filename.startswith(self.subdir), (filename, self.subdir) return filename[len(self.subdir):].lstrip(r"\/")
[ "def", "_GetRelPath", "(", "self", ",", "filename", ")", ":", "assert", "filename", ".", "startswith", "(", "self", ".", "subdir", ")", ",", "(", "filename", ",", "self", ".", "subdir", ")", "return", "filename", "[", "len", "(", "self", ".", "subdir",...
51.2
0.023077
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) from cleverhans.attacks_tf import...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "from", "cleverhans", ".", "attacks_tf", "import", "spm", "labels",...
32.818182
0.001346
def request(self, **kwargs): """ Perform network request. You can specify grab settings in ``**kwargs``. Any keyword argument will be passed to ``self.config``. Returns: ``Document`` objects. """ self.prepare_request(**kwargs) refresh_count = 0 ...
[ "def", "request", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "prepare_request", "(", "*", "*", "kwargs", ")", "refresh_count", "=", "0", "while", "True", ":", "self", ".", "log_request", "(", ")", "try", ":", "self", ".", "transport...
37.865385
0.00099
def access_request(pid, record, template, **kwargs): """Create an access request.""" recid = int(pid.pid_value) datastore = LocalProxy( lambda: current_app.extensions['security'].datastore) # Record must be in restricted access mode. if record.get('access_right') != 'restricted' or \ ...
[ "def", "access_request", "(", "pid", ",", "record", ",", "template", ",", "*", "*", "kwargs", ")", ":", "recid", "=", "int", "(", "pid", ".", "pid_value", ")", "datastore", "=", "LocalProxy", "(", "lambda", ":", "current_app", ".", "extensions", "[", "...
33.189655
0.000505
def decode_offset_fetch_response(cls, data): """ Decode bytes to an OffsetFetchResponse Arguments: data: bytes to decode """ ((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _ in r...
[ "def", "decode_offset_fetch_response", "(", "cls", ",", "data", ")", ":", "(", "(", "correlation_id", ",", ")", ",", "cur", ")", "=", "relative_unpack", "(", "'>i'", ",", "data", ",", "0", ")", "(", "(", "num_topics", ",", ")", ",", "cur", ")", "=", ...
37.545455
0.002361
def types_of_coordination_environments(self, anonymous=False): """ Extract information on the different co-ordination environments present in the graph. :param anonymous: if anonymous, will replace specie names with A, B, C, etc. :return: a list of co-ordination environm...
[ "def", "types_of_coordination_environments", "(", "self", ",", "anonymous", "=", "False", ")", ":", "motifs", "=", "set", "(", ")", "for", "idx", ",", "site", "in", "enumerate", "(", "self", ".", "structure", ")", ":", "centre_sp", "=", "site", ".", "spe...
35.809524
0.001294
def upload_to_pypi(): """ Upload sdist and bdist_eggs to pypi """ # One more safety input and then we are ready to go :) x = prompt("Are you sure to upload the current version to pypi?") if not x or not x.lower() in ["y", "yes"]: return local("rm -rf dist") local("python setup.py sdist"...
[ "def", "upload_to_pypi", "(", ")", ":", "# One more safety input and then we are ready to go :)", "x", "=", "prompt", "(", "\"Are you sure to upload the current version to pypi?\"", ")", "if", "not", "x", "or", "not", "x", ".", "lower", "(", ")", "in", "[", "\"y\"", ...
36.631579
0.001401
def qteDisconnectHook(self, hookName: str, slot: (types.FunctionType, types.MethodType)): """ Disconnect ``slot`` from ``hookName``. If ``hookName`` does not exist, or ``slot`` is not connected to ``hookName`` then return **False**, otherwise disassociate ...
[ "def", "qteDisconnectHook", "(", "self", ",", "hookName", ":", "str", ",", "slot", ":", "(", "types", ".", "FunctionType", ",", "types", ".", "MethodType", ")", ")", ":", "# Shorthand.", "reg", "=", "self", ".", "_qteRegistryHooks", "# Return immediately if no...
33.608696
0.001886
def html_parser(self, scode, *args): """ args[0] = cssselector args[1] = text / html / xml / @attribute_name """ allow_method = ('text', 'html', 'xml') css_path, method = args assert method in allow_method or method.startswith( '@'), 'method allow: %s...
[ "def", "html_parser", "(", "self", ",", "scode", ",", "*", "args", ")", ":", "allow_method", "=", "(", "'text'", ",", "'html'", ",", "'xml'", ")", "css_path", ",", "method", "=", "args", "assert", "method", "in", "allow_method", "or", "method", ".", "s...
35.590909
0.002488
def build_event_handler(self, runnable, regime, event_handler): """ Build event handler code. @param event_handler: Event handler object @type event_handler: lems.model.dynamics.EventHandler @return: Generated event handler code. @rtype: list(string) """ ...
[ "def", "build_event_handler", "(", "self", ",", "runnable", ",", "regime", ",", "event_handler", ")", ":", "if", "isinstance", "(", "event_handler", ",", "OnCondition", ")", ":", "return", "self", ".", "build_on_condition", "(", "runnable", ",", "regime", ",",...
39
0.002384
def hashes_above(path, line_number): """Yield hashes from contiguous comment lines before line ``line_number``. """ def hash_lists(path): """Yield lists of hashes appearing between non-comment lines. The lists will be in order of appearance and, for each non-empty list, their place...
[ "def", "hashes_above", "(", "path", ",", "line_number", ")", ":", "def", "hash_lists", "(", "path", ")", ":", "\"\"\"Yield lists of hashes appearing between non-comment lines.\n\n The lists will be in order of appearance and, for each non-empty\n list, their place in the re...
41.074074
0.000881
def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0, subset=None, text_color_threshold=0.408): """ Color the background in a gradient according to the data in each column (optionally row). Requires matplotlib. Parameters --------...
[ "def", "background_gradient", "(", "self", ",", "cmap", "=", "'PuBu'", ",", "low", "=", "0", ",", "high", "=", "0", ",", "axis", "=", "0", ",", "subset", "=", "None", ",", "text_color_threshold", "=", "0.408", ")", ":", "subset", "=", "_maybe_numeric_s...
38.102041
0.001567
def parse_collection(path, excludes=None): """Parse a file structure to a data structure given the path to a collection directory. """ file = path / COLLECTION_FILENAME if not file.exists(): raise MissingFile(file) id = _parse_document_id(etree.parse(file.open())) excludes = exclud...
[ "def", "parse_collection", "(", "path", ",", "excludes", "=", "None", ")", ":", "file", "=", "path", "/", "COLLECTION_FILENAME", "if", "not", "file", ".", "exists", "(", ")", ":", "raise", "MissingFile", "(", "file", ")", "id", "=", "_parse_document_id", ...
33.052632
0.001548
def set_option_value(self, opt_name, value, parse=False): """ Set the value of one option. # TODO/FIXME * add force/hide argument * add default argument * remove methods force option value * remove change_option_default :para...
[ "def", "set_option_value", "(", "self", ",", "opt_name", ",", "value", ",", "parse", "=", "False", ")", ":", "if", "not", "self", ".", "has_option", "(", "opt_name", ")", ":", "raise", "ValueError", "(", "\"Unknow option name (%s)\"", "%", "opt_name", ")", ...
36.105263
0.009943
def process_delete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Recreate queryset from the index and rebuild the index.""" build_kwargs = self.delete_cache.take(obj) if build_kwargs: self.index.build(**build_kwargs)
[ "def", "process_delete", "(", "self", ",", "obj", ",", "pk_set", "=", "None", ",", "action", "=", "None", ",", "update_fields", "=", "None", ",", "*", "*", "kwargs", ")", ":", "build_kwargs", "=", "self", ".", "delete_cache", ".", "take", "(", "obj", ...
45.5
0.010791
def _project_images(reference_sources, estimated_source, flen, G=None): """Least-squares projection of estimated source on the subspace spanned by delayed versions of reference sources, with delays between 0 and flen-1. Passing G as all zeros will populate the G matrix and return it so it can be passed ...
[ "def", "_project_images", "(", "reference_sources", ",", "estimated_source", ",", "flen", ",", "G", "=", "None", ")", ":", "nsrc", "=", "reference_sources", ".", "shape", "[", "0", "]", "nsampl", "=", "reference_sources", ".", "shape", "[", "1", "]", "ncha...
46.368421
0.000278
def iterate_templates(self): """ Iterate self starter templates. :returns: A templates generator """ return [t for dd in self.dirs for t in Template.scan(dd)]
[ "def", "iterate_templates", "(", "self", ")", ":", "return", "[", "t", "for", "dd", "in", "self", ".", "dirs", "for", "t", "in", "Template", ".", "scan", "(", "dd", ")", "]" ]
26.571429
0.010417
def stringize( self, rnf_profile=RnfProfile(), ): """Create RNF representation of this read. Args: read_tuple_id_width (int): Maximal expected string length of read tuple ID. genome_id_width (int): Maximal expected string length of genome ID. chr_id_width (int): Maximal expected ...
[ "def", "stringize", "(", "self", ",", "rnf_profile", "=", "RnfProfile", "(", ")", ",", ")", ":", "sorted_segments", "=", "sorted", "(", "self", ".", "segments", ",", "key", "=", "lambda", "x", ":", "(", "x", ".", "genome_id", "*", "(", "10", "**", ...
30.6
0.01086
def verify (self, complain=True): """Validate that the attributes are self-consistent. This function does some basic checks of the object attributes to ensure that astrometric calculations can legally be performed. If the *complain* keyword is true, messages may be printed to :d...
[ "def", "verify", "(", "self", ",", "complain", "=", "True", ")", ":", "import", "sys", "if", "self", ".", "ra", "is", "None", ":", "raise", "ValueError", "(", "'AstrometryInfo missing \"ra\"'", ")", "if", "self", ".", "dec", "is", "None", ":", "raise", ...
42.150685
0.010162
def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuse...
[ "def", "check_managed_changes", "(", "name", ",", "source", ",", "source_hash", ",", "source_hash_name", ",", "user", ",", "group", ",", "mode", ",", "attrs", ",", "template", ",", "context", ",", "defaults", ",", "saltenv", ",", "contents", "=", "None", "...
29.21519
0.001676
def update_parameters(parameters, grads, learning_rate=1.2): """ Updates parameters using the gradient descent update rule given above Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradients Returns: parameters -- python di...
[ "def", "update_parameters", "(", "parameters", ",", "grads", ",", "learning_rate", "=", "1.2", ")", ":", "# Retrieve each parameter from the dictionary \"parameters\"", "W1", "=", "parameters", "[", "\"W1\"", "]", "b1", "=", "parameters", "[", "\"b1\"", "]", "W2", ...
27.085714
0.001018
def unweaned(self): """This attribute generates a queryset of unweaned animals for this breeding cage. It is filtered for only Alive animals.""" return Animal.objects.filter(Breeding=self, Weaned__isnull=True, Alive=True)
[ "def", "unweaned", "(", "self", ")", ":", "return", "Animal", ".", "objects", ".", "filter", "(", "Breeding", "=", "self", ",", "Weaned__isnull", "=", "True", ",", "Alive", "=", "True", ")" ]
79
0.020921
def clean(self): """ Validates the forum instance. """ super().clean() if self.parent and self.parent.is_link: raise ValidationError(_('A forum can not have a link forum as parent')) if self.is_category and self.parent and self.parent.is_category: raise Validati...
[ "def", "clean", "(", "self", ")", ":", "super", "(", ")", ".", "clean", "(", ")", "if", "self", ".", "parent", "and", "self", ".", "parent", ".", "is_link", ":", "raise", "ValidationError", "(", "_", "(", "'A forum can not have a link forum as parent'", ")...
42.166667
0.009671
def header(text): '''Display an header''' print(' '.join((blue('>>'), cyan(text)))) sys.stdout.flush()
[ "def", "header", "(", "text", ")", ":", "print", "(", "' '", ".", "join", "(", "(", "blue", "(", "'>>'", ")", ",", "cyan", "(", "text", ")", ")", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
27.75
0.008772
def projects_from_requirements(requirements): """Extract the project dependencies from a Requirements specification.""" log = logging.getLogger('ciu') valid_reqs = [] for requirements_path in requirements: with io.open(requirements_path) as file: requirements_text = file.read() ...
[ "def", "projects_from_requirements", "(", "requirements", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "'ciu'", ")", "valid_reqs", "=", "[", "]", "for", "requirements_path", "in", "requirements", ":", "with", "io", ".", "open", "(", "requirements_pa...
44.586207
0.002271
def generate_schedule(today=None): """Helper function which creates an ordered list of schedule days""" # We create a list of slots and schedule items schedule_days = {} seen_items = {} for slot in Slot.objects.all().order_by('end_time', 'start_time', 'day'): day = slot.get_day() if ...
[ "def", "generate_schedule", "(", "today", "=", "None", ")", ":", "# We create a list of slots and schedule items", "schedule_days", "=", "{", "}", "seen_items", "=", "{", "}", "for", "slot", "in", "Slot", ".", "objects", ".", "all", "(", ")", ".", "order_by", ...
44.375
0.001379
def _reindex(self): """ Index every sentence into a cluster """ self._len2split_idx = {} last_split = -1 for split_idx, split in enumerate(self._splits): self._len2split_idx.update( dict(list(zip(list(range(last_split + 1, split)), [split_idx] ...
[ "def", "_reindex", "(", "self", ")", ":", "self", ".", "_len2split_idx", "=", "{", "}", "last_split", "=", "-", "1", "for", "split_idx", ",", "split", "in", "enumerate", "(", "self", ".", "_splits", ")", ":", "self", ".", "_len2split_idx", ".", "update...
38.222222
0.008523
def extract(self, text: str) -> List[Extraction]: """ Extracts and structures email message from UTF8-encoded text Args: text: str Returns: Extraction """ content = BeautifulSoup(text, 'html5lib') subject = content.find('h1').text.strip() ...
[ "def", "extract", "(", "self", ",", "text", ":", "str", ")", "->", "List", "[", "Extraction", "]", ":", "content", "=", "BeautifulSoup", "(", "text", ",", "'html5lib'", ")", "subject", "=", "content", ".", "find", "(", "'h1'", ")", ".", "text", ".", ...
29.020833
0.011111
def unscheduleFirst(self, runnable): """ Remove from given item from the schedule. If runnable is scheduled to run multiple times, only the temporally first is removed. """ for evt in self.store.query(TimedEvent, TimedEvent.runnable == runnable, sort=TimedEvent.time.asce...
[ "def", "unscheduleFirst", "(", "self", ",", "runnable", ")", ":", "for", "evt", "in", "self", ".", "store", ".", "query", "(", "TimedEvent", ",", "TimedEvent", ".", "runnable", "==", "runnable", ",", "sort", "=", "TimedEvent", ".", "time", ".", "ascendin...
37
0.010554
def main(): """A simple command-line interface for :py:func:`run_simple`.""" # in contrast to argparse, this works at least under Python < 2.7 import optparse from .utils import import_string parser = optparse.OptionParser(usage="Usage: %prog [options] app_module:app_object") parser.add_option...
[ "def", "main", "(", ")", ":", "# in contrast to argparse, this works at least under Python < 2.7", "import", "optparse", "from", ".", "utils", "import", "import_string", "parser", "=", "optparse", ".", "OptionParser", "(", "usage", "=", "\"Usage: %prog [options] app_module:...
26.960784
0.001404
def has_child_logs(self, log_id): """Tests if a log has any children. arg: log_id (osid.id.Id): the ``Id`` of a log return: (boolean) - ``true`` if the ``log_id`` has children, ``false`` otherwise raise: NotFound - ``log_id`` is not found raise: NullArgument...
[ "def", "has_child_logs", "(", "self", ",", "log_id", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchySession.has_child_bins", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog_session", ".", "has_...
45.277778
0.002404
def vei_CoR_veX(X, C=None, R=None): """ Args: X: NxPxS tensor C: CxC row covariance (if None: C set to I_PP) R: NxN row covariance (if None: R set to I_NN) Returns: NxPxS tensor obtained as ve^{-1}((C \kron R) ve(X)) where ve(X) reshapes X as a NPxS matrix. """...
[ "def", "vei_CoR_veX", "(", "X", ",", "C", "=", "None", ",", "R", "=", "None", ")", ":", "_X", "=", "X", ".", "transpose", "(", "(", "0", ",", "2", ",", "1", ")", ")", "if", "R", "is", "not", "None", ":", "RV", "=", "sp", ".", "tensordot", ...
33.466667
0.01938
def ReadHuntResults(self, hunt_id, offset, count, with_tag=None, with_type=None, with_substring=None, with_timestamp=None): """Reads hunt results of a given hunt ...
[ "def", "ReadHuntResults", "(", "self", ",", "hunt_id", ",", "offset", ",", "count", ",", "with_tag", "=", "None", ",", "with_type", "=", "None", ",", "with_substring", "=", "None", ",", "with_timestamp", "=", "None", ")", ":", "all_results", "=", "[", "]...
34.78125
0.01049
def proxy_config(commands, **kwargs): ''' Send configuration commands over SSH or NX-API commands List of configuration commands no_save_config If True, don't save configuration commands to startup configuration. If False, save configuration to startup configuration. De...
[ "def", "proxy_config", "(", "commands", ",", "*", "*", "kwargs", ")", ":", "no_save_config", "=", "DEVICE_DETAILS", "[", "'no_save_config'", "]", "no_save_config", "=", "kwargs", ".", "get", "(", "'no_save_config'", ",", "no_save_config", ")", "if", "not", "is...
30.404255
0.000678
def change_password(self, previous, new_password): """ Change the user's password and save to the database :param previous: plain text previous password :param new_password: plain text new password :raises: ValidationError """ if not self.verify_password(previous...
[ "def", "change_password", "(", "self", ",", "previous", ",", "new_password", ")", ":", "if", "not", "self", ".", "verify_password", "(", "previous", ")", ":", "raise", "exceptions", ".", "Unauthorized", "(", "'Incorrect password'", ")", "if", "len", "(", "ne...
39.826087
0.002132
def render(self, template, **kwargs): """Renders the template :param template: The template to render. The template is actually a file, which is usually generated by :class:`rtcclient.template.Templater.getTemplate` and can also be modified by user accordingly. ...
[ "def", "render", "(", "self", ",", "template", ",", "*", "*", "kwargs", ")", ":", "try", ":", "temp", "=", "self", ".", "environment", ".", "get_template", "(", "template", ")", "return", "temp", ".", "render", "(", "*", "*", "kwargs", ")", "except",...
37.512821
0.001332
def encode_multipart_formdata(fields): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files. Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------T...
[ "def", "encode_multipart_formdata", "(", "fields", ")", ":", "BOUNDARY", "=", "'----------ThIs_Is_tHe_bouNdaRY_$'", "CRLF", "=", "'\\r\\n'", ".", "encode", "(", "'utf-8'", ")", "L", "=", "[", "]", "for", "(", "key", ",", "value", ")", "in", "fields", ":", ...
42.37037
0.001709
def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) """ # abandon query paramete...
[ "def", "translate_path", "(", "self", ",", "path", ")", ":", "# abandon query parameters", "path", "=", "path", ".", "split", "(", "'?'", ",", "1", ")", "[", "0", "]", "path", "=", "path", ".", "split", "(", "'#'", ",", "1", ")", "[", "0", "]", "...
37.307692
0.00201
def _linkUser(self, user): """Set the UID of the current Contact in the User properties and update all relevant own properties. """ KEY = "linked_contact_uid" username = user.getId() contact = self.getContactByUsername(username) # User is linked to another conta...
[ "def", "_linkUser", "(", "self", ",", "user", ")", ":", "KEY", "=", "\"linked_contact_uid\"", "username", "=", "user", ".", "getId", "(", ")", "contact", "=", "self", ".", "getContactByUsername", "(", "username", ")", "# User is linked to another contact (fix in U...
37.307692
0.001005
def isEnabled( self ): """ Returns whether or not this node is enabled. """ if ( self._disableWithLayer and self._layer ): lenabled = self._layer.isEnabled() else: lenabled = True return self._enabled and lenabled
[ "def", "isEnabled", "(", "self", ")", ":", "if", "(", "self", ".", "_disableWithLayer", "and", "self", ".", "_layer", ")", ":", "lenabled", "=", "self", ".", "_layer", ".", "isEnabled", "(", ")", "else", ":", "lenabled", "=", "True", "return", "self", ...
28.9
0.02349