code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _check_log_scale(base, sides, scales, coord): """ Check the log transforms Parameters ---------- base : float or None Base of the logarithm in which the ticks will be calculated. If ``None``, the base of the log transform the scale will be...
Check the log transforms Parameters ---------- base : float or None Base of the logarithm in which the ticks will be calculated. If ``None``, the base of the log transform the scale will be used. sides : str (default: bl) Sides onto which ...
def primers(dna, tm=65, min_len=10, tm_undershoot=1, tm_overshoot=3, end_gc=False, tm_parameters='cloning', overhangs=None, structure=False): '''Design primers for PCR amplifying any arbitrary sequence. :param dna: Input sequence. :type dna: coral.DNA :param tm: Ideal primer Tm ...
Design primers for PCR amplifying any arbitrary sequence. :param dna: Input sequence. :type dna: coral.DNA :param tm: Ideal primer Tm in degrees C. :type tm: float :param min_len: Minimum primer length. :type min_len: int :param tm_undershoot: Allowed Tm undershoot. :type tm_undershoot:...
def init_layer(self): """ initialize a layer object Returns ------- """ self.layer = self.vector.GetLayer() self.__features = [None] * self.nfeatures
initialize a layer object Returns -------
def new_bundle(self, name: str, created_at: dt.datetime=None) -> models.Bundle: """Create a new file bundle.""" new_bundle = self.Bundle(name=name, created_at=created_at) return new_bundle
Create a new file bundle.
def describe_usage_plans(name=None, plan_id=None, region=None, key=None, keyid=None, profile=None): ''' Returns a list of existing usage plans, optionally filtered to match a given plan name .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion boto_apigateway.descri...
Returns a list of existing usage plans, optionally filtered to match a given plan name .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_usage_plans salt myminion boto_apigateway.describe_usage_plans name='usage plan name' salt my...
def _calc_thumb_filename(self, thumb_name): """ Calculates the correct filename for a would-be (or potentially existing) thumbnail of the given size. NOTE: This includes the path leading up to the thumbnail. IE: uploads/cbid_images/photo.png size: (tuple...
Calculates the correct filename for a would-be (or potentially existing) thumbnail of the given size. NOTE: This includes the path leading up to the thumbnail. IE: uploads/cbid_images/photo.png size: (tuple) In the format of (width, height) Returns a st...
def calculate(self): """ calculates the estimated happiness of a person living in a world self._update_pref(self.person.prefs['tax_min'], self.person.prefs['tax_max'], self.world.tax_rate) self._update_pref(self.person.prefs['tradition'], self.person.prefs['tradition'], self.worl...
calculates the estimated happiness of a person living in a world self._update_pref(self.person.prefs['tax_min'], self.person.prefs['tax_max'], self.world.tax_rate) self._update_pref(self.person.prefs['tradition'], self.person.prefs['tradition'], self.world.tradition) self._update_pref(se...
def values(self): """ in order """ tmp = self while tmp is not None: yield tmp.data tmp = tmp.next
in order
def run_type(self): """ Returns the run type. Currently supports LDA, GGA, vdW-DF and HF calcs. TODO: Fix for other functional types like PW91, other vdW types, etc. """ METAGGA_TYPES = {"TPSS", "RTPSS", "M06L", "MBJL", "SCAN", "MS0", "MS1", "MS2"} if self.parameters.g...
Returns the run type. Currently supports LDA, GGA, vdW-DF and HF calcs. TODO: Fix for other functional types like PW91, other vdW types, etc.
def check_rdn_deposits(raiden, user_deposit_proxy: UserDeposit): """ Check periodically for RDN deposits in the user-deposits contract """ while True: rei_balance = user_deposit_proxy.effective_balance(raiden.address, "latest") rdn_balance = to_rdn(rei_balance) if rei_balance < MIN_REI_T...
Check periodically for RDN deposits in the user-deposits contract
def _variants_fills(fields, fills, info_types): """Utility function to determine fill values for variants fields with missing values.""" if fills is None: # no fills specified by user fills = dict() for f, vcf_type in zip(fields, info_types): if f == 'FILTER': fills[f...
Utility function to determine fill values for variants fields with missing values.
def add_message(self, msg_content, folder, **kwargs): """ Inject a message :params string msg_content: The entire message's content. :params string folder: Folder pathname (starts with '/') or folder ID """ content = {'m': kwargs} content['m']['l'] = str(folder) ...
Inject a message :params string msg_content: The entire message's content. :params string folder: Folder pathname (starts with '/') or folder ID
def randomize_args(self): '''Get new parameters for spirograph generation near agent's current location (*spiro_args*). ''' args = self.spiro_args + np.random.normal(0, self.move_radius, self.spiro_args.shape) np.clip(args, -199, ...
Get new parameters for spirograph generation near agent's current location (*spiro_args*).
def _read_output(self, stream, callback, output_file): """ Read the output of the process, executed the callback and save the output. Args: stream: A file object pointing to the output stream that should be read. callback(callable, None): A callback function that is called for e...
Read the output of the process, executed the callback and save the output. Args: stream: A file object pointing to the output stream that should be read. callback(callable, None): A callback function that is called for each new line of output. output_file: A ...
def _get_lsun(directory, category, split_name): """Downloads all lsun files to directory unless they are there.""" generator_utils.maybe_download(directory, _LSUN_DATA_FILENAME % (category, split_name), _LSUN_URL % (category, split_name))
Downloads all lsun files to directory unless they are there.
def evaluator(evaluate): """Return an inspyred evaluator function based on the given function. This function generator takes a function that evaluates only one candidate. The generator handles the iteration over each candidate to be evaluated. The given function ``evaluate`` must have the fol...
Return an inspyred evaluator function based on the given function. This function generator takes a function that evaluates only one candidate. The generator handles the iteration over each candidate to be evaluated. The given function ``evaluate`` must have the following signature:: ...
def info(self, channel_name): """ https://api.slack.com/methods/channels.info """ channel_id = self.get_channel_id(channel_name) self.params.update({'channel': channel_id}) return FromUrl('https://slack.com/api/channels.info', self._requests)(data=self.params).get()
https://api.slack.com/methods/channels.info
async def resume_dialog(self, dc, reason: DialogReason, result: object): """ Method called when an instance of the dialog is being returned to from another dialog that was started by the current instance using `begin_dialog()`. If this method is NOT implemented then the dialog will be au...
Method called when an instance of the dialog is being returned to from another dialog that was started by the current instance using `begin_dialog()`. If this method is NOT implemented then the dialog will be automatically ended with a call to `end_dialog()`. Any result passed from the called di...
def _years_in_date_range_within_decade(self, decade, begin_date, end_date): """Return a list of years in one decade which is covered by date range.""" begin_year = begin_date.year end_year = end_date.year if begin_year < decade: begin_year = decade if end_year > decad...
Return a list of years in one decade which is covered by date range.
def select(self, select, table_name, where=None, extra=None): """ Send a SELECT query to the database. :param str select: Attribute for the ``SELECT`` query. :param str table_name: |arg_select_table_name| :param where: |arg_select_where| :type where: |arg_where_type| ...
Send a SELECT query to the database. :param str select: Attribute for the ``SELECT`` query. :param str table_name: |arg_select_table_name| :param where: |arg_select_where| :type where: |arg_where_type| :param str extra: |arg_select_extra| :return: Result of the query exe...
def chunk(self, seek=None, lenient=False): """ Read the next PNG chunk from the input file returns a (*chunk_type*, *data*) tuple. *chunk_type* is the chunk's type as a byte string (all PNG chunk types are 4 bytes long). *data* is the chunk's data content, as a byte string. ...
Read the next PNG chunk from the input file returns a (*chunk_type*, *data*) tuple. *chunk_type* is the chunk's type as a byte string (all PNG chunk types are 4 bytes long). *data* is the chunk's data content, as a byte string. If the optional `seek` argument is specified then ...
def _check_section_option(self, section, option): """ Private method to check section and option types """ if section is None: section = self.DEFAULT_SECTION_NAME elif not is_text_string(section): raise RuntimeError("Argument 'section' must be a str...
Private method to check section and option types
def defaultAutoRangeMethods(inspector, intialItems=None): """ Creates an ordered dict with default autorange methods for an inspector. :param inspector: the range methods will work on (the sliced array) of this inspector. :param intialItems: will be passed on to the OrderedDict constructor. ""...
Creates an ordered dict with default autorange methods for an inspector. :param inspector: the range methods will work on (the sliced array) of this inspector. :param intialItems: will be passed on to the OrderedDict constructor.
def get_freesasa_annotations(self, include_hetatms=False, representatives_only=True, force_rerun=False): """Run freesasa on structures and store calculations. Annotations are stored in the protein structure's chain sequence at: ``<chain_prop>.seq_record.letter_annotations['*-freesasa']`` ...
Run freesasa on structures and store calculations. Annotations are stored in the protein structure's chain sequence at: ``<chain_prop>.seq_record.letter_annotations['*-freesasa']`` Args: include_hetatms (bool): If HETATMs should be included in calculations. Defaults to ``False``. ...
def rec2csv(r, filename): """Export a recarray *r* to a CSV file *filename*""" names = r.dtype.names def translate(x): if x is None or str(x).lower == "none": x = "" return str(x) with open(filename, "w") as csv: csv.write(",".join([str(x) for x in names])+"\n") ...
Export a recarray *r* to a CSV file *filename*
def __process_by_python(self): """! @brief Performs processing using python code. """ self.__scores = {} for k in range(self.__kmin, self.__kmax): clusters = self.__calculate_clusters(k) if len(clusters) != k: self.__scores[k] =...
! @brief Performs processing using python code.
def _prerun(self): """ To execute before running message """ self.check_required_params() self._set_status("RUNNING") logger.debug( "{}.PreRun: {}[{}]: running...".format( self.__class__.__name__, self.__class__.path, self.uuid ), ...
To execute before running message
def owner(self): """ Returns the owner of these capabilities, if any. :return: the owner, can be None :rtype: JavaObject """ obj = javabridge.call(self.jobject, "getOwner", "()Lweka/core/CapabilitiesHandler;") if obj is None: return None else:...
Returns the owner of these capabilities, if any. :return: the owner, can be None :rtype: JavaObject
def findItems(self, data, cls=None, initpath=None, **kwargs): """ Load the specified data to find and build all items with the specified tag and attrs. See :func:`~plexapi.base.PlexObject.fetchItem` for more details on how this is used. """ # filter on cls attrs if specif...
Load the specified data to find and build all items with the specified tag and attrs. See :func:`~plexapi.base.PlexObject.fetchItem` for more details on how this is used.
def create_apirack(self): """Get an instance of Api Rack Variables services facade.""" return ApiRack( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of Api Rack Variables services facade.
def get_users_batch(self, ids): """ Ids: a list of ids that we want to return """ # Allowed maximum number of ids is 50 assert len(ids) <= 50 ids_ = ','.join(ids) url = _USERS_BATCH.format(c_api=_C_API_BEGINNING, api=_API_VERSION, ...
Ids: a list of ids that we want to return
def source(self): """Return the source code for the definition.""" full_src = self._source[self._slice] def is_empty_or_comment(line): return line.strip() == '' or line.strip().startswith('#') filtered_src = dropwhile(is_empty_or_comment, reversed(full_src)) return ...
Return the source code for the definition.
def not_(self): ''' Negates this instance's query expression using MongoDB's ``$not`` operator **Example**: ``(User.name == 'Jeff').not_()`` .. note:: Another usage is via an operator, but parens are needed to get past precedence issues: ``~ (User.name == 'J...
Negates this instance's query expression using MongoDB's ``$not`` operator **Example**: ``(User.name == 'Jeff').not_()`` .. note:: Another usage is via an operator, but parens are needed to get past precedence issues: ``~ (User.name == 'Jeff')``
def minimize(grad_and_hessian_loss_fn, x_start, tolerance, l1_regularizer, l2_regularizer=None, maximum_iterations=1, maximum_full_sweeps_per_iteration=1, learning_rate=None, name=None): """Minimize using Hessian-i...
Minimize using Hessian-informed proximal gradient descent. This function solves the regularized minimization problem ```none argmin{ Loss(x) + l1_regularizer * ||x||_1 + l2_regularizer * ||x||_2**2 : x in R^n } ``` where `Loss` is a convex C^2 function (typically, `Loss` i...
def to_unicode(string): """Convert a string (bytes, str or unicode) to unicode.""" assert isinstance(string, basestring) if sys.version_info[0] >= 3: if isinstance(string, bytes): return string.decode('utf-8') else: return string else: if isinstance(string...
Convert a string (bytes, str or unicode) to unicode.
def _replace_placeholder_with(self, element): """ Substitute *element* for this placeholder element in the shapetree. This placeholder's `._element` attribute is set to |None| and its original element is free for garbage collection. Any attribute access (including a method call) ...
Substitute *element* for this placeholder element in the shapetree. This placeholder's `._element` attribute is set to |None| and its original element is free for garbage collection. Any attribute access (including a method call) on this placeholder after this call raises |AttributeError...
def connect(cls, host, public_key, private_key, verbose=0, use_cache=True): """ Connect the client with the given host and the provided credentials. Parameters ---------- host : str The Cytomine host (without protocol). public_key : str The Cytomi...
Connect the client with the given host and the provided credentials. Parameters ---------- host : str The Cytomine host (without protocol). public_key : str The Cytomine public key. private_key : str The Cytomine private key. verbose :...
def process_jwt(jwt): """ Process a JSON Web Token without verifying it. Call this before :func:`verify_jwt` if you need access to the header or claims in the token before verifying it. For example, the claims might identify the issuer such that you can retrieve the appropriate public key. :param jwt:...
Process a JSON Web Token without verifying it. Call this before :func:`verify_jwt` if you need access to the header or claims in the token before verifying it. For example, the claims might identify the issuer such that you can retrieve the appropriate public key. :param jwt: The JSON Web Token to verify. ...
def getAllViewsAsDict(self): """Return all the stats views (dict).""" return {p: self._plugins[p].get_views() for p in self._plugins}
Return all the stats views (dict).
def add_z(xy: np.ndarray, z: float) -> np.ndarray: """ Turn a 2-D transform matrix into a 3-D transform matrix (scale/shift only, no rotation). :param xy: A two-dimensional transform matrix (a 3x3 numpy ndarray) in the following form: [ 1 0 x ] [ 0 1 y ] ...
Turn a 2-D transform matrix into a 3-D transform matrix (scale/shift only, no rotation). :param xy: A two-dimensional transform matrix (a 3x3 numpy ndarray) in the following form: [ 1 0 x ] [ 0 1 y ] [ 0 0 1 ] :param z: a float for the z component :retu...
def get_transcript_ids(ensembl, gene_id): """ gets transcript IDs for a gene. Args: ensembl: EnsemblRequest object to request data from ensembl gene_id: HGNC symbol for gene Returns: dictionary of transcript ID: transcript lengths for all transcripts for a given HGN...
gets transcript IDs for a gene. Args: ensembl: EnsemblRequest object to request data from ensembl gene_id: HGNC symbol for gene Returns: dictionary of transcript ID: transcript lengths for all transcripts for a given HGNC symbol.
def capture(self, event_type, date=None, context=None, custom=None, stack=None, handled=True, **kwargs): """ Captures and processes an event and pipes it off to Client.send. """ if event_type == "Exception": # never gather log stack for exceptions stack = False ...
Captures and processes an event and pipes it off to Client.send.
def exists(self, table_id): """ Check if a table exists in Google BigQuery Parameters ---------- table : str Name of table to be verified Returns ------- boolean true if table exists, otherwise false """ from google.api_co...
Check if a table exists in Google BigQuery Parameters ---------- table : str Name of table to be verified Returns ------- boolean true if table exists, otherwise false
def build_header(self, title): """Generate the header for the Markdown file.""" header = ['---', 'title: ' + title, 'author(s): ' + self.user, 'tags: ', 'created_at: ' + str(self.date_created), 'updated_at: ' + str...
Generate the header for the Markdown file.
def gpg_app_delete_key( blockchain_id, appname, keyname, txid=None, immutable=False, proxy=None, wallet_keys=None, config_dir=None ): """ Remove an application GPG key. Unstash the local private key. Return {'status': True, ...} on success Return {'error': ...} on error If immutable is True, ...
Remove an application GPG key. Unstash the local private key. Return {'status': True, ...} on success Return {'error': ...} on error If immutable is True, then remove the data from the user's zonefile, not profile. The delete may take on the order of an hour to complete on the blockchain. A tra...
def _timedatectl(): ''' get the output of timedatectl ''' ret = __salt__['cmd.run_all'](['timedatectl'], python_shell=False) if ret['retcode'] != 0: msg = 'timedatectl failed: {0}'.format(ret['stderr']) raise CommandExecutionError(msg) return ret
get the output of timedatectl
def _lincomb(self, a, x1, b, x2, out): """Raw linear combination.""" self.tspace._lincomb(a, x1.tensor, b, x2.tensor, out.tensor)
Raw linear combination.
def format2(self, raw, out = None, scheme = ''): """ Parse and send the colored source. If out and scheme are not specified, the defaults (given to constructor) are used. out should be a file-type object. Optionally, out can be given as the string 'str' and the parser will auto...
Parse and send the colored source. If out and scheme are not specified, the defaults (given to constructor) are used. out should be a file-type object. Optionally, out can be given as the string 'str' and the parser will automatically return the output in a string.
def _ref_prop_matches(prop, target_classname, ref_classname, resultclass_names, role): """ Test filters for a reference property Returns `True` if matches the criteria. Returns `False` if it does not match. The match criteria are: - target_cl...
Test filters for a reference property Returns `True` if matches the criteria. Returns `False` if it does not match. The match criteria are: - target_classname == prop_reference_class - if result_classes are not None, ref_classname is in result_classes - If role is...
def _make_tuple(self, env): """Instantiate the Tuple based on this TupleNode.""" t = runtime.Tuple(self, env, dict2tuple) # A tuple also provides its own schema spec schema = schema_spec_from_tuple(t) t.attach_schema(schema) return t
Instantiate the Tuple based on this TupleNode.
def select(self): """ Select the current bitmap into this wxDC instance """ if sys.platform=='win32': self.dc.SelectObject(self.bitmap) self.IsSelected = True
Select the current bitmap into this wxDC instance
def volume_present(name, volume_name=None, volume_id=None, instance_name=None, instance_id=None, device=None, size=None, snapshot_id=None, volume_type=None, iops=None, encrypted=False, kms_key_id=None, region=None, key=None, keyid=None, profile=None): ''' ...
Ensure the EC2 volume is present and attached. .. name State definition name. volume_name The Name tag value for the volume. If no volume with that matching name tag is found, a new volume will be created. If multiple volumes are matched, the state will fail. volume_id ...
def parse( data = None, template = None, data_file = None, template_file = None, interp = None, debug = False, predefines = True, int3 = True, keep_successful = False, printf ...
Parse the data stream using the supplied template. The data stream WILL NOT be automatically closed. :data: Input data, can be either a string or a file-like object (StringIO, file, etc) :template: template contents (str) :data_file: PATH to the data to be used as the input stream :template_file: t...
def get_current_price(crypto, fiat, services=None, convert_to=None, helper_prices=None, **modes): """ High level function for getting current exchange rate for a cryptocurrency. If the fiat value is not explicitly defined, it will try the wildcard service. if that does not work, it tries converting to a...
High level function for getting current exchange rate for a cryptocurrency. If the fiat value is not explicitly defined, it will try the wildcard service. if that does not work, it tries converting to an intermediate cryptocurrency if available.
def add_email_address(self, email, hidden=None): """Add email address. Args: :param email: email of the author. :type email: string :param hidden: if email is public or not. :type hidden: boolean """ existing_emails = get_value(self.obj, ...
Add email address. Args: :param email: email of the author. :type email: string :param hidden: if email is public or not. :type hidden: boolean
def brokers(self): """Get all BrokerMetadata Returns: set: {BrokerMetadata, ...} """ return set(self._brokers.values()) or set(self._bootstrap_brokers.values())
Get all BrokerMetadata Returns: set: {BrokerMetadata, ...}
def bfx(value, msb, lsb): """! @brief Extract a value from a bitfield.""" mask = bitmask((msb, lsb)) return (value & mask) >> lsb
! @brief Extract a value from a bitfield.
def _to_bel_lines_header(graph) -> Iterable[str]: """Iterate the lines of a BEL graph's corresponding BEL script's header. :param pybel.BELGraph graph: A BEL graph """ yield '# This document was created by PyBEL v{} and bel-resources v{} on {}\n'.format( VERSION, bel_resources.constants.VERSION...
Iterate the lines of a BEL graph's corresponding BEL script's header. :param pybel.BELGraph graph: A BEL graph
def _lu_reconstruct_assertions(lower_upper, perm, validate_args): """Returns list of assertions related to `lu_reconstruct` assumptions.""" assertions = [] message = 'Input `lower_upper` must have at least 2 dimensions.' if lower_upper.shape.ndims is not None: if lower_upper.shape.ndims < 2: raise Va...
Returns list of assertions related to `lu_reconstruct` assumptions.
def is_model_mpttmeta_subclass(node): """Checks that node is derivative of MPTTMeta class.""" if node.name != 'MPTTMeta' or not isinstance(node.parent, ClassDef): return False parents = ('django.db.models.base.Model', '.Model', # for the transformed version used in this plugin ...
Checks that node is derivative of MPTTMeta class.
def _remap_input(self, operation, path, *args, **kw): """Called for path inputs""" if operation in self.write_ops and not self._ok(path): self._violation(operation, os.path.realpath(path), *args, **kw) return path
Called for path inputs
def from_path_by_criterion(dir_path, criterion, keepboth=False): """Create a new FileCollection, and select some files from ``dir_path``. How to construct your own criterion function:: def filter_image(winfile): if winfile.ext in [".jpg", ".png", ".bmp"]: ...
Create a new FileCollection, and select some files from ``dir_path``. How to construct your own criterion function:: def filter_image(winfile): if winfile.ext in [".jpg", ".png", ".bmp"]: return True else: retu...
def pkt_check(*args, func=None): """Check if arguments are valid packets.""" func = func or inspect.stack()[2][3] for var in args: dict_check(var, func=func) dict_check(var.get('frame'), func=func) enum_check(var.get('protocol'), func=func) real_check(var.get('timestamp'), fu...
Check if arguments are valid packets.
def fit(self, index, n_nodes, tau_matrix, previous_tree, edges=None): """Fits tree object. Args: :param index: index of the tree :param n_nodes: number of nodes in the tree :tau_matrix: kendall's tau matrix of the data :previous_tree: tree object of previ...
Fits tree object. Args: :param index: index of the tree :param n_nodes: number of nodes in the tree :tau_matrix: kendall's tau matrix of the data :previous_tree: tree object of previous level :type index: int :type n_nodes: int ...
def validate_empty_values(self, data): """ Validate empty values, and either: * Raise `ValidationError`, indicating invalid data. * Raise `SkipField`, indicating that the field should be ignored. * Return (True, data), indicating an empty value that should be returned ...
Validate empty values, and either: * Raise `ValidationError`, indicating invalid data. * Raise `SkipField`, indicating that the field should be ignored. * Return (True, data), indicating an empty value that should be returned without any further validation being applied. * Ret...
def collect_gaps(blast, use_subject=False): """ Collect the gaps between adjacent HSPs in the BLAST file. """ key = lambda x: x.sstart if use_subject else x.qstart blast.sort(key=key) for a, b in zip(blast, blast[1:]): if use_subject: if a.sstop < b.sstart: y...
Collect the gaps between adjacent HSPs in the BLAST file.
def activate(request, activation_key, template_name='accounts/activate_fail.html', success_url=None, extra_context=None): """ Activate a user with an activation key. The key is a SHA1 string. When the SHA1 is found with an :class:`AccountsSignup`, the :class:`User` of that acc...
Activate a user with an activation key. The key is a SHA1 string. When the SHA1 is found with an :class:`AccountsSignup`, the :class:`User` of that account will be activated. After a successful activation the view will redirect to ``success_url``. If the SHA1 is not found, the user will be shown the ...
def newDocText(self, content): """Creation of a new text node within a document. """ ret = libxml2mod.xmlNewDocText(self._o, content) if ret is None:raise treeError('xmlNewDocText() failed') __tmp = xmlNode(_obj=ret) return __tmp
Creation of a new text node within a document.
def create_info_endpoint(self, name, data): """Create an endpoint to serve info GET requests.""" # make sure data is serializable data = make_serializable(data) # create generic restful resource to serve static JSON data class InfoBase(Resource): @staticmethod ...
Create an endpoint to serve info GET requests.
async def set_tz(self): """ set the environment timezone to the timezone set in your twitter settings """ settings = await self.api.account.settings.get() tz = settings.time_zone.tzinfo_name os.environ['TZ'] = tz time.tzset()
set the environment timezone to the timezone set in your twitter settings
def _set_opts(self, schema=None, **options): """ Set named options (filter out those the value is None) """ if schema is not None: self.schema(schema) for k, v in options.items(): if v is not None: self.option(k, v)
Set named options (filter out those the value is None)
def compare(string1, string2): """Compare two strings while protecting against timing attacks :param str string1: the first string :param str string2: the second string :returns: True if the strings are equal, False if not :rtype: :obj:`bool` """ if len(string1) != len(string2): re...
Compare two strings while protecting against timing attacks :param str string1: the first string :param str string2: the second string :returns: True if the strings are equal, False if not :rtype: :obj:`bool`
def get_cost_per_mol(self, comp): """ Get best estimate of minimum cost/mol based on known data Args: comp: Composition as a pymatgen.core.structure.Composition Returns: float of cost/mol """ comp = comp if isinstance(comp, Compos...
Get best estimate of minimum cost/mol based on known data Args: comp: Composition as a pymatgen.core.structure.Composition Returns: float of cost/mol
def prune_neighbors(self): """ If the CellDataFrame has been subsetted, some of the cell-cell contacts may no longer be part of the the dataset. This prunes those no-longer existant connections. Returns: CellDataFrame: A CellDataFrame with only valid cell-cell contacts """ ...
If the CellDataFrame has been subsetted, some of the cell-cell contacts may no longer be part of the the dataset. This prunes those no-longer existant connections. Returns: CellDataFrame: A CellDataFrame with only valid cell-cell contacts
def html_error_template(): """Provides a template that renders a stack trace in an HTML format, providing an excerpt of code as well as substituting source template filenames, line numbers and code for that of the originating source template, as applicable. The template's default ``encoding_errors`...
Provides a template that renders a stack trace in an HTML format, providing an excerpt of code as well as substituting source template filenames, line numbers and code for that of the originating source template, as applicable. The template's default ``encoding_errors`` value is ``'htmlentityreplac...
def data(self, index, role): """QAbstractItemModel method implementation """ if role == Qt.DisplayRole and \ index.row() < len(self.words): text = self.words[index.row()] typed = text[:len(self._typedText)] canComplete = text[len(self._typedText):le...
QAbstractItemModel method implementation
def kill_pane(self, pane): """ Kill the given pane, and remove it from the arrangement. """ assert isinstance(pane, Pane) # Send kill signal. if not pane.process.is_terminated: pane.process.kill() # Remove from layout. self.arrangement.remove...
Kill the given pane, and remove it from the arrangement.
def _getconf(self, rscpath, logger=None, conf=None): """Get specific conf from one driver path. :param str rscpath: resource path. :param Logger logger: logger to use. """ result = None resource = self.pathresource(rscpath=rscpath, logger=logger) if resource i...
Get specific conf from one driver path. :param str rscpath: resource path. :param Logger logger: logger to use.
def connect_mturk(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.mturk.connecti...
:type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.mturk.connection.MTurkConnection` :return: A connection to MTurk
def delete_editor(userid): """ :param userid: a string representing the user's UW NetID :return: True if request is successful, False otherwise. raise DataFailureException or a corresponding TrumbaException if the request failed or an error code has been returned. """ url = _make_del_account...
:param userid: a string representing the user's UW NetID :return: True if request is successful, False otherwise. raise DataFailureException or a corresponding TrumbaException if the request failed or an error code has been returned.
def send_to_observer(self, msg, frm): """ Send the message to the observer. :param msg: the message to send :param frm: the name of the node which sent this `msg` """ logger.debug("{} sending message to observer: {}". format(self, (msg, frm))) ...
Send the message to the observer. :param msg: the message to send :param frm: the name of the node which sent this `msg`
def subsample(self, proposals, targets): """ This method performs the positive/negative sampling, and return the sampled proposals. Note: this function keeps a state. Arguments: proposals (list[BoxList]) targets (list[BoxList]) """ labels...
This method performs the positive/negative sampling, and return the sampled proposals. Note: this function keeps a state. Arguments: proposals (list[BoxList]) targets (list[BoxList])
def get_item_project(self, eitem): """ Get project mapping enrichment field. Twitter mappings is pretty special so it needs a special implementacion. """ project = None eitem_project = {} ds_name = self.get_connector_name() # data source name in projects map ...
Get project mapping enrichment field. Twitter mappings is pretty special so it needs a special implementacion.
def ListNames(self): """List the names of all keys and values.""" # TODO: This check is flawed, because the current definition of # "IsDirectory" is the negation of "is a file". One registry path can # actually refer to a key ("directory"), a value of the same name ("file") # and the default value ...
List the names of all keys and values.
def print_help(self): """ Print the help menu. """ print('\n %s %s' % (self._title or self._name, self._version or '')) if self._usage: print('\n %s' % self._usage) else: cmd = self._name if hasattr(self, '_parent') and isinstance(s...
Print the help menu.
def _complete_type_chain(self, symbol, fullsymbol): """Suggests completion for the end of a type chain.""" target, targmod = self._get_chain_parent_symbol(symbol, fullsymbol) if target is None: return {} result = {} #We might know what kind of symbol to limit the com...
Suggests completion for the end of a type chain.
def device_query_update(self, query_id, body, **kwargs): # noqa: E501 """Update a device query # noqa: E501 Update a specifc device query. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True ...
Update a device query # noqa: E501 Update a specifc device query. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.device_query_update(query_id, body, asynchronous=True) >...
def compute_Pi_V_given_J(self, CDR3_seq, V_usage_mask, J_usage_mask): """Compute Pi_V conditioned on J. This function returns the Pi array from the model factors of the V genomic contributions, P(V, J)*P(delV|V). This corresponds to V(J)_{x_1}. For clarity in parsing the a...
Compute Pi_V conditioned on J. This function returns the Pi array from the model factors of the V genomic contributions, P(V, J)*P(delV|V). This corresponds to V(J)_{x_1}. For clarity in parsing the algorithm implementation, we include which instance attributes are used i...
def validate_url(self, url): """Validate the :class:`~urllib.parse.ParseResult` object. This method will make sure the :meth:`~brownant.app.BrownAnt.parse_url` could work as expected even meet a unexpected URL string. :param url: the parsed url. :type url: :class:`~urllib.parse...
Validate the :class:`~urllib.parse.ParseResult` object. This method will make sure the :meth:`~brownant.app.BrownAnt.parse_url` could work as expected even meet a unexpected URL string. :param url: the parsed url. :type url: :class:`~urllib.parse.ParseResult`
def _persisted_last_epoch(self) -> int: """ Return number of last epoch already calculated """ epoch_number = 0 self._make_sure_dir_exists() for x in os.listdir(self.model_config.checkpoint_dir()): match = re.match('checkpoint_(\\d+)\\.data', x) if match: ...
Return number of last epoch already calculated
def init(FILE): """ Read config file :param FILE: Absolute path to config file (incl. filename) :type FILE: str """ try: cfg.read(FILE) global _loaded _loaded = True except: file_not_found_message(FILE)
Read config file :param FILE: Absolute path to config file (incl. filename) :type FILE: str
def list_themes(directory=None): """Gets a list of the installed themes.""" repo = require_repo(directory) path = os.path.join(repo, themes_dir) return os.listdir(path) if os.path.isdir(path) else None
Gets a list of the installed themes.
def fire_lasers( self, modules: Optional[List[str]] = None, verbose_report: bool = False, transaction_count: Optional[int] = None, ) -> Report: """ :param modules: The analysis modules which should be executed :param verbose_report: Gives out the transaction s...
:param modules: The analysis modules which should be executed :param verbose_report: Gives out the transaction sequence of the vulnerability :param transaction_count: The amount of transactions to be executed :return: The Report class which contains the all the issues/vulnerabilities
def finalize(self): """finalize for PathConsumer""" super(TransposedConsumer, self).finalize() self.result = map(list, zip(*self.result))
finalize for PathConsumer
def handler(event, context): """ Historical {{cookiecutter.technology_name}} event collector. This collector is responsible for processing Cloudwatch events and polling events. """ records = deserialize_records(event['Records']) # Split records into two groups, update and delete. # We don't...
Historical {{cookiecutter.technology_name}} event collector. This collector is responsible for processing Cloudwatch events and polling events.
def get_mac(self): ''' Obtain the device's mac address. ''' ifreq = struct.pack('16sH14s', self.name, AF_UNIX, b'\x00'*14) res = fcntl.ioctl(sockfd, SIOCGIFHWADDR, ifreq) address = struct.unpack('16sH14s', res)[2] mac = struct.unpack('6B8x', address) return ":".join(['%0...
Obtain the device's mac address.
def setPermanences(self, segments, presynapticCellsBySource, permanence): """ Set the permanence of a specific set of synapses. Any synapses that don't exist will be initialized. Any existing synapses will be overwritten. Conceptually, this method takes a list of [segment, presynapticCell] pairs an...
Set the permanence of a specific set of synapses. Any synapses that don't exist will be initialized. Any existing synapses will be overwritten. Conceptually, this method takes a list of [segment, presynapticCell] pairs and initializes their permanence. For each segment, one synapse is added (although o...
def load_indexed_audio(self, indexed_audio_file_abs_path): """ Parameters ---------- indexed_audio_file_abs_path : str """ with open(indexed_audio_file_abs_path, "rb") as f: self.__timestamps = pickle.load(f)
Parameters ---------- indexed_audio_file_abs_path : str
def forward(self, inputs, context, inference=False): """ Execute the decoder. :param inputs: tensor with inputs to the decoder :param context: state of encoder, encoder sequence lengths and hidden state of decoder's LSTM layers :param inference: if True stores and re...
Execute the decoder. :param inputs: tensor with inputs to the decoder :param context: state of encoder, encoder sequence lengths and hidden state of decoder's LSTM layers :param inference: if True stores and repackages hidden state
def search_kv_store(self, key): """Search for a key in the key-value store. :param key: string :rtype: string """ data = { 'operation': 'RETRIEVE', 'key': key } return self.post_json(self.make_url("/useragent-kv"), data)['value']
Search for a key in the key-value store. :param key: string :rtype: string