code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def add_to_buffer(self, content, read_position): """Add additional bytes content as read from the read_position. Args: content (bytes): data to be added to buffer working BufferWorkSpac. read_position (int): where in the file pointer the data was read from. """ s...
Add additional bytes content as read from the read_position. Args: content (bytes): data to be added to buffer working BufferWorkSpac. read_position (int): where in the file pointer the data was read from.
def serve_get(self, path, **params): """ Find a GET callback for the given HTTP path, call it and return the results. The callback is called with two arguments, the path used to match it, and params which include the BaseHTTPRequestHandler instance. The callback must return a t...
Find a GET callback for the given HTTP path, call it and return the results. The callback is called with two arguments, the path used to match it, and params which include the BaseHTTPRequestHandler instance. The callback must return a tuple: (code, content, content_type) ...
def __stringify_predicate(predicate): """ Reflection of function name and parameters of the predicate being used. """ funname = getsource(predicate).strip().split(' ')[2].rstrip(',') params = 'None' # if args dig in the stack if '()' not in funname: stack = getouterframes(currentframe()...
Reflection of function name and parameters of the predicate being used.
def newPage(doc, pno=-1, width=595, height=842): """Create and return a new page object. """ doc._newPage(pno, width=width, height=height) return doc[pno]
Create and return a new page object.
def all_casings(input_string): """ Permute all casings of a given string. A pretty algorithm, via @Amber http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python """ if not input_string: yield "" else: first = input_string[:1] if fi...
Permute all casings of a given string. A pretty algorithm, via @Amber http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python
def fitness(self, parsimony_coefficient=None): """Evaluate the penalized fitness of the program according to X, y. Parameters ---------- parsimony_coefficient : float, optional If automatic parsimony is being used, the computed value according to the population. ...
Evaluate the penalized fitness of the program according to X, y. Parameters ---------- parsimony_coefficient : float, optional If automatic parsimony is being used, the computed value according to the population. Otherwise the initialized value is used. Returns ...
def _request(self, buf, properties, date=None): """Send a request to the CoreNLP server. :param (str | unicode) text: raw text for the CoreNLPServer to parse :param (dict) properties: properties that the server expects :param (str) date: reference date of document, used by server to set...
Send a request to the CoreNLP server. :param (str | unicode) text: raw text for the CoreNLPServer to parse :param (dict) properties: properties that the server expects :param (str) date: reference date of document, used by server to set docDate - expects YYYY-MM-DD :return: request resu...
def disable(cls, args): """Disable subcommand.""" mgr = NAppsManager() if args['all']: napps = mgr.get_enabled() else: napps = args['<napp>'] for napp in napps: mgr.set_napp(*napp) LOG.info('NApp %s:', mgr.napp_id) cls...
Disable subcommand.
def _config_profile_list(self): """Get list of supported config profile from DCNM.""" url = self._cfg_profile_list_url payload = {} try: res = self._send_request('GET', url, payload, 'config-profile') if res and res.status_code in self._resp_ok: r...
Get list of supported config profile from DCNM.
def sample(self, size=1): """Generate samples of the random variable. Parameters ---------- size : int The number of samples to generate. Returns ------- :obj:`numpy.ndarray` of int or int The samples of the random variable. If `size == 1...
Generate samples of the random variable. Parameters ---------- size : int The number of samples to generate. Returns ------- :obj:`numpy.ndarray` of int or int The samples of the random variable. If `size == 1`, then the returned valu...
def GammaContrast(gamma=1, per_channel=False, name=None, deterministic=False, random_state=None): """ Adjust contrast by scaling each pixel value to ``255 * ((I_ij/255)**gamma)``. Values in the range ``gamma=(0.5, 2.0)`` seem to be sensible. dtype support:: See :func:`imgaug.augmenters.contra...
Adjust contrast by scaling each pixel value to ``255 * ((I_ij/255)**gamma)``. Values in the range ``gamma=(0.5, 2.0)`` seem to be sensible. dtype support:: See :func:`imgaug.augmenters.contrast.adjust_contrast_gamma`. Parameters ---------- gamma : number or tuple of number or list of num...
def set_value(self, value, timeout): """ Sets a new value and extends its expiration. :param value: a new cached value. :param timeout: a expiration timeout in milliseconds. """ self.value = value self.expiration = time.perf_counter() * 1000 + timeout
Sets a new value and extends its expiration. :param value: a new cached value. :param timeout: a expiration timeout in milliseconds.
def l2_regularizer(decay, name_filter='weights'): """Create an l2 regularizer.""" return regularizer( 'l2_regularizer', lambda x: tf.nn.l2_loss(x) * decay, name_filter=name_filter)
Create an l2 regularizer.
def gen_accept(id_, keysize=2048, force=False): r''' Generate a key pair then accept the public key. This function returns the key pair in a dict, only the public key is preserved on the master. Returns a dictionary. id\_ The name of the minion for which to generate a key pair. keysize...
r''' Generate a key pair then accept the public key. This function returns the key pair in a dict, only the public key is preserved on the master. Returns a dictionary. id\_ The name of the minion for which to generate a key pair. keysize The size of the key pair to generate. The s...
def parse_valu(text, off=0): ''' Special syntax for the right side of equals in a macro ''' _, off = nom(text, off, whites) if nextchar(text, off, '('): return parse_list(text, off) if isquote(text, off): return parse_string(text, off) # since it's not quoted, we can assum...
Special syntax for the right side of equals in a macro
def import_locations(self, data): """Parse geonames.org country database exports. ``import_locations()`` returns a list of :class:`trigpoints.Trigpoint` objects generated from the data exported by geonames.org_. It expects data files in the following tab separated format:: ...
Parse geonames.org country database exports. ``import_locations()`` returns a list of :class:`trigpoints.Trigpoint` objects generated from the data exported by geonames.org_. It expects data files in the following tab separated format:: 2633441 Afon Wyre Afon Wyre River Wayrai,Riv...
def portdate(port_number, date=None, return_format=None): """Information about a particular port at a particular date. If the date is ommited, today's date is used. :param port_number: a string or integer port number :param date: an optional string in 'Y-M-D' format or datetime.date() object """ ...
Information about a particular port at a particular date. If the date is ommited, today's date is used. :param port_number: a string or integer port number :param date: an optional string in 'Y-M-D' format or datetime.date() object
def _GetTSKPartitionIdentifiers(self, scan_node): """Determines the TSK partition identifiers. Args: scan_node (SourceScanNode): scan node. Returns: list[str]: TSK partition identifiers. Raises: ScannerError: if the format of or within the source is not supported or the sc...
Determines the TSK partition identifiers. Args: scan_node (SourceScanNode): scan node. Returns: list[str]: TSK partition identifiers. Raises: ScannerError: if the format of or within the source is not supported or the scan node is invalid or if the volume for a specific identi...
def vofile(filename, **kwargs): """ Open and return a handle on a VOSpace data connection @param filename: @param kwargs: @return: """ basename = os.path.basename(filename) if os.access(basename, os.R_OK): return open(basename, 'r') kwargs['view'] = kwargs.get('view', 'data')...
Open and return a handle on a VOSpace data connection @param filename: @param kwargs: @return:
def hybrid_forward(self, F, inputs, token_types, valid_length=None, masked_positions=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model. ...
Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model.
def find_first_fit(unoccupied_columns, row, row_length): """ Finds the first index that the row's items can fit. """ for free_col in unoccupied_columns: # The offset is that such that the first item goes in the free column. first_item_x = row[0][0] offset = free_col - first_item_...
Finds the first index that the row's items can fit.
def _to_numeric_float(number, nums_int): """ Transforms a string into a float. The nums_int parameter indicates the number of characters, starting from the left, to be used for the integer value. All the remaining ones will be used for the decimal value. :param number: string with the number ...
Transforms a string into a float. The nums_int parameter indicates the number of characters, starting from the left, to be used for the integer value. All the remaining ones will be used for the decimal value. :param number: string with the number :param nums_int: characters, counting from the lef...
def unmarshal_json( obj, cls, allow_extra_keys=True, ctor=None, ): """ Unmarshal @obj into @cls Args: obj: dict, A JSON object cls: type, The class to unmarshal into allow_extra_keys: bool, False to raise an exception when extra ...
Unmarshal @obj into @cls Args: obj: dict, A JSON object cls: type, The class to unmarshal into allow_extra_keys: bool, False to raise an exception when extra keys are present, True to ignore ctor: None-or-static-method:...
def tostring(self, fully_qualified=True, pretty_print=True, encoding="UTF-8"): """ Serialize and return a string of this METS document. To write to file, see :meth:`write`. The default encoding is ``UTF-8``. This method will return a unicode string when ``encoding`` is set to `...
Serialize and return a string of this METS document. To write to file, see :meth:`write`. The default encoding is ``UTF-8``. This method will return a unicode string when ``encoding`` is set to ``unicode``. :return: String of this document
def sigma_filter(filename, region, step_size, box_size, shape, domask, sid): """ Calculate the background and rms for a sub region of an image. The results are written to shared memory - irms and ibkg. Parameters ---------- filename : string Fits file to open region : list ...
Calculate the background and rms for a sub region of an image. The results are written to shared memory - irms and ibkg. Parameters ---------- filename : string Fits file to open region : list Region within the fits file that is to be processed. (row_min, row_max). step_size :...
def get_clipboard_text_and_convert(paste_list=False): u"""Get txt from clipboard. if paste_list==True the convert tab separated data to list of lists. Enclose list of list in array() if all elements are numeric""" txt = GetClipboardText() if txt: if paste_list and u"\t" in txt: ...
u"""Get txt from clipboard. if paste_list==True the convert tab separated data to list of lists. Enclose list of list in array() if all elements are numeric
def image_id_from_registry(image_name): """Get the docker id from a public or private registry""" registry, repository, tag = parse(image_name) try: token = auth_token(registry, repository).get("token") # dockerhub is crazy if registry == "index.docker.io": registry = "re...
Get the docker id from a public or private registry
def acceptRecord(self, item): """ Closes the tree popup and sets the current record. :param record | <orb.Table> """ record = item.record() self.treePopupWidget().close() self.setCurrentRecord(record)
Closes the tree popup and sets the current record. :param record | <orb.Table>
def _publish_message(host, amqp_settings, routing_key, data): """Publish an AMQP message. Returns: bool: True if message was sent successfully. """ if host == "stdout": print("Published to %s: %s" % (routing_key, data)) return True try: conn = Connection(**remove_no...
Publish an AMQP message. Returns: bool: True if message was sent successfully.
def _add_generic(self, start_node, type_name, group_type_name, args, kwargs, add_prefix=True, check_naming=True): """Adds a given item to the tree irrespective of the subtree. Infers the subtree from the arguments. :param start_node: The parental node the adding was initia...
Adds a given item to the tree irrespective of the subtree. Infers the subtree from the arguments. :param start_node: The parental node the adding was initiated from :param type_name: The type of the new instance. Whether it is a parameter, parameter group, config, con...
def rotate_v1(array, k): """ Rotate the entire array 'k' times T(n)- O(nk) :type array: List[int] :type k: int :rtype: void Do not return anything, modify array in-place instead. """ array = array[:] n = len(array) for i in range(k): # unused variable is not a problem ...
Rotate the entire array 'k' times T(n)- O(nk) :type array: List[int] :type k: int :rtype: void Do not return anything, modify array in-place instead.
def update(self): """re-persist the updated field values of this orm that has a primary key""" ret = True fields = self.depopulate(True) q = self.query q.set_fields(fields) pk = self.pk if pk: q.is_field(self.schema.pk.name, pk) else: ...
re-persist the updated field values of this orm that has a primary key
def generate_monthly(rain_day_threshold, day_end_hour, use_dst, daily_data, monthly_data, process_from): """Generate monthly summaries from daily data.""" start = monthly_data.before(datetime.max) if start is None: start = datetime.min start = daily_data.after(start + SECOND...
Generate monthly summaries from daily data.
def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ lineno = lineno - 1 lower_bound = max(0, lineno - context_lines) up...
Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context).
def store(self, database, validate=True, role=None): """Store the document in the given database. :param database: the `Database` object source for storing the document. :return: an updated instance of `Document` / self. """ if validate: self.validate() self....
Store the document in the given database. :param database: the `Database` object source for storing the document. :return: an updated instance of `Document` / self.
def batch_run(self, *commands): """ Run batch of commands in sequence. Input is positional arguments with (function pointer, *args) tuples. This method is useful for executing commands to multiple groups with retries, without having too long delays. For example, ...
Run batch of commands in sequence. Input is positional arguments with (function pointer, *args) tuples. This method is useful for executing commands to multiple groups with retries, without having too long delays. For example, - Set group 1 to red and brightness to 10%...
def _get_schema_loader(self, strict=False): """Gets a closure for schema.load_schema with the correct/current Opsview version """ return functools.partial(schema.load_schema, version=self.version, strict=strict)
Gets a closure for schema.load_schema with the correct/current Opsview version
def readin_rho(filename, rhofile=True, aniso=False): """Read in the values of the resistivity in Ohmm. The format is variable: rho-file or mag-file. """ if aniso: a = [[0, 1, 2], [2, 3, 4]] else: a = [0, 2] if rhofile: if filename is None: filename = 'rho/rho....
Read in the values of the resistivity in Ohmm. The format is variable: rho-file or mag-file.
def sighash(self, sighash_type, index=0, joinsplit=False, script_code=None, anyone_can_pay=False, prevout_value=None): ''' ZIP243 https://github.com/zcash/zips/blob/master/zip-0243.rst ''' if joinsplit and anyone_can_pay: raise ValueError('ANYONECANPA...
ZIP243 https://github.com/zcash/zips/blob/master/zip-0243.rst
def _validate_caller_vcf(call_vcf, truth_vcf, callable_bed, svcaller, work_dir, data): """Validate a caller VCF against truth within callable regions using SURVIVOR. Combines files with SURIVOR merge and counts (https://github.com/fritzsedlazeck/SURVIVOR/) """ stats = _calculate_comparison_stats(truth_...
Validate a caller VCF against truth within callable regions using SURVIVOR. Combines files with SURIVOR merge and counts (https://github.com/fritzsedlazeck/SURVIVOR/)
def _ValidateDataTypeDefinition(cls, data_type_definition): """Validates the data type definition. Args: data_type_definition (DataTypeDefinition): data type definition. Raises: ValueError: if the data type definition is not considered valid. """ if not cls._IsIdentifier(data_type_defi...
Validates the data type definition. Args: data_type_definition (DataTypeDefinition): data type definition. Raises: ValueError: if the data type definition is not considered valid.
def decode_bbox_target(box_predictions, anchors): """ Args: box_predictions: (..., 4), logits anchors: (..., 4), floatbox. Must have the same shape Returns: box_decoded: (..., 4), float32. With the same shape. """ orig_shape = tf.shape(anchors) box_pred_txtytwth = tf.res...
Args: box_predictions: (..., 4), logits anchors: (..., 4), floatbox. Must have the same shape Returns: box_decoded: (..., 4), float32. With the same shape.
async def serve( app: ASGIFramework, config: Config, *, task_status: trio._core._run._TaskStatus = trio.TASK_STATUS_IGNORED, ) -> None: """Serve an ASGI framework app given the config. This allows for a programmatic way to serve an ASGI framework, it can be used via, .. code-block:: py...
Serve an ASGI framework app given the config. This allows for a programmatic way to serve an ASGI framework, it can be used via, .. code-block:: python trio.run(partial(serve, app, config)) It is assumed that the event-loop is configured before calling this function, therefore configurat...
def gene_tree( self, scale_to=None, population_size=1, trim_names=True, ): """ Using the current tree object as a species tree, generate a gene tree using the constrained Kingman coalescent process from dendropy. The species tree should probabl...
Using the current tree object as a species tree, generate a gene tree using the constrained Kingman coalescent process from dendropy. The species tree should probably be a valid, ultrametric tree, generated by some pure birth, birth-death or coalescent process, but no checks are made. Op...
def get_plugin(self, name): """ Get a plugin by its name from the plugins loaded for the current namespace :param name: :return: """ for p in self._plugins: if p.name == name: return p return None
Get a plugin by its name from the plugins loaded for the current namespace :param name: :return:
def parse_def(self, text): """Parse the function definition text.""" self.__init__() if not is_start_of_function(text): return self.func_indent = get_indent(text) text = text.strip() text = text.replace('\r\n', '') text = text.replace('\n...
Parse the function definition text.
def draw(self, viewer): """General draw method for RGB image types. Note that actual insertion of the image into the output is handled in `draw_image()` """ cache = self.get_cache(viewer) if not cache.drawn: cache.drawn = True viewer.redraw(whence...
General draw method for RGB image types. Note that actual insertion of the image into the output is handled in `draw_image()`
def make_geohash_tables(table,listofprecisions,**kwargs): ''' sort_by - field to sort by for each group return_squares - boolean arg if true returns a list of squares instead of writing out to table ''' return_squares = False sort_by = 'COUNT' # logic for accepting kwarg inputs for key,value in kwargs.iteritems...
sort_by - field to sort by for each group return_squares - boolean arg if true returns a list of squares instead of writing out to table
def ckf_transform(Xs, Q): """ Compute mean and covariance of array of cubature points. Parameters ---------- Xs : ndarray Cubature points Q : ndarray Noise covariance Returns ------- mean : ndarray mean of the cubature points variance: ndarray ...
Compute mean and covariance of array of cubature points. Parameters ---------- Xs : ndarray Cubature points Q : ndarray Noise covariance Returns ------- mean : ndarray mean of the cubature points variance: ndarray covariance matrix of the cubature ...
def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configura...
Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team mem...
def PILTowx(pimg): '''convert a PIL Image to a wx image''' from MAVProxy.modules.lib.wx_loader import wx wimg = wx.EmptyImage(pimg.size[0], pimg.size[1]) try: wimg.SetData(pimg.convert('RGB').tobytes()) except NotImplementedError: # old, removed method: wimg.SetData(pimg.conv...
convert a PIL Image to a wx image
def _what_default(self, pronunciation): """Provide the default prediction of the what task. This function is used to predict the probability of a given pronunciation being reported for a given token. :param pronunciation: The list or array of confusion probabilities at each index """ ...
Provide the default prediction of the what task. This function is used to predict the probability of a given pronunciation being reported for a given token. :param pronunciation: The list or array of confusion probabilities at each index
def purge_stream(self, stream_id, remove_definition=False, sandbox=None): """ Purge the stream :param stream_id: The stream identifier :param remove_definition: Whether to remove the stream definition as well :param sandbox: The sandbox for this stream :return: None ...
Purge the stream :param stream_id: The stream identifier :param remove_definition: Whether to remove the stream definition as well :param sandbox: The sandbox for this stream :return: None :raises: NotImplementedError
def is_empty(self): """Returns True if this node has no children, or if all of its children are ParseNode instances and are empty. """ return all(isinstance(c, ParseNode) and c.is_empty for c in self.children)
Returns True if this node has no children, or if all of its children are ParseNode instances and are empty.
def join(chord_root, quality='', extensions=None, bass=''): r"""Join the parts of a chord into a complete chord label. Parameters ---------- chord_root : str Root pitch class of the chord, e.g. 'C', 'Eb' quality : str Quality of the chord, e.g. 'maj', 'hdim7' (Default value ...
r"""Join the parts of a chord into a complete chord label. Parameters ---------- chord_root : str Root pitch class of the chord, e.g. 'C', 'Eb' quality : str Quality of the chord, e.g. 'maj', 'hdim7' (Default value = '') extensions : list Any added or absent scaled d...
def get_all_alert(self, **kwargs): # noqa: E501 """Get all alerts for a customer # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_all_alert(async_req=True)...
Get all alerts for a customer # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_all_alert(async_req=True) >>> result = thread.get() :param async_req...
def remove(self, element, multiplicity=None): """Removes an element from the multiset. If no multiplicity is specified, the element is completely removed from the multiset: >>> ms = Multiset('aabbbc') >>> ms.remove('a') 2 >>> sorted(ms) ['b', 'b', 'b', 'c'] ...
Removes an element from the multiset. If no multiplicity is specified, the element is completely removed from the multiset: >>> ms = Multiset('aabbbc') >>> ms.remove('a') 2 >>> sorted(ms) ['b', 'b', 'b', 'c'] If the multiplicity is given, it is subtracted from ...
def resolve_memory_access(self, tb, x86_mem_operand): """Return operand memory access translation. """ size = self.__get_memory_access_size(x86_mem_operand) addr = None if x86_mem_operand.base: addr = ReilRegisterOperand(x86_mem_operand.base, size) if x86_m...
Return operand memory access translation.
def change_dir(self, session, path): """ Changes the working directory """ if path == "-": # Previous directory path = self._previous_path or "." try: previous = os.getcwd() os.chdir(path) except IOError as ex: ...
Changes the working directory
def LogoOverlay(sites, overlayfile, overlay, nperline, sitewidth, rmargin, logoheight, barheight, barspacing, fix_limits={}, fixlongname=False, overlay_cmap=None, underlay=False, scalebar=False): """Makes overlay for *LogoPlot*. This function creates colored bars overlay bars showing up to two properties. ...
Makes overlay for *LogoPlot*. This function creates colored bars overlay bars showing up to two properties. The trick of this function is to create the bars the right size so they align when they overlay the logo plot. CALLING VARIABLES: * *sites* : same as the variable of this name used by ...
def _encode_sequence(self, inputs, token_types, valid_length=None): """Generate the representation given the input sequences. This is used for pre-training or fine-tuning a BERT model. """ # embedding word_embedding = self.word_embed(inputs) type_embedding = self.token_t...
Generate the representation given the input sequences. This is used for pre-training or fine-tuning a BERT model.
def clear(self): 'od.clear() -> None. Remove all items from od.' try: for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() except AttributeError: pass ...
od.clear() -> None. Remove all items from od.
def well(self, idx) -> Well: """Deprecated---use result of `wells` or `wells_by_index`""" if isinstance(idx, int): res = self._wells[idx] elif isinstance(idx, str): res = self.wells_by_index()[idx] else: res = NotImplemented return res
Deprecated---use result of `wells` or `wells_by_index`
def determine_override_options(selected_options: tuple, override_opts: DictLike, set_of_possible_options: tuple = ()) -> Dict[str, Any]: """ Recursively extract the dict described in override_options(). In particular, this searches for selected options in the override_opts dict. It stores only the override...
Recursively extract the dict described in override_options(). In particular, this searches for selected options in the override_opts dict. It stores only the override options that are selected. Args: selected_options: The options selected for this analysis, in the order defined used wi...
def broadcast_1d_array(arr, ndim, axis=1): """ Broadcast 1-d array `arr` to `ndim` dimensions on the first axis (`axis`=0) or on the last axis (`axis`=1). Useful for 'outer' calculations involving 1-d arrays that are related to different axes on a multidimensional grid. """ ext_arr = arr ...
Broadcast 1-d array `arr` to `ndim` dimensions on the first axis (`axis`=0) or on the last axis (`axis`=1). Useful for 'outer' calculations involving 1-d arrays that are related to different axes on a multidimensional grid.
def read_tpld_stats(self): """ :return: dictionary {tpld index {group name {stat name: value}}}. Sea XenaTpld.stats_captions. """ payloads_stats = OrderedDict() for tpld in self.tplds.values(): payloads_stats[tpld] = tpld.read_stats() return payloa...
:return: dictionary {tpld index {group name {stat name: value}}}. Sea XenaTpld.stats_captions.
def format_out_of_country_keeping_alpha_chars(numobj, region_calling_from): """Formats a phone number for out-of-country dialing purposes. Note that in this version, if the number was entered originally using alpha characters and this version of the number is stored in raw_input, this representation of...
Formats a phone number for out-of-country dialing purposes. Note that in this version, if the number was entered originally using alpha characters and this version of the number is stored in raw_input, this representation of the number will be used rather than the digit representation. Grouping informa...
def decrypt(*args, **kwargs): """ Decrypts legacy or spec-compliant JOSE token. First attempts to decrypt the token in a legacy mode (https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-19). If it is not a valid legacy token then attempts to decrypt it in a spec-compliant way (http://tools.i...
Decrypts legacy or spec-compliant JOSE token. First attempts to decrypt the token in a legacy mode (https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-19). If it is not a valid legacy token then attempts to decrypt it in a spec-compliant way (http://tools.ietf.org/html/rfc7519)
def stats(self) -> pd.DataFrame: """Statistics about flights contained in the structure. Useful for a meaningful representation. """ key = ["icao24", "callsign"] if self.flight_ids is None else "flight_id" return ( self.data.groupby(key)[["timestamp"]] .co...
Statistics about flights contained in the structure. Useful for a meaningful representation.
def cross_entropy_reward_loss(logits, actions, rewards, name=None): """Calculate the loss for Policy Gradient Network. Parameters ---------- logits : tensor The network outputs without softmax. This function implements softmax inside. actions : tensor or placeholder The agent action...
Calculate the loss for Policy Gradient Network. Parameters ---------- logits : tensor The network outputs without softmax. This function implements softmax inside. actions : tensor or placeholder The agent actions. rewards : tensor or placeholder The rewards. Returns ...
def call(self, itemMethod): """ Invoke the given bound item method in the batch process. Return a Deferred which fires when the method has been invoked. """ item = itemMethod.im_self method = itemMethod.im_func.func_name return self.batchController.getProcess().a...
Invoke the given bound item method in the batch process. Return a Deferred which fires when the method has been invoked.
def mark_validation(institute_id, case_name, variant_id): """Mark a variant as sanger validated.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) variant_obj = store.variant(variant_id) user_obj = store.user(current_user.email) validate_type = request.form['type'] or N...
Mark a variant as sanger validated.
def _get_variant_effect(cls, variants, ref_sequence): '''variants = list of variants in the same codon. returns type of variant (cannot handle more than one indel in the same codon).''' assert len(variants) != 0 var_types = [x.var_type for x in variants] if len(set(var_types)...
variants = list of variants in the same codon. returns type of variant (cannot handle more than one indel in the same codon).
def get_groups(self, username): """ Get a user's groups :param username: 'key' attribute of the user :type username: string :rtype: list of groups """ try: return self.users[username]['groups'] except Exception as e: raise UserDoesntExist(...
Get a user's groups :param username: 'key' attribute of the user :type username: string :rtype: list of groups
def submit(self, command, blocksize, job_name="parsl.auto"): ''' Submits the command onto an Local Resource Manager job of blocksize parallel elements. Submit returns an ID that corresponds to the task that was just submitted. If tasks_per_node < 1 : ! This is illegal. tasks_per_node should be...
Submits the command onto an Local Resource Manager job of blocksize parallel elements. Submit returns an ID that corresponds to the task that was just submitted. If tasks_per_node < 1 : ! This is illegal. tasks_per_node should be integer If tasks_per_node == 1: A single node is p...
def _init_scratch(self): """Initializes a scratch pad equal in size to the wavefunction.""" scratch = np.zeros((self._num_shards, self._shard_size), dtype=np.complex64) scratch_handle = mem_manager.SharedMemManager.create_array( scratch.view(dtype=np.float3...
Initializes a scratch pad equal in size to the wavefunction.
def SetColor(self, color): """ *color* may be any color understood by ROOT or matplotlib. Set all color attributes with one method call. For full documentation of accepted *color* arguments, see :class:`rootpy.plotting.style.Color`. """ self.SetFillColor(color) ...
*color* may be any color understood by ROOT or matplotlib. Set all color attributes with one method call. For full documentation of accepted *color* arguments, see :class:`rootpy.plotting.style.Color`.
def alias_field(model, field): """ Return the prefix name of a field """ for part in field.split(LOOKUP_SEP)[:-1]: model = associate_model(model,part) return model.__name__ + "-" + field.split(LOOKUP_SEP)[-1]
Return the prefix name of a field
def get_contingency_tables(self): """ Create an Array of ContingencyTable objects for each probability threshold. Returns: Array of ContingencyTable objects """ return np.array([ContingencyTable(*ct) for ct in self.contingency_tables.values])
Create an Array of ContingencyTable objects for each probability threshold. Returns: Array of ContingencyTable objects
def driver_name(self): """ Returns the name of the motor driver that loaded this device. See the list of [supported devices] for a list of drivers. """ self._driver_name, value = self.get_attr_string(self._driver_name, 'driver_name') return value
Returns the name of the motor driver that loaded this device. See the list of [supported devices] for a list of drivers.
def _hash_categorical(c, encoding, hash_key): """ Hash a Categorical by hashing its categories, and then mapping the codes to the hashes Parameters ---------- c : Categorical encoding : string, default 'utf8' hash_key : string key to encode, default to _default_hash_key Returns ...
Hash a Categorical by hashing its categories, and then mapping the codes to the hashes Parameters ---------- c : Categorical encoding : string, default 'utf8' hash_key : string key to encode, default to _default_hash_key Returns ------- ndarray of hashed values array, same size as ...
def _fs_match(pattern, filename, sep, follow, symlinks): """ Match path against the pattern. Since `globstar` doesn't match symlinks (unless `FOLLOW` is enabled), we must look for symlinks. If we identify a symlink in a `globstar` match, we know this result should not actually match. """ match...
Match path against the pattern. Since `globstar` doesn't match symlinks (unless `FOLLOW` is enabled), we must look for symlinks. If we identify a symlink in a `globstar` match, we know this result should not actually match.
def commit( self, confirm=False, confirm_delay=None, check=False, comment="", and_quit=False, delay_factor=1, ): """ Commit the candidate configuration. Commit the entered configuration. Raise an error and return the failure if...
Commit the candidate configuration. Commit the entered configuration. Raise an error and return the failure if the commit fails. Automatically enters configuration mode default: command_string = commit check and (confirm or confirm_dely or comment): Exc...
def apply_integer_offsets(image2d, offx, offy): """Apply global (integer) offsets to image. Parameters ---------- image2d : numpy array Input image offx : int Offset in the X direction (must be integer). offy : int Offset in the Y direction (must be integer). Return...
Apply global (integer) offsets to image. Parameters ---------- image2d : numpy array Input image offx : int Offset in the X direction (must be integer). offy : int Offset in the Y direction (must be integer). Returns ------- image2d_shifted : numpy array ...
def wait_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): ''' Waits wrapper that'll wait for the condition to become true, but will not error if the condition isn't met. Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: time...
Waits wrapper that'll wait for the condition to become true, but will not error if the condition isn't met. Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wa...
def visit_Expr(self, node: AST, dfltChaining: bool = True) -> str: """Return representation of nested expression.""" return self.visit(node.value)
Return representation of nested expression.
def _dict_native_ok(d): """ This checks if a dictionary can be saved natively as HDF5 groups. If it can't, it will be pickled. """ if len(d) >= 256: return False # All keys must be strings for k in d: if not isinstance(k, six.string_types): return False ret...
This checks if a dictionary can be saved natively as HDF5 groups. If it can't, it will be pickled.
def wait(self, condition, interval, *args): """ :Description: Create an interval in vm.window, will clear interval after condition met. :param condition: Condition in javascript to pass to interval. :example: '$el.innerText == "cheesecake"' :example: '$el[0].disabled && $el[1].di...
:Description: Create an interval in vm.window, will clear interval after condition met. :param condition: Condition in javascript to pass to interval. :example: '$el.innerText == "cheesecake"' :example: '$el[0].disabled && $el[1].disabled' :type condition: string :param interval:...
def get_class_name(class_key, classification_key): """Helper to get class name from a class_key of a classification. :param class_key: The key of the class. :type class_key: str :type classification_key: The key of a classification. :param classification_key: str :returns: The name of the cla...
Helper to get class name from a class_key of a classification. :param class_key: The key of the class. :type class_key: str :type classification_key: The key of a classification. :param classification_key: str :returns: The name of the class. :rtype: str
def build_target_areas(entry): """Cleanup the raw target areas description string""" target_areas = [] areas = str(entry['cap:areaDesc']).split(';') for area in areas: target_areas.append(area.strip()) return target_areas
Cleanup the raw target areas description string
def uavionix_adsb_out_cfg_encode(self, ICAO, callsign, emitterType, aircraftSize, gpsOffsetLat, gpsOffsetLon, stallSpeed, rfSelect): ''' Static data to configure the ADS-B transponder (send within 10 sec of a POR and every 10 sec thereafter) ICAO ...
Static data to configure the ADS-B transponder (send within 10 sec of a POR and every 10 sec thereafter) ICAO : Vehicle address (24 bit) (uint32_t) callsign : Vehicle identifier (8 characters, null terminated, valid characters are A-...
def _read_journal(self): """Extracts the USN journal from the disk and parses its content.""" root = self._filesystem.inspect_get_roots()[0] inode = self._filesystem.stat('C:\\$Extend\\$UsnJrnl')['ino'] with NamedTemporaryFile(buffering=0) as tempfile: self._filesystem.downl...
Extracts the USN journal from the disk and parses its content.
def set(self, subscribed, ignored): """Set the user's subscription for this subscription :param bool subscribed: (required), determines if notifications should be received from this thread. :param bool ignored: (required), determines if notifications should be ignored fr...
Set the user's subscription for this subscription :param bool subscribed: (required), determines if notifications should be received from this thread. :param bool ignored: (required), determines if notifications should be ignored from this thread.
def hourly_horizontal_infrared(self): """A data collection containing hourly horizontal infrared intensity in W/m2. """ sky_cover = self._sky_condition.hourly_sky_cover db_temp = self._dry_bulb_condition.hourly_values dp_temp = self._humidity_condition.hourly_dew_point_values( ...
A data collection containing hourly horizontal infrared intensity in W/m2.
def sign(self): """ Returns 1 if a credit should increase the value of the account, or -1 if a credit should decrease the value of the account. This is based on the account type as is standard accounting practice. The signs can be derrived from the following expanded for...
Returns 1 if a credit should increase the value of the account, or -1 if a credit should decrease the value of the account. This is based on the account type as is standard accounting practice. The signs can be derrived from the following expanded form of the accounting equation...
def dtype(self): """Data-type of the array's elements. Returns ------- numpy.dtype This NDArray's data type. Examples -------- >>> x = mx.nd.zeros((2,3)) >>> x.dtype <type 'numpy.float32'> >>> y = mx.nd.zeros((2,3), dtype='int...
Data-type of the array's elements. Returns ------- numpy.dtype This NDArray's data type. Examples -------- >>> x = mx.nd.zeros((2,3)) >>> x.dtype <type 'numpy.float32'> >>> y = mx.nd.zeros((2,3), dtype='int32') >>> y.dtype ...
def _gen_ticket(prefix=None, lg=settings.CAS_TICKET_LEN): """ Generate a ticket with prefix ``prefix`` and length ``lg`` :param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU) :param int lg: The length of the generated ticket (with the prefix) :return: A randomll...
Generate a ticket with prefix ``prefix`` and length ``lg`` :param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU) :param int lg: The length of the generated ticket (with the prefix) :return: A randomlly generated ticket of length ``lg`` :rtype: unicode
def block_splitter(data, block_size): """ Creates a generator by slicing ``data`` into chunks of ``block_size``. >>> data = range(10) >>> list(block_splitter(data, 2)) [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]] If ``data`` cannot be evenly divided by ``block_size``, the last block will simpl...
Creates a generator by slicing ``data`` into chunks of ``block_size``. >>> data = range(10) >>> list(block_splitter(data, 2)) [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]] If ``data`` cannot be evenly divided by ``block_size``, the last block will simply be the remainder of the data. Example: >>> ...
def getmakeidfobject(idf, key, name): """get idfobject or make it if it does not exist""" idfobject = idf.getobject(key, name) if not idfobject: return idf.newidfobject(key, Name=name) else: return idfobject
get idfobject or make it if it does not exist
def has_permissions(**perms): """A :func:`.check` that is added that checks if the member has all of the permissions necessary. The permissions passed in must be exactly like the properties shown under :class:`.discord.Permissions`. This check raises a special exception, :exc:`.MissingPermissions`...
A :func:`.check` that is added that checks if the member has all of the permissions necessary. The permissions passed in must be exactly like the properties shown under :class:`.discord.Permissions`. This check raises a special exception, :exc:`.MissingPermissions` that is inherited from :exc:`.Ch...