Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
337,600
def get_bounding_box(self, maxdist): return utils.get_bounding_box([ps.location for ps in self], maxdist)
Bounding box containing all the point sources, enlarged by the maximum distance.
337,601
def get(self, key=NOT_SET, index=NOT_SET, d=None): if index is NOT_SET and key is not NOT_SET: try: index, value = self._dict[key] except KeyError: return d else: return value elif index is not NOT_SET and key is NOT_SET: try: key, value = self._list[index] except IndexError: r...
Return value with given key or index. If no value is found, return d (None by default).
337,602
def check_crc(f, inf, desc): exp = inf._md_expect if exp is None: return ucrc = f._md_context.digest() if ucrc != exp: print( % (desc, exp, ucrc))
Compare result crc to expected value.
337,603
def _construct_arrow_tip(self, pos): arrow_tip = None width = 0 if self._arrow_tip_char: txt = urwid.Text(self._arrow_tip_char) arrow_tip = urwid.AttrMap( txt, self._arrow_tip_att or self._arrow_att) width = len(self._arrow_tip_char) ...
returns arrow tip as (width, widget)
337,604
def critical(self, message, *args, **kwargs): self.system.critical(message, *args, **kwargs)
Log critical event. Compatible with logging.critical signature.
337,605
def add_margins(df, vars, margins=True): margin_vars = _margins(vars, margins) if not margin_vars: return df margin_dfs = [df] for vlst in margin_vars[1:]: dfx = df.copy() for v in vlst: dfx.loc[0:, v] = margin_dfs.append(dfx) merged = pd.conc...
Add margins to a data frame. All margining variables will be converted to factors. Parameters ---------- df : dataframe input data frame vars : list a list of 2 lists | tuples vectors giving the variables in each dimension margins : bool | list variable names ...
337,606
def model_to_pdag(model): if not isinstance(model, DAG): raise TypeError("model: Expected DAG instance, " + "got type {model_type}".format(model_type=type(model))) skel, separating_sets = ConstraintBasedEstimator.build_skeleton( ...
Construct the DAG pattern (representing the I-equivalence class) for a given DAG. This is the "inverse" to pdag_to_dag.
337,607
def load(cls, cache_key, deserializer, key_attr): items = unitdata.kv().get(cache_key) or [] return cls(cache_key, [deserializer(item) for item in items], key_attr)
Load the persisted cache and return a new instance of this class.
337,608
def update_progress(self, complete=False): if self.progressbar: try: self.bar.update(self.transfered) except Exception as e: logger.debug("{0}: {1}, {2} exceeds memsize {3}".format( self.remote_addr, ...
Logs capture progress :type complete: bool :params complete: toggle to finish ncurses progress bar
337,609
def end_offsets(self, partitions): offsets = self._fetcher.end_offsets( partitions, self.config[]) return offsets
Get the last offset for the given partitions. The last offset of a partition is the offset of the upcoming message, i.e. the offset of the last available message + 1. This method does not change the current consumer position of the partitions. Note: This method may ...
337,610
def page(self, number=None): if number is None: return int(self.url.page) self.url.page = str(number)
If page is given, modify the URL correspondingly, return the current page otherwise.
337,611
def keep_alive(self): it = (side.keep_alive for (_, (side, _)) in self.poller.readers) return sum(it, 0)
Return :data:`True` if any reader's :attr:`Side.keep_alive` attribute is :data:`True`, or any :class:`Context` is still registered that is not the master. Used to delay shutdown while some important work is in progress (e.g. log draining).
337,612
def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ** ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({: _parse_snapshot_description(sn...
Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overrid...
337,613
def extract_tar(self, suffix, path=): mode = suffix.split()[-1] tar_fd, tar_fn = tempfile.mkstemp(prefix=, suffix= % mode) os.close(tar_fd) try: _download_url(self.artifact_url(suffix), tar_fn) LOG.info() with tarfile.open(tar_fn, mode= % mode...
Extract builds with .tar.(*) extension When unpacking a build archive, only extract the firefox directory @type suffix: @param suffix: @type path: @param path:
337,614
def base_http_parser(): base_parser = ArgumentParser(add_help=False) base_parser.add_argument( , type=str, help="identify the URL of the validator-u--userUSERNAME[:PASSWORD]specify the user to authorize request') return base_parser
Creates a parser with arguments specific to sending an HTTP request to the REST API. Returns: {ArgumentParser}: Base parser with default HTTP args
337,615
def swipe_by_coordinates(self, sx, sy, ex, ey, steps=10): self.device.swipe(sx, sy, ex, ey, steps)
Swipe from (sx, sy) to (ex, ey) with *steps* . Example: | Swipe By Coordinates | 540 | 1340 | 940 | 1340 | | # Swipe from (540, 1340) to (940, 100) with default steps 10 | | Swipe By Coordinates | 540 | 1340 | 940 | 1340 | 100 | # Swipe from (540, 1340) to (940, 100) with steps 100 |
337,616
def is_identity(): for index, row in enumerate(self.dta): if row[index] == 1: for num, element in enumerate(row): if num != index: if element != 0: return False else: return F...
Check to see if this matrix is an identity matrix.
337,617
def set_file_idx_offset(self, file_idx_offset=0): if isinstance(file_idx_offset, int): self.file_idx_offset = file_idx_offset elif file_idx_offset == : self.file_idx_offset = self.storage.max_file_idx() else: raise ValueError()
Set offset of file index. Args: file_idx_offset: It can be either an integer or 'auto'. If set to an integer, the filename will start from ``file_idx_offset`` + 1. If set to ``'auto'``, the filename will start from existing max file index plus 1.
337,618
def _get_crud_params(compiler, stmt, **kw): compiler.postfetch = [] compiler.insert_prefetch = [] compiler.update_prefetch = [] compiler.returning = [] if compiler.column_keys is None and stmt.parameters is None: return [(c, crud._create_b...
extract values from crud parameters taken from SQLAlchemy's crud module (since 1.0.x) and adapted for Crate dialect
337,619
def gridsearch_color_plot(model, x_param, y_param, X=None, y=None, ax=None, **kwargs): visualizer = GridSearchColorPlot(model, x_param, y_param, ax=ax, **kwargs) if X is not None: visualizer.fit(X, y) else: visualizer.draw() return visualiz...
Quick method: Create a color plot showing the best grid search scores across two parameters. This helper function is a quick wrapper to utilize GridSearchColorPlot for one-off analysis. If no `X` data is passed, the model is assumed to be fit already. This allows quick exploration without wait...
337,620
def get_profile_info(self): return sorted(self.profile_info.items(), key=lambda kv: kv[1], reverse=False) return
Show the accumulated results of how many times each rule was used
337,621
def _collapse_default(self, entry): if isinstance(entry, tuple) or isinstance(entry, list): sets = [] i = 0 while i < len(entry): if isinstance(entry[i], str) and i+1 < len(entry) and isinstance(entry[i+1], list): sets.append((entr...
Collapses the list structure in entry to a single string representing the default value assigned to a variable or its dimensions.
337,622
def tsplit(string, delimiters): delimiters = tuple(delimiters) if len(delimiters) < 1: return [string,] final_delimiter = delimiters[0] for i in delimiters[1:]: string = string.replace(i, final_delimiter) return string.split(final_delimiter)
Behaves str.split but supports tuples of delimiters.
337,623
def get_motion_detection(self): url = ( ) % self.root_url try: response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT) except (requests.exceptions.RequestException, requests.exceptions.ConnectionError) as err: _LOGGING.error(...
Fetch current motion state from camera
337,624
def list_files(directory): ret = set() ret.add(directory) for root, dirs, files in safe_walk(directory): for name in files: ret.add(os.path.join(root, name)) for name in dirs: ret.add(os.path.join(root, name)) return list(ret)
Return a list of all files found under directory (and its subdirectories)
337,625
def _build_page(self, filepath): filename = filepath.split("/")[-1] if not filename.startswith(("_", ".")) and (filename.endswith(PAGE_FORMAT)): meta = self._get_page_meta(filepath) content = self._get_page_content(filepath) _default_pa...
To build from filepath, relative to pages_dir
337,626
def lookup_ips (ips): hosts = set() for ip in ips: try: hosts.add(socket.gethostbyaddr(ip)[0]) except socket.error: hosts.add(ip) return hosts
Return set of host names that resolve to given ips.
337,627
async def create_http_connection(loop, protocol_factory, host, port=25105, auth=None): protocol = protocol_factory() transport = HttpTransport(loop, protocol, host, port, auth) _LOGGER.debug("create_http_connection Finished creating connection") return (transport, p...
Create an HTTP session used to connect to the Insteon Hub.
337,628
def StielPolar(Tc=None, Pc=None, omega=None, CASRN=, Method=None, AvailableMethods=False): rs Stiel Polar factor, directly through the definition of Stiel-polar factor if possible. Requires Tc, Pc, acentric factor, and a vapor pressure datum at Tr=0.6. Will automatically select a method ...
r'''This function handles the calculation of a chemical's Stiel Polar factor, directly through the definition of Stiel-polar factor if possible. Requires Tc, Pc, acentric factor, and a vapor pressure datum at Tr=0.6. Will automatically select a method to use if no Method is provided; returns None if th...
337,629
def install_provisions(ctx, provision, clear_provisions=False, overwrite=False, list_provisions=False): log("Installing HFOS default provisions") from hfos import database database.initialize(ctx.obj[], ctx.obj[]) from hfos.provisions import build_provision_store provision_store ...
Install default provisioning data
337,630
def reader_trampoline(start, allow_flush=False): data_event = yield if data_event is None or data_event.type is not ReadEventType.NEXT: raise TypeError() trans = Transition(None, start) while True: trans = trans.delegate.send(Transition(data_event, trans.delegate)) data_even...
Provides the co-routine trampoline for a reader state machine. The given co-routine is a state machine that yields :class:`Transition` and takes a Transition of :class:`amazon.ion.core.DataEvent` and the co-routine itself. A reader must start with a ``ReadEventType.NEXT`` event to prime the parser. In ma...
337,631
def AddNodeTags(r, node, tags, dry_run=False): query = { "tag": tags, "dry-run": dry_run, } return r.request("put", "/2/nodes/%s/tags" % node, query=query, content=tags)
Adds tags to a node. @type node: str @param node: node to add tags to @type tags: list of str @param tags: tags to add to the node @type dry_run: bool @param dry_run: whether to perform a dry run @rtype: int @return: job id
337,632
def start_update(self, layer_id): target_url = self.client.get_url(, , , {: layer_id}) r = self.client.request(, target_url, json={}) return self.parent.create_from_result(r.json())
A shortcut to create a new version and start importing it. Effectively the same as :py:meth:`koordinates.layers.LayerManager.create_draft` followed by :py:meth:`koordinates.layers.LayerManager.start_import`.
337,633
def compare(self, other, t_threshold=1e-3, r_threshold=1e-3): return compute_rmsd(self.t, other.t) < t_threshold and compute_rmsd(self.r, other.r) < r_threshold
Compare two transformations The RMSD values of the rotation matrices and the translation vectors are computed. The return value is True when the RMSD values are below the thresholds, i.e. when the two transformations are almost identical.
337,634
def fields(self): process_markdown = ("fields" in self._raw.get("mrkdwn_in", [])) fields = self._raw.get("fields", []) if fields: logging.debug("Rendering with markdown markdown %s for %s", process_markdown, fields) return [ {"title": e["title"], "short":...
Fetch the "fields" list, and process the text within each field, including markdown processing if the message indicates that the fields contain markdown. Only present on attachments, not files--this abstraction isn't 100% awesome.'
337,635
def save(self, filename=None): if filename is None: raise IOError() cnt = self.output() with (open(filename, )) as f: f.write(cnt.encode())
Generates output and saves to given file :param filename File name :type str or unicode
337,636
def download(self, localfile: str, remotefile: str, overwrite: bool = True, **kwargs): valid = self._sb.file_info(remotefile, quiet = True) if valid is None: return { : False, : "File "+str(remotefile)+" does not exist."} if valid == {}: return { : Fal...
This method downloads a remote file from the SAS servers file system. localfile - path to the local file to create or overwrite remotefile - path to remote file tp dpwnload overwrite - overwrite the output file if it exists?
337,637
def Pull(self, device_filename, dest_file=None, timeout_ms=None, progress_callback=None): if not dest_file: dest_file = io.BytesIO() elif isinstance(dest_file, str): dest_file = open(dest_file, ) elif isinstance(dest_file, file): pass else: ...
Pull a file from the device. Args: device_filename: Filename on the device to pull. dest_file: If set, a filename or writable file-like object. timeout_ms: Expected timeout for any part of the pull. progress_callback: callback method that accepts filename, bytes_written ...
337,638
def finish(self): self.status = self.time_completed = timestamp() self.thing.action_notify(self)
Finish performing the action.
337,639
def select_header_accept(self, accepts): if not accepts: return accepts = [x.lower() for x in accepts] if in accepts: return else: return .join(accepts)
Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json).
337,640
def unblock(self, item: str) -> None: assert item is not None item = self._encode_item(item) watchlist_key = self.__redis_conf[].format(item) blacklist_key = self.__redis_conf[].format(item) connection = self.__get_connection() connection.delete(watchlist_key) ...
Unblock an item and/or reset it's fail count :param str item: The item to unblock
337,641
def visit(self, node): method = getattr(self, + node.expr_name, self.generic_visit) try: return method(node, [self.visit(child) for child in reversed(list(node))]) except (VisitationError, UndefinedLabel): ...
See the ``NodeVisitor`` visit method. This just changes the order in which we visit nonterminals from right to left to left to right.
337,642
def _parse_game_date_and_location(self, boxscore): scheme = BOXSCORE_SCHEME["game_info"] items = [i.text() for i in boxscore(scheme).items()] game_info = items[0].split() attendance = None date = None duration = None stadium = None time = None ...
Retrieve the game's date and location. The games' meta information, such as date, location, attendance, and duration, follow a complex parsing scheme that changes based on the layout of the page. The information should be able to be parsed and set regardless of the order and how much in...
337,643
def _collect_mdsec_elements(files): dmdsecs = [] amdsecs = [] for f in files: for d in f.dmdsecs: dmdsecs.append(d) for a in f.amdsecs: amdsecs.append(a) dmdsecs.sort(key=lambda x: x.id_string) amdsecs.sort(key=lam...
Return all dmdSec and amdSec classes associated with the files. Returns all dmdSecs, then all amdSecs, so they only need to be serialized before being appended to the METS document. :param List files: List of :class:`FSEntry` to collect MDSecs for. :returns: List of AMDSecs and SubSect...
337,644
def add(self, *terminals): for term in terminals: if term in self: continue super().add(term) self._assign_map[term] = set()
Add terminals into the set. :param terminals: Terminals to insert.
337,645
def monitor_exit(self): return pyhsm.debug_cmd.YHSM_Cmd_Monitor_Exit(self.stick).execute(read_response=False)
Ask YubiHSM to exit to configuration mode (requires 'debug' mode enabled). @returns: None @rtype: NoneType @see: L{pyhsm.debug_cmd.YHSM_Cmd_Monitor_Exit}
337,646
def DeserializeUnsigned(self, reader): txtype = reader.ReadByte() if txtype != int.from_bytes(self.Type, ): raise Exception(.format(txtype, int.from_bytes(self.Type, ))) self.DeserializeUnsignedWithoutType(reader)
Deserialize object. Args: reader (neo.IO.BinaryReader): Raises: Exception: if transaction type is incorrect.
337,647
def expandFunction(self, func, args=[]): params = self._autoParams.allData() steps = self.autoParamRanges() ntraces = 1 for p in steps: ntraces = ntraces*len(p) varylist = [[None for x in range(len(params))] for y in range(ntraces)] x = 1 ...
applies the given function to each of this stimulus's memerships when autoparamters are applied :param func: callable to execute for each version of the stimulus :type instancemethod: :param args: arguments to feed to func :type args: list :returns: list<results of *func*>, one ...
337,648
def read(self, size=-1): "Reads up to size bytes, but always completes the last line." buf = self.fin.read(size) if not buf: return lines = buf.splitlines() if not buf.endswith(): last = lines.pop() partial = self.fin.readline() ...
Reads up to size bytes, but always completes the last line.
337,649
def run_main(args): if args.command and args.script: raise ValueError() provider_base.check_for_unsupported_flag(args) input_file_param_util = param_util.InputFileParamUtil( DEFAULT_INPUT_LOCAL_PATH) output_file_param_util = param_util.OutputFileParamUtil( DEFAULT_OUTPUT_LOCAL_PATH) m...
Execute job/task submission from command-line arguments.
337,650
def value(self): if not hasattr(self, "_value") and self._path is not None: self._value = self._load(self._path) return self._value
Return the broadcasted value
337,651
def connected_transformer(network, busids): mask = (network.transformers.bus0.isin(busids)) return network.transformers[mask]
Get transformer connected to given buses. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA busids : list List containing bus-ids. Returns ------- :class:`pandas.DataFrame PyPSA transformer.
337,652
def macro_def(self, macro_ref, frame): arg_tuple = .join(repr(x.name) for x in macro_ref.node.args) name = getattr(macro_ref.node, , None) if len(macro_ref.node.args) == 1: arg_tuple += self.write( % (name, arg_tuple, macro_ref...
Dump the macro definition for the def created by macro_body.
337,653
def defaults(self): defaults = ConfigParser.defaults(self).copy() for key, val in iteritems(defaults): defaults[key] = self.get(, key) or val return defaults
Return the defaults, with their values interpolated (with the defaults dict itself) Mainly to support defaults using values such as %(here)s
337,654
def create_server(self, server): if isinstance(server, Server): body = server.prepare_post_body() else: server = Server._create_server_obj(server, cloud_manager=self) body = server.prepare_post_body() res = self.post_request(, body) server_t...
Create a server and its storages based on a (locally created) Server object. Populates the given Server instance with the API response. 0.3.0: also supports giving the entire POST body as a dict that is directly serialised into JSON. Refer to the REST API documentation for correct format. ...
337,655
def terrain_data_encode(self, lat, lon, grid_spacing, gridbit, data): return MAVLink_terrain_data_message(lat, lon, grid_spacing, gridbit, data)
Terrain data sent from GCS. The lat/lon and grid_spacing must be the same as a lat/lon from a TERRAIN_REQUEST lat : Latitude of SW corner of first grid (degrees *10^7) (int32_t) lon : Longitude of SW corner of first grid (in de...
337,656
def _region_code_for_number_from_list(numobj, regions): national_number = national_significant_number(numobj) for region_code in regions: metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) if metadata is None: continue ...
Find the region in a list that matches a number
337,657
def perform_create(self, data): instance = self.model(**data) self.request.dbsession.add(instance) self.request.dbsession.flush() return instance
Hook for controlling the creation of an model instance. Override this if you need to do more with your data before saving your object than just mapping the deserialized data to a new instance of ``self.model``.
337,658
def inflate_dtype(arr, names): arr = np.asanyarray(arr) if has_structured_dt(arr): return arr.dtype s_dt = arr.dtype dt = [(n, s_dt) for n in names] dt = np.dtype(dt) return dt
Create structured dtype from a 2d ndarray with unstructured dtype.
337,659
def eidos_process_text(): if request.method == : return {} req = request.body.read().decode() body = json.loads(req) text = body.get() webservice = body.get() if not webservice: response.status = 400 response.content_type = return json.dumps({: }) ep = e...
Process text with EIDOS and return INDRA Statements.
337,660
def iglob(pathname): if not has_magic(pathname): yield pathname return dirname, basename = os.path.split(pathname) if not dirname: for name in glob1(dirname, basename): yield name return if has_magic(dirname): dirs = iglob(dirname) else: ...
Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch.
337,661
def parse_coverage_args(argv): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument( , type=str, help=COVERAGE_XML_HELP, nargs= ) parser.add_argument( , metavar=, type=str, default=None, help=HTML_REP...
Parse command line arguments, returning a dict of valid options: { 'coverage_xml': COVERAGE_XML, 'html_report': None | HTML_REPORT, 'external_css_file': None | CSS_FILE, } where `COVERAGE_XML`, `HTML_REPORT`, and `CSS_FILE` are paths. The path strings m...
337,662
def cross(self, vec): if not isinstance(vec, Vector3Array): raise TypeError() if self.nV != 1 and vec.nV != 1 and self.nV != vec.nV: raise ValueError( ) return Vector3Array(np.cross(self, vec))
Cross product with another Vector3Array
337,663
def cycle_slice(sliceable, start, end): if type(sliceable) != list: sliceable = list(sliceable) length = len(sliceable) if length == 0: raise ValueError("sliceable cannot be empty!") start = start % length end = end % length if end > start: return sliceable[start:e...
Given a list, return right hand cycle direction slice from start to end. Example:: >>> array = [0, 1, 2, 3] >>> cycle_slice(array, 1, 3) # from array[1] to array[3] [1, 2] >>> cycle_slice(array, 3, 1) # from array[3] to array[1] [3, 0] **中文文档**
337,664
def copy(self, deep=True): values = self.values if deep: values = values.copy() return self.make_block_same_class(values, ndim=self.ndim)
copy constructor
337,665
def display_drilldown_as_ul(category, using=): cat = get_category(category, using) if cat is None: return {: cat, : []} else: return {: cat, : drilldown_tree_for_node(cat)}
Render the category with ancestors and children using the ``categories/ul_tree.html`` template. Example:: {% display_drilldown_as_ul "/Grandparent/Parent" %} or :: {% display_drilldown_as_ul category_obj %} Returns:: <ul> <li><a href="/categories/">Top</a> ...
337,666
def import_flow_node_to_graph(bpmn_graph, process_id, process_attributes, flow_node_element): element_id = flow_node_element.getAttribute(consts.Consts.id) bpmn_graph.add_node(element_id) bpmn_graph.node[element_id][consts.Consts.id] = element_id bpmn_graph.node[element_id][cons...
Adds a new node to graph. Input parameter is object of class xml.dom.Element. Nodes are identified by ID attribute of Element. Method adds basic attributes (shared by all BPMN elements) to node. Those elements are: - id - added as key value, we assume that this is a required value, ...
337,667
def resample(self, indexer: Optional[Mapping[Hashable, str]] = None, skipna=None, closed: Optional[str] = None, label: Optional[str] = None, base: int = 0, keep_attrs: Optional[bool] = None, loffset=None, **indexer_kwargs: str): ...
Returns a Resample object for performing resampling operations. Handles both downsampling and upsampling. If any intervals contain no values from the original object, they will be given the value ``NaN``. Parameters ---------- indexer : {dim: freq}, optional Mapping...
337,668
def post(self, url, data=None, params=None): return self.request("post", url, data, params)
Low-level POST request interface to mite. Takes a URL to request (relative), and optionally data to add to the request. Either returns the JSON body of the request or raises a HttpException.
337,669
def property_notify(self, property_): message = json.dumps({ : , : { property_.name: property_.get_value(), } }) for subscriber in list(self.subscribers): try: subscriber.write_message(message) ...
Notify all subscribers of a property change. property_ -- the property that changed
337,670
def buildProtocol(self, addr): self.resetDelay() clargs = self.client_args.copy() hostport = .format(addr.host, addr.port) logger.debug(, hostport) if hostport in self.antenna_dict: clargs[] = [ int(x) for x in self.antenn...
Get a new LLRP client protocol object. Consult self.antenna_dict to look up antennas to use.
337,671
def _parse_sentence(self, paragraph, node, state): text = state["paragraph"]["text"] field = state["paragraph"]["field"] name = node.attrib["name"] if "name" in node.attrib else None document = state["document"] for parts in self.tokenize_and_split_se...
Parse the Sentences of the node. :param node: The lxml node to parse :param state: The global state necessary to place the node in context of the document as a whole.
337,672
def parse(parser=None, args=None): if not parser: parser = make_parser() try: parsed_args = parser.parse_args(args) except SystemExit as err: raise CommandLineExit(err.code) try: columns = parsed_args.columns except AttributeError: columns = collections...
Parse the command line arguments, return an argparse namespace object. Other projects can call this function and pass in their own ArgumentParser object (which should have a losser ArgumentParser from make_parser() above as parent) to do the argument parsing and get the result (this does some custom po...
337,673
def get_gosubdagplot(self, goids=None, **kws_usr): if goids is None: goids = self.grprobj.usrgos kws_plt, kws_dag = self._get_kws_plt(goids, **kws_usr) gosubdag = GoSubDag( goids, self.grprobj.gosubdag.get_go2obj(goids), self.grprobj.gosub...
Plot GO IDs.
337,674
def dwell_axes(self, axes): XYZABC axes = .join(set(axes) & set(AXES) - set(DISABLE_AXES)) dwelling_currents = { ax: self._dwelling_current_settings[][ax] for ax in axes if self._active_axes[ax] is True } if dwelling_currents: self....
Sets motors to low current, for when they are not moving. Dwell for XYZA axes is only called after HOMING Dwell for BC axes is called after both HOMING and MOVING axes: String containing the axes to set to low current (eg: 'XYZABC')
337,675
def require(name, field, data_type): if not isinstance(field, data_type): msg = .format(name, data_type, field) raise AssertionError(msg)
Require that the named `field` has the right `data_type`
337,676
def build_type(self, build_type): allowed_values = ["MVN", "NPM"] if build_type not in allowed_values: raise ValueError( "Invalid value for `build_type` ({0}), must be one of {1}" .format(build_type, allowed_values) ) self._build_...
Sets the build_type of this BuildConfigurationRest. :param build_type: The build_type of this BuildConfigurationRest. :type: str
337,677
def length(cls, dataset): return np.product([len(d.points) for d in dataset.data.coords(dim_coords=True)], dtype=np.intp)
Returns the total number of samples in the dataset.
337,678
def mean_date(dt_list): dt_list_sort = sorted(dt_list) dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort] avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel) return dt_list_sort[0] + avg_timedelta
Calcuate mean datetime from datetime list
337,679
def get_plugin_classes(modules): classes = (_ConnectionPlugin, _ContentPlugin, _ParserPlugin) return loader.get_plugins(modules, classes)
Get plugin classes for given modules.
337,680
def getEndpoint(self): port = endpoint = keyConfig = self.getKeyConfig() if in keyConfig: port = + keyConfig[] elif self._data[] != self.PORT: port = + self._data[] if in keyConfig: endpoint = keyConfig[] else: ...
Retrieve the NS1 API Endpoint URL that will be used for requests. :return: URL of the NS1 API that will be used for requests
337,681
def _IsIdentifier(cls, string): return ( string and not string[0].isdigit() and all(character.isalnum() or character == for character in string))
Checks if a string contains an identifier. Args: string (str): string to check. Returns: bool: True if the string contains an identifier, False otherwise.
337,682
def sum(self): return self._constructor(self.values.sum(axis=self.baseaxes, keepdims=True))
Compute the sum across records.
337,683
def handle(self): body = None req = self.request res = self.response rou = self.router con = None start = time.time() try: con = self.create_controller() con.call = self self.controller = con if not self.qu...
Called from the interface to actually handle the request.
337,684
def embed(**kwargs): config = kwargs.get() header = kwargs.pop(, u) if config is None: config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell kwargs[] = config global _embedded_shell if _embedded_shell is None: _embedded_she...
Call this to embed IPython at the current point in your program. The first invocation of this will create an :class:`InteractiveShellEmbed` instance and then call it. Consecutive calls just call the already created instance. Here is a simple example:: from IPython import embed a = 10...
337,685
def _prepare(constituents, t0, t = None, radians = True): if isinstance(t0, Iterable): t0 = t0[0] if t is None: t = [t0] if not isinstance(t, Iterable): t = [t] a0 = astro(t0) a = [astro(t_i) for t_i in t] V0 = np.array([c.V(a0) for c in constituents])[:, np.newaxis] speed = np...
Return constituent speed and equilibrium argument at a given time, and constituent node factors at given times. Arguments: constituents -- list of constituents to prepare t0 -- time at which to evaluate speed and equilibrium argument for each constituent t -- list of times at which to evaluate node factors for ...
337,686
def main(): logging.basicConfig(level=logging.INFO) app = RunSnakeRunApp(0) app.MainLoop()
Mainloop for the application
337,687
def parse_genome_results(self, f): regexes = { : r"bam file = (.+)", : r"number of reads = ([\d,]+)", : r"number of mapped reads = ([\d,]+)", : r"number of mapped bases = ([\d,]+)", : r"number of sequenced bases = ([\d,]+)", : r"mean insert size = ([\d,\.]+)", ...
Parse the contents of the Qualimap BamQC genome_results.txt file
337,688
def contains(array, ty, string): weld_obj = WeldObject(encoder_, decoder_) string_obj = weld_obj.update(string) if isinstance(string, WeldObject): string_obj = string.obj_id weld_obj.dependencies[string_obj] = string array_var = weld_obj.update(array) if isinstance(array, Wel...
Checks if given string is contained in each string in the array. Output is a vec of booleans. Args: array (WeldObject / Numpy.ndarray): Input array start (int): starting index size (int): length to truncate at ty (WeldType): Type of each element in the input array Returns: ...
337,689
def _auto_compile(self, template, use_format=False): is_replace = _is_replace(template) is_string = isinstance(template, (str, bytes)) if is_replace and use_format != template.use_format: raise ValueError("Compiled replace cannot be a format object!") if is_replace ...
Compile replacements.
337,690
def send_mass_card(self, group_or_users, card_id, is_to_all=False, preview=False, send_ignore_reprint=0, client_msg_id=None): return self._send_mass_message( group_or_users, , { : { : c...
群发卡券消息 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1481187827_i0l21 :param group_or_users: 值为整型数字时为按分组群发,值为列表/元组时为按 OpenID 列表群发 当 is_to_all 为 True 时,传入 None 即对所有用户发送。 :param card_id: 卡券 ID :param is_to_all: 用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户...
337,691
def assert_raises_regex(expected_exception, expected_regex, extras=None, *args, **kwargs): context = _AssertRaisesContext( expected_exception, expected_regex, extras=extras) return context
Assert that an exception is raised when a function is called. If no exception is raised, test fail. If an exception is raised but not of the expected type, the exception is let through. If an exception of the expected type is raised but the error message does not match the expected_regex, test fail. ...
337,692
def load_config(deploy_dir): config = Config() config_filename = path.join(deploy_dir, ) if path.exists(config_filename): extract_file_config(config_filename, config) exec_file(config_filename) return config
Loads any local config.py file.
337,693
def parse_att(output, att, indent): if isinstance(att[1], bs): outputStr = .format( indent=indent, attribute=ATTRIBUTE, name=NAME, attname=sanitize(att[0], spaces=False), value=VALUE, attvalue=sanitize(att[1]) ) if ...
att is a tuple: (name, value)
337,694
def get_vboxes(self): vbox_list = [] vbox_max = None for node in self.nodes: if node[] == : vbox_list.append(node[]) if len(vbox_list) > 0: vbox_max = max(vbox_list) return vbox_max
Get the maximum ID of the VBoxes :return: Maximum VBox ID :rtype: int
337,695
def is_running(self): if self.block: return False return self.thread.is_alive() or self.process.poll() is None
Check if the command is currently running Returns: bool: True if running, else False
337,696
def logout(self): params = { self.PLOGOUT: } self.call(self.CGI_LOGIN, params) self._close_http_session() logger.debug("Bugzilla user logged out from %s", self.base_url)
Logout from the server.
337,697
def capture(self, to_camera_storage=False): target = self.config[][] if to_camera_storage and target.value != "Memory card": target.set("Memory card") elif not to_camera_storage and target.value != "Internal RAM": target.set("Internal RAM") lib.gp_camera_...
Capture an image. Some cameras (mostly Canon and Nikon) support capturing to internal RAM. On these devices, you have to specify `to_camera_storage` if you want to save the images to the memory card. On devices that do not support saving to RAM, the only difference is that the file ...
337,698
def rime_solver_cfg(**kwargs): from configuration import (load_config, config_validator, raise_validator_errors) def _merge_copy(d1, d2): return { k: _merge_copy(d1[k], d2[k]) if k in d1 and isinstance(d1[k], dict) ...
Produces a SolverConfiguration object, inherited from a simple python dict, and containing the options required to configure the RIME Solver. Keyword arguments ----------------- Any keyword arguments are inserted into the returned dict. Returns ------- A SolverConfiguration object.
337,699
def build_method_map(self, prototype, prefix=): if not isinstance(prototype, dict): prototype = dict((method, getattr(prototype, method)) for method in dir(prototype) if not method.startswith()) for attr, method in prototype...
Add prototype methods to the dispatcher. Parameters ---------- prototype : object or dict Initial method mapping. If given prototype is a dictionary then all callable objects will be added to dispatcher. If given prototype is an object then all pu...