code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def encode_time(o): """ Encodes a Python datetime.time object as an ECMA-262 compliant time string.""" r = o.isoformat() if o.microsecond: r = r[:12] if r.endswith('+00:00'): r = r[:-6] + 'Z' return r
Encodes a Python datetime.time object as an ECMA-262 compliant time string.
def iplot(figure,validate=True,sharing=None,filename='', online=None,asImage=False,asUrl=False,asPlot=False, dimensions=None,display_image=True,**kwargs): """ Plots a figure in IPython, creates an HTML or generates an Image figure : figure Plotly figure to be charted validate : bool If True then all va...
Plots a figure in IPython, creates an HTML or generates an Image figure : figure Plotly figure to be charted validate : bool If True then all values are validated before it is charted sharing : string Sets the sharing level permission public - anyone can see this chart private - only you can see this...
def add_to_loader(loader_cls: Type, classes: List[Type]) -> None: """Registers one or more classes with a YAtiML loader. Once a class has been registered, it can be recognized and \ constructed when reading a YAML text. Args: loader_cls: The loader to register the classes with. classes...
Registers one or more classes with a YAtiML loader. Once a class has been registered, it can be recognized and \ constructed when reading a YAML text. Args: loader_cls: The loader to register the classes with. classes: The class(es) to register, a plain Python class or a \ ...
def _list_of_dicts_to_column_headers(list_of_dicts): """ Detects if all entries in an list of ``dict``'s have identical keys. Returns the keys if all keys are the same and ``None`` otherwise. Parameters ---------- list_of_dicts : list List of dictionaries to ...
Detects if all entries in an list of ``dict``'s have identical keys. Returns the keys if all keys are the same and ``None`` otherwise. Parameters ---------- list_of_dicts : list List of dictionaries to test for identical keys. Returns ------- list or...
def _get_net_runner_opts(): ''' Return the net.find runner options. ''' runner_opts = __opts__.get('runners', {}).get('net.find', {}) return { 'target': runner_opts.get('target', _DEFAULT_TARGET), 'expr_form': runner_opts.get('expr_form', _DEFAULT_EXPR_FORM), 'ignore_interfac...
Return the net.find runner options.
def distanceToMesh(self, actor, signed=False, negate=False): ''' Computes the (signed) distance from one mesh to another. .. hint:: |distance2mesh| |distance2mesh.py|_ ''' poly1 = self.polydata() poly2 = actor.polydata() df = vtk.vtkDistancePolyDataFilter...
Computes the (signed) distance from one mesh to another. .. hint:: |distance2mesh| |distance2mesh.py|_
def run_plate_bias(in_prefix, in_type, out_prefix, base_dir, options): """Runs step7 (plate bias). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param options: the optio...
Runs step7 (plate bias). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param options: the options needed. :type in_prefix: str :type in_type: str :type out_pref...
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args): ''' Create an ElastiCache subnet group Example: .. code-block:: bash salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \ ...
Create an ElastiCache subnet group Example: .. code-block:: bash salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \ CacheSubnetGroupDescription="description" \ subnets='[myVPCSubn...
def random_patt_uniform(nrows, ncols, patt_type=scalar): """Returns a ScalarPatternUniform object or a VectorPatternUniform object where each of the elements is set to a normal random variable with zero mean and unit standard deviation. *nrows* is the number of rows in the pattern, which correspon...
Returns a ScalarPatternUniform object or a VectorPatternUniform object where each of the elements is set to a normal random variable with zero mean and unit standard deviation. *nrows* is the number of rows in the pattern, which corresponds to the theta axis. *ncols* must be even and is the number...
def openByVendorIDAndProductID( self, vendor_id, product_id, skip_on_access_error=False, skip_on_error=False): """ Get the first USB device matching given vendor and product ids. Returns an USBDeviceHandle instance, or None if no present device match. skip...
Get the first USB device matching given vendor and product ids. Returns an USBDeviceHandle instance, or None if no present device match. skip_on_error (bool) (see getDeviceList) skip_on_access_error (bool) (see getDeviceList)
def selectInvert( self ): """ Inverts the currently selected items in the scene. """ currLayer = self._currentLayer for item in self.items(): layer = item.layer() if ( layer == currLayer or not layer ): item.setSelected(not item.isSelected(...
Inverts the currently selected items in the scene.
def decode_to_bin_keypath(path): """ Decodes bytes into a sequence of 0s and 1s Used in decoding key path of a KV-NODE """ path = encode_to_bin(path) if path[0] == 1: path = path[4:] assert path[0:2] == PREFIX_00 padded_len = TWO_BITS.index(path[2:4]) return path[4+((4 - padd...
Decodes bytes into a sequence of 0s and 1s Used in decoding key path of a KV-NODE
def validate_table_name(name): """ :param str name: Table name to validate. :raises NameValidationError: |raises_validate_table_name| """ try: validate_sqlite_table_name(name) except (InvalidCharError, InvalidReservedNameError) as e: raise NameValidationError(e) except NullN...
:param str name: Table name to validate. :raises NameValidationError: |raises_validate_table_name|
def dump_bulk(cls, parent=None, keep_ids=True): """Dumps a tree branch to a python data structure.""" cls = get_result_class(cls) # Because of fix_tree, this method assumes that the depth # and numchild properties in the nodes can be incorrect, # so no helper methods are used ...
Dumps a tree branch to a python data structure.
def post_user_contact_lists_contacts(self, id, contact_list_id, **data): """ POST /users/:id/contact_lists/:contact_list_id/contacts/ Adds a new contact to the contact list. Returns ``{"created": true}``. There is no way to update entries in the list; just delete the old one and ...
POST /users/:id/contact_lists/:contact_list_id/contacts/ Adds a new contact to the contact list. Returns ``{"created": true}``. There is no way to update entries in the list; just delete the old one and add the updated version.
def get_first_properties(elt, keys=None, ctx=None): """Get first properties related to one input key. :param elt: first property elt. Not None methods. :param list keys: property keys to get. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties...
Get first properties related to one input key. :param elt: first property elt. Not None methods. :param list keys: property keys to get. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function...
def create_secgroup_rule(self, protocol, from_port, to_port, source, target): """ Creates a new server security group rule. :param str protocol: E.g. ``tcp``, ``icmp``, etc... :param int from_port: E.g. ``1`` :param int to_port: E.g. ``65535`` :param str s...
Creates a new server security group rule. :param str protocol: E.g. ``tcp``, ``icmp``, etc... :param int from_port: E.g. ``1`` :param int to_port: E.g. ``65535`` :param str source: :param str target: The target security group. I.e. the group in which this rule s...
def load(cls, filename, gzipped, byteorder='big'): """Read, parse and return the file at the specified location. The `gzipped` argument is used to indicate if the specified file is gzipped. The `byteorder` argument lets you specify whether the file is big-endian or little-endian. ...
Read, parse and return the file at the specified location. The `gzipped` argument is used to indicate if the specified file is gzipped. The `byteorder` argument lets you specify whether the file is big-endian or little-endian.
def update(self, figure): """Updates figure on data change Parameters ---------- * figure: matplotlib.figure.Figure \tMatplotlib figure object that is displayed in self """ if hasattr(self, "figure_canvas"): self.figure_canvas.Destroy() sel...
Updates figure on data change Parameters ---------- * figure: matplotlib.figure.Figure \tMatplotlib figure object that is displayed in self
def process_escape(self, char): '''Handle the char after the escape char''' # Always only run once, switch back to the last processor. self.process_char = self.last_process_char if self.part == [] and char in self.whitespace: # Special case where \ is by itself and not at the...
Handle the char after the escape char
def list2pd(all_data, subjindex=None, listindex=None): """ Makes multi-indexed dataframe of subject data Parameters ---------- all_data : list of lists of strings strings are either all presented or all recalled items, in the order of presentation or recall *should also work for pre...
Makes multi-indexed dataframe of subject data Parameters ---------- all_data : list of lists of strings strings are either all presented or all recalled items, in the order of presentation or recall *should also work for presented / recalled ints and floats, if desired Returns ---...
async def dispatch_request( self, request_context: Optional[RequestContext]=None, ) -> ResponseReturnValue: """Dispatch the request to the view function. Arguments: request_context: The request context, optional as Flask omits this argument. """ r...
Dispatch the request to the view function. Arguments: request_context: The request context, optional as Flask omits this argument.
def add_custom_fields(cls, *args, **kw): """ Add any custom fields defined in the configuration. """ for factory in config.custom_field_factories: for field in factory(): setattr(cls, field.name, field)
Add any custom fields defined in the configuration.
def right_join(self, table, one=None, operator=None, two=None): """ Add a right join to the query :param table: The table to join with, can also be a JoinClause instance :type table: str or JoinClause :param one: The first column of the join condition :type one: str ...
Add a right join to the query :param table: The table to join with, can also be a JoinClause instance :type table: str or JoinClause :param one: The first column of the join condition :type one: str :param operator: The operator of the join condition :type operator: st...
def from_etree(cls, etree_element): """ creates a ``SaltEdge`` instance from the etree representation of an <edges> element from a SaltXMI file. """ ins = SaltElement.from_etree(etree_element) # TODO: this looks dangerous, ask Stackoverflow about it! ins.__class__...
creates a ``SaltEdge`` instance from the etree representation of an <edges> element from a SaltXMI file.
def collect_output(mr_out_dir, out_file=None): """ Return all mapreduce output in ``mr_out_dir``. Append the output to ``out_file`` if provided. Otherwise, return the result as a single string (it is the caller's responsibility to ensure that the amount of data retrieved fits into memory). """...
Return all mapreduce output in ``mr_out_dir``. Append the output to ``out_file`` if provided. Otherwise, return the result as a single string (it is the caller's responsibility to ensure that the amount of data retrieved fits into memory).
def to_json_object(self): """Returns a dict representation that can be serialized to JSON.""" obj_dict = dict(namespace_start=self.namespace_start, namespace_end=self.namespace_end) if self.app is not None: obj_dict['app'] = self.app return obj_dict
Returns a dict representation that can be serialized to JSON.
def set_mode_cb(self, mode, tf): """Called when one of the Move/Draw/Edit radio buttons is selected.""" if tf: self.canvas.set_draw_mode(mode) if mode == 'edit': self.edit_select_cuts() return True
Called when one of the Move/Draw/Edit radio buttons is selected.
def save_and_close_enable(self, top_left, bottom_right): """Handle the data change event to enable the save and close button.""" self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True)
Handle the data change event to enable the save and close button.
def _getFromTime(self, atDate=None): """ Time that the event starts (in the local time zone). """ return getLocalTime(self.date_from, self.time_from, self.tz)
Time that the event starts (in the local time zone).
def decodeLength(length): """ Decode length based on given bytes. :param length: Bytes string to decode. :return: Decoded length. """ bytes_length = len(length) if bytes_length < 2: offset = b'\x00\x00\x00' XOR = 0 elif bytes_leng...
Decode length based on given bytes. :param length: Bytes string to decode. :return: Decoded length.
def ispercolating(am, inlets, outlets, mode='site'): r""" Determines if a percolating clusters exists in the network spanning the given inlet and outlet sites Parameters ---------- am : adjacency_matrix The adjacency matrix with the ``data`` attribute indicating if a bond is occ...
r""" Determines if a percolating clusters exists in the network spanning the given inlet and outlet sites Parameters ---------- am : adjacency_matrix The adjacency matrix with the ``data`` attribute indicating if a bond is occupied or not inlets : array_like An array of...
def get_family_admin_session(self): """Gets the ``OsidSession`` associated with the family administrative service. return: (osid.relationship.FamilyAdminSession) - a ``FamilyAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``sup...
Gets the ``OsidSession`` associated with the family administrative service. return: (osid.relationship.FamilyAdminSession) - a ``FamilyAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_family_admin()`` is ``false`` *co...
def adjacent(geohash, direction): """Return the adjacent geohash for a given direction.""" # Based on an MIT licensed implementation by Chris Veness from: # http://www.movable-type.co.uk/scripts/geohash.html assert direction in 'nsew', "Invalid direction: %s"%direction assert geohash, "Invalid geohash: %s"%...
Return the adjacent geohash for a given direction.
def from_labeled_point(rdd, categorical=False, nb_classes=None): """Convert a LabeledPoint RDD back to a pair of numpy arrays :param rdd: LabeledPoint RDD :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: optional int, indicating the number of class labels...
Convert a LabeledPoint RDD back to a pair of numpy arrays :param rdd: LabeledPoint RDD :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: optional int, indicating the number of class labels :return: pair of numpy arrays, features and labels
def _update(self): """Update the current model using one round of Gibbs sampling. """ initial_time = time.time() self._updateHiddenStateTrajectories() self._updateEmissionProbabilities() self._updateTransitionMatrix() final_time = time.time() elapsed_ti...
Update the current model using one round of Gibbs sampling.
def addInHeaderInfo(self, name, type, namespace, element_type=0, mustUnderstand=0): """Add an input SOAP header description to the call info.""" headerinfo = HeaderInfo(name, type, namespace, element_type) if mustUnderstand: headerinfo.mustUnderstand = 1 ...
Add an input SOAP header description to the call info.
def calculate_perimeters(labels, indexes): """Count the distances between adjacent pixels in the perimeters of the labels""" # # Create arrays that tell whether a pixel is like its neighbors. # index = 0 is the pixel -1,-1 from the pixel of interest, 1 is -1,0, etc. # m = table_idx_from_labels(l...
Count the distances between adjacent pixels in the perimeters of the labels
def list(self, verbose=True): """Print a table of contents to sys.stdout. If `verbose' is False, only the names of the members are printed. If it is True, an `ls -l'-like output is produced. """ self._check() for tarinfo in self: if verbose: ...
Print a table of contents to sys.stdout. If `verbose' is False, only the names of the members are printed. If it is True, an `ls -l'-like output is produced.
def publish(self, subject, payload): """ Sends a PUB command to the server on the specified subject. ->> PUB hello 5 ->> MSG_PAYLOAD: world <<- MSG hello 2 5 """ if self.is_closed: raise ErrConnectionClosed if self.is_draining_pubs: ...
Sends a PUB command to the server on the specified subject. ->> PUB hello 5 ->> MSG_PAYLOAD: world <<- MSG hello 2 5
def get_beta_list(queue, *args): """获取调整后的风险因子列表,用于归一化风险因子系数 Keyword arguments: queue -- 标题候选队列 *args -- 强化ef,客串如多个list Return: beta_list -- 所有候选标题的beta,list类型 """ beta_list = [] for i in queue: c = CDM(i) beta_lis...
获取调整后的风险因子列表,用于归一化风险因子系数 Keyword arguments: queue -- 标题候选队列 *args -- 强化ef,客串如多个list Return: beta_list -- 所有候选标题的beta,list类型
def do_until(lambda_expr, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, message=None): ''' A retry wrapper that'll keep performing the action until it succeeds. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the ...
A retry wrapper that'll keep performing the action until it succeeds. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: lambda_expr (lambda) : Expression to evaluate. ...
def emit(self, event, *args, **kwargs): """Call all callback functions registered with an event. Any positional and keyword arguments can be passed here, and they will be forwarded to the callback functions. Return the list of callback return results. """ callbacks = s...
Call all callback functions registered with an event. Any positional and keyword arguments can be passed here, and they will be forwarded to the callback functions. Return the list of callback return results.
def create_symbol(self, type_, **kwargs): """ Banana banana """ unique_name = kwargs.get('unique_name') if not unique_name: unique_name = kwargs.get('display_name') kwargs['unique_name'] = unique_name filename = kwargs.get('filename') if f...
Banana banana
def render_app_name(context, app, template="/admin_app_name.html"): """ Render the application name using the default template name. If it cannot find a template matching the given path, fallback to the application name. """ try: template = app['app_label'] + template text = render_t...
Render the application name using the default template name. If it cannot find a template matching the given path, fallback to the application name.
def AgregarFrigorifico(self, cuit, nro_planta): "Agrego el frigorifico a la liquidacíon (opcional)." frig = {'cuit': cuit, 'nroPlanta': nro_planta} self.solicitud['datosLiquidacion']['frigorifico'] = frig return True
Agrego el frigorifico a la liquidacíon (opcional).
def ply2gii(in_file, metadata, out_file=None): """Convert from ply to GIfTI""" from pathlib import Path from numpy import eye from nibabel.gifti import ( GiftiMetaData, GiftiCoordSystem, GiftiImage, GiftiDataArray, ) from pyntcloud import PyntCloud in_file = Path(in_file) surf =...
Convert from ply to GIfTI
def picture(self, row): """Create a simplified character representation of the data row, which can be pattern matched with a regex """ template = '_Xn' types = (type(None), binary_type, int) def guess_type(v): try: v = text_type(v).strip() ...
Create a simplified character representation of the data row, which can be pattern matched with a regex
def last(symbol: str): """ displays last price, for symbol if provided """ app = PriceDbApplication() # convert to uppercase if symbol: symbol = symbol.upper() # extract namespace sec_symbol = SecuritySymbol("", "") sec_symbol.parse(symbol) latest = app.get_late...
displays last price, for symbol if provided
def freeze(sess, output_file_path, output_node_names): """Freeze and shrink the graph based on a session and the output node names.""" with TemporaryDirectory() as temp_dir_name: checkpoint_path = os.path.join(temp_dir_name, 'model.ckpt') tf.train.Saver().save(sess, checkpoint_path) fre...
Freeze and shrink the graph based on a session and the output node names.
def patterson_d(aca, acb, acc, acd): """Unbiased estimator for D(A, B; C, D), the normalised four-population test for admixture between (A or B) and (C or D), also known as the "ABBA BABA" test. Parameters ---------- aca : array_like, int, shape (n_variants, 2), Allele counts for popula...
Unbiased estimator for D(A, B; C, D), the normalised four-population test for admixture between (A or B) and (C or D), also known as the "ABBA BABA" test. Parameters ---------- aca : array_like, int, shape (n_variants, 2), Allele counts for population A. acb : array_like, int, shape (n_...
def cons(head_ele,l,**kwargs): ''' from elist.elist import * ol=[1,2,3,4] id(ol) new = cons(5,ol) new id(new) #### ol=[1,2,3,4] id(ol) rslt = cons(5,ol,mode="original") rslt id(rslt) ''' if('mode' in kwargs): ...
from elist.elist import * ol=[1,2,3,4] id(ol) new = cons(5,ol) new id(new) #### ol=[1,2,3,4] id(ol) rslt = cons(5,ol,mode="original") rslt id(rslt)
def at(self, timestamp): """ Force the create date of an object to be at a certain time; This method can be invoked only on a freshly created Versionable object. It must not have been cloned yet. Raises a SuspiciousOperation exception, otherwise. :param timestamp: a datet...
Force the create date of an object to be at a certain time; This method can be invoked only on a freshly created Versionable object. It must not have been cloned yet. Raises a SuspiciousOperation exception, otherwise. :param timestamp: a datetime.datetime instance
def get_default_template(): """ Returns default getTemplate request specification. :return: """ return { "format": 1, "protocol": 1, "environment": Environment.DEV, # shows whether the UO should be for production (live), ...
Returns default getTemplate request specification. :return:
def pillar_dir(self): ''' Returns the directory of the pillars (repo cache + branch + root) ''' repo_dir = self.repo_dir root = self.root branch = self.branch if branch == 'trunk' or branch == 'base': working_dir = os.path.join(repo_dir, 'trunk', root)...
Returns the directory of the pillars (repo cache + branch + root)
def register_callbacks(self, on_create, on_modify, on_delete): """ Register callbacks for file creation, modification, and deletion """ self.on_create = on_create self.on_modify = on_modify self.on_delete = on_delete
Register callbacks for file creation, modification, and deletion
def changes_in(self, rev_or_range): """ :API: public """ try: return self._scm.changes_in(rev_or_range, relative_to=get_buildroot()) except Scm.ScmException as e: raise self.WorkspaceError("Problem detecting changes in {}.".format(rev_or_range), e)
:API: public
def get_edxml_with_aws_urls(self): """stub""" edxml = self.get_edxml() soup = BeautifulSoup(edxml, 'xml') attrs = { 'draggable': 'icon', 'drag_and_drop_input': 'img', 'files': 'included_files', 'img': 'src' } # replace all ...
stub
def check_auth(user): ''' Check if the user should or shouldn't be inside the system: - If the user is staff or superuser: LOGIN GRANTED - If the user has a Person and it is not "disabled": LOGIN GRANTED - Elsewhere: LOGIN DENIED ''' # Initialize authentication auth = None person = ...
Check if the user should or shouldn't be inside the system: - If the user is staff or superuser: LOGIN GRANTED - If the user has a Person and it is not "disabled": LOGIN GRANTED - Elsewhere: LOGIN DENIED
def detect_stream_mode(stream): ''' detect_stream_mode - Detect the mode on a given stream @param stream <object> - A stream object If "mode" is present, that will be used. @return <type> - "Bytes" type or "str" type ''' # If "Mode" is present, pull from that i...
detect_stream_mode - Detect the mode on a given stream @param stream <object> - A stream object If "mode" is present, that will be used. @return <type> - "Bytes" type or "str" type
def __clear_in_buffer(self): """ Zeros out the in buffer :return: None """ self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
Zeros out the in buffer :return: None
def accuracy(self, test_set, format=None): """Compute the accuracy on a test set. :param test_set: A list of tuples of the form ``(text, label)``, or a filename. :param format: If ``test_set`` is a filename, the file format, e.g. ``"csv"`` or ``"json"``. If ``None``, wil...
Compute the accuracy on a test set. :param test_set: A list of tuples of the form ``(text, label)``, or a filename. :param format: If ``test_set`` is a filename, the file format, e.g. ``"csv"`` or ``"json"``. If ``None``, will attempt to detect the file format.
def process(self): """ Loops over the underlying queue of events and processes them in order. """ assert self.queue is not None while True: event = self.queue.get() if self.pre_process_event(event): self.invoke_handlers(event) s...
Loops over the underlying queue of events and processes them in order.
def unionfs(rw='rw', ro=None, union='union'): """ Decorator for the UnionFS feature. This configures a unionfs for projects. The given base_dir and/or image_dir are layered as follows: image_dir=RW:base_dir=RO All writes go to the image_dir, while base_dir delivers the (read-only) versions...
Decorator for the UnionFS feature. This configures a unionfs for projects. The given base_dir and/or image_dir are layered as follows: image_dir=RW:base_dir=RO All writes go to the image_dir, while base_dir delivers the (read-only) versions of the rest of the filesystem. The unified version w...
def delete(self): """Delete this stream from Device Cloud along with its history This call will return None on success and raise an exception in the event of an error performing the deletion. :raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error ...
Delete this stream from Device Cloud along with its history This call will return None on success and raise an exception in the event of an error performing the deletion. :raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error :raises devicecloud.streams.N...
def get_language(self): """\ Returns the language is by the article or the configuration language """ # we don't want to force the target language # so we use the article.meta_lang if self.config.use_meta_language: if self.article.meta_lang: ...
\ Returns the language is by the article or the configuration language
def grade(adjective, suffix=COMPARATIVE): """ Returns the comparative or superlative form of the given (inflected) adjective. """ b = predicative(adjective) # groß => großt, schön => schönst if suffix == SUPERLATIVE and b.endswith(("s", u"ß")): suffix = suffix[1:] # große => großere, sch...
Returns the comparative or superlative form of the given (inflected) adjective.
def _startRecording(self, filename): """ Start recording the session to a file for debug purposes. """ self.setOption('_log_file_name', filename) self.setOption('_log_input_only', True) self.setOption('_log', True)
Start recording the session to a file for debug purposes.
def insert_paragraph_before(self, text=None, style=None): """ Return a newly created paragraph, inserted directly before this paragraph. If *text* is supplied, the new paragraph contains that text in a single run. If *style* is provided, that style is assigned to the new paragrap...
Return a newly created paragraph, inserted directly before this paragraph. If *text* is supplied, the new paragraph contains that text in a single run. If *style* is provided, that style is assigned to the new paragraph.
def _isLastCodeColumn(self, block, column): """Return true if the given column is at least equal to the column that contains the last non-whitespace character at the given line, or if the rest of the line is a comment. """ return column >= self._lastColumn(block) or \ ...
Return true if the given column is at least equal to the column that contains the last non-whitespace character at the given line, or if the rest of the line is a comment.
def cdsparse(self, record): """ Finds core genes, and records gene names and sequences in dictionaries :param record: SeqIO record """ try: # Find genes that are present in all strains of interest - the number of times the gene is found is # equal to the n...
Finds core genes, and records gene names and sequences in dictionaries :param record: SeqIO record
def consume_item(rlp, start): """Read an item from an RLP string. :param rlp: the rlp string to read from :param start: the position at which to start reading :returns: a tuple ``(item, per_item_rlp, end)``, where ``item`` is the read item, per_item_rlp is a list containing the RLP ...
Read an item from an RLP string. :param rlp: the rlp string to read from :param start: the position at which to start reading :returns: a tuple ``(item, per_item_rlp, end)``, where ``item`` is the read item, per_item_rlp is a list containing the RLP encoding of each item and ``e...
def tomof(self, indent=MOF_INDENT, maxline=MAX_MOF_LINE, line_pos=0): """ Return a MOF string with the specification of this CIM qualifier as a qualifier value. The items of array values are tried to keep on the same line. If the generated line would exceed the maximum MOF line ...
Return a MOF string with the specification of this CIM qualifier as a qualifier value. The items of array values are tried to keep on the same line. If the generated line would exceed the maximum MOF line length, the value is split into multiple lines, on array item boundaries, and/or w...
def to_mongo(self, disjunction=True): """Create from current state a valid MongoDB query expression. :return: MongoDB query expression :rtype: dict """ q = {} # add all the main clauses to `q` clauses = [e.expr for e in self._main] if clauses: ...
Create from current state a valid MongoDB query expression. :return: MongoDB query expression :rtype: dict
def _get_record(self, record_type): """This overrides _get_record in osid.Extensible. Perhaps we should leverage it somehow? """ if (not self.has_record_type(record_type) and record_type.get_identifier() not in self._record_type_data_sets): raise errors.Unsu...
This overrides _get_record in osid.Extensible. Perhaps we should leverage it somehow?
def get_default_datatable_kwargs(self, **kwargs): """ Builds the default set of kwargs for initializing a Datatable class. Note that by default the MultipleDatatableMixin does not support any configuration via the view's class attributes, and instead relies completely on the Datatable c...
Builds the default set of kwargs for initializing a Datatable class. Note that by default the MultipleDatatableMixin does not support any configuration via the view's class attributes, and instead relies completely on the Datatable class itself to declare its configuration details.
async def flush(self, request: Request, stacks: List[Stack]): """ Add a typing stack after each stack. """ ns: List[Stack] = [] for stack in stacks: ns.extend(self.typify(stack)) if len(ns) > 1 and ns[-1] == Stack([lyr.Typing()]): ns[-1].get_lay...
Add a typing stack after each stack.
def namedb_select_where_unexpired_names(current_block, only_registered=True): """ Generate part of a WHERE clause that selects from name records joined with namespaces (or projections of them) that are not expired. Also limit to names that are registered at this block, if only_registered=True. If o...
Generate part of a WHERE clause that selects from name records joined with namespaces (or projections of them) that are not expired. Also limit to names that are registered at this block, if only_registered=True. If only_registered is False, then as long as current_block is before the expire block, then th...
def R(self,*args,**kwargs): """ NAME: R PURPOSE: return cylindrical radius at time t INPUT: t - (optional) time at which to get the radius ro= (Object-wide default) physical scale for distances to use to convert use_physical= use to ...
NAME: R PURPOSE: return cylindrical radius at time t INPUT: t - (optional) time at which to get the radius ro= (Object-wide default) physical scale for distances to use to convert use_physical= use to override Object-wide default for using a physica...
def _load_data(self): """ Load data from raw_data or file_path """ if self.raw_data is None and self.data_format is not FormatType.PYTHON: if self.file_path is None: raise ArgumentInvalid('One of "raw_data" or "file_path" should be set!') if not os...
Load data from raw_data or file_path
def cur_model(model=None): """Get and/or set the current model. If ``model`` is given, set the current model to ``model`` and return it. ``model`` can be the name of a model object, or a model object itself. If ``model`` is not given, the current model is returned. """ if model is None: ...
Get and/or set the current model. If ``model`` is given, set the current model to ``model`` and return it. ``model`` can be the name of a model object, or a model object itself. If ``model`` is not given, the current model is returned.
def clean_all(G, settings): """ Removes all the output files from all targets. Takes the graph as the only argument Args: The networkx graph object The settings dictionary Returns: 0 if successful 1 if removing even one file failed """ quiet = settings["quie...
Removes all the output files from all targets. Takes the graph as the only argument Args: The networkx graph object The settings dictionary Returns: 0 if successful 1 if removing even one file failed
def parse_full_atom(data): """Some atoms are versioned. Split them up in (version, flags, payload). Can raise ValueError. """ if len(data) < 4: raise ValueError("not enough data") version = ord(data[0:1]) flags = cdata.uint_be(b"\x00" + data[1:4]) return version, flags, data[4:]
Some atoms are versioned. Split them up in (version, flags, payload). Can raise ValueError.
def clean(self, data): """Method returns cleaned list of stock closing prices (i.e. dict(date=datetime.date(2015, 1, 2), price='23.21')).""" cleaned_data = list() if not isinstance(data, list): data = [data] for item in data: date = datetime.datetime.str...
Method returns cleaned list of stock closing prices (i.e. dict(date=datetime.date(2015, 1, 2), price='23.21')).
def read_one(self, sequence): """ Reads one item from the Ringbuffer. If the sequence is one beyond the current tail, this call blocks until an item is added. Currently it isn't possible to control how long this call is going to block. :param sequence: (long), the sequence of the item t...
Reads one item from the Ringbuffer. If the sequence is one beyond the current tail, this call blocks until an item is added. Currently it isn't possible to control how long this call is going to block. :param sequence: (long), the sequence of the item to read. :return: (object), the read item.
def update_subscription_user_settings(self, user_settings, subscription_id, user_id): """UpdateSubscriptionUserSettings. [Preview API] Update the specified user's settings for the specified subscription. This API is typically used to opt in or out of a shared subscription. User settings can only be appl...
UpdateSubscriptionUserSettings. [Preview API] Update the specified user's settings for the specified subscription. This API is typically used to opt in or out of a shared subscription. User settings can only be applied to shared subscriptions, like team subscriptions or default subscriptions. :param :cl...
def _receive(self, root, directory, dirs, files, include, exclude): """Internal function processing each yield from os.walk.""" self._received += 1 if not self.symlinks: where = root + os.path.sep + directory + os.path.sep files = [ file_name for file_na...
Internal function processing each yield from os.walk.
def run(self, cmd=None): """ Call this function at the end of your class's `__init__` function. """ diagnostics.prefix.append(self.name) if not cmd: cmd = self.cmd stderr = os.path.abspath(self.name + '.log') self.args.append('2>>'+stderr) if self.pipe: self.args += ('|', self.pipe, '2>>'+stder...
Call this function at the end of your class's `__init__` function.
def debug_log_template(self, record): """ Return the prefix for the log message. Template for Formatter. Parameters ---------- record : :py:class:`logging.LogRecord` This is passed in from inside the :py:meth:`logging.Formatter.format` record. Returns ------- str ...
Return the prefix for the log message. Template for Formatter. Parameters ---------- record : :py:class:`logging.LogRecord` This is passed in from inside the :py:meth:`logging.Formatter.format` record. Returns ------- str Log template.
def bridge_list(): ''' Lists all existing real and fake bridges. Returns: List of bridges (or empty list), False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.bridge_list ''' cmd = 'ovs-vsctl list-br' result = __salt...
Lists all existing real and fake bridges. Returns: List of bridges (or empty list), False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.bridge_list
def profiling_query_formatter(view, context, query_document, name): """Format a ProfilingQuery entry for a ProfilingRequest detail field Parameters ---------- query_document : model.ProfilingQuery """ return Markup( ''.join( [ '<div class="pymongo-query row">...
Format a ProfilingQuery entry for a ProfilingRequest detail field Parameters ---------- query_document : model.ProfilingQuery
def plot_shapes(df_shapes, shape_i_columns, axis=None, autoxlim=True, autoylim=True, **kwargs): ''' Plot shapes from table/data-frame where each row corresponds to a vertex of a shape. Shape vertices are grouped by `shape_i_columns`. For example, consider the following dataframe: ...
Plot shapes from table/data-frame where each row corresponds to a vertex of a shape. Shape vertices are grouped by `shape_i_columns`. For example, consider the following dataframe: shape_i vertex_i x y 0 0 0 81.679949 264.69306 1 0 1 8...
def find(self, *args, **kwargs): """Create a :class:`MotorCursor`. Same parameters as for PyMongo's :meth:`~pymongo.collection.Collection.find`. Note that ``find`` does not require an ``await`` expression, because ``find`` merely creates a :class:`MotorCursor` without performing...
Create a :class:`MotorCursor`. Same parameters as for PyMongo's :meth:`~pymongo.collection.Collection.find`. Note that ``find`` does not require an ``await`` expression, because ``find`` merely creates a :class:`MotorCursor` without performing any operations on the server. ``Mot...
def password(self, password): """ Encode a string and set as password """ from boiler.user.util.passlib import passlib_context password = str(password) encrypted = passlib_context.encrypt(password) self._password = encrypted
Encode a string and set as password
def log(verbose=False): """ print a log test :param verbose: show more logs """ terminal.log.config(verbose=verbose) terminal.log.info('this is a info message') terminal.log.verbose.info('this is a verbose message')
print a log test :param verbose: show more logs
def new(preset, name, silent, update): """Create new default preset \b Usage: $ be new ad "blue_unicorn" created $ be new film --name spiderman "spiderman" created """ if self.isactive(): lib.echo("Please exit current preset before starting a new") ...
Create new default preset \b Usage: $ be new ad "blue_unicorn" created $ be new film --name spiderman "spiderman" created
def multiChoiceParam(parameters, name, type_converter = str): """ multi choice parameter values. :param parameters: the parameters tree. :param name: the name of the parameter. :param type_converter: function to convert the chosen value to a different type (e.g. str, float, int). default = 'str' :re...
multi choice parameter values. :param parameters: the parameters tree. :param name: the name of the parameter. :param type_converter: function to convert the chosen value to a different type (e.g. str, float, int). default = 'str' :returns dictionary: value -> values
def reply_bytes(self, request): """Take a `Request` and return an OP_MSG message as bytes.""" flags = struct.pack("<I", self._flags) payload_type = struct.pack("<b", 0) payload_data = bson.BSON.encode(self.doc) data = b''.join([flags, payload_type, payload_data]) reply_i...
Take a `Request` and return an OP_MSG message as bytes.
def save_data(self, idx): """Save the internal data of all sequences with an activated flag. Write to file if the corresponding disk flag is activated; store in working memory if the corresponding ram flag is activated.""" for name in self: actual = getattr(self, name) ...
Save the internal data of all sequences with an activated flag. Write to file if the corresponding disk flag is activated; store in working memory if the corresponding ram flag is activated.
def list_deploy_keys(self, auth, username, repo_name): """ List deploy keys for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :return: a list of d...
List deploy keys for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :return: a list of deploy keys for the repo :rtype: List[GogsRepo.DeployKey] :r...