Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
363,100
def _get_optimal_thresholds(nd_dict, quantized_dtype, num_bins=8001, num_quantized_bins=255, logger=None): if stats is None: raise ImportError( ) assert isinstance(nd_dict, dict) if logger is not None: logger.info( ...
Given a ndarray dict, find the optimal threshold for quantizing each value of the key.
363,101
def _parse_prior(self): paths = self.prior_ if isinstance(paths, str): paths = [paths] chain_data = [] for path in paths: parsed_output = _read_output(path) for sample, sample_stats, config, adaptation, timing in parsed_output: ...
Read csv paths to list of dataframes.
363,102
def url_with_auth(regex, view, kwargs=None, name=None, prefix=): from djapiauth.auth import api_auth if isinstance(view, six.string_types): return url(regex, api_auth(import_by_path(prefix + "." + view if prefix else view))) elif isinstance(view, (list, tuple)): return url(regex, vi...
if view is string based, must be a full path
363,103
def prepare(self, start=-1): if start == -1: start = self.grammar.start self.root = None current_node = Node(start, None, [], 0, 0) self.stack = [] self.stack.append((self.grammar.dfas[start - 256], 0, current_node))
Setup the parser for parsing. Takes the starting symbol as an argument.
363,104
def GET(self, *args, **kwargs): return self._handle_api(self.API_GET, args, kwargs)
GET request
363,105
def _chip_erase_program_double_buffer(self, progress_cb=_stub_progress): LOG.debug("%i of %i pages have erased data", len(self.page_list) - self.chip_erase_count, len(self.page_list)) progress_cb(0.0) progress = 0 self.flash.init(self.flash.Operation.ERASE) self.flash.e...
! @brief Double-buffered program by first performing an erase all.
363,106
def inc(self): inc1 = self.get(, None) inc2 = self.get(, None) if inc1 is None and inc2 is None: return None if inc2 is None: return inc1 if inc1 is None: return -1 * inc2 return (inc1 - inc2) / 2.0
Corrected inclination, taking into account backsight and clino corrections.
363,107
def list_storage_accounts(call=None): if call == : raise SaltCloudSystemExit( ) storconn = get_conn(client_type=) ret = {} try: accounts_query = storconn.storage_accounts.list() accounts = __utils__[](accounts_query) for account in...
List storage accounts within the subscription.
363,108
def update_module_state(cursor, module_ident, state_name, recipe): cursor.execute(, (state_name, recipe, module_ident))
This updates the module's state in the database.
363,109
def move(x, y, absolute=True, duration=0): x = int(x) y = int(y) position_x, position_y = get_position() if not absolute: x = position_x + x y = position_y + y if duration: start_x = position_x start_y = position_y dx = x - start_x dy...
Moves the mouse. If `absolute`, to position (x, y), otherwise move relative to the current position. If `duration` is non-zero, animates the movement.
363,110
def check_no_element_by_selector(self, selector): elems = find_elements_by_jquery(world.browser, selector) if elems: raise AssertionError("Expected no matching elements, found {}.".format( len(elems)))
Assert an element does not exist matching the given selector.
363,111
def isodate(datestamp=None, microseconds=False): datestamp = datestamp or datetime.datetime.now() if not microseconds: usecs = datetime.timedelta(microseconds=datestamp.microsecond) datestamp = datestamp - usecs return datestamp.isoformat(b if PY2 else u)
Return current or given time formatted according to ISO-8601.
363,112
def add_lb_nodes(self, lb_id, nodes): log.info("Adding load balancer nodes %s" % nodes) resp, body = self._request( , % lb_id, data={: nodes}) return body
Adds nodes to an existing LBaaS instance :param string lb_id: Balancer id :param list nodes: Nodes to add. {address, port, [condition]} :rtype :class:`list`
363,113
def attributes(self, params=None): if params is None: params = {} if not self.can_update(): self._tcex.handle_error(910, [self.type]) for a in self.tc_requests.attributes( self.api_type, self.api_sub_type, self.unique_id, owner=self.owner, params=par...
Gets the attributes from a Group/Indicator or Victim Yields: attribute json
363,114
def _build(self, inputs, keep_prob=None, is_training=None, test_local_stats=True): if (self._use_batch_norm or keep_prob is not None) and is_training is None: raise ValueError("Boolean is_training flag must be explicitly specified " "when using batch normalization...
Connects the AlexNet module into the graph. The is_training flag only controls the batch norm settings, if `False` it does not force no dropout by overriding any input `keep_prob`. To avoid any confusion this may cause, if `is_training=False` and `keep_prob` would cause dropout to be applied, an error ...
363,115
def btc_bitcoind_tx_serialize( tx ): tx_ins = [] tx_outs = [] try: for inp in tx[]: next_inp = { "outpoint": { "index": int(inp[]), "hash": str(inp[]) } } if in inp: ...
Convert a *Bitcoind*-given transaction into its hex string. tx format is {'vin': [...], 'vout': [...], 'locktime': ..., 'version': ...}, with the same formatting rules as getrawtransaction. (in particular, each value in vout is a Decimal, in BTC)
363,116
def setStr(self, name, n, value): return _core.CHeaderMap_setStr(self, name, n, value)
setStr(CHeaderMap self, std::string name, limix::muint_t n, std::string value) Parameters ---------- name: std::string n: limix::muint_t value: std::string
363,117
def createmeta(self, projectKeys=None, projectIds=[], issuetypeIds=None, issuetypeNames=None, expand=None, ): params = {} if projectKeys is not None: params[] = projectK...
Get the metadata required to create issues, optionally filtered by projects and issue types. :param projectKeys: keys of the projects to filter the results with. Can be a single value or a comma-delimited string. May be combined with projectIds. :type projectKeys: Union[None, Tu...
363,118
def on(self, event, handler=None): if event not in self.event_names: raise ValueError() def set_handler(handler): self.handlers[event] = handler return handler if handler is None: return set_handler set_handler(handler)
Register an event handler. :param event: The event name. Can be ``'connect'``, ``'message'`` or ``'disconnect'``. :param handler: The function that should be invoked to handle the event. When this parameter is not given, the method a...
363,119
def confindr_targets(self, database_name=): logging.info() secret_file = os.path.join(self.credentials, ) confindr_db_setup.setup_confindr_database(output_folder=os.path.join(self.databasepath, database_name), consumer_secret=se...
Download OLC-specific ConFindr targets :param database_name: name of current database
363,120
def set_idlesleep(self, idlesleep): is_running = yield from self.is_running() if is_running: yield from self._hypervisor.send(.format(name=self._name, idlesleep=idlesleep)) ...
Sets CPU idle sleep time value. :param idlesleep: idle sleep value (integer)
363,121
def reverse_tree(tree): rtree = defaultdict(list) child_keys = set(c.key for c in flatten(tree.values())) for k, vs in tree.items(): for v in vs: node = find_tree_root(rtree, v.key) or v rtree[node].append(k.as_required_by(v)) if k.key not in child_keys: ...
Reverse the dependency tree. ie. the keys of the resulting dict are objects of type ReqPackage and the values are lists of DistPackage objects. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: reversed tree :rtype: dict
363,122
def nifti2db(file_path, file_type, is_copy, step_id, db_conn, sid_by_patient=False, pid_in_vid=False): logging.info("Processing " % file_path) df = db_conn.db_session.query(db_conn.DataFile).filter_by(path=file_path).one_or_none() dataset = db_conn.get_dataset(step_id) _extract_participant(db_con...
Extract some meta-data from NIFTI files (actually mostly from their paths) and stores it in a DB. Arguments: :param file_path: File path. :param file_type: File type. :param is_copy: Indicate if this file is a copy. :param step_id: Step ID. :param db_conn: Database connection. :param sid_by...
363,123
def inject_python_code2(fpath, patch_code, tag): import utool as ut text = ut.readfrom(fpath) start_tag = % tag end_tag = % tag new_text = ut.replace_between_tags(text, patch_code, start_tag, end_tag) ut.writeto(fpath, new_text)
Does autogeneration stuff
363,124
def load_class_by_name(name: str): mod_path, _, cls_name = name.rpartition() mod = importlib.import_module(mod_path) cls = getattr(mod, cls_name) return cls
Given a dotted path, returns the class
363,125
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1, database_filter=None): model = pcc.graph_query(, source_genes, target_genes, neighbor_limit=neighbor_limit, database_filter=database_filter) if model...
Returns a BiopaxProcessor for a PathwayCommons paths-from-to query. The paths-from-to query finds the paths from a set of source genes to a set of target genes. http://www.pathwaycommons.org/pc2/#graph http://www.pathwaycommons.org/pc2/#graph_kind Parameters ---------- source_genes : lis...
363,126
def _merge_expressions(self, other): new_inputs = tuple(set(self.inputs).union(other.inputs)) new_self_expr = self._rebind_variables(new_inputs) new_other_expr = other._rebind_variables(new_inputs) return new_self_expr, new_other_expr, new_inputs
Merge the inputs of two NumericalExpressions into a single input tuple, rewriting their respective string expressions to make input names resolve correctly. Returns a tuple of (new_self_expr, new_other_expr, new_inputs)
363,127
def prepare(self): if self._create: self.create() for k in self._children: self._children[k]._env = self._env self._children[k].prepare()
Prepare the Directory for use in an Environment. This will create the directory if the create flag is set.
363,128
def load_package(package_dir, package=None, exclude=None, default_section=_DEFAULT_SECTION): init_py = py_ext = files = os.listdir(package_dir) if init_py in files: files = [f for f in files if f != init_py] if package: files.insert(0, package) def init_package(it...
从目录中载入配置文件 :param package_dir: :param package: :param exclude: :param default_section: :return:
363,129
def prettify_metrics(metrics: List[Tuple[str, float]], precision: int = 4) -> OrderedDict: prettified_metrics = OrderedDict() for key, value in metrics: value = round(value, precision) prettified_metrics[key] = value return prettified_metrics
Prettifies the dictionary of metrics.
363,130
def fit_ahrs(A, H, Aoff, Arot, Hoff, Hrot): Acal = np.dot(A - Aoff, Arot) Hcal = np.dot(H - Hoff, Hrot) for i in (1, 2): Acal[i] = -Acal[i] Hcal[i] = -Hcal[i] roll = arctan2(-Acal[1], -Acal[2]) pitch = arctan2(Acal[0], np.sqrt(Acal[1] * Acal[1] + Acal[2] * Acal[2])) y...
Calculate yaw, pitch and roll for given A/H and calibration set. Author: Vladimir Kulikovsky Parameters ---------- A: list, tuple or numpy.array of shape (3,) H: list, tuple or numpy.array of shape (3,) Aoff: numpy.array of shape(3,) Arot: numpy.array of shape(3, 3) Hoff: numpy.array o...
363,131
def constant_jump_targets_and_jumpkinds(self): exits = dict() if self.exit_statements: for _, _, stmt_ in self.exit_statements: exits[stmt_.dst.value] = stmt_.jumpkind default_target = self.default_exit_target if default_target is not None: ...
A dict of the static jump targets of the basic block to their jumpkind.
363,132
def active_element(self): if self._driver.w3c: return self._driver.execute(Command.W3C_GET_ACTIVE_ELEMENT)[] else: return self._driver.execute(Command.GET_ACTIVE_ELEMENT)[]
Returns the element with focus, or BODY if nothing has focus. :Usage: :: element = driver.switch_to.active_element
363,133
def find_file_ident_desc_by_name(self, currpath): if not self._initialized: raise pycdlibexception.PyCdlibInternalError() if self.icb_tag.file_type != 4 or not self.fi_descs: raise pycdlibexception.PyCdlibInvalidInput() tmp = currpath...
A method to find a UDF File Identifier descriptor by its name. Parameters: currpath - The UTF-8 encoded name to look up. Returns: The UDF File Identifier descriptor corresponding to the passed in name.
363,134
def split_prefix(self, ctx, item): app = ctx._app try: if hasattr(app, ): blueprint, name = item.split(, 1) directory = get_static_folder(app.blueprints[blueprint]) endpoint = % blueprint item = name else: ...
See if ``item`` has blueprint prefix, return (directory, rel_path).
363,135
def _lib(self, name, only_if_have=False): emit = True if only_if_have: emit = self.env.get( + self.env_key(name)) if emit: return + name return
Specify a linker library. Example: LDFLAGS={{ lib("rt") }} {{ lib("pthread", True) }} Will unconditionally add `-lrt` and check the environment if the key `HAVE_LIBPTHREAD` is set to be true, then add `-lpthread`.
363,136
def ini_load_hook(cfg, **kwargs): cfg.tmpini = configparser.ConfigParser() try: cfg.tmpini.read_file(cfg.fd) except ValueError as e: raise exc.LoaderException("Could not decode INI file: {}".format(e)) from e tmpdict = {} for name in cfg.tmpini.sections(): dat...
This handles automatically opening/creating the INI configuration files. >>> import configmaster.INIConfigFile >>> cfg = configmaster.INIConfigFile.INIConfigFile("tesr.ini") # Accepts a string for input >>> fd = open("test.ini") # Accepts a file descriptor too >>> cfg2 = configmaster.INIConfigFile.INI...
363,137
def check_precondition(self, key, value): timeout = float(value) curr_time = self.get_current_time() if curr_time > timeout: return True return False
Override to check for timeout
363,138
def execute(self, operation, *args, **kwargs): def pop_models(): models = kwargs.pop(, None) if models is None: return None else: if isinstance(models, str): return [models] else: ...
execute High-level api: Supported operations are get, get_config, get_schema, dispatch, edit_config, copy_config, validate, commit, discard_changes, delete_config, lock, unlock, close_session, kill_session, poweroff_machine and reboot_machine. Since ModelDevice is a subclass of ...
363,139
def _get_indexes_in_altered_table(self, diff): indexes = diff.from_table.get_indexes() column_names = self._get_column_names_in_altered_table(diff) for key, index in OrderedDict([(k, v) for k, v in indexes.items()]).items(): for old_index_name, renamed_index in diff.renamed...
:param diff: The table diff :type diff: orator.dbal.table_diff.TableDiff :rtype: dict
363,140
def changes_found(self): if self.dest is None: warnings.warn("dest directory not found!") if self.src is None: warnings.warn("src directory not found!") if self.src is None or self.dest is None: return False dest_mtime = -1 src_mtime =...
Returns True if the target folder is older than the source folder.
363,141
def main(): prog = version = __version__ usage = doc_text = for line in __doc__.splitlines(): if line.find() == 0: break doc_text += % line parser = OptionParser(prog=prog, usage=usage, version=version) parser.add_option(, , a...
Set up "optparse" and pass the options to a new instance of L{LatexMaker}.
363,142
def account_id(self, value): if value == self._defaults[] and in self._values: del self._values[] else: self._values[] = value
The account_id property. Args: value (string). the property value.
363,143
def _bfs(node, visited): queue = collections.deque() queue.appendleft(node) while queue: node = queue.pop() if node not in visited: if node.lo is not None: queue.appendleft(node.lo) if node.hi is not None: queue.appendleft(node.hi)...
Iterate through nodes in BFS order.
363,144
def get(self): gtype = self.gvalue.g_type fundamental = gobject_lib.g_type_fundamental(gtype) result = None if gtype == GValue.gbool_type: result = bool(gobject_lib.g_value_get_boolean(self.gvalue)) elif gtype == GValue.gint_type: res...
Get the contents of a GValue. The contents of the GValue are read out as a Python type.
363,145
def decode(cls, string, errors=): if errors != : raise UnicodeError(.format(errors)) unicode_string = cls._ensure_unicode_string(string) decoded = unicode_string.translate(cls._decoding_table) return decoded, len(string)
Return the decoded version of a string. :param string: The input string to decode. :type string: `basestring` :param errors: The error handling scheme. Only 'strict' is supported. :type errors: `basestring` :return: T...
363,146
def _get_base_defaultLayer(self): name = self.defaultLayerName layer = self.getLayer(name) return layer
This is the environment implementation of :attr:`BaseFont.defaultLayer`. Return the default layer as a :class:`BaseLayer` object. The layer will be normalized with :func:`normalizers.normalizeLayer`. Subclasses must override this method.
363,147
def tag_dssp_solvent_accessibility(self, force=False): tagged = [ in x.tags.keys() for x in self._monomers] if (not all(tagged)) or force: dssp_out = run_dssp(self.pdb, path=False) if dssp_out is None: return dssp_acc_list = extract_solvent_ac...
Tags each `Residues` Polymer with its solvent accessibility. Notes ----- For more about DSSP's solvent accessibilty metric, see: http://swift.cmbi.ru.nl/gv/dssp/HTML/descrip.html#ACC References ---------- .. [1] Kabsch W, Sander C (1983) "Dictionary of prote...
363,148
def received_response(self, value): if value == self._defaults[] and in self._values: del self._values[] else: self._values[] = value
The received_response property. Args: value (string). the property value.
363,149
def _init_sqlite_functions(self): self.connection.create_function("sqrt", 1,sqlfunctions._sqrt) self.connection.create_function("sqr", 1,sqlfunctions._sqr) self.connection.create_function("periodic", 1,sqlfunctions._periodic) self.connection.create_function("pow", 2,sqlfunction...
additional SQL functions to the database
363,150
def on_start(self): LOGGER.debug("natsd.Service.on_start") self.service = threading.Thread(target=self.run_event_loop, name=self.serviceQ + " service thread") self.service.start() while not self.is_started: time.sleep(0.01)
start the service
363,151
def create_handler(Model, name=None, **kwds): async def action_handler(service, action_type, payload, props, notify=True, **kwds): if action_type == get_crud_action(, name or Model): try: message_props = {} ...
This factory returns an action handler that creates a new instance of the specified model when a create action is recieved, assuming the action follows nautilus convetions. Args: Model (nautilus.BaseModel): The model to create when the action received. Retur...
363,152
def delete_detector(self, detector_id, **kwargs): resp = self._delete(self._u(self._DETECTOR_ENDPOINT_SUFFIX, detector_id), **kwargs) resp.raise_for_status() return resp
Remove a detector. Args: detector_id (string): the ID of the detector.
363,153
def is_enable_action_dependent(self, hosts, services): enable_action = False for (dep_id, status, _, _) in self.act_depend_of: if in status: enable_action = True else: if dep_id in hosts: dep = hosts[dep_id] ...
Check if dependencies states match dependencies statuses This basically means that a dependency is in a bad state and it can explain this object state. :param hosts: hosts objects, used to get object in act_depend_of :type hosts: alignak.objects.host.Hosts :param services: servi...
363,154
def dameraulevenshtein(seq1, seq2): oneago = None thisrow = list(range_(1, len(seq2) + 1)) + [0] for x in range_(len(seq1)): twoago, oneago, thisrow = oneago, thisrow, [0] * len(seq2) + [x + 1] for y in range_(len(seq2)): delcos...
Calculate the Damerau-Levenshtein distance between sequences. This distance is the number of additions, deletions, substitutions, and transpositions needed to transform the first sequence into the second. Although generally used with strings, any sequences of comparable objects will work. Transpos...
363,155
def get(*args, **kwargs): try: from invenio.modules.accounts.models import UserEXT except ImportError: from invenio_accounts.models import UserEXT q = UserEXT.query return q.count(), q.all()
Get UserEXT objects.
363,156
def search(self): matches = [] for pattern in Config.patterns: matches += self.termfinder(pattern) return sorted(set(matches), key=int)
Search srt in project for cells matching list of terms.
363,157
def set_wx_window_layout(wx_window, layout): try: wx_window.SetSize(layout.size) wx_window.SetPosition(layout.pos) except Exception as ex: print(ex)
set a WinLayout for a wx window
363,158
def find_by_example(self, crash, offset = None, limit = None): if limit is not None and not limit: warnings.warn("CrashDAO.find_by_example() was set a limit of 0" " results, returning without executing a query.") return [] qu...
Find all crash dumps that have common properties with the crash dump provided. Results can be paged to avoid consuming too much memory if the database is large. @see: L{find} @type crash: L{Crash} @param crash: Crash object to compare with. Fields set to C{None} are ...
363,159
def json_to_string(value, null_string_repr=, trimable=False): return null_string_repr if is_undefined(value) \ else obj.jsonify(value, trimable=trimable)
Return a string representation of the specified JSON object. @param value: a JSON object. @param null_string_rep: the string representation of the null object. @return: a string representation of the specified JSON object.
363,160
def silent_exec_method(self, code): local_uuid = to_text_string(uuid.uuid1()) code = to_text_string(code) if self.kernel_client is None: return msg_id = self.kernel_client.execute(, silent=True, user_expr...
Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a variable but instead replies that can be handled by ast.literal_eval. To get a value see `get_value` Parameters ---------- code : string ...
363,161
def build(self, docs=None, filename=None): if docs: if hasattr(docs, ): for (idx, doc) in sorted(getattr(docs, )(), key=lambda x: x[0]): self.fm.push_back(doc) else: for doc in filter(bo...
Build FM-index Params: <iterator> | <generator> docs <str> filename
363,162
def first_interesting_frame(self): root_frame = self.root_frame() frame = root_frame while len(frame.children) <= 1: if frame.children: frame = frame.children[0] else: return root_frame return frame
Traverse down the frame hierarchy until a frame is found with more than one child
363,163
def has_credentials(self): credentials = _credentials_from_request(self.request) return (credentials and not credentials.invalid and credentials.has_scopes(self._get_scopes()))
Returns True if there are valid credentials for the current user and required scopes.
363,164
def stylize(obj, style=, theme=): obj.setStyle(style) if theme: sheet = resources.read(.format(theme)) if sheet: obj.setStyleSheet(sheet)
Styles the inputed object with the given options. :param obj | <QtGui.QWidget> || <QtGui.QApplication> style | <str> base | <str>
363,165
def delete_property(self, key): if key in self.RESERVED_ATTRIBUTE_NAMES: raise KeyError(key) del self.o[key]
Remove a property from the document. Calling code should use this method to remove properties on the document instead of modifying ``properties`` directly. If there is a property with the name in ``key``, it will be removed. Otherwise, a ``KeyError`` will be thrown.
363,166
def create_vmfs_datastore(host_ref, datastore_name, disk_ref, vmfs_major_version, storage_system=None): hostname = get_managed_object_name(host_ref) disk_id = disk_ref.canonicalName log.debug(%s\%s\%s\ , datastore_name, hostname, disk_id, vmfs_major_version)...
Creates a VMFS datastore from a disk_id host_ref vim.HostSystem object referencing a host to create the datastore on datastore_name Name of the datastore disk_ref vim.HostScsiDislk on which the datastore is created vmfs_major_version VMFS major version to use
363,167
def delete_bams(job, bams, patient_id): bams = {b: v for b, v in bams.items() if (b.endswith() or b.endswith()) and v is not None} if bams: for key, val in bams.items(): job.fileStore.logToMaster( % (key, patient_id)) job.fileStore.deleteGlobalFile(val) elif ...
Delete the bams from the job Store once their purpose has been achieved (i.e. after all mutation calling steps). Will also delete the chimeric junction file from Star. :param dict bams: Dict of bam and bai files :param str patient_id: The ID of the patient for logging purposes.
363,168
def _add_loss_summaries(total_loss): loss_averages = tf.train.ExponentialMovingAverage(0.9, name=) losses = tf.get_collection() loss_averages_op = loss_averages.apply(losses + [total_loss]) for l in losses + [total_loss]: tf.summary.scalar(l.op.name + , l) tf.summary.scalar(l.op.n...
Add summaries for losses in CIFAR-10 model. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for generating moving averages of losses.
363,169
def recurrent_transformer_decoder( decoder_input, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, hparams, name="decoder", nonpadding=None, save_weights_to=None, make_image_summary=True): x = decoder_input attention_dropout_broadcast_dims = ( ...
Recurrent decoder function.
363,170
async def addMachines(self, params=None): params = params or {} params = {normalize_key(k): params[k] for k in params.keys()} if in params: if params[].startswith(): unit = self.resolve(params[])[0] params[] = unit.machine...
:param params dict: Dictionary specifying the machine to add. All keys are optional. Keys include: series: string specifying the machine OS series. constraints: string holding machine constraints, if any. We'll parse this into the json friendly dict that...
363,171
def timedelta_seconds(td): try: return int(round(td.total_seconds())) except AttributeError: days = td.days seconds = td.seconds microseconds = td.microseconds return int(round((days * 86400) + seconds + (microseconds / 1000000)))
Return the offset stored by a :class:`datetime.timedelta` object as an integer number of seconds. Microseconds, if present, are rounded to the nearest second. Delegates to :meth:`timedelta.total_seconds() <datetime.timedelta.total_seconds()>` if available. >>> timedelta_seconds(timedelta(hour...
363,172
def is_path_python_module(thepath): thepath = path.normpath(thepath) if path.isfile(thepath): base, ext = path.splitext(thepath) if ext in _py_suffixes: return True return False if path.isdir(thepath): for suffix in _py_suffixes: if path.isfile(...
Given a path, find out of the path is a python module or is inside a python module.
363,173
def target_for_product(self, product): for target, products in self._products_by_target.items(): if product in products: return target return None
Looks up the target key for a product. :API: public :param product: The product to search for :return: None if there is no target for the product
363,174
def users(self): if not self._users: self._users = self._call_api()[] return self._users
List of users of this slack team
363,175
def kinesia_scores(self, data_frame): ks = sum(data_frame.action_type == 1) duration = math.ceil(data_frame.td[-1]) return ks, duration
This method calculates the number of key taps :param data_frame: the data frame :type data_frame: pandas.DataFrame :return ks: key taps :rtype ks: float :return duration: test duration (seconds) :rtype duration: float
363,176
def reverse_index_mapping(self): if self._reverse_index_mapping is None: if self.is_indexed: r = np.zeros(self.base_length, dtype=np.int32) - 1 r[self.order] = np.arange(len(self.order), dtype=np.int32) elif self.data.base is None...
Get mapping from this segment's indexes to the indexes of the base array. If the index is < 0, the index is out of range, meaning that it doesn't exist in this segment and is not mapped to the base array
363,177
def get(self, url, **kwargs): r kwargs.setdefault(, True) return self.request(, url, **kwargs)
r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
363,178
def validate(self, arg=None): if os.path.isdir(self.path): self.validator.object = None else: self.validator.object = ICONS[]
Check that inputted path is valid - set validator accordingly
363,179
def set_child_value( self, sensor_id, child_id, value_type, value, **kwargs): if not self.is_sensor(sensor_id, child_id): return if self.sensors[sensor_id].new_state: self.sensors[sensor_id].set_child_value( child_id, value_type, value, ...
Add a command to set a sensor value, to the queue. A queued command will be sent to the sensor when the gateway thread has sent all previously queued commands. If the sensor attribute new_state returns True, the command will be buffered in a queue on the sensor, and only the internal s...
363,180
def remove_root_family(self, family_id): if self._catalog_session is not None: return self._catalog_session.remove_root_catalog(catalog_id=family_id) return self._hierarchy_session.remove_root(id_=family_id)
Removes a root family. arg: family_id (osid.id.Id): the ``Id`` of a family raise: NotFound - ``family_id`` not a root raise: NullArgument - ``family_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure ...
363,181
def CLJP(S, color=False): if not isspmatrix_csr(S): raise TypeError() S = remove_diagonal(S) colorid = 0 if color: colorid = 1 T = S.T.tocsr() splitting = np.empty(S.shape[0], dtype=) amg_core.cljp_naive_splitting(S.shape[0], S.indp...
Compute a C/F splitting using the parallel CLJP algorithm. Parameters ---------- S : csr_matrix Strength of connection matrix indicating the strength between nodes i and j (S_ij) color : bool use the CLJP coloring approach Returns ------- splitting : array A...
363,182
def set_up(self): self.menu.pause() curses.def_prog_mode() self.menu.clear_screen()
This class overrides this method
363,183
def Kn2Der(nu, y, n=0): r n = int(n) y = scipy.asarray(y, dtype=float) sqrty = scipy.sqrt(y) if n == 0: K = scipy.special.kv(nu, sqrty) else: K = scipy.zeros_like(y) x = scipy.asarray( [ fixed_poch(1.5 - j, j) * y**(0.5 - j) for...
r"""Find the derivatives of :math:`K_\nu(y^{1/2})`. Parameters ---------- nu : float The order of the modified Bessel function of the second kind. y : array of float The values to evaluate at. n : nonnegative int, optional The order of derivative to take.
363,184
def send_all(): EMAIL_BACKEND = getattr( settings, "MAILER_EMAIL_BACKEND", "django.core.mail.backends.smtp.EmailBackend" ) acquired, lock = acquire_lock() if not acquired: return start_time = time.time() deferred = 0 sent = 0 try: ...
Send all eligible messages in the queue.
363,185
def select(self): print("\nDetected Slackware binary package for installation:\n") for pkg in self.packages: print(" " + pkg.split("/")[-1]) print("") self.msg.template(78) print("| Choose a Slackware command:") self.msg.template(78) for com i...
Select Slackware command
363,186
def dict_to_path(as_dict): result = as_dict.copy() loaders = {: Arc, : Line} entities = [None] * len(as_dict[]) for entity_index, entity in enumerate(as_dict[]): entities[entity_index] = loaders[entity[]]( points=entity[], closed=entity[]) result[] = enti...
Turn a pure dict into a dict containing entity objects that can be sent directly to a Path constructor. Parameters ----------- as_dict : dict Has keys: 'vertices', 'entities' Returns ------------ kwargs : dict Has keys: 'vertices', 'entities'
363,187
def subselect(self, obj): return dict( (key, value) for (key, value) in obj.items() if key in self.defaults)
Filter a dict of hyperparameter settings to only those keys defined in this HyperparameterDefaults .
363,188
def p_statements(self, p): n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [, p[1]]
statements : statements statement | statement
363,189
def _build_cache(): sets = current_oaiserver.sets if sets is None: sets = current_oaiserver.sets = [ oaiset.spec for oaiset in OAISet.query.filter( OAISet.search_pattern.is_(None)).all()] return sets
Build sets cache.
363,190
def resolve(self, var, context): if var is None: return var if var[0] in (, "'") and var[-1] == var[0]: return var[1:-1] else: return template.Variable(var).resolve(context)
Resolves a variable out of context if it's not in quotes
363,191
def record_get(self, creative_ids, nick=None): request = TOPRequest() request[] = creative_ids if nick!=None: request[] = nick self.create(self.execute(request), models = {:CreativeRecord}) return self.result
xxxxx.xxxxx.creatives.record.get =================================== 根据一个创意Id列表取得创意对应的修改记录
363,192
def Then(self, f, *args, **kwargs): return self.ThenAt(1, f, *args, **kwargs)
`Then(f, ...)` is equivalent to `ThenAt(1, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
363,193
def unit_client(self): client = TCPClient(self.host, self.port, self.prefix) self._configure_client(client) return client
Return a TCPClient with same settings of the batch TCP client
363,194
def main(argv=None, directory=None): logging.basicConfig(format=) argv = argv or sys.argv arg_dict = parse_quality_args(argv[1:]) GitPathTool.set_cwd(directory) fail_under = arg_dict.get() tool = arg_dict[] user_options = arg_dict.get() if user_options: first_char ...
Main entry point for the tool, used by setup.py Returns a value that can be passed into exit() specifying the exit code. 1 is an error 0 is successful run
363,195
def get_file_systems(filesystemid=None, keyid=None, key=None, profile=None, region=None, creation_token=None, **kwargs): my-minion result = None client = _get_conn(key=key, keyid=ke...
Get all EFS properties or a specific instance property if filesystemid is specified filesystemid (string) - ID of the file system to retrieve properties creation_token (string) - A unique token that identifies an EFS. If fileysystem created via create_file_system this would ...
363,196
def list(self): before, after = self.filename_template.split(, 1) filename_re = re.compile(r % (re.escape(before), re.escape(after))) result = [] for filename in os.listdir(self.path): if filename.endsw...
Lists all sessions in the store. .. versionadded:: 0.6
363,197
def single_val(self): sv_t = self._sv(self._tdsphere) sv_p = self._sv(self._tdsphere) return (sv_t, sv_p)
return relative error of worst point that might make the data none symmetric.
363,198
def output(self, output, status=None): if output: size = self.cli.output.get_size() margin = self.get_output_margin(status) fits = True buf = [] output_via_pager = self.explicit_pager and special.is_pager_enabled() for i, line in...
Output text to stdout or a pager command. The status text is not outputted to pager or files. The message will be logged in the audit log, if enabled. The message will be written to the tee file, if enabled. The message will be written to the output file, if enabled.
363,199
def _set_automatic_tag(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=automatic_tag.automatic_tag, is_container=, presence=False, yang_name="automatic-tag", rest_name="automatic-tag", parent=self, path_helper=self._path_helper, extmethods=self._extme...
Setter method for automatic_tag, mapped from YANG variable /routing_system/route_map/content/set/automatic_tag (container) If this variable is read-only (config: false) in the source YANG file, then _set_automatic_tag is considered as a private method. Backends looking to populate this variable should d...