code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def search_value(self, xpath, default=None, single_value=True): """ Try to find a value in the result :param str xpath: a xpath filter see https://github.com/kennknowles/python-jsonpath-rw#jsonpath-syntax :param any default: default value if not found :param bool single_value: is the re...
Try to find a value in the result :param str xpath: a xpath filter see https://github.com/kennknowles/python-jsonpath-rw#jsonpath-syntax :param any default: default value if not found :param bool single_value: is the result is multivalued :return: the value found or None
def visit_Call(self, node): """ Transform call site to have normal function call. Examples -------- For methods: >> a = [1, 2, 3] >> a.append(1) Becomes >> __list__.append(a, 1) For functions: >> __builtin__.dict.fromkeys([1, ...
Transform call site to have normal function call. Examples -------- For methods: >> a = [1, 2, 3] >> a.append(1) Becomes >> __list__.append(a, 1) For functions: >> __builtin__.dict.fromkeys([1, 2, 3]) Becomes >> __builtin__....
def removeXmlElement(name, directory, file_pattern, logger=None): """ Recursively walk a directory and remove XML elements """ for path, dirs, files in os.walk(os.path.abspath(directory)): for filename in fnmatch.filter(files, file_pattern): filepath = os.path.join(path, filename) ...
Recursively walk a directory and remove XML elements
def get_exchange_group_info(self, symprec=1e-2, angle_tolerance=5.0): """ Returns the information on the symmetry of the Hamiltonian describing the exchange energy of the system, taking into account relative direction of magnetic moments but not their absolute direction. ...
Returns the information on the symmetry of the Hamiltonian describing the exchange energy of the system, taking into account relative direction of magnetic moments but not their absolute direction. This is not strictly accurate (e.g. some/many atoms will have zero magnetic momen...
def _validate_slices_form_uniform_grid(slice_datasets): ''' Perform various data checks to ensure that the list of slices form a evenly-spaced grid of data. Some of these checks are probably not required if the data follows the DICOM specification, however it seems pertinent to check anyway. '''...
Perform various data checks to ensure that the list of slices form a evenly-spaced grid of data. Some of these checks are probably not required if the data follows the DICOM specification, however it seems pertinent to check anyway.
def CWDE(cpu): """ Converts word to doubleword. :: DX = sign-extend of AX. :param cpu: current CPU. """ bit = Operators.EXTRACT(cpu.AX, 15, 1) cpu.EAX = Operators.SEXTEND(cpu.AX, 16, 32) cpu.EDX = Operators.SEXTEND(bit, 1, 32)
Converts word to doubleword. :: DX = sign-extend of AX. :param cpu: current CPU.
def make_multisig_segwit_wallet( m, n ): """ Create a bundle of information that can be used to generate an m-of-n multisig witness script. """ pks = [] for i in xrange(0, n): pk = BitcoinPrivateKey(compressed=True).to_wif() pks.append(pk) return make_multisig_segwit_inf...
Create a bundle of information that can be used to generate an m-of-n multisig witness script.
def diff(candidate, running, *models): ''' Returns the difference between two configuration entities structured according to the YANG model. .. note:: This function is recommended to be used mostly as a state helper. candidate First model to compare. running Second mod...
Returns the difference between two configuration entities structured according to the YANG model. .. note:: This function is recommended to be used mostly as a state helper. candidate First model to compare. running Second model to compare. models A list of models...
def read_stb(library, session): """Reads a status byte of the service request. Corresponds to viReadSTB function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :return: Service request status byte, return value of th...
Reads a status byte of the service request. Corresponds to viReadSTB function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :return: Service request status byte, return value of the library call. :rtype: int, :class...
def transform(self, X): """Transform a sequence of documents to a document-term matrix. Transformation is done in parallel, and correctly handles dask collections. Parameters ---------- X : dask.Bag of raw text documents, length = n_samples Samples. Each sam...
Transform a sequence of documents to a document-term matrix. Transformation is done in parallel, and correctly handles dask collections. Parameters ---------- X : dask.Bag of raw text documents, length = n_samples Samples. Each sample must be a text document (either...
def get_runs_by_id(self, config_id): """ returns a list of runs for a given config id The runs are sorted by ascending budget, so '-1' will give the longest run for this config. """ d = self.data[config_id] runs = [] for b in d.results.keys(): try: err_logs = d.exceptions.get(b, None) if d...
returns a list of runs for a given config id The runs are sorted by ascending budget, so '-1' will give the longest run for this config.
def target_query(plugin, port, location): """ prepared ReQL for target """ return ((r.row[PLUGIN_NAME_KEY] == plugin) & (r.row[PORT_FIELD] == port) & (r.row[LOCATION_FIELD] == location))
prepared ReQL for target
def _verify_signed_jwt_with_certs( jwt, time_now, cache, cert_uri=_DEFAULT_CERT_URI): """Verify a JWT against public certs. See http://self-issued.info/docs/draft-jones-json-web-token.html. The PyCrypto library included with Google App Engine is severely limited and so you have to use it very carefull...
Verify a JWT against public certs. See http://self-issued.info/docs/draft-jones-json-web-token.html. The PyCrypto library included with Google App Engine is severely limited and so you have to use it very carefully to verify JWT signatures. The first issue is that the library can't read X.509 files, so we mak...
def dump(destination, xs, model=None, properties=False, indent=True, **kwargs): """ Serialize Xmrs (or subclass) objects to PENMAN and write to a file. Args: destination: filename or file object xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to serialize model: ...
Serialize Xmrs (or subclass) objects to PENMAN and write to a file. Args: destination: filename or file object xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to serialize model: Xmrs subclass used to get triples properties: if `True`, encode variable properties ...
def addChild(self,item): """ When you add a child to a Node, you are adding yourself as a parent to the child You cannot have the same node as a child more than once. If you add a Node, it is used. If you add a non-node, a new child Node is created. Thus: You cannot add a child as an item which is a...
When you add a child to a Node, you are adding yourself as a parent to the child You cannot have the same node as a child more than once. If you add a Node, it is used. If you add a non-node, a new child Node is created. Thus: You cannot add a child as an item which is a Node. (You can, however, construct s...
def length(self): """Total surveyed cave length, not including splays.""" return sum([shot.length for shot in self.shots if not shot.is_splay])
Total surveyed cave length, not including splays.
def iter(self, match="*", count=1000): """ Iterates the set of keys in :prop:key_prefix in :prop:_client @match: #str pattern to match after the :prop:key_prefix @count: the user specified the amount of work that should be done at every call in order to retrieve elements ...
Iterates the set of keys in :prop:key_prefix in :prop:_client @match: #str pattern to match after the :prop:key_prefix @count: the user specified the amount of work that should be done at every call in order to retrieve elements from the collection -> yields redis ke...
def _prepare_data_payload(data): """ Make a copy of the `data` object, preparing it to be sent to the server. The data will be sent via x-www-form-urlencoded or multipart/form-data mechanisms. Both of them work with plain lists of key/value pairs, so this method converts the data into s...
Make a copy of the `data` object, preparing it to be sent to the server. The data will be sent via x-www-form-urlencoded or multipart/form-data mechanisms. Both of them work with plain lists of key/value pairs, so this method converts the data into such format.
def get_banks_by_assessment_taken(self, assessment_taken_id): """Gets the list of ``Banks`` mapped to an ``AssessmentTaken``. arg: assessment_taken_id (osid.id.Id): ``Id`` of an ``AssessmentTaken`` return: (osid.assessment.BankList) - list of banks raise: NotFound - ...
Gets the list of ``Banks`` mapped to an ``AssessmentTaken``. arg: assessment_taken_id (osid.id.Id): ``Id`` of an ``AssessmentTaken`` return: (osid.assessment.BankList) - list of banks raise: NotFound - ``assessment_taken_id`` is not found raise: NullArgument - ``ass...
def collect_phrases (sent, ranks, spacy_nlp): """ iterator for collecting the noun phrases """ tail = 0 last_idx = sent[0].idx - 1 phrase = [] while tail < len(sent): w = sent[tail] if (w.word_id > 0) and (w.root in ranks) and ((w.idx - last_idx) == 1): # keep c...
iterator for collecting the noun phrases
def mem(args, opts): """ %prog mem database.fasta read1.fq [read2.fq] Wrapper for `bwa mem`. Output will be read1.sam. """ dbfile, read1file = args[:2] readtype = opts.readtype pl = readtype or "illumina" pf = op.basename(read1file).split(".")[0] rg = opts.rg or r"@RG\tID:{0}\tSM:s...
%prog mem database.fasta read1.fq [read2.fq] Wrapper for `bwa mem`. Output will be read1.sam.
def setmode(mode): """ You must call this method prior to using all other calls. :param mode: the mode, one of :py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM`, :py:attr:`GPIO.SUNXI`, or a `dict` or `object` representing a custom pin mapping. """ if hasattr(mode, '__getitem__'): s...
You must call this method prior to using all other calls. :param mode: the mode, one of :py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM`, :py:attr:`GPIO.SUNXI`, or a `dict` or `object` representing a custom pin mapping.
def placeholders(cls,dic): """Placeholders for fields names and value binds""" keys = [str(x) for x in dic] entete = ",".join(keys) placeholders = ",".join(cls.named_style.format(x) for x in keys) entete = f"({entete})" placeholders = f"({placeholders})" return en...
Placeholders for fields names and value binds
def _function(self): """ Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click. """ start_time = datetime.datetime.now() # calculate stop time if self.settings['wait_mode'] == 'absolute': stop_time = start_time...
Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click.
def requires_lock(function): """ Decorator to check if the user owns the required lock. The first argument must be the filename. """ def new_lock_requiring_function(self, filename, *args, **kwargs): if self.owns_lock(filename): return function(self, filename, *args, **kwargs) ...
Decorator to check if the user owns the required lock. The first argument must be the filename.
def set_window_pos_callback(window, cbfun): """ Sets the position callback for the specified window. Wrapper for: GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes...
Sets the position callback for the specified window. Wrapper for: GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun);
def compute_gaussian_krnl(M): """Creates a gaussian kernel following Foote's paper.""" g = signal.gaussian(M, M // 3., sym=True) G = np.dot(g.reshape(-1, 1), g.reshape(1, -1)) G[M // 2:, :M // 2] = -G[M // 2:, :M // 2] G[:M // 2, M // 2:] = -G[:M // 2, M // 2:] return G
Creates a gaussian kernel following Foote's paper.
def getsockopt(self, level, optname, *args, **kwargs): """get the value of a given socket option the values for ``level`` and ``optname`` will usually come from constants in the standard library ``socket`` module. consult the unix manpage ``getsockopt(2)`` for more information. ...
get the value of a given socket option the values for ``level`` and ``optname`` will usually come from constants in the standard library ``socket`` module. consult the unix manpage ``getsockopt(2)`` for more information. :param level: the level of the requested socket option :t...
def essl(lw): """ESS (Effective sample size) computed from log-weights. Parameters ---------- lw: (N,) ndarray log-weights Returns ------- float the ESS of weights w = exp(lw), i.e. the quantity sum(w**2) / (sum(w))**2 Note ---- The ESS is a popula...
ESS (Effective sample size) computed from log-weights. Parameters ---------- lw: (N,) ndarray log-weights Returns ------- float the ESS of weights w = exp(lw), i.e. the quantity sum(w**2) / (sum(w))**2 Note ---- The ESS is a popular criterion to determ...
def dskmi2(vrtces, plates, finscl, corscl, worksz, voxpsz, voxlsz, makvtl, spxisz): """ Make spatial index for a DSK type 2 segment. The index is returned as a pair of arrays, one of type int and one of type float. These arrays are suitable for use with the DSK type 2 writer dskw02. http://naif...
Make spatial index for a DSK type 2 segment. The index is returned as a pair of arrays, one of type int and one of type float. These arrays are suitable for use with the DSK type 2 writer dskw02. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskmi2_c.html :param vrtces: Vertices :typ...
def main(): """This is the mainline. It first invokes the pipermail archiver to add the message to the archive, then calls the function above to do whatever with the archived message after it's URL and path are known. """ listname = sys.argv[2] hostname = sys.argv[1] # We must get the...
This is the mainline. It first invokes the pipermail archiver to add the message to the archive, then calls the function above to do whatever with the archived message after it's URL and path are known.
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by ...
Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by the template :index: current ind...
def update_ff(self, ff, mol2=False, force_ff_assign=False): """Manages assigning the force field parameters. The aim of this method is to avoid unnecessary assignment of the force field. Parameters ---------- ff: BuffForceField The force field to be used for...
Manages assigning the force field parameters. The aim of this method is to avoid unnecessary assignment of the force field. Parameters ---------- ff: BuffForceField The force field to be used for scoring. mol2: bool, optional If true, mol2 style ...
def from_json_and_lambdas(cls, file: str, lambdas): """Builds a GrFN from a JSON object. Args: cls: The class variable for object creation. file: Filename of a GrFN JSON file. Returns: type: A GroundedFunctionNetwork object. """ with open(fi...
Builds a GrFN from a JSON object. Args: cls: The class variable for object creation. file: Filename of a GrFN JSON file. Returns: type: A GroundedFunctionNetwork object.
def get_ec_names(ecfile, fasta_names): """ convert equivalence classes to their set of transcripts """ df = pd.read_table(ecfile, header=None, names=["ec", "transcripts"]) transcript_groups = [x.split(",") for x in df["transcripts"]] transcripts = [] for group in transcript_groups: t...
convert equivalence classes to their set of transcripts
def pprint(self, imports=None, prefix="\n ",unknown_value='<?>', qualify=False, separator=""): """ Same as Parameterized.pprint, except that X.classname(Y is replaced with X.classname.instance(Y """ r = Parameterized.pprint(self,imports,prefix, ...
Same as Parameterized.pprint, except that X.classname(Y is replaced with X.classname.instance(Y
def assemble(experiments, backend=None, qobj_id=None, qobj_header=None, # common run options shots=1024, memory=False, max_credits=None, seed_simulator=None, default_qubit_los=None, default_meas_los=None, # schedule run options schedule_los=None, meas_l...
Assemble a list of circuits or pulse schedules into a Qobj. This function serializes the payloads, which could be either circuits or schedules, to create Qobj "experiments". It further annotates the experiment payload with header and configurations. Args: experiments (QuantumCircuit or list[Qu...
def format_subpages(self, page, subpages): """Banana banana """ if not subpages: return None try: template = self.get_template('subpages.html') except IOError: return None ret = etree.XML(template.render({'page': page, ...
Banana banana
def Q(self): """ The quality factor of the scale, or, the ratio of center frequencies to bandwidths """ return np.array(list(self.center_frequencies)) \ / np.array(list(self.bandwidths))
The quality factor of the scale, or, the ratio of center frequencies to bandwidths
def recursive_build_tree(self, intervals): """ recursively builds a BST based on the elementary intervals. each node is an array: [interval value, left descendent nodes, right descendent nodes, [ids]]. nodes with no descendents have a -1 value in left/right descendent positions. ...
recursively builds a BST based on the elementary intervals. each node is an array: [interval value, left descendent nodes, right descendent nodes, [ids]]. nodes with no descendents have a -1 value in left/right descendent positions. for example, a node with two empty descendents: [5...
def destroy(self, force=False): """ Like shutdown(), but also removes all accounts, hosts, etc., and does not restart the queue. In other words, the queue can no longer be used after calling this method. :type force: bool :param force: Whether to wait until all jobs wer...
Like shutdown(), but also removes all accounts, hosts, etc., and does not restart the queue. In other words, the queue can no longer be used after calling this method. :type force: bool :param force: Whether to wait until all jobs were processed.
def lease(self, lease_time, num_tasks, group_by_tag=False, tag=None, client=None): """ Acquires a lease on the topmost N unowned tasks in the specified queue. :type lease_time: int :param lease_time: How long to lease this task, in seconds. :type num_tasks: int :param num_tasks...
Acquires a lease on the topmost N unowned tasks in the specified queue. :type lease_time: int :param lease_time: How long to lease this task, in seconds. :type num_tasks: int :param num_tasks: The number of tasks to lease. :type group_by_tag: bool :param group_by_tag: ...
def compare(args): """ Compare the extant river with the given name to the passed JSON. The command will exit with a return code of 0 if the named river is configured as specified, and 1 otherwise. """ data = json.load(sys.stdin) m = RiverManager(args.hosts) if m.compare(args.name, data)...
Compare the extant river with the given name to the passed JSON. The command will exit with a return code of 0 if the named river is configured as specified, and 1 otherwise.
def adjustSizeConstraint(self): """ Adjusts the min/max size based on the current tab. """ widget = self.currentWidget() if not widget: return offw = 4 offh = 4 #if self.tabBar().isVisible(): # offh += 20 # tab ...
Adjusts the min/max size based on the current tab.
def delete_last_line(self, file_path='', date=str(datetime.date.today())): """ The following code was modified from http://stackoverflow.com/a/10289740 & http://stackoverflow.com/a/17309010 It essentially will check if the total for the current date already exists in tota...
The following code was modified from http://stackoverflow.com/a/10289740 & http://stackoverflow.com/a/17309010 It essentially will check if the total for the current date already exists in total.csv. If it does, it just removes the last line. This is so the script could be run mo...
def get(data_label=None, destination_dir="."): """ Download sample data by data label. Labels can be listed by sample_data.data_urls.keys() :param data_label: label of data. If it is set to None, all data are downloaded :param destination_dir: output dir for data :return: """ try: os...
Download sample data by data label. Labels can be listed by sample_data.data_urls.keys() :param data_label: label of data. If it is set to None, all data are downloaded :param destination_dir: output dir for data :return:
def are_domains_equal(domain1, domain2): """Compare two International Domain Names. :Parameters: - `domain1`: domains name to compare - `domain2`: domains name to compare :Types: - `domain1`: `unicode` - `domain2`: `unicode` :return: True `domain1` and `domain2` are equ...
Compare two International Domain Names. :Parameters: - `domain1`: domains name to compare - `domain2`: domains name to compare :Types: - `domain1`: `unicode` - `domain2`: `unicode` :return: True `domain1` and `domain2` are equal as domain names.
def authorized(resp, remote): """Authorized callback handler for GitHub. :param resp: The response. :param remote: The remote application. """ if resp and 'error' in resp: if resp['error'] == 'bad_verification_code': # See https://developer.github.com/v3/oauth/#bad-verification-...
Authorized callback handler for GitHub. :param resp: The response. :param remote: The remote application.
def formatday(self, day, weekday): """Return a day as a table cell.""" super(MiniEventCalendar, self).formatday(day, weekday) now = get_now() self.day = day if day == 0: return '<td class="noday">&nbsp;</td>' # day outside month elif now.month == self.mo and...
Return a day as a table cell.
def load(self): """ Extract tabular data as |TableData| instances from a CSV text object. |load_source_desc_text| :return: Loaded table data. |load_table_name_desc| =================== ======================================== Format spec...
Extract tabular data as |TableData| instances from a CSV text object. |load_source_desc_text| :return: Loaded table data. |load_table_name_desc| =================== ======================================== Format specifier Value after the replacemen...
def objects_reachable_from(obj): """ Return graph of objects reachable from *obj* via ``gc.get_referrers``. Returns an :class:`~refcycle.object_graph.ObjectGraph` object holding all objects reachable from the given one by following the output of ``gc.get_referrers``. Note that unlike the :func...
Return graph of objects reachable from *obj* via ``gc.get_referrers``. Returns an :class:`~refcycle.object_graph.ObjectGraph` object holding all objects reachable from the given one by following the output of ``gc.get_referrers``. Note that unlike the :func:`~refcycle.creators.snapshot` function, the ...
def buy_open_order_quantity(self): """ [int] 买方向挂单量 """ return sum(order.unfilled_quantity for order in self.open_orders if order.side == SIDE.BUY and order.position_effect == POSITION_EFFECT.OPEN)
[int] 买方向挂单量
def emailclients(self, tag=None, fromdate=None, todate=None): """ Gets an overview of the email clients used to open your emails. This is only recorded when open tracking is enabled for that email. """ return self.call("GET", "/stats/outbound/opens/emailclients", tag=tag, fromdat...
Gets an overview of the email clients used to open your emails. This is only recorded when open tracking is enabled for that email.
def start(self, **kwargs): """ Start this container. Similar to the ``docker start`` command, but doesn't support attach options. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ return self.client.api.start(self....
Start this container. Similar to the ``docker start`` command, but doesn't support attach options. Raises: :py:class:`docker.errors.APIError` If the server returns an error.
def get_hacr_channels(db=None, gps=None, connection=None, **conectkwargs): """Return the names of all channels present in the given HACR database """ # connect if needed if connection is None: if gps is None: gps = from_gps('now') if db is None: ...
Return the names of all channels present in the given HACR database
def get(self, cls, id_field, id_val): """ Retrieve an object which `id_field` matches `id_val`. If it exists in the cache, it will be fetched from Redis. If not, it will be fetched via the `fetch` method and cached in Redis (unless the cache flag got invalidated in the meantime)....
Retrieve an object which `id_field` matches `id_val`. If it exists in the cache, it will be fetched from Redis. If not, it will be fetched via the `fetch` method and cached in Redis (unless the cache flag got invalidated in the meantime).
def disconnect_container_from_network(container, network_id): ''' .. versionadded:: 2015.8.3 Disconnect container from network container Container name or ID network_id Network name or ID CLI Examples: .. code-block:: bash salt myminion docker.disconnect_contain...
.. versionadded:: 2015.8.3 Disconnect container from network container Container name or ID network_id Network name or ID CLI Examples: .. code-block:: bash salt myminion docker.disconnect_container_from_network web-1 mynet salt myminion docker.disconnect_contai...
def format_property(name, value): """Format the name and value (both unicode) of a property as a string.""" result = b'' utf8_name = utf8_bytes_string(name) result = b'property ' + utf8_name if value is not None: utf8_value = utf8_bytes_string(value) result += b' ' + ('%d' % len(utf...
Format the name and value (both unicode) of a property as a string.
def get_astrom(official='%',provisional='%'): """Query the measure table for all measurements of a particular object. Default is to return all the astrometry in the measure table, sorted by mjdate""" sql= "SELECT m.* FROM measure m " sql+="LEFT JOIN object o ON m.provisional LIKE o.provisional " ...
Query the measure table for all measurements of a particular object. Default is to return all the astrometry in the measure table, sorted by mjdate
def get_realms_and_credentials(self, uri, http_method='GET', body=None, headers=None): """Fetch realms and credentials for the presented request token. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, H...
Fetch realms and credentials for the presented request token. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :returns:...
def _removeSegment(self, segment, preserveCurve, **kwargs): """ segment will be a valid segment index. preserveCurve will be a boolean. Subclasses may override this method. """ segment = self.segments[segment] for point in segment.points: self.removeP...
segment will be a valid segment index. preserveCurve will be a boolean. Subclasses may override this method.
def try_utf8_decode(value): """Try to decode an object. :param value: :return: """ if not value or not is_string(value): return value elif PYTHON3 and not isinstance(value, bytes): return value elif not PYTHON3 and not isinstance(value, unicode): return value tr...
Try to decode an object. :param value: :return:
def read_bitpacked_deprecated(file_obj, byte_count, count, width, debug_logging): """Read `count` values from `fo` using the deprecated bitpacking encoding.""" raw_bytes = array.array(ARRAY_BYTE_STR, file_obj.read(byte_count)).tolist() mask = _mask_for_bits(width) index = 0 res = [] word = 0 ...
Read `count` values from `fo` using the deprecated bitpacking encoding.
def do_cspvarica(self, varfit='ensemble', random_state=None): """ Perform CSPVARICA Perform CSPVARICA source decomposition and VAR model fitting. Parameters ---------- varfit : string Determines how to calculate the residuals for source decomposition. 'e...
Perform CSPVARICA Perform CSPVARICA source decomposition and VAR model fitting. Parameters ---------- varfit : string Determines how to calculate the residuals for source decomposition. 'ensemble' (default) fits one model to the whole data set, 'clas...
def timezone(self): """The name of the time zone for the location. A list of time zone names can be obtained from pytz. For example. >>> from pytz import all_timezones >>> for timezone in all_timezones: ... print(timezone) """ if not self._timezone_group an...
The name of the time zone for the location. A list of time zone names can be obtained from pytz. For example. >>> from pytz import all_timezones >>> for timezone in all_timezones: ... print(timezone)
def ancestral_states(self, n): """ Generate ancestral sequence states from the equilibrium frequencies """ anc = np.empty(n, dtype=np.intc) _weighted_choices(self.state_indices, self.freqs, anc) return anc
Generate ancestral sequence states from the equilibrium frequencies
def asset_view_prj(self, ): """View the project of the current asset :returns: None :rtype: None :raises: None """ if not self.cur_asset: return prj = self.cur_asset.project self.view_prj(prj)
View the project of the current asset :returns: None :rtype: None :raises: None
def image_plane_pix_grid_from_regular_grid(self, regular_grid): """Calculate the image-plane pixelization from a regular-grid of coordinates (and its mask). See *grid_stacks.SparseToRegularGrid* for details on how this grid is calculated. Parameters ----------- regular_grid : g...
Calculate the image-plane pixelization from a regular-grid of coordinates (and its mask). See *grid_stacks.SparseToRegularGrid* for details on how this grid is calculated. Parameters ----------- regular_grid : grids.RegularGrid The grid of (y,x) arc-second coordinates at th...
def accept_ws(buf, pos): """Skip whitespace at the current buffer position.""" match = re_ws.match(buf, pos) if not match: return None, pos return buf[match.start(0):match.end(0)], match.end(0)
Skip whitespace at the current buffer position.
def should_recover(self): """Returns whether the trial qualifies for restoring. This is if a checkpoint frequency is set and has not failed more than max_failures. This may return true even when there may not yet be a checkpoint. """ return (self.checkpoint_freq > 0 ...
Returns whether the trial qualifies for restoring. This is if a checkpoint frequency is set and has not failed more than max_failures. This may return true even when there may not yet be a checkpoint.
def use_pickle(): """Revert to using stdlib pickle. Reverts custom serialization enabled by use_dill|cloudpickle. """ from . import serialize serialize.pickle = serialize._stdlib_pickle # restore special function handling can_map[FunctionType] = _original_can_map[FunctionType]
Revert to using stdlib pickle. Reverts custom serialization enabled by use_dill|cloudpickle.
def wind_series(self): """Returns the wind speed time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples """ return [(timestamp, \ self._station_history.get_measu...
Returns the wind speed time series relative to the meteostation, in the form of a list of tuples, each one containing the couple timestamp-value :returns: a list of tuples
def fromdict(dict): """Takes a dictionary as an argument and returns a new Challenge object from the dictionary. :param dict: the dictionary to convert """ seed = hb_decode(dict['seed']) index = dict['index'] return Challenge(seed, index)
Takes a dictionary as an argument and returns a new Challenge object from the dictionary. :param dict: the dictionary to convert
def session_to_hour(timestamp): """:param timestamp: as string in YYYYMMDDHHmmSS format :return string in YYYYMMDDHH format""" t = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN) return t.strftime(SYNERGY_HOURLY_PATTERN)
:param timestamp: as string in YYYYMMDDHHmmSS format :return string in YYYYMMDDHH format
def _http_headers(self): """Return dictionary of http headers necessary for making an http connection to the endpoint of this Connection. :return: Dictionary of headers """ if not self.usertag: return {} creds = u'{}:{}'.format( self.usertag, ...
Return dictionary of http headers necessary for making an http connection to the endpoint of this Connection. :return: Dictionary of headers
def CheckAccess(self, token): """Enforce a dual approver policy for access.""" namespace, _ = self.urn.Split(2) if namespace != "ACL": raise access_control.UnauthorizedAccess( "Approval object has invalid urn %s." % self.urn, subject=self.urn, requested_access=token.requ...
Enforce a dual approver policy for access.
def combine_sample_regions(*samples): """Create batch-level sets of callable regions for multi-sample calling. Intersects all non-callable (nblock) regions from all samples in a batch, producing a global set of callable regions. """ samples = utils.unpack_worlds(samples) samples = cwlutils.unpa...
Create batch-level sets of callable regions for multi-sample calling. Intersects all non-callable (nblock) regions from all samples in a batch, producing a global set of callable regions.
def power_off(env, identifier, hard): """Power off an active virtual server.""" virtual_guest = env.client['Virtual_Guest'] vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not (env.skip_confirmations or formatting.confirm('This will...
Power off an active virtual server.
def _convert(cls, record): """ Core method of the converter. Converts a single dictionary into another dictionary. """ if not record: return {} converted_dict = {} for field in cls.conversion: key = field[0] if len(field) >= 2 and fiel...
Core method of the converter. Converts a single dictionary into another dictionary.
def on_redraw(self): """ Called when the Layer should be redrawn. If a subclass uses the :py:meth:`initialize()` Method, it is very important to also call the Super Class Method to prevent crashes. """ super(WidgetLayer,self).on_redraw() if not self._initialized:...
Called when the Layer should be redrawn. If a subclass uses the :py:meth:`initialize()` Method, it is very important to also call the Super Class Method to prevent crashes.
def Wp(self): """Total energy in protons """ Wp = trapz_loglog(self._Ep * self._J, self._Ep) * u.GeV return Wp.to("erg")
Total energy in protons
def skip(self, num_bytes): """Jump the ahead the specified bytes in the buffer.""" if num_bytes is None: self._offset = len(self._data) else: self._offset += num_bytes
Jump the ahead the specified bytes in the buffer.
def _add_child(self, child, logical_block_size, allow_duplicate, check_overflow): # type: (DirectoryRecord, int, bool, bool) -> bool ''' An internal method to add a child to this object. Note that this is called both during parsing and when adding a new object to the system, so it ...
An internal method to add a child to this object. Note that this is called both during parsing and when adding a new object to the system, so it it shouldn't have any functionality that is not appropriate for both. Parameters: child - The child directory record object to add. ...
def prepare_inputseries(self, ramflag: bool = True) -> None: """Call method |Element.prepare_inputseries| of all handled |Element| objects.""" for element in printtools.progressbar(self): element.prepare_inputseries(ramflag)
Call method |Element.prepare_inputseries| of all handled |Element| objects.
def lvdisplay(lvname='', quiet=False): ''' Return information about the logical volume(s) lvname logical device name quiet if the logical volume is not present, do not show any error CLI Examples: .. code-block:: bash salt '*' lvm.lvdisplay salt '*' lvm.lvdis...
Return information about the logical volume(s) lvname logical device name quiet if the logical volume is not present, do not show any error CLI Examples: .. code-block:: bash salt '*' lvm.lvdisplay salt '*' lvm.lvdisplay /dev/vg_myserver/root
def _process_field_queries(field_dictionary): """ We have a field_dictionary - we want to match the values for an elasticsearch "match" query This is only potentially useful when trying to tune certain search operations """ def field_item(field): """ format field match as "match" item for el...
We have a field_dictionary - we want to match the values for an elasticsearch "match" query This is only potentially useful when trying to tune certain search operations
def assemble(asmcode, pc=0, fork=DEFAULT_FORK): """ Assemble an EVM program :param asmcode: an evm assembler program :type asmcode: str :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork name (optional) :type fork: str ...
Assemble an EVM program :param asmcode: an evm assembler program :type asmcode: str :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork name (optional) :type fork: str :return: the hex representation of the bytecode ...
def read_mail(window): """ Reads late emails from IMAP server and displays them in the Window :param window: window to display emails in :return: """ mail = imaplib.IMAP4_SSL(IMAP_SERVER) (retcode, capabilities) = mail.login(LOGIN_EMAIL, LOGIN_PASSWORD) mail.list() typ, data = mail....
Reads late emails from IMAP server and displays them in the Window :param window: window to display emails in :return:
def download_unzip(names=None, normalize_filenames=False, verbose=True): r""" Download CSV or HTML tables listed in `names`, unzip and to DATA_PATH/`names`.csv .txt etc TODO: move to web or data_utils or futils Also normalizes file name extensions (.bin.gz -> .w2v.bin.gz). Uses table in data_info.csv (...
r""" Download CSV or HTML tables listed in `names`, unzip and to DATA_PATH/`names`.csv .txt etc TODO: move to web or data_utils or futils Also normalizes file name extensions (.bin.gz -> .w2v.bin.gz). Uses table in data_info.csv (internal DATA_INFO) to determine URL or file path from dataset name. Also...
def convert_to_string(data, headers, **_): """Convert all *data* and *headers* to strings. Binary data that cannot be decoded is converted to a hexadecimal representation via :func:`binascii.hexlify`. :param iterable data: An :term:`iterable` (e.g. list) of rows. :param iterable headers: The colum...
Convert all *data* and *headers* to strings. Binary data that cannot be decoded is converted to a hexadecimal representation via :func:`binascii.hexlify`. :param iterable data: An :term:`iterable` (e.g. list) of rows. :param iterable headers: The column headers. :return: The processed data and hea...
def add_actors(self, doc:Document, event: str, cameo_code: int) -> List[Document]: """ Each event has two actors. The relationship of the event to the actors depends on the cameo code and is defined by the mapping. Args: doc: the document containing the evence eve...
Each event has two actors. The relationship of the event to the actors depends on the cameo code and is defined by the mapping. Args: doc: the document containing the evence event: one of "event1", "event2", or "event3" cameo_code: Returns: the documents crea...
def createNotification(self, ulOverlayHandle, ulUserValue, type_, pchText, style): """ Create a notification and enqueue it to be shown to the user. An overlay handle is required to create a notification, as otherwise it would be impossible for a user to act on it. To create a two-line n...
Create a notification and enqueue it to be shown to the user. An overlay handle is required to create a notification, as otherwise it would be impossible for a user to act on it. To create a two-line notification, use a line break ('\n') to split the text into two lines. The pImage argument may ...
def is_ancestor_of_repository(self, id_, repository_id): """Tests if an ``Id`` is an ancestor of a repository. arg: id (osid.id.Id): an ``Id`` arg: repository_id (osid.id.Id): the Id of a repository return: (boolean) - ``true`` if this ``id`` is an ancestor of ``re...
Tests if an ``Id`` is an ancestor of a repository. arg: id (osid.id.Id): an ``Id`` arg: repository_id (osid.id.Id): the Id of a repository return: (boolean) - ``true`` if this ``id`` is an ancestor of ``repository_id,`` ``false`` otherwise raise: NotFound - ``rep...
def parse_personalities(personalities_line): """Parse the "personalities" line of ``/proc/mdstat``. Lines are expected to be like: Personalities : [linear] [raid0] [raid1] [raid5] [raid4] [raid6] If they do not have this format, an error will be raised since it would be considered an unexpect...
Parse the "personalities" line of ``/proc/mdstat``. Lines are expected to be like: Personalities : [linear] [raid0] [raid1] [raid5] [raid4] [raid6] If they do not have this format, an error will be raised since it would be considered an unexpected parsing error. Parameters ---------- ...
def noise_despike(sig, win=3, nlim=24., maxiter=4): """ Apply standard deviation filter to remove anomalous values. Parameters ---------- win : int The window used to calculate rolling statistics. nlim : float The number of standard deviations above the rolling mean abov...
Apply standard deviation filter to remove anomalous values. Parameters ---------- win : int The window used to calculate rolling statistics. nlim : float The number of standard deviations above the rolling mean above which data are considered outliers. Returns ------- ...
def from_dict(cls, serialized): '''Create an error from a JSON-deserialized object @param serialized the object holding the serialized error {dict} ''' # Some servers return lower case field names for message and code. # The Go client is tolerant of this, so be similarly tolerant...
Create an error from a JSON-deserialized object @param serialized the object holding the serialized error {dict}
def store_memory_object(self, mo, overwrite=True): """ This function optimizes a large store by storing a single reference to the :class:`SimMemoryObject` instead of one for each byte. :param memory_object: the memory object to store """ for p in self._containing_pages_...
This function optimizes a large store by storing a single reference to the :class:`SimMemoryObject` instead of one for each byte. :param memory_object: the memory object to store
def remove_shard(self, shard, drop_buffered_records=False): """Remove a Shard from the Coordinator. Drops all buffered records from the Shard. If the Shard is active or a root, it is removed and any children promoted to those roles. :param shard: The shard to remove :type shard: :cla...
Remove a Shard from the Coordinator. Drops all buffered records from the Shard. If the Shard is active or a root, it is removed and any children promoted to those roles. :param shard: The shard to remove :type shard: :class:`~bloop.stream.shard.Shard` :param bool drop_buffered_record...
def _sigfigs(n, sigfigs=3): 'helper function to round a number to significant figures' n = float(n) if n == 0 or math.isnan(n): # avoid math domain errors return n return round(n, -int(math.floor(math.log10(abs(n))) - sigfigs + 1))
helper function to round a number to significant figures
def p_referenceInitializer(p): """referenceInitializer : objectHandle | aliasIdentifier """ if p[1][0] == '$': try: p[0] = p.parser.aliases[p[1]] except KeyError: ce = CIMError( CIM_ERR_FAILED, ...
referenceInitializer : objectHandle | aliasIdentifier