code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def logs(self, follow=False): """ Get logs from this container. Iterator has one log line followed by a newline in next item. The logs are NOT encoded (they are str, not bytes). Let's look at an example:: image = conu.PodmanImage("fedora", tag="27") command = ["...
Get logs from this container. Iterator has one log line followed by a newline in next item. The logs are NOT encoded (they are str, not bytes). Let's look at an example:: image = conu.PodmanImage("fedora", tag="27") command = ["bash", "-c", "for x in `seq 1 5`; do echo $x; slee...
def get_genericpage(cls, kb_app): """ Return the one class if configured, otherwise default """ # Presumes the registry has been committed q = dectate.Query('genericpage') klasses = sorted(q(kb_app), key=lambda args: args[0].order) if not klasses: # The site doesn't ...
Return the one class if configured, otherwise default
def _check_dtype(self, dtype): """Check if dtype string is valid and return ctype string.""" try: return _ffi_types[dtype] except KeyError: raise ValueError("dtype must be one of {0!r} and not {1!r}".format( sorted(_ffi_types.keys()), dtype))
Check if dtype string is valid and return ctype string.
def saveData(self, dataOutputFile, categoriesOutputFile): """ Save the processed data and the associated category mapping. @param dataOutputFile (str) Location to save data @param categoriesOutputFile (str) Location to save category map @return (str) Path to the saved...
Save the processed data and the associated category mapping. @param dataOutputFile (str) Location to save data @param categoriesOutputFile (str) Location to save category map @return (str) Path to the saved data file iff saveData() is s...
def cli(env, sortby, columns, datacenter, username, storage_type): """List block storage.""" block_manager = SoftLayer.BlockStorageManager(env.client) block_volumes = block_manager.list_block_volumes(datacenter=datacenter, username=username, ...
List block storage.
def processing_blocks(self): """Return the a JSON dict encoding the PBs known to SDP.""" pb_list = ProcessingBlockList() # TODO(BMo) realtime, offline etc. return json.dumps(dict(active=pb_list.active, completed=pb_list.completed, ...
Return the a JSON dict encoding the PBs known to SDP.
def to_pandas_df(self, column_names=None, selection=None, strings=True, virtual=False, index_name=None): """Return a pandas DataFrame containing the ndarray corresponding to the evaluated data If index is given, that column is used for the index of the dataframe. Example >>> df_pan...
Return a pandas DataFrame containing the ndarray corresponding to the evaluated data If index is given, that column is used for the index of the dataframe. Example >>> df_pandas = df.to_pandas_df(["x", "y", "z"]) >>> df_copy = vaex.from_pandas(df_pandas) :param column_nam...
def get_fc2(supercell, symmetry, dataset, atom_list=None, decimals=None): """Force constants are computed. Force constants, Phi, are calculated from sets for forces, F, and atomic displacement, d: Phi = -F / d This is solved by matrix pseudo-inversi...
Force constants are computed. Force constants, Phi, are calculated from sets for forces, F, and atomic displacement, d: Phi = -F / d This is solved by matrix pseudo-inversion. Crystal symmetry is included when creating F and d matrices. Returns ------- ndarray Force constants...
def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): """Sync most recent file by date, time attribues""" files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Directi...
Sync most recent file by date, time attribues
def merge(cls, *args, **kwargs): """Create a new Ent from one or more existing Ents. Keys in the later Ent objects will overwrite the keys of the previous Ents. Later keys of different type than in earlier Ents will be bravely ignored. The following keyword arguments are recogn...
Create a new Ent from one or more existing Ents. Keys in the later Ent objects will overwrite the keys of the previous Ents. Later keys of different type than in earlier Ents will be bravely ignored. The following keyword arguments are recognized: newkeys: boolean value to det...
def apply_policy(self, policy): """Apply a firewall policy. """ tenant_name = policy['tenant_name'] fw_id = policy['fw_id'] fw_name = policy['fw_name'] LOG.info("asa_apply_policy: tenant=%(tenant)s fw_id=%(fw_id)s " "fw_name=%(fw_name)s", {'tenan...
Apply a firewall policy.
def run(file, access_key, secret_key, **kwargs): """命令行运行huobitrade""" if file: import sys file_path, file_name = os.path.split(file) sys.path.append(file_path) strategy_module = importlib.import_module(os.path.splitext(file_name)[0]) init = getattr(strategy_module, 'init...
命令行运行huobitrade
def set_owner(obj_name, principal, obj_type='file'): ''' Set the owner of an object. This can be a file, folder, registry key, printer, service, etc... Args: obj_name (str): The object for which to set owner. This can be the path to a file or folder, a registry key, pri...
Set the owner of an object. This can be a file, folder, registry key, printer, service, etc... Args: obj_name (str): The object for which to set owner. This can be the path to a file or folder, a registry key, printer, etc. For more information about how to format t...
def _update_service_profile(self, handle, service_profile, vlan_id, ucsm_ip): """Updates Service Profile on the UCS Manager. Each of the ethernet ports on the Service Profile representing the UCS Server, is updated with the VLAN profile corresponding to t...
Updates Service Profile on the UCS Manager. Each of the ethernet ports on the Service Profile representing the UCS Server, is updated with the VLAN profile corresponding to the vlan_id passed in.
def get_max_value(self): """ Get the maximum value """ value = self.get_default_value() if self.attribute_type is str: max_value = value.ljust(self.max_length + 1, 'a') elif self.attribute_type is int: max_value = self.max_length + 1 else: ...
Get the maximum value
def readLocationElement(self, locationElement): """ Format 0 location reader """ if self._strictAxisNames and not self.documentObject.axes: raise DesignSpaceDocumentError("No axes defined") loc = {} for dimensionElement in locationElement.findall(".dimension"): di...
Format 0 location reader
def get_security_attributes_for_user(user=None): """ Return a SECURITY_ATTRIBUTES structure with the SID set to the specified user (uses current user if none is specified). """ if user is None: user = get_current_user() assert isinstance(user, security.TOKEN_USER), ( "user must be TOKEN_USER instance") SD ...
Return a SECURITY_ATTRIBUTES structure with the SID set to the specified user (uses current user if none is specified).
def recorddiff(a, b, buffersize=None, tempdir=None, cache=True, strict=False): """ Find the difference between records in two tables. E.g.:: >>> import petl as etl >>> a = [['foo', 'bar', 'baz'], ... ['A', 1, True], ... ['C', 7, False], ... ['B', 2, False]...
Find the difference between records in two tables. E.g.:: >>> import petl as etl >>> a = [['foo', 'bar', 'baz'], ... ['A', 1, True], ... ['C', 7, False], ... ['B', 2, False], ... ['C', 9, True]] >>> b = [['bar', 'foo', 'baz'], ... ...
def run_interrupted(self): """ Runs custodian in a interuppted mode, which sets up and validates jobs but doesn't run the executable Returns: number of remaining jobs Raises: ValidationError: if a job fails validation ReturnCodeError: if the ...
Runs custodian in a interuppted mode, which sets up and validates jobs but doesn't run the executable Returns: number of remaining jobs Raises: ValidationError: if a job fails validation ReturnCodeError: if the process has a return code different from 0 ...
def get_date_822(): """return output of 822-date command""" cmd = '/bin/date' if not os.path.exists(cmd): raise ValueError('%s command does not exist.'%cmd) args = [cmd,'-R'] result = get_cmd_stdout(args).strip() result = normstr(result) return result
return output of 822-date command
def qn_to_qubo(expr): """Convert Sympy's expr to QUBO. Args: expr: Sympy's quadratic expression with variable `q0`, `q1`, ... Returns: [[float]]: Returns QUBO matrix. """ try: import sympy except ImportError: raise ImportError("This function requires sympy. P...
Convert Sympy's expr to QUBO. Args: expr: Sympy's quadratic expression with variable `q0`, `q1`, ... Returns: [[float]]: Returns QUBO matrix.
def parse_env(self, env=None, namespace=None): """Parse environment variables.""" env = env or os.environ results = {} if not namespace: namespace = self.prog namespace = namespace.upper() # pylint: disable=no-member for option in self._options: e...
Parse environment variables.
def _get_fields(self): """ Used by str, unicode, repr and __reduce__. Returns only the fields necessary to reconstruct the Interval. :return: reconstruction info :rtype: tuple """ if self.data is not None: return self.begin, self.end, self.data ...
Used by str, unicode, repr and __reduce__. Returns only the fields necessary to reconstruct the Interval. :return: reconstruction info :rtype: tuple
def reorient(self, up, look): ''' Reorient the mesh by specifying two vectors. up: The foot-to-head direction. look: The direction the body is facing. In the result, the up will end up along +y, and look along +z (i.e. facing towards a default OpenGL camera). '...
Reorient the mesh by specifying two vectors. up: The foot-to-head direction. look: The direction the body is facing. In the result, the up will end up along +y, and look along +z (i.e. facing towards a default OpenGL camera).
def _process_callbacks(self): """ Process callbacks from `call_from_executor` in eventloop. """ # Flush all the pipe content. os.read(self._schedule_pipe[0], 1024) # Process calls from executor. calls_from_executor, self._calls_from_executor = self._calls_from_ex...
Process callbacks from `call_from_executor` in eventloop.
def get_line_value(self, context_type): """ Get the values defined on this line. :param context_type: "ENV" or "LABEL" :return: values of given type defined on this line """ if context_type.upper() == "ENV": return self.line_envs elif context_type.upp...
Get the values defined on this line. :param context_type: "ENV" or "LABEL" :return: values of given type defined on this line
def peek_assoc(store, container, _stack=None): """ Deserialize association lists. """ assoc = [] try: if store.getRecordAttr('key', container) == 'escaped': for i in container: assoc.append(store.peek(i, container, _stack=_stack)) else: for i i...
Deserialize association lists.
async def _post(self, zone_id: int = None, json: dict = None) -> dict: """Post data to a (non)existing zone.""" return await self._request( 'post', 'zone/{0}/properties'.format(zone_id), json=json)
Post data to a (non)existing zone.
def thumbUrl(self): """ Return the first first thumbnail url starting on the most specific thumbnail for that item. """ thumb = self.firstAttr('thumb', 'parentThumb', 'granparentThumb') return self._server.url(thumb, includeToken=True) if thumb else None
Return the first first thumbnail url starting on the most specific thumbnail for that item.
def retry(ex=RETRIABLE, tries=4, delay=5, backoff=2, logger=None): """Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ex: the exce...
Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ex: the exception to check. may be a tuple of exceptions to check :param tries: nu...
def set_job(self, key, func, args): """ Get a scheduled task or set if none exists. Returns: - task coroutine/continuation """ res, pk = key jobs, lock = self._jobs task = _tasks.UpdateTask(func(*args), key) with lock: job = jobs[r...
Get a scheduled task or set if none exists. Returns: - task coroutine/continuation
def generate_strip_subparser(subparsers): """Adds a sub-command parser to `subparsers` to process prepared files for use with the tacl ngrams command.""" parser = subparsers.add_parser( 'strip', description=constants.STRIP_DESCRIPTION, epilog=constants.STRIP_EPILOG, formatter_class=Paragraph...
Adds a sub-command parser to `subparsers` to process prepared files for use with the tacl ngrams command.
def get_attached_pipettes(self): """ Mimic the behavior of robot.get_attached_pipettes""" api = object.__getattribute__(self, '_api') instrs = {} for mount, data in api.attached_instruments.items(): instrs[mount.name.lower()] = { 'model': data.get('name', None...
Mimic the behavior of robot.get_attached_pipettes
def run(self,evloop=None): """ Runs the application main loop. This method is blocking and needs to be called from the main thread to avoid OpenGL bugs that can occur. ``evloop`` may optionally be a subclass of :py:class:`pyglet.app.base.EventLoop` to replace the defaul...
Runs the application main loop. This method is blocking and needs to be called from the main thread to avoid OpenGL bugs that can occur. ``evloop`` may optionally be a subclass of :py:class:`pyglet.app.base.EventLoop` to replace the default event loop.
def _read_opt_pad(self, code, *, desc): """Read HOPOPT padding options. Structure of HOPOPT padding options [RFC 8200]: * Pad1 Option: +-+-+-+-+-+-+-+-+ | 0 | +-+-+-+-+-+-+-+-+ Octets Bits Name ...
Read HOPOPT padding options. Structure of HOPOPT padding options [RFC 8200]: * Pad1 Option: +-+-+-+-+-+-+-+-+ | 0 | +-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 ...
def store(self, store_item): """ Store for tweets and user information. Must have all required information and types """ required_keys = {"type": str, "timestamp": float} if not isinstance(store_item, dict): raise TypeError("The stored item should be a di...
Store for tweets and user information. Must have all required information and types
def lock(self, key, client): """Set the key that will be used to ensure messages come from one party Args: key (string): The key used to validate future messages client (string): A string that will be returned to indicate who locked this device. """ ...
Set the key that will be used to ensure messages come from one party Args: key (string): The key used to validate future messages client (string): A string that will be returned to indicate who locked this device.
def PSLLDQ(cpu, dest, src): """ Packed Shift Left Logical Double Quadword Shifts the destination operand (first operand) to the left by the number of bytes specified in the count operand (second operand). The empty low-order bytes are cleared (set to all 0s). If the value specified by ...
Packed Shift Left Logical Double Quadword Shifts the destination operand (first operand) to the left by the number of bytes specified in the count operand (second operand). The empty low-order bytes are cleared (set to all 0s). If the value specified by the count operand is greater th...
def calculate_overlap(self): """Create the array that describes how junctions overlap""" overs = [] if not self.tx_obj1.range.overlaps(self.tx_obj2.range): return [] # if they dont overlap wont find anything for i in range(0,len(self.j1)): for j in range(0,len(self.j2)): if sel...
Create the array that describes how junctions overlap
def compute(self, bottomUpInput, enableLearn, enableInference=None): """ Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.compute`. """ # The C++ TM takes 32 bit floats as input. uint32 works as well since the # code only checks whether elements are non-zero assert (bottomUpInput...
Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.compute`.
def authenticate(self, provider=None, identifier=None): "Fetch user for a given provider by id." provider_q = Q(provider__name=provider) if isinstance(provider, Provider): provider_q = Q(provider=provider) try: access = AccountAccess.objects.filter( ...
Fetch user for a given provider by id.
def _generate_throw_error(self, name, reason): """Emits a generic error throwing line.""" throw_exc = '@throw([NSException exceptionWithName:@"{}" reason:{} userInfo:nil]);' self.emit(throw_exc.format(name, reason))
Emits a generic error throwing line.
def FinalizeTaskStorage(self, task): """Finalizes a processed task storage. Args: task (Task): task. Raises: IOError: if the task storage does not exist. OSError: if the task storage does not exist. """ if task.identifier not in self._task_storage_writers: raise IOError('St...
Finalizes a processed task storage. Args: task (Task): task. Raises: IOError: if the task storage does not exist. OSError: if the task storage does not exist.
def aggregation_not_used_text_element(feature, parent): """Retrieve reference title header string from definitions.""" _ = feature, parent # NOQA header = aggregation_not_used_text['string_format'] return header.capitalize()
Retrieve reference title header string from definitions.
def safe_cast(invar, totype): """Performs a "safe" typecast. Ensures that `invar` properly casts to `totype`. Checks after casting that the result is actually of type `totype`. Any exceptions raised by the typecast itself are unhandled. Parameters ---------- invar (arbitrary) -- Va...
Performs a "safe" typecast. Ensures that `invar` properly casts to `totype`. Checks after casting that the result is actually of type `totype`. Any exceptions raised by the typecast itself are unhandled. Parameters ---------- invar (arbitrary) -- Value to be typecast. totype ...
def interpret_element(element_type: str, text: str, span: str) -> Element: """ Construct an Element instance from regexp groups. """ return Element(element_type, interpret_span(span), text)
Construct an Element instance from regexp groups.
def clause_indices(self): """The list of clause indices in ``words`` layer. The indices are unique only in the boundary of a single sentence. """ if not self.is_tagged(CLAUSE_ANNOTATION): self.tag_clause_annotations() return [word.get(CLAUSE_IDX, None) for word in sel...
The list of clause indices in ``words`` layer. The indices are unique only in the boundary of a single sentence.
def scrape_links(self, text, context=False): '''Convenience function for scraping from a text string.''' return self.iter_processed_links(io.StringIO(text), context=context)
Convenience function for scraping from a text string.
def mpim_open(self, *, users: List[str], **kwargs) -> SlackResponse: """This method opens a multiparty direct message. Args: users (list): A lists of user ids. The ordering of the users is preserved whenever a MPIM group is returned. e.g. ['W1234567890', 'U23...
This method opens a multiparty direct message. Args: users (list): A lists of user ids. The ordering of the users is preserved whenever a MPIM group is returned. e.g. ['W1234567890', 'U2345678901', 'U3456789012']
def intervals(graph): """ Compute the intervals of the graph Returns interval_graph: a graph of the intervals of G interv_heads: a dict of (header node, interval) """ interval_graph = Graph() # graph of intervals heads = [graph.entry] # list of header nodes interv_heads = {} # int...
Compute the intervals of the graph Returns interval_graph: a graph of the intervals of G interv_heads: a dict of (header node, interval)
def _indexed_ifilter(self, recursive=True, matches=None, flags=FLAGS, forcetype=None): """Iterate over nodes and their corresponding indices in the node list. The arguments are interpreted as for :meth:`ifilter`. For each tuple ``(i, node)`` yielded by this method, ``se...
Iterate over nodes and their corresponding indices in the node list. The arguments are interpreted as for :meth:`ifilter`. For each tuple ``(i, node)`` yielded by this method, ``self.index(node) == i``. Note that if *recursive* is ``True``, ``self.nodes[i]`` might not be the node itself...
def p_continue_statement_2(self, p): """continue_statement : CONTINUE identifier SEMI | CONTINUE identifier AUTOSEMI """ p[0] = self.asttypes.Continue(p[2]) p[0].setpos(p)
continue_statement : CONTINUE identifier SEMI | CONTINUE identifier AUTOSEMI
def print_number_str(self, value, justify_right=True): """Print a 4 character long string of numeric values to the display. This function is similar to print_str but will interpret periods not as characters but as decimal points associated with the previous character. """ # Calcu...
Print a 4 character long string of numeric values to the display. This function is similar to print_str but will interpret periods not as characters but as decimal points associated with the previous character.
def _set_mct_l2ys_state(self, v, load=False): """ Setter method for mct_l2ys_state, mapped from YANG variable /mct_l2ys_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_mct_l2ys_state is considered as a private method. Backends looking to populate th...
Setter method for mct_l2ys_state, mapped from YANG variable /mct_l2ys_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_mct_l2ys_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_mct_...
def parse_fields_http(self, response, extra_org_map=None): """ The function for parsing ASN fields from a http response. Args: response (:obj:`str`): The response from the ASN http server. extra_org_map (:obj:`dict`): Dictionary mapping org handles to RIR...
The function for parsing ASN fields from a http response. Args: response (:obj:`str`): The response from the ASN http server. extra_org_map (:obj:`dict`): Dictionary mapping org handles to RIRs. This is for limited cases where ARIN REST (ASN fallback HTTP...
def setup_client(self, client_id=None, user_data=None, scan=True, broadcast=False): """Setup a newly connected client. ``client_id`` must be unique among all connected clients. If it is passed as None, a random client_id will be generated as a string and returned. This method ...
Setup a newly connected client. ``client_id`` must be unique among all connected clients. If it is passed as None, a random client_id will be generated as a string and returned. This method reserves internal resources for tracking what devices this client has connected to and ...
def _compare_rows(from_recs, to_recs, keys): "Return the set of keys which have changed." return set( k for k in keys if sorted(from_recs[k].items()) != sorted(to_recs[k].items()) )
Return the set of keys which have changed.
def build_url_request(self): """ Consults the authenticator and grant for HTTP request parameters and headers to send with the access token request, builds the request using the stored endpoint and returns it. """ params = {} headers = {} self._authenticat...
Consults the authenticator and grant for HTTP request parameters and headers to send with the access token request, builds the request using the stored endpoint and returns it.
def from_iterable(cls, frames, sort=False): """ Build a :class:`FrameSet` from an iterable of frames. Args: frames (collections.Iterable): an iterable object containing frames as integers sort (bool): True to sort frames before creation, default is False Returns...
Build a :class:`FrameSet` from an iterable of frames. Args: frames (collections.Iterable): an iterable object containing frames as integers sort (bool): True to sort frames before creation, default is False Returns: :class:`FrameSet`:
def trace_dispatch(self, frame, event, arg): """allow to switch to Pdb instance""" if hasattr(self, 'pdb'): return self.pdb.trace_dispatch(frame, event, arg) else: return Pdb.trace_dispatch(self, frame, event, arg)
allow to switch to Pdb instance
def add(self, f_ipaddr, f_macaddr, f_hostname, f_netbios_name, f_engineer, f_asset_group, f_confirmed): """ Add a t_hosts record :param f_ipaddr: IP address :param f_macaddr: MAC Address :param f_hostname: Hostname :param f_netbios_name: NetBIOS Name :param f_eng...
Add a t_hosts record :param f_ipaddr: IP address :param f_macaddr: MAC Address :param f_hostname: Hostname :param f_netbios_name: NetBIOS Name :param f_engineer: Engineer username :param f_asset_group: Asset group :param f_confirmed: Confirmed boolean :re...
def save(self, filename, ftype='HDF5'): # pragma: no coverage """ Save all the model parameters into a file (HDF5 by default). This is not supported yet. We are working on having a consistent, human readable way of saving and loading GPy models. This only saves the parameter arr...
Save all the model parameters into a file (HDF5 by default). This is not supported yet. We are working on having a consistent, human readable way of saving and loading GPy models. This only saves the parameter array to a hdf5 file. In order to load the model again, use the same script f...
def create_mbed_detector(**kwargs): """! Factory used to create host OS specific mbed-lstools object :param kwargs: keyword arguments to pass along to the constructors @return Returns MbedLsTools object or None if host OS is not supported """ host_os = platform.system() if host_os == "Windows"...
! Factory used to create host OS specific mbed-lstools object :param kwargs: keyword arguments to pass along to the constructors @return Returns MbedLsTools object or None if host OS is not supported
def get_sorted_source_files( self, source_filenames_or_globs: Union[str, List[str]], recursive: bool = True) -> List[str]: """ Returns a sorted list of filenames to process, from a filename, a glob string, or a list of filenames/globs. Args: ...
Returns a sorted list of filenames to process, from a filename, a glob string, or a list of filenames/globs. Args: source_filenames_or_globs: filename/glob, or list of them recursive: use :func:`glob.glob` in recursive mode? Returns: sorted list of files to ...
def create_host(self, host_id, name, ipaddr, rack_id = None): """ Create a host. @param host_id: The host id. @param name: Host name @param ipaddr: IP address @param rack_id: Rack id. Default None. @return: An ApiHost object """ return hosts.create_host(self, host_id, name, ...
Create a host. @param host_id: The host id. @param name: Host name @param ipaddr: IP address @param rack_id: Rack id. Default None. @return: An ApiHost object
def _encode_dict_as_string(value): """Takes the PLIST string of a dict, and returns the same string encoded such that it can be included in the string representation of a GSNode.""" # Strip the first and last newlines if value.startswith("{\n"): value = "{" + value[2:...
Takes the PLIST string of a dict, and returns the same string encoded such that it can be included in the string representation of a GSNode.
def get_extended_summaryf(self, *args, **kwargs): """Extract the extended summary from a function docstring This function can be used as a decorator to extract the extended summary of a function docstring (similar to :meth:`get_sectionsf`). Parameters ---------- ``*args...
Extract the extended summary from a function docstring This function can be used as a decorator to extract the extended summary of a function docstring (similar to :meth:`get_sectionsf`). Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_extended_s...
def _get_pieces(tiles, ports, players_opts, pieces_opts): """ Generate a dictionary of pieces using the given options. pieces options supported: - Opt.empty -> no locations have pieces - Opt.random -> - Opt.preset -> robber is placed on the first desert found - Opt.debug -> a variety of pie...
Generate a dictionary of pieces using the given options. pieces options supported: - Opt.empty -> no locations have pieces - Opt.random -> - Opt.preset -> robber is placed on the first desert found - Opt.debug -> a variety of pieces are placed around the board :param tiles: list of tiles from ...
def pull_alignments_from(self, reads_to_use, shallow=False): """ Pull out alignments of certain reads :param reads_to_use: numpy array of dtype=bool specifying which reads to use :param shallow: whether to copy sparse 3D matrix only or not :return: a new AlignmentPropertyM...
Pull out alignments of certain reads :param reads_to_use: numpy array of dtype=bool specifying which reads to use :param shallow: whether to copy sparse 3D matrix only or not :return: a new AlignmentPropertyMatrix object that particular reads are
def crop_to_seg_extents(img, seg, padding): """Crop the image (usually MRI) to fit within the bounding box of a segmentation (or set of seg)""" beg_coords, end_coords = crop_coords(seg, padding) img = crop_3dimage(img, beg_coords, end_coords) seg = crop_3dimage(seg, beg_coords, end_coords) return...
Crop the image (usually MRI) to fit within the bounding box of a segmentation (or set of seg)
def update_item(self, item, expected_value=None, return_values=None): """ Commit pending item updates to Amazon DynamoDB. :type item: :class:`boto.dynamodb.item.Item` :param item: The Item to update in Amazon DynamoDB. It is expected that you would have called the add_attri...
Commit pending item updates to Amazon DynamoDB. :type item: :class:`boto.dynamodb.item.Item` :param item: The Item to update in Amazon DynamoDB. It is expected that you would have called the add_attribute, put_attribute and/or delete_attribute methods on this Item prior to call...
def cmp(self,range2,overlap_size=0): """the comparitor for ranges * return 1 if greater than range2 * return -1 if less than range2 * return 0 if overlapped :param range2: :param overlap_size: allow some padding for an 'equal' comparison (default 0) :type range2: GenomicRange :type ...
the comparitor for ranges * return 1 if greater than range2 * return -1 if less than range2 * return 0 if overlapped :param range2: :param overlap_size: allow some padding for an 'equal' comparison (default 0) :type range2: GenomicRange :type overlap_size: int
def version(self): """Return the build date of the gentoo container.""" try: _version = (curl[Gentoo._LATEST_TXT] | \ awk['NR==2{print}'] | \ cut["-f2", "-d="])().strip() _version = datetime.utcfromtimestamp(int(_version))\ ...
Return the build date of the gentoo container.
def create(self): """Create the write buffer and cache directory.""" if not self._sync and not hasattr(self, '_buffer'): self._buffer = {} if not os.path.exists(self.cache_dir): os.makedirs(self.cache_dir)
Create the write buffer and cache directory.
def add(self, interval, offset): """ The added interval must be overlapping or beyond the last stored interval ie. added in sorted order. :param interval: interval to add :param offset: full virtual offset to add :return: """ start, stop = self.get_start_stop(int...
The added interval must be overlapping or beyond the last stored interval ie. added in sorted order. :param interval: interval to add :param offset: full virtual offset to add :return:
def make_request(self, method, path, params={}, body="", username=None, password=None, base_uri=None, content_type=None): headers = { 'User-Agent': CreateSend.user_agent, 'Content-Type': 'application/json; charset=utf-8', 'Accept-Encoding': 'gzip, deflate...
username and password should only be set when it is intended that the default basic authentication mechanism using the API key be overridden (e.g. when using the apikey route with username and password).
def derivative(self, point=None): """Return the derivative operator. The partial derivative is usually linear, but in case the 'constant' ``pad_mode`` is used with nonzero ``pad_const``, the derivative is given by the derivative with 0 ``pad_const``. Parameters --------...
Return the derivative operator. The partial derivative is usually linear, but in case the 'constant' ``pad_mode`` is used with nonzero ``pad_const``, the derivative is given by the derivative with 0 ``pad_const``. Parameters ---------- point : `domain` `element-like`, o...
def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, )
Returns the returner modules
def generate(self, api): # type: (Api) -> None """ Generates a module for each namespace. Each namespace will have Python classes to represent data types and routes in the Stone spec. """ for namespace in api.namespaces.values(): with self.output_to_r...
Generates a module for each namespace. Each namespace will have Python classes to represent data types and routes in the Stone spec.
def clr(args): """ %prog clr [bamfile|bedpefile] ref.fasta Use mates from BEDPE to extract ranges where the ref is covered by mates. This is useful in detection of chimeric contigs. """ p = OptionParser(clr.__doc__) p.set_bedpe() opts, args = p.parse_args(args) if len(args) != 2: ...
%prog clr [bamfile|bedpefile] ref.fasta Use mates from BEDPE to extract ranges where the ref is covered by mates. This is useful in detection of chimeric contigs.
def get_all_resources(datasets): # type: (List['Dataset']) -> List[hdx.data.resource.Resource] """Get all resources from a list of datasets (such as returned by search) Args: datasets (List[Dataset]): list of datasets Returns: List[hdx.data.resource.Resource]: l...
Get all resources from a list of datasets (such as returned by search) Args: datasets (List[Dataset]): list of datasets Returns: List[hdx.data.resource.Resource]: list of resources within those datasets
def DeleteResource(self, path, type, id, initial_headers, options=None): """Deletes a Azure Cosmos resource and returns it. :param str path: :param str type: :param str id: :param dict initial_headers: :param dict options: The request options for the request....
Deletes a Azure Cosmos resource and returns it. :param str path: :param str type: :param str id: :param dict initial_headers: :param dict options: The request options for the request. :return: The deleted Azure Cosmos resource. :rtype: ...
def update_existing_peers( self, num_to_remove, peer_table=None, con=None, path=None ): """ Update the set of existing peers: * revalidate the existing but old peers * remove at most $num_to_remove unhealthy peers Return the number of peers removed """ i...
Update the set of existing peers: * revalidate the existing but old peers * remove at most $num_to_remove unhealthy peers Return the number of peers removed
def _does_not_contain_replica_sections(sysmeta_pyxb): """Assert that ``sysmeta_pyxb`` does not contain any replica information.""" if len(getattr(sysmeta_pyxb, 'replica', [])): raise d1_common.types.exceptions.InvalidSystemMetadata( 0, 'A replica section was included. A new objec...
Assert that ``sysmeta_pyxb`` does not contain any replica information.
def generate_key(filepath): ''' generates a new, random secret key at the given location on the filesystem and returns its path ''' fs = path.abspath(path.expanduser(filepath)) with open(fs, 'wb') as outfile: outfile.write(Fernet.generate_key()) chmod(fs, 0o400) return fs
generates a new, random secret key at the given location on the filesystem and returns its path
def build_absolute_uri(request, url): """ Allow to override printing url, not necessarily on the same server instance. """ if app_settings.get('CAPTURE_ROOT_URL'): return urljoin(app_settings.get('CAPTURE_ROOT_URL'), url) return request.build_absolute_uri(url)
Allow to override printing url, not necessarily on the same server instance.
def valid_address(address): """ Determines whether the specified address string is valid. """ if not address: return False components = str(address).split(':') if len(components) > 2 or not valid_hostname(components[0]): return False if len(components) == 2 and not valid_po...
Determines whether the specified address string is valid.
def _plot_ts_cols(ts): """ Get variable + values vs year, age, depth (whichever are available) :param dict ts: TimeSeries dictionary :return dict: Key: variableName, Value: Panda Series object """ logger_dataframes.info("enter get_ts_cols()") d = {} # Not entirely necessary, but this wi...
Get variable + values vs year, age, depth (whichever are available) :param dict ts: TimeSeries dictionary :return dict: Key: variableName, Value: Panda Series object
def video_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Compute loss numerator and denominator for one shard of output.""" del vocab_size # unused arg logits = top_out logits = tf.reshape(logits, [-1] + common_layers.shape_list(logits)[2:]) targets = tf.reshape(targets, [-1] + common_laye...
Compute loss numerator and denominator for one shard of output.
def _collect_args(args) -> ISeq: """Collect Python starred arguments into a Basilisp list.""" if isinstance(args, tuple): return llist.list(args) raise TypeError("Python variadic arguments should always be a tuple")
Collect Python starred arguments into a Basilisp list.
def diff_medians(array_one, array_two): """ Computes the difference in medians between two arrays of values. Given arrays will be flattened (to 1D array) regardless of dimension, and any non-finite/NaN values will be ignored. Parameters ---------- array_one, array_two : iterable ...
Computes the difference in medians between two arrays of values. Given arrays will be flattened (to 1D array) regardless of dimension, and any non-finite/NaN values will be ignored. Parameters ---------- array_one, array_two : iterable Two arrays of values, possibly of different length...
def get_equalisers(self): """Get the equaliser modes supported by this device.""" if not self.__equalisers: self.__equalisers = yield from self.handle_list( self.API.get('equalisers')) return self.__equalisers
Get the equaliser modes supported by this device.
def getDataFromFIFO(self, bytesToRead): """ reads the specified number of bytes from the FIFO, should be called after a call to getFifoCount to ensure there is new data available (to avoid reading duplicate data). :param bytesToRead: the number of bytes to read. :return: the byte...
reads the specified number of bytes from the FIFO, should be called after a call to getFifoCount to ensure there is new data available (to avoid reading duplicate data). :param bytesToRead: the number of bytes to read. :return: the bytes read.
def delete(self): """Delete the persistent identifier. If the persistent identifier haven't been registered yet, it is removed from the database. Otherwise, it's marked as :attr:`invenio_pidstore.models.PIDStatus.DELETED`. :returns: `True` if the PID is successfully removed. ...
Delete the persistent identifier. If the persistent identifier haven't been registered yet, it is removed from the database. Otherwise, it's marked as :attr:`invenio_pidstore.models.PIDStatus.DELETED`. :returns: `True` if the PID is successfully removed.
def dim(self): """ NAME: dim PURPOSE: return the dimension of the Orbit INPUT: (none) OUTPUT: dimension HISTORY: 2011-02-03 - Written - Bovy (NYU) """ if len(self._orb.vxvv) == 2: ...
NAME: dim PURPOSE: return the dimension of the Orbit INPUT: (none) OUTPUT: dimension HISTORY: 2011-02-03 - Written - Bovy (NYU)
def QA_SU_save_stock_terminated(client=DATABASE): ''' 获取已经被终止上市的股票列表,数据从上交所获取,目前只有在上海证券交易所交易被终止的股票。 collection: code:股票代码 name:股票名称 oDate:上市日期 tDate:终止上市日期 :param client: :return: None ''' # 🛠todo 已经失效从wind 资讯里获取 # 这个函数已经失效 print("!!! tushare 这个函数已经失效!!!") df = QATs.get...
获取已经被终止上市的股票列表,数据从上交所获取,目前只有在上海证券交易所交易被终止的股票。 collection: code:股票代码 name:股票名称 oDate:上市日期 tDate:终止上市日期 :param client: :return: None
def analyses(self): """Retrieve a list of analyzed samples. :rtype: list :return: List of objects referencing each analyzed file. """ response = self._request("tasks/list") return json.loads(response.content.decode('utf-8'))['tasks']
Retrieve a list of analyzed samples. :rtype: list :return: List of objects referencing each analyzed file.
def set_level(self, position, channel=None): """Seek a specific value by specifying a float() from 0.0 to 1.0.""" try: position = float(position) except Exception as err: LOG.debug("HelperLevel.set_level: Exception %s" % (err,)) return False self.writ...
Seek a specific value by specifying a float() from 0.0 to 1.0.
def set_breaks_and_labels(self, ranges, layout_info, pidx): """ Add breaks and labels to the axes Parameters ---------- ranges : dict-like range information for the axes layout_info : dict-like facet layout information pidx : int ...
Add breaks and labels to the axes Parameters ---------- ranges : dict-like range information for the axes layout_info : dict-like facet layout information pidx : int Panel index
def read_input_registers(slave_id, starting_address, quantity): """ Return ADU for Modbus function code 04: Read Input Registers. :param slave_id: Number of slave. :return: Byte array with ADU. """ function = ReadInputRegisters() function.starting_address = starting_address function.quantit...
Return ADU for Modbus function code 04: Read Input Registers. :param slave_id: Number of slave. :return: Byte array with ADU.