code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get(self, resource, **params): """ Generic TeleSign REST API GET handler. :param resource: The partial resource URI to perform the request against, as a string. :param params: Body params to perform the GET request with, as a dictionary. :return: The RestClient Response obje...
Generic TeleSign REST API GET handler. :param resource: The partial resource URI to perform the request against, as a string. :param params: Body params to perform the GET request with, as a dictionary. :return: The RestClient Response object.
def to_UNIXtime(timeobject): """ Returns the UNIXtime corresponding to the time value conveyed by the specified object, which can be either a UNIXtime, a ``datetime.datetime`` object or an ISO8601-formatted string in the format `YYYY-MM-DD HH:MM:SS+00``. :param timeobject: the object conveying ...
Returns the UNIXtime corresponding to the time value conveyed by the specified object, which can be either a UNIXtime, a ``datetime.datetime`` object or an ISO8601-formatted string in the format `YYYY-MM-DD HH:MM:SS+00``. :param timeobject: the object conveying the time value :type timeobject: int,...
async def play(self): """ Starts playback from lavalink. """ if self.repeat and self.current is not None: self.queue.append(self.current) self.current = None self.position = 0 self._paused = False if not self.queue: await self.sto...
Starts playback from lavalink.
def set_canvas_properties(self, canvas, x_title=None, y_title=None, x_lim=None, y_lim=None, x_labels=True, y_labels=True): """! @brief Set properties for specified canvas. @param[in] canvas (uint): Index of canvas whose properties should changed. @param[in] x_title (string): Title ...
! @brief Set properties for specified canvas. @param[in] canvas (uint): Index of canvas whose properties should changed. @param[in] x_title (string): Title for X axis, if 'None', then nothing is displayed. @param[in] y_title (string): Title for Y axis, if 'None', then nothing is di...
def get_users_with_permission(obj, permission): """Return users with specific permission on object. :param obj: Object to return users for :param permission: Permission codename """ user_model = get_user_model() return user_model.objects.filter( userobjectpermission__object_pk=obj.pk, ...
Return users with specific permission on object. :param obj: Object to return users for :param permission: Permission codename
def _folder_item_duedate(self, analysis_brain, item): """Set the analysis' due date to the item passed in. :param analysis_brain: Brain that represents an analysis :param item: analysis' dictionary counterpart that represents a row """ # Note that if the analysis is a Reference...
Set the analysis' due date to the item passed in. :param analysis_brain: Brain that represents an analysis :param item: analysis' dictionary counterpart that represents a row
def get_assets_by_provider(self, resource_id=None): """Gets an ``AssetList`` from the given provider. In plenary mode, the returned list contains all known assets or an error results. Otherwise, the returned list may contain only those assets that are accessible through this session. ...
Gets an ``AssetList`` from the given provider. In plenary mode, the returned list contains all known assets or an error results. Otherwise, the returned list may contain only those assets that are accessible through this session. arg: resource_id (osid.id.Id): a resource ``Id`` ...
def introspect_operation(self, operation): """ Introspects an entire operation, returning:: * the method name (to expose to the user) * the API name (used server-side) * docs * introspected information about the parameters * information about the output ...
Introspects an entire operation, returning:: * the method name (to expose to the user) * the API name (used server-side) * docs * introspected information about the parameters * information about the output :param operation: The operation to introspect :type ope...
def _request(self, endpoint, method, data=None, **kwargs): """ Method to hanle both GET and POST requests. :param endpoint: Endpoint of the API. :param method: Method of HTTP request. :param data: POST DATA for the request. :param kwargs: Other keyword arguments. ...
Method to hanle both GET and POST requests. :param endpoint: Endpoint of the API. :param method: Method of HTTP request. :param data: POST DATA for the request. :param kwargs: Other keyword arguments. :return: Response for the request.
def recall(): """RECALL Section 9.3.18a""" a = TpPd(pd=0x3) b = MessageType(mesType=0xb) # 00001011 c = RecallType() d = Facility() packet = a / b / c / d return packet
RECALL Section 9.3.18a
def remove(self, method_or_response=None, url=None): """ Removes a response previously added using ``add()``, identified either by a response object inheriting ``BaseResponse`` or ``method`` and ``url``. Removes all matching responses. >>> response.add(responses.GET, 'http://exa...
Removes a response previously added using ``add()``, identified either by a response object inheriting ``BaseResponse`` or ``method`` and ``url``. Removes all matching responses. >>> response.add(responses.GET, 'http://example.org') >>> response.remove(responses.GET, 'http://example.org...
def namedb_get_name(cur, name, current_block, include_expired=False, include_history=True, only_registered=True): """ Get a name and all of its history. Note: will return a revoked name Return the name + history on success Return None if the name doesn't exist, or is expired (NOTE: will return a revoke...
Get a name and all of its history. Note: will return a revoked name Return the name + history on success Return None if the name doesn't exist, or is expired (NOTE: will return a revoked name)
def threshold(self, scalars, vmin=None, vmax=None, useCells=False): """ Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of the scalars array. :type scalars: str, list :param float vmin: minimum value of the scalar :param float vmax: ...
Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of the scalars array. :type scalars: str, list :param float vmin: minimum value of the scalar :param float vmax: maximum value of the scalar :param bool useCells: if `True`, assume array scalar...
def topWindow(): """ Returns the very top window for all Qt purposes. :return <QWidget> || None """ import_qt(globals()) window = QtGui.QApplication.instance().activeWindow() if not window: return None parent = window.parent() while paren...
Returns the very top window for all Qt purposes. :return <QWidget> || None
def make_helix(aa, axis_distance, z_shift, phi, splay, off_plane): """Builds a helix for a given set of parameters.""" start = numpy.array([axis_distance, 0 + z_shift, 0]) end = numpy.array([axis_distance, (aa * 1.52) + z_shift, 0]) mid = (start + end) / 2 helix = Helix.from_sta...
Builds a helix for a given set of parameters.
def _first_stoppoint(self, irsb, extra_stop_points=None): """ Enumerate the imarks in the block. If any of them (after the first one) are at a stop point, returns the address of the stop point. None is returned otherwise. """ if self._stop_points is None and extra_stop_points is ...
Enumerate the imarks in the block. If any of them (after the first one) are at a stop point, returns the address of the stop point. None is returned otherwise.
def get_vm_host_info(hostip, auth, url): """ function takes hostId as input to RESTFUL call to HP IMC :param hostip: int or string of hostip of Hypervisor host :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually aut...
function takes hostId as input to RESTFUL call to HP IMC :param hostip: int or string of hostip of Hypervisor host :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: Dict...
def get_portchannel_info_by_intf_output_lacp_actor_priority(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf") config = get_portchannel_info_by_intf output = ET.SubElement(get...
Auto Generated Code
def cal_gpa(grades): """ 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组 """ # 课程总数 courses_sum = len(grades) # 课程绩点和 points_sum = 0 # 学分和 credit_sum = 0 # 课程学分 x 课程绩点之和 gpa_...
根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组
def getSchema(cls): """ return all persistent class attributes """ schema = [] for name, atr in cls.__attributes__: atr = atr.__get__(None, cls) if isinstance(atr, SQLAttribute): schema.append((name, atr)) cls.getSchema = staticmeth...
return all persistent class attributes
def remove_imaginary_terms(pauli_sums: PauliSum) -> PauliSum: """ Remove the imaginary component of each term in a Pauli sum. :param pauli_sums: The Pauli sum to process. :return: a purely Hermitian Pauli sum. """ if not isinstance(pauli_sums, PauliSum): raise TypeError("not a pauli sum...
Remove the imaginary component of each term in a Pauli sum. :param pauli_sums: The Pauli sum to process. :return: a purely Hermitian Pauli sum.
def _lint(self): """Run linter in a subprocess.""" command = self._get_command() process = subprocess.run(command, stdout=subprocess.PIPE, # nosec stderr=subprocess.PIPE) LOG.info('Finished %s', ' '.join(command)) stdout, stderr = self._get_outpu...
Run linter in a subprocess.
def get_empty_dimension(**kwargs): """ Returns a dimension object initialized with empty values """ dimension = JSONObject(Dimension()) dimension.id = None dimension.name = '' dimension.description = '' dimension.project_id = None dimension.units = [] return dimension
Returns a dimension object initialized with empty values
def propertySearch(self, pid, getall=0): """ Searches this 'GameTree' for nodes containing matching properties. Returns a 'GameTree' containing the matched node(s). Arguments: - pid : string -- ID of properties to search for. - getall : boolean -- Set to true (1) to return all 'Node''s that match, or...
Searches this 'GameTree' for nodes containing matching properties. Returns a 'GameTree' containing the matched node(s). Arguments: - pid : string -- ID of properties to search for. - getall : boolean -- Set to true (1) to return all 'Node''s that match, or to false (0) to return only the first match.
def get_dataframe(self, force_computation=False): """ Preprocesses then transforms the return of fetch(). Args: force_computation (bool, optional) : Defaults to False. If set to True, forces the computation of DataFrame at each call. Returns: pandas.DataFrame: P...
Preprocesses then transforms the return of fetch(). Args: force_computation (bool, optional) : Defaults to False. If set to True, forces the computation of DataFrame at each call. Returns: pandas.DataFrame: Preprocessed and transformed DataFrame.
def _check_accessed_members(self, node, accessed): """check that accessed members are defined""" # XXX refactor, probably much simpler now that E0201 is in type checker excs = ("AttributeError", "Exception", "BaseException") for attr, nodes in accessed.items(): try: ...
check that accessed members are defined
def modules(): ''' Return list of static and shared modules (``apachectl -M``) CLI Example: .. code-block:: bash salt '*' apache.modules ''' cmd = '{0} -M'.format(_detect_os()) ret = {} ret['static'] = [] ret['shared'] = [] out = __salt__['cmd.run'](cmd).splitlines() ...
Return list of static and shared modules (``apachectl -M``) CLI Example: .. code-block:: bash salt '*' apache.modules
def read_storage_class(self, name, **kwargs): """ read the specified StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_storage_class(name, async_req=True) >>> result...
read the specified StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_storage_class(name, async_req=True) >>> result = thread.get() :param async_req bool :param str ...
def metar(data: MetarData, units: Units) -> str: """ Convert MetarData into a string for text-to-speech """ speech = [] if data.wind_direction and data.wind_speed: speech.append(wind(data.wind_direction, data.wind_speed, data.wind_gust, data.wind_variable_direction...
Convert MetarData into a string for text-to-speech
def get_success_enrollment_message(cls, users, enrolled_in): """ Create message for the users who were enrolled in a course or program. Args: users: An iterable of users who were successfully enrolled enrolled_in (str): A string identifier for the course or program the u...
Create message for the users who were enrolled in a course or program. Args: users: An iterable of users who were successfully enrolled enrolled_in (str): A string identifier for the course or program the users were enrolled in Returns: tuple: A 2-tuple containing a...
def get_route_to(self, destination='', protocol=''): """Return route details to a specific destination, learned from a certain protocol.""" # Note, it should be possible to query the FIB: # "<show><routing><fib></fib></routing></show>" # To add informations to this getter routes...
Return route details to a specific destination, learned from a certain protocol.
def copy(self): """ Creates a copy of itself """ return Particle(copy(self.position), copy(self.velocity), self.fitness)
Creates a copy of itself
def parallel_bulk( client, actions, thread_count=4, chunk_size=500, max_chunk_bytes=100 * 1024 * 1024, queue_size=4, expand_action_callback=expand_action, *args, **kwargs ): """ Parallel version of the bulk helper run in multiple threads at once. :arg client: instance of...
Parallel version of the bulk helper run in multiple threads at once. :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use :arg actions: iterator containing the actions :arg thread_count: size of the threadpool to use for the bulk requests :arg chunk_size: number of docs in one chunk se...
def circles(st, layer, axis, ax=None, talpha=1.0, cedge='white', cface='white'): """ Plots a set of circles corresponding to a slice through the platonic structure. Copied from twoslice_overlay with comments, standaloneness. Inputs ------ pos : array of particle positions; [N,3] rad...
Plots a set of circles corresponding to a slice through the platonic structure. Copied from twoslice_overlay with comments, standaloneness. Inputs ------ pos : array of particle positions; [N,3] rad : array of particle radii; [N] ax : plt.axis instance layer : Which layer of...
def _syspath(dev): ''' Full SysFS path of a device ''' dev = _devbase(dev) dev = re.sub(r'^([vhs][a-z]+)([0-9]+)', r'\1/\1\2', dev) # name = re.sub(r'^([a-z]+)(?<!(bcache|md|dm))([0-9]+)', r'\1/\1\2', name) return os.path.join('/sys/block/', dev)
Full SysFS path of a device
def update_note(note, **kwargs): """ Update a note """ note_i = _get_note(note.id) if note.ref_key != note_i.ref_key: raise HydraError("Cannot convert a %s note to a %s note. Please create a new note instead."%(note_i.ref_key, note.ref_key)) note_i.set_ref(note.ref_key, note.ref_id) ...
Update a note
def server_list(endpoint_id): """ Executor for `globus endpoint server list` """ # raises usage error on shares for us endpoint, server_list = get_endpoint_w_server_list(endpoint_id) if server_list == "S3": # not GCS -- this is an S3 endpoint server_list = {"s3_url": endpoint["s3_url"]...
Executor for `globus endpoint server list`
def add_hotkey(control, key, func, id = None): """ Add a global hotkey bound to control via id that should call func. control: The control to bind to. key: The hotkey to use. func: The func to call. id: The new ID to use (defaults to creating a new ID. """ if win32con is None: raise RuntimeError('win32con i...
Add a global hotkey bound to control via id that should call func. control: The control to bind to. key: The hotkey to use. func: The func to call. id: The new ID to use (defaults to creating a new ID.
def modify_product(self, product_id, name=None, description=None, attributes={}): ''' modify_product(self, product_id, name=None, description=None, attributes={}) Modify an existing product :Parameters: * *product_id* (`string`) -- identifier of an existing product * *n...
modify_product(self, product_id, name=None, description=None, attributes={}) Modify an existing product :Parameters: * *product_id* (`string`) -- identifier of an existing product * *name* (`string`) -- name of the product * *description* (`string`) -- product description ...
def name_scope(name=None): """ This decorator wraps a function so that it runs inside a TensorFlow name scope. The name is given by the `name` option; if this is None, then the name of the function will be used. ``` >>> @name_scope() >>> def foo(...): >>> # now runs inside scope "foo...
This decorator wraps a function so that it runs inside a TensorFlow name scope. The name is given by the `name` option; if this is None, then the name of the function will be used. ``` >>> @name_scope() >>> def foo(...): >>> # now runs inside scope "foo" >>> @name_scope('bar') >>> de...
def build_vep_string(vep_info, vep_columns): """ Build a vep string formatted string. Take a list with vep annotations and build a new vep string Args: vep_info (list): A list with vep annotation dictionaries vep_columns (list): A list with the vep column names found in the ...
Build a vep string formatted string. Take a list with vep annotations and build a new vep string Args: vep_info (list): A list with vep annotation dictionaries vep_columns (list): A list with the vep column names found in the header of the vcf Returns: string: ...
def _attempting(self, text): """Keeps track of the furthest point in the source code the parser has reached to this point.""" consumed = len(self.original_text) - len(text) self.most_consumed = max(consumed, self.most_consumed)
Keeps track of the furthest point in the source code the parser has reached to this point.
def Pn(x): """Calculate Legendre polyomials P0 to P28 and returns them in a dictionary ``Pn``. :param float x: argument to calculate Legendre polynomials :return Pn: dictionary which contains order of Legendre polynomials (from 0 to 28) as keys and the corresponding ...
Calculate Legendre polyomials P0 to P28 and returns them in a dictionary ``Pn``. :param float x: argument to calculate Legendre polynomials :return Pn: dictionary which contains order of Legendre polynomials (from 0 to 28) as keys and the corresponding evaluation ...
def get_rsa_pub_key(path): ''' Read a public key off the disk. ''' log.debug('salt.crypt.get_rsa_pub_key: Loading public key') if HAS_M2: with salt.utils.files.fopen(path, 'rb') as f: data = f.read().replace(b'RSA ', b'') bio = BIO.MemoryBuffer(data) key = RSA.loa...
Read a public key off the disk.
def from_config(cls, cp, **kwargs): r"""Initializes an instance of this class from the given config file. Parameters ---------- cp : WorkflowConfigParser Config file parser to read. \**kwargs : All additional keyword arguments are passed to the class. Any...
r"""Initializes an instance of this class from the given config file. Parameters ---------- cp : WorkflowConfigParser Config file parser to read. \**kwargs : All additional keyword arguments are passed to the class. Any provided keyword will over ride...
def on_connection_open(self, connection): """This method is called by pika once the connection to RabbitMQ has been established. :type connection: pika.TornadoConnection """ LOGGER.debug('Connection opened') connection.add_on_connection_blocked_callback( sel...
This method is called by pika once the connection to RabbitMQ has been established. :type connection: pika.TornadoConnection
def get_string_plus_property_value(value): # type: (Any) -> Optional[List[str]] """ Converts a string or list of string into a list of strings :param value: A string or a list of strings :return: A list of strings or None """ if value: if isinstance(value, str): return [...
Converts a string or list of string into a list of strings :param value: A string or a list of strings :return: A list of strings or None
def _curvelength(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20): """ Returns the length of the spline. Integrates the estimated length of the cubic bezier spline defined by x0, y0, ... x3, y3, by adding the lengths of lineair lines between points at t. The number of points is de...
Returns the length of the spline. Integrates the estimated length of the cubic bezier spline defined by x0, y0, ... x3, y3, by adding the lengths of lineair lines between points at t. The number of points is defined by n (n=10 would add the lengths of lines between 0.0 an...
def split_sequence_as_iterable(self, values): """Group sequence into iterables Parameters ---------- values : iterable of length equal to keys iterable of values to be grouped Yields ------ iterable of items in values Notes ----- ...
Group sequence into iterables Parameters ---------- values : iterable of length equal to keys iterable of values to be grouped Yields ------ iterable of items in values Notes ----- This is the preferred method if values has random ac...
def from_grpc_status(status_code, message, **kwargs): """Create a :class:`GoogleAPICallError` from a :class:`grpc.StatusCode`. Args: status_code (grpc.StatusCode): The gRPC status code. message (str): The exception message. kwargs: Additional arguments passed to the :class:`GoogleAPICal...
Create a :class:`GoogleAPICallError` from a :class:`grpc.StatusCode`. Args: status_code (grpc.StatusCode): The gRPC status code. message (str): The exception message. kwargs: Additional arguments passed to the :class:`GoogleAPICallError` constructor. Returns: Google...
def clean(self): """ Get the .txt file from within the many-layered directory structure, then delete the directories. """ logger.info('Cleaning up archive') shutil.move( os.path.join( self.data_dir, 'var/IRS/data/scripts/pofd/do...
Get the .txt file from within the many-layered directory structure, then delete the directories.
def update_submit_s3_uri(estimator, job_name): """Updated the S3 URI of the framework source directory in given estimator. Args: estimator (sagemaker.estimator.Framework): The Framework estimator to update. job_name (str): The new job name included in the submit S3 URI Returns: str...
Updated the S3 URI of the framework source directory in given estimator. Args: estimator (sagemaker.estimator.Framework): The Framework estimator to update. job_name (str): The new job name included in the submit S3 URI Returns: str: The updated S3 URI of framework source directory
def p_LD_reg_val(p): """ asm : LD reg8 COMMA expr | LD reg8 COMMA pexpr | LD reg16 COMMA expr | LD reg8_hl COMMA expr | LD A COMMA expr | LD SP COMMA expr | LD reg8i COMMA expr """ s = 'LD %s,N' % p[2] if p[2] in REGS16: s +...
asm : LD reg8 COMMA expr | LD reg8 COMMA pexpr | LD reg16 COMMA expr | LD reg8_hl COMMA expr | LD A COMMA expr | LD SP COMMA expr | LD reg8i COMMA expr
def scheduler(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, inqueue_limit, delete_time, active_tasks, loop_limit, fail_pause_num, scheduler_cls, threads, get_object=False): """ Run Scheduler, only one scheduler is allowed. """ g = ctx.obj Scheduler = load_cls(None, None, schedul...
Run Scheduler, only one scheduler is allowed.
def delete_model_translation(self, request, translation): """ Hook for deleting a translation. This calls :func:`get_translation_objects` to collect all related objects for the translation. By default, that includes the translations for inline objects. """ master = transl...
Hook for deleting a translation. This calls :func:`get_translation_objects` to collect all related objects for the translation. By default, that includes the translations for inline objects.
def is_floating(self): """Returns whether this is a (non-quantized, real) floating point type.""" return ( self.is_numpy_compatible and np.issubdtype(self.as_numpy_dtype, np.floating) ) or self.base_dtype == bfloat16
Returns whether this is a (non-quantized, real) floating point type.
def getstats(self, save=True, filename=None, samples=None, subset=None, ablation_time=False): """ Return pandas dataframe of all sample statistics. """ slst = [] if samples is not None: subset = self.make_subset(samples) samples = self._get_samples(subset) ...
Return pandas dataframe of all sample statistics.
def handle(self, argv=None): """ Main function. Parses command, load settings and dispatches accordingly. """ desc = ('Zappa - Deploy Python applications to AWS Lambda' ' and API Gateway.\n') parser = argparse.ArgumentParser(description=desc) pa...
Main function. Parses command, load settings and dispatches accordingly.
def serviceQueues(self, limit=None): """ Process `limit` number of messages in the inBox. :param limit: the maximum number of messages to process :return: the number of messages successfully processed """ # TODO should handle SuspiciousNode here r = self.dequeue_...
Process `limit` number of messages in the inBox. :param limit: the maximum number of messages to process :return: the number of messages successfully processed
def dereplicate_seqs(seqs_fp, output_fp, min_size=2, use_log=False, threads=1): """Dereplicate FASTA sequences and remove singletons using VSEARCH. Parameters ---------- seqs_fp : string filepath to FASTA sequen...
Dereplicate FASTA sequences and remove singletons using VSEARCH. Parameters ---------- seqs_fp : string filepath to FASTA sequence file output_fp : string file path to dereplicated sequences (FASTA format) min_size : integer, optional discard sequences with an abundance valu...
def from_spec(spec, kwargs=None): """ Creates a layer from a specification dict. """ layer = util.get_object( obj=spec, predefined_objects=tensorforce.core.networks.layers, kwargs=kwargs ) assert isinstance(layer, Layer) return ...
Creates a layer from a specification dict.
def lines(self): """ Array of all the lines. """ # Cache, because this one is reused very often. if self._cache.lines is None: self._cache.lines = _ImmutableLineList(self.text.split('\n')) return self._cache.lines
Array of all the lines.
def get_rsn_ie(defcipher, defauth, data): """http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n441. Positional arguments: defcipher -- default cipher if not in data (string). defauth -- default authentication suites if not in data (string). data -- bytearray data to rea...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n441. Positional arguments: defcipher -- default cipher if not in data (string). defauth -- default authentication suites if not in data (string). data -- bytearray data to read. Returns: Dict.
def root(self): """ Property provides access to root object in CFB. """ sector = self.header.directory_sector_start position = (sector + 1) << self.header.sector_shift return RootEntry(self, position)
Property provides access to root object in CFB.
def songs_iter(self, *, continuation_token=None, export_type=1): """Get a paged iterator of Music Library songs. Parameters: continuation_token (str, Optional): The token of the page to return. Default: Not sent to get first page. export_type (int, Optional): The type of tracks to return. 1 for all track...
Get a paged iterator of Music Library songs. Parameters: continuation_token (str, Optional): The token of the page to return. Default: Not sent to get first page. export_type (int, Optional): The type of tracks to return. 1 for all tracks, 2 for promotional and purchased. Default: ``1`` Yields: l...
def _cdata_io(self, action, data, ctype, frames): """Call one of libsndfile's read/write functions.""" assert ctype in _ffi_types.values() self._check_if_closed() if self.seekable(): curr = self.tell() func = getattr(_snd, 'sf_' + action + 'f_' + ctype) frames...
Call one of libsndfile's read/write functions.
def set_attributes(self, **kwargs): """ Set a group of attributes (parameters and members). Calls `setp` directly, so kwargs can include more than just the parameter value (e.g., bounds, free, etc.). """ self.clear_derived() kwargs = dict(kwargs) for name...
Set a group of attributes (parameters and members). Calls `setp` directly, so kwargs can include more than just the parameter value (e.g., bounds, free, etc.).
def pairdists(alignment, subs_model, alpha=None, ncat=4, tolerance=1e-6, verbose=False): """ Load an alignment, calculate all pairwise distances and variances model parameter must be a Substitution model type from phylo_utils """ # Check if not isinstance(subs_model, phylo_utils.models.Model): ...
Load an alignment, calculate all pairwise distances and variances model parameter must be a Substitution model type from phylo_utils
def prep_hla(work_dir, sample, calls, hlas, normal_bam, tumor_bam): """Convert HLAs into ABSOLUTE format for use with LOHHLA. LOHHLA hard codes names to hla_a, hla_b, hla_c so need to move """ work_dir = utils.safe_makedir(os.path.join(work_dir, sample, "inputs")) hla_file = os.path.join(work_dir, ...
Convert HLAs into ABSOLUTE format for use with LOHHLA. LOHHLA hard codes names to hla_a, hla_b, hla_c so need to move
def evaluation_get(self, service_staff_id, start_date, end_date, session): '''taobao.wangwang.eservice.evaluation.get 客服评价统计 根据操作者ID,返回被查者ID指定日期内每个帐号每日的"客服评价统计" 备注: - 1、如果是操作者ID=被查者ID,返回被查者ID的"客服评价统计"。 - 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"客服评价统计"。 - 3、如果操作者是主账户,他可以...
taobao.wangwang.eservice.evaluation.get 客服评价统计 根据操作者ID,返回被查者ID指定日期内每个帐号每日的"客服评价统计" 备注: - 1、如果是操作者ID=被查者ID,返回被查者ID的"客服评价统计"。 - 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"客服评价统计"。 - 3、如果操作者是主账户,他可以查询所有子帐号的"客服评价统计"。 - 4、被查者ID可以是多个,用 "," 隔开,id数不能超过30。 - 5、开始时间与结束时间之间...
def genealogic_types(self): """ Get genealogic types Returns: Returns a list of all parent types """ types = [] parent = self while parent: types.append(parent.rest_name) parent = parent.parent_object return types
Get genealogic types Returns: Returns a list of all parent types
def _delete(self, namespace, stream, start_id, end_time, configuration): """ Delete events with id > `start_id` and end_time <= `end_time`. """ start_id_event = Event(start_id) end_id_event = Event(uuid_from_kronos_time(end_time, _type=UUIDType.HIGHEST)...
Delete events with id > `start_id` and end_time <= `end_time`.
def delete_lbaas_member(self, lbaas_member, lbaas_pool): """Deletes the specified lbaas_member.""" return self.delete(self.lbaas_member_path % (lbaas_pool, lbaas_member))
Deletes the specified lbaas_member.
def json_minify(string, strip_space=True): # pragma: no cover """Removes whitespace from json strings, returning the string """ in_string = False in_multi = False in_single = False new_str = [] index = 0 for match in re.finditer(TOKENIZER, string): if not (in_multi or in_singl...
Removes whitespace from json strings, returning the string
def removeFriend(self, friend_id=None): """ Removes a specifed friend from your friend list :param friend_id: The ID of the friend that you want to remove :return: Returns error if the removing was unsuccessful, returns True when successful. """ payload = {"friend_id": f...
Removes a specifed friend from your friend list :param friend_id: The ID of the friend that you want to remove :return: Returns error if the removing was unsuccessful, returns True when successful.
def create(obj: PersistedObject, obj_type: Type[T], errors: Dict[Type, Exception]): """ Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests https://github.com/nose-devs/nose/issues/725 :param obj: :param errors: a dictiona...
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests https://github.com/nose-devs/nose/issues/725 :param obj: :param errors: a dictionary of the errors raised for each alternate type tried :return:
def delete_joined_table_sql(qualified_name, removing_qualified_name, primary_key): """SQL statement for a joined delete from. Generate SQL statement for deleting the intersection of rows between both tables from table referenced by tablename. """ condition_template = 't.{}=d.{}' where_clause = ...
SQL statement for a joined delete from. Generate SQL statement for deleting the intersection of rows between both tables from table referenced by tablename.
def parse_colors(path): """Parse the given color files. Supported are: * .txt for X11 colors * .json for colornames """ if path.endswith(".txt"): return parse_rgb_txt_file(path) elif path.endswith(".json"): return parse_json_color_file(path) raise TypeError("col...
Parse the given color files. Supported are: * .txt for X11 colors * .json for colornames
def has_option(self, option_name): """ Check that an option exists. :param str option_name: The name of the option to check. :return: True of the option exists in the configuration. :rtype: bool """ if self.prefix: option_name = self.prefix + self.seperator + option_name item_names = option_name.spl...
Check that an option exists. :param str option_name: The name of the option to check. :return: True of the option exists in the configuration. :rtype: bool
def derive_from_seed(self, offset): """ Derive private key using "generate_from_seed" method. Here, the key itself serves as a `seed`, and `offset` is expected to be a sha256 digest. """ seed = int(hexlify(bytes(self)).decode("ascii"), 16) z = int(hexlify(offset)....
Derive private key using "generate_from_seed" method. Here, the key itself serves as a `seed`, and `offset` is expected to be a sha256 digest.
def __shouldSysExit(self, iteration): """ Checks to see if the model should exit based on the exitAfter dummy parameter """ if self._exitAfter is None \ or iteration < self._exitAfter: return False results = self._jobsDAO.modelsGetFieldsForJob(self._jobID, ['params']) modelID...
Checks to see if the model should exit based on the exitAfter dummy parameter
def items_to_extract(self, offset=0, length=None): """ Return an iterable of specific items to extract. As a side-effect, set self.items_to_extract_length. :param offset: where to start extracting :param length: how many to extract :return: An iterable of the specific ...
Return an iterable of specific items to extract. As a side-effect, set self.items_to_extract_length. :param offset: where to start extracting :param length: how many to extract :return: An iterable of the specific
def team_absent(name, profile="github", **kwargs): ''' Ensure a team is absent. Example: .. code-block:: yaml ensure team test is present in github: github.team_absent: - name: 'test' The following parameters are required: name This is the name o...
Ensure a team is absent. Example: .. code-block:: yaml ensure team test is present in github: github.team_absent: - name: 'test' The following parameters are required: name This is the name of the team in the organization. .. versionadded:: 2016.11....
def findCaller(self, stack_info=False, callers=0): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. Not only ignore this class's and logger's source, but also as many callers as requested. """ f = logging.curr...
Find the stack frame of the caller so that we can note the source file name, line number and function name. Not only ignore this class's and logger's source, but also as many callers as requested.
def _call_lrem(self, command, count, value, *args, **kwargs): """ If count is 0, we remove all elements equal to value, so we know we have nothing to index, and this value to deindex. In other case, we don't know how much elements will remain in the list, so we have to do a full ...
If count is 0, we remove all elements equal to value, so we know we have nothing to index, and this value to deindex. In other case, we don't know how much elements will remain in the list, so we have to do a full deindex/reindex. So do it carefuly.
def ellplot (mjr, mnr, pa): """Utility for debugging.""" _ellcheck (mjr, mnr, pa) import omega as om th = np.linspace (0, 2 * np.pi, 200) x, y = ellpoint (mjr, mnr, pa, th) return om.quickXY (x, y, 'mjr=%f mnr=%f pa=%f' % (mjr, mnr, pa * 180 / np.pi))
Utility for debugging.
def members(self, as_set=False): """Return the set members tuple/frozenset.""" if as_set: return frozenset(map(self._members.__getitem__, self._indexes())) return tuple(map(self._members.__getitem__, self._indexes()))
Return the set members tuple/frozenset.
def get_context_from_xlsx(self): """ Get context from an Excel file """ if re.search('^(http|https)://', self.project.CONTEXT_SOURCE_FILE): resp = requests.get(self.project.CONTEXT_SOURCE_FILE) content = resp.content else: try: ...
Get context from an Excel file
def update_repository(self, repository_form): """Updates an existing repository. arg: repository_form (osid.repository.RepositoryForm): the form containing the elements to be updated raise: IllegalState - ``repository_form`` already used in an update transact...
Updates an existing repository. arg: repository_form (osid.repository.RepositoryForm): the form containing the elements to be updated raise: IllegalState - ``repository_form`` already used in an update transaction raise: InvalidArgument - the form contains a...
def as_list(self): "return some attributes as a list" netloc = '' if self.vpath_connector: netloc = '(('+self.vpath_connector+'))' elif self.authority: netloc = self.authority else: netloc = self.netloc return [ self.scheme,...
return some attributes as a list
def grab_zipped_url(zipped_url, ensure=True, appname='utool', download_dir=None, force_commonprefix=True, cleanup=False, redownload=False, spoof=False): r""" downloads and unzips the url Args: zipped_url (str): url which must be either a .zip of a .tar.gz fil...
r""" downloads and unzips the url Args: zipped_url (str): url which must be either a .zip of a .tar.gz file ensure (bool): eager evaluation if True(default = True) appname (str): (default = 'utool') download_dir (str): containing downloading directory force_commonprefix...
def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout, sep=',', ignored_columns=None, significance=None): """ Print a summary of the difference between the two files. """ from_records = list(records.load(from_csv, sep=sep)) to_records = records.load(to_cs...
Print a summary of the difference between the two files.
def refreshResults( self ): """ Joins together the queries from the fixed system, the search, and the query builder to generate a query for the browser to display. """ if ( self.currentMode() == XOrbBrowserWidget.Mode.Detail ): self.refreshDetails() eli...
Joins together the queries from the fixed system, the search, and the query builder to generate a query for the browser to display.
def _set_collector_ip(self, v, load=False): """ Setter method for collector_ip, mapped from YANG variable /telemetry/collector/collector_ip (container) If this variable is read-only (config: false) in the source YANG file, then _set_collector_ip is considered as a private method. Backends looking to...
Setter method for collector_ip, mapped from YANG variable /telemetry/collector/collector_ip (container) If this variable is read-only (config: false) in the source YANG file, then _set_collector_ip is considered as a private method. Backends looking to populate this variable should do so via calling thi...
def is_dec(ip): """Return true if the IP address is in decimal notation.""" try: dec = int(str(ip)) except ValueError: return False if dec > 4294967295 or dec < 0: return False return True
Return true if the IP address is in decimal notation.
def check_membership(self, groups): ''' Allows for objects with no required groups ''' if not groups or groups == ['']: return True if self.request.user.is_superuser: return True user_groups = self.request.user.groups.values_list("name", flat=True) ...
Allows for objects with no required groups
def connect(self, output_port, input_port): """ Connect two :class:`.Effect` instances in this pedalboard. For this, is necessary informs the output port origin and the input port destination:: >>> pedalboard.append(driver) >>> pedalboard.append(reverb) >>> d...
Connect two :class:`.Effect` instances in this pedalboard. For this, is necessary informs the output port origin and the input port destination:: >>> pedalboard.append(driver) >>> pedalboard.append(reverb) >>> driver_output = driver.outputs[0] >>> reverb_input = ...
def get_hla(sample, cromwell_dir, hla_glob): """Retrieve HLA calls and input fastqs for a sample. """ hla_dir = glob.glob(os.path.join(cromwell_dir, hla_glob, "align", sample, "hla"))[0] fastq = os.path.join(hla_dir, "OptiType-HLA-A_B_C-input.fq") calls = os.path.join(hla_dir, "%s-optitype.csv" % sa...
Retrieve HLA calls and input fastqs for a sample.
def set_max_image_pixels(self, pixels): """Set PIL limit on pixel size of images to load if non-zero. WARNING: This is a global setting in PIL, it is not local to this manipulator instance! Setting a value here will not only set the given limit but also convert the PIL "Decompr...
Set PIL limit on pixel size of images to load if non-zero. WARNING: This is a global setting in PIL, it is not local to this manipulator instance! Setting a value here will not only set the given limit but also convert the PIL "DecompressionBombWarning" into an error. Thus sett...
def _compute_stddevs(self, C, mag, rjb, imt, stddev_types): """ Compute total standard deviation, equations 5 and 6, page 48. """ # aleatory uncertainty sigma_ale_m = np.interp(mag, [5.0, 5.5, 8.0], [C['m50'], C['m55'], C['m80']]) sigma_ale...
Compute total standard deviation, equations 5 and 6, page 48.