code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def from_start_and_end(cls, start, end, sequence, helix_type='b_dna', phos_3_prime=False): """Generates a helical `Polynucleotide` that is built along an axis. Parameters ---------- start: [float, float, float] Start of the build axis. end:...
Generates a helical `Polynucleotide` that is built along an axis. Parameters ---------- start: [float, float, float] Start of the build axis. end: [float, float, float] End of build axis. sequence: str The nucleotide sequence of the nucleic ac...
def listen(self): """Blocking call on widgets. """ while self._listen: key = u'' key = self.term.inkey(timeout=0.2) try: if key.code == KEY_ENTER: self.on_enter(key=key) elif key.code in (KEY_DOWN, KEY_UP): ...
Blocking call on widgets.
def get_keyboard_mapping(conn): """ Return a keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment. :rtype: xcb.xproto.GetKeyboardMappingCookie """ mn, mx = get_min_max_keycode(conn) return conn.core.GetKeyboardMapping(mn, mx - mn + 1)
Return a keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment. :rtype: xcb.xproto.GetKeyboardMappingCookie
def takes_kwargs(obj) -> bool: """ Checks whether a provided object takes in any positional arguments. Similar to takes_arg, we do this for both the __init__ function of the class or a function / method Otherwise, we raise an error """ if inspect.isclass(obj): signature = inspect.sig...
Checks whether a provided object takes in any positional arguments. Similar to takes_arg, we do this for both the __init__ function of the class or a function / method Otherwise, we raise an error
def makeLogic(self): # *** When camera list has been closed, re-create the cameralist tree and update filterchains *** # self.manage_cameras_win.signals.close.connect(self.updateCameraTree) # now put into save_camera_config_slot # self.manage_cameras_win.signals.close.connect(self.filte...
self.configmenu.manage_cameras. triggered.connect( self.manage_cameras_slot) self.configmenu.memory_usage. triggered.connect( self.memory_usage_slot)
def bake(self): """Find absolute times for all keys. Absolute time is stored in the KeyFrame dictionary as the variable __abs_time__. """ self.unbake() for key in self.dct: self.get_absolute_time(key) self.is_baked = True
Find absolute times for all keys. Absolute time is stored in the KeyFrame dictionary as the variable __abs_time__.
def un_priority(op,val): "unary expression order-of-operations helper" if isinstance(val,BinX) and val.op < op: return bin_priority(val.op,UnX(op,val.left),val.right) else: return UnX(op,val)
unary expression order-of-operations helper
def dfa_intersection(dfa_1: dict, dfa_2: dict) -> dict: """ Returns a DFA accepting the intersection of the DFAs in input. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs. Then there is a DFA :math:`A_∧` that runs simultaneously both ...
Returns a DFA accepting the intersection of the DFAs in input. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs. Then there is a DFA :math:`A_∧` that runs simultaneously both :math:`A_1` and :math:`A_2` on the input word and accepts w...
def set_locale(request): """Return locale from GET lang param or automatically.""" return request.query.get('lang', app.ps.babel.select_locale_by_request(request))
Return locale from GET lang param or automatically.
def compute_performance(SC, verbose=True, output='dict'): """ Return some performance value for comparison. Parameters ------- SC: SortingComparison instance The SortingComparison verbose: bool Display on console or not output: dict or pandas Returns ---------- ...
Return some performance value for comparison. Parameters ------- SC: SortingComparison instance The SortingComparison verbose: bool Display on console or not output: dict or pandas Returns ---------- performance: dict or pandas.Serie depending output param
def eth_getBlockByHash(self, bhash, tx_objects=True): """https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblockbyhash :param bhash: Block hash :type bhash: str :param tx_objects: Return txs full object (optional) :type tx_objects: bool :return: block :rtyp...
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblockbyhash :param bhash: Block hash :type bhash: str :param tx_objects: Return txs full object (optional) :type tx_objects: bool :return: block :rtype: dict or None
def get_kline(self, symbol, period, size=150): """ 获取K线 :param symbol :param period: 可选值:{1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year } :param size: 可选值: [1,2000] :return: """ params = {'symbol': symbol, 'period': period, 'size': size} ...
获取K线 :param symbol :param period: 可选值:{1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year } :param size: 可选值: [1,2000] :return:
def persist_uncles(self, uncles: Tuple[BlockHeader]) -> Hash32: """ Persists the list of uncles to the database. Returns the uncles hash. """ return self._persist_uncles(self.db, uncles)
Persists the list of uncles to the database. Returns the uncles hash.
def update_ip_address(context, id, ip_address): """Due to NCP-1592 ensure that address_type cannot change after update.""" LOG.info("update_ip_address %s for tenant %s" % (id, context.tenant_id)) ports = [] if 'ip_address' not in ip_address: raise n_exc.BadRequest(resource="ip_addresses", ...
Due to NCP-1592 ensure that address_type cannot change after update.
def template_global(self, name: Optional[str]=None) -> Callable: """Add a template global. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.template_global('name') def five(): return 5 Arguments: ...
Add a template global. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.template_global('name') def five(): return 5 Arguments: name: The global name (defaults to function name).
def validate_tenant_data(self, expected, actual): """Validate tenant data. Validate a list of actual tenant data vs list of expected tenant data. """ self.log.debug('Validating tenant data...') self.log.debug('actual: {}'.format(repr(actual))) for e in e...
Validate tenant data. Validate a list of actual tenant data vs list of expected tenant data.
def unregisterHandler(self, fh): """ Unregister a file descriptor. Clean data, if such operation has been scheduled. Parameters ---------- fh : int File descriptor. """ try: self.fds.remove(fh) except KeyError: pass ...
Unregister a file descriptor. Clean data, if such operation has been scheduled. Parameters ---------- fh : int File descriptor.
def _sample_template(sample, out_dir): """R code to get QC for one sample""" bam_fn = dd.get_work_bam(sample) genome = dd.get_genome_build(sample) if genome in supported: peaks = sample.get("peaks_files", []).get("main") if peaks: r_code = ("library(ChIPQC);\n" ...
R code to get QC for one sample
def parse_args(): """ Parse the command line arguments """ parser = argparse.ArgumentParser(description = "Validate secrets using YubiHSM", add_help=True, formatter_class=argparse.ArgumentDefaultsHelpFormatter, ...
Parse the command line arguments
def sort_stats(stats, sortedby='cpu_percent', sortedby_secondary='memory_percent', reverse=True): """Return the stats (dict) sorted by (sortedby). Reverse the sort if reverse is True. """ if sortedby is None and sortedby_secondary is None: # No need ...
Return the stats (dict) sorted by (sortedby). Reverse the sort if reverse is True.
def update_or_append_line(filename, prefix, new_line, keep_backup=True, append=True): '''Search in file 'filename' for a line starting with 'prefix' and replace the line by 'new_line'. If a line starting with 'prefix' not exists 'new_line' will be appended. If the file not exi...
Search in file 'filename' for a line starting with 'prefix' and replace the line by 'new_line'. If a line starting with 'prefix' not exists 'new_line' will be appended. If the file not exists, it will be created. Return False if new_line was appended, else True (i.e. if the prefix was found within...
def elide(self, line: str, regexp: str, quantity: int = 1, offset: int = 0) -> str: """ Erase a section of a line, matching on a regex, pushing in a quantity of blank spaces, and jumping forward with an offset if necessary. If the elided vowel was strong, the vowel merged with takes on t...
Erase a section of a line, matching on a regex, pushing in a quantity of blank spaces, and jumping forward with an offset if necessary. If the elided vowel was strong, the vowel merged with takes on the stress. :param line: :param regexp: :param quantity: :param offset: ...
def record2marcxml(record): """Convert a JSON record to a MARCXML string. Deduces which set of rules to use by parsing the ``$schema`` key, as it unequivocally determines which kind of record we have. Args: record(dict): a JSON record. Returns: str: a MARCXML string converted from...
Convert a JSON record to a MARCXML string. Deduces which set of rules to use by parsing the ``$schema`` key, as it unequivocally determines which kind of record we have. Args: record(dict): a JSON record. Returns: str: a MARCXML string converted from the record.
def cache_from_names(self): """Yield the image names to do --cache-from from""" cache_from = self.cache_from() if not cache_from or cache_from is NotSpecified: return if cache_from is True: yield self.image_name return for thing in cache_fro...
Yield the image names to do --cache-from from
def addparentstofks(rels, fks): """ Get a list of relations, between parents and sons and a dict of clases named in dia, and modifies the fks to add the parent as fk to get order on the output of classes and replaces the base class of the son, to put the class parent name. """ for j in rels:...
Get a list of relations, between parents and sons and a dict of clases named in dia, and modifies the fks to add the parent as fk to get order on the output of classes and replaces the base class of the son, to put the class parent name.
def _disambiguate_star_fusion_junctions(star_junction_file, contamination_bam, disambig_out_file, data): """ Disambiguate detected fusions based on alignments to another species. """ out_file = disambig_out_file fusiondict = {} with open(star_junction_file, "r") as in_handle: for my_line in ...
Disambiguate detected fusions based on alignments to another species.
def entry_point(entry_point_name): """Use this to decorate a DNAnexus execution environment entry point. Example: .. code-block:: python @dxpy.entry_point('main') def hello(i): pass """ def wrap(f): ENTRY_POINT_TABLE[entry_point_name] = f @wraps(f) ...
Use this to decorate a DNAnexus execution environment entry point. Example: .. code-block:: python @dxpy.entry_point('main') def hello(i): pass
def instantiate_config(config): '''setup the config and load external modules This updates 'config' as follows: * All paths are replaced with absolute paths * A hash and JSON dump of the config are stored in the config * If 'pythonpath' is in the config, it is added to sys.path * If 'setup_mod...
setup the config and load external modules This updates 'config' as follows: * All paths are replaced with absolute paths * A hash and JSON dump of the config are stored in the config * If 'pythonpath' is in the config, it is added to sys.path * If 'setup_modules' is in the config, all modules nam...
def _signed_sub_overflow(state, a, b): """ Sign extend the value to 512 bits and check the result can be represented in 256. Following there is a 32 bit excerpt of this condition: a - b -80000000 -3fffffff -00000001 +00000000 +00000001 +3fffffff +7fffffff +80000000 False ...
Sign extend the value to 512 bits and check the result can be represented in 256. Following there is a 32 bit excerpt of this condition: a - b -80000000 -3fffffff -00000001 +00000000 +00000001 +3fffffff +7fffffff +80000000 False False False False True True True ...
def insert(self, index, child): '''Insert ``child`` into the list of :attr:`children` at ``index``. :param index: The index (positive integer) where to insert ``child``. :param child: String, bytes or another :class:`String`. If it is an :class:`.String`, this instance will be set a...
Insert ``child`` into the list of :attr:`children` at ``index``. :param index: The index (positive integer) where to insert ``child``. :param child: String, bytes or another :class:`String`. If it is an :class:`.String`, this instance will be set as its :attr:`parent`. ...
def read_raw(self, params=None): """Get information about the current entity. Make an HTTP GET call to ``self.path('self')``. Return the response. :return: A ``requests.response`` object. """ path_type = self._meta.get('read_type', 'self') return client.get( ...
Get information about the current entity. Make an HTTP GET call to ``self.path('self')``. Return the response. :return: A ``requests.response`` object.
def main(): """Parse the command-line arguments and run the bot.""" parser = argparse.ArgumentParser(description = 'XMPP echo bot', parents = [XMPPSettings.get_arg_parser()]) parser.add_argument('jid', metavar = 'JID', help = 'The ...
Parse the command-line arguments and run the bot.
def make_even_size(x): """Pad x to be even-sized on axis 1 and 2, but only if necessary.""" x_shape = x.get_shape().as_list() assert len(x_shape) > 2, "Only 3+-dimensional tensors supported." shape = [dim if dim is not None else -1 for dim in x_shape] new_shape = x_shape # To make sure constant shapes remain...
Pad x to be even-sized on axis 1 and 2, but only if necessary.
def create_system(self): """Get an instance of Api System Variables services facade.""" return System( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of Api System Variables services facade.
def jd_corr(jd, ra, dec, obslon=None, obslat=None, obsalt=None, jd_type='bjd'): '''Returns BJD_TDB or HJD_TDB for input JD_UTC. The equation used is:: BJD_TDB = JD_UTC + JD_to_TDB_corr + romer_delay where: - JD_to_TDB_corr is the di...
Returns BJD_TDB or HJD_TDB for input JD_UTC. The equation used is:: BJD_TDB = JD_UTC + JD_to_TDB_corr + romer_delay where: - JD_to_TDB_corr is the difference between UTC and TDB JDs - romer_delay is the delay caused by finite speed of light from Earth-Sun This is based on the code at: ...
def read_csv_with_errors(cls, url, delimiter=',', header=True, comment_char='', escape_char='\\', double_quote=True, ...
Constructs an SFrame from a CSV file or a path to multiple CSVs, and returns a pair containing the SFrame and a dict of filenames to SArrays indicating for each file, what are the incorrectly parsed lines encountered. Parameters ---------- url : string Locati...
def update(self, auth_payload=values.unset): """ Update the ChallengeInstance :param unicode auth_payload: Optional payload to verify the Challenge :returns: Updated ChallengeInstance :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance """ ...
Update the ChallengeInstance :param unicode auth_payload: Optional payload to verify the Challenge :returns: Updated ChallengeInstance :rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance
def build_plane_arrays(x, y, qlist): """Build a 2-D array out of data taken in the same plane, for contour plotting. """ if type(qlist) is not list: return_list = False qlist = [qlist] else: return_list = True xv = x[np.where(y==y[0])[0]] yv = y[np.where(x==...
Build a 2-D array out of data taken in the same plane, for contour plotting.
def merge_links_from(self, other_node, merge_same_value_targets=False): """ Merge links from another node with ``self.link_list``. Copy links from another node, merging when copied links point to a node which this already links to. Args: other_node (Node): The node ...
Merge links from another node with ``self.link_list``. Copy links from another node, merging when copied links point to a node which this already links to. Args: other_node (Node): The node to merge links from merge_same_value_targets (bool): Whether or not to merge lin...
def comment(self, issue, body): """Comment on existing issue on Github. For JSON data returned by Github refer: https://developer.github.com/v3/issues/comments/#create-a-comment :param issue: object of exisiting issue :param body: body of the comment :returns: dict of JS...
Comment on existing issue on Github. For JSON data returned by Github refer: https://developer.github.com/v3/issues/comments/#create-a-comment :param issue: object of exisiting issue :param body: body of the comment :returns: dict of JSON data returned by Github of the new comme...
def insert_data(self, travel_impedance_measure_name, data): """ Parameters ---------- travel_impedance_measure_name: str data: list[dict] Each list element must contain keys: "from_stop_I", "to_stop_I", "min", "max", "median" and "mean" """ ...
Parameters ---------- travel_impedance_measure_name: str data: list[dict] Each list element must contain keys: "from_stop_I", "to_stop_I", "min", "max", "median" and "mean"
def span_path(cls, project, trace, span): """Return a fully-qualified span string.""" return google.api_core.path_template.expand( "projects/{project}/traces/{trace}/spans/{span}", project=project, trace=trace, span=span, )
Return a fully-qualified span string.
def _handle_output(self, channel, output): """ Given an initial channel and a sequence of messages or sentinels, output the messages. """ augmented = Sentinel.augment_items(output, channel=channel, secret=False) for message in augmented: self.out(message.channel, message, not message.secret)
Given an initial channel and a sequence of messages or sentinels, output the messages.
def to_range(obj, score=None, id=None, strand=None): """ Given a gffutils object, convert it to a range object """ from jcvi.utils.range import Range if score or id: _score = score if score else obj.score _id = id if id else obj.id return Range(seqid=obj.seqid, start=obj.sta...
Given a gffutils object, convert it to a range object
def get_metadata(self, obj, prefix=None): """ Returns the metadata for the specified object as a dict. """ uri = "/%s/%s" % (self.uri_base, utils.get_name(obj)) resp, resp_body = self.api.method_head(uri) ret = {} # Add the metadata prefix, if needed. if p...
Returns the metadata for the specified object as a dict.
def importProteinDatabase(filePath, proteindb=None, decoyTag='[decoy]', contaminationTag='[cont]', headerParser=None, forceId=False, cleavageRule='[KR]', minLength=5, maxLength=40, missedCleavage=2, ignoreIsoleucine=False, removeNtermM=True): """Generates a :class:`ProteinDatabase` by in sil...
Generates a :class:`ProteinDatabase` by in silico digestion of proteins from a fasta file. :param filePath: File path :param proteindb: optional an existing :class:`ProteinDatabase` can be specified, otherwise a new instance is generated and returned :param decoyTag: If a fasta file contains de...
def request(self, method, url, body=None, content_type='application/json'): """Send http request.""" headers = self.make_auth_headers(content_type) connection = http_client.HTTPSConnection(self.apibase) connection.request(method, url, body, headers=headers) response = connection....
Send http request.
def predict_log_proba(self, X): """ Apply transforms, and predict_log_proba of the final estimator Parameters ---------- X : iterable Data to predict on. Must fulfill input requirements of first step of the pipeline. Returns ------- ...
Apply transforms, and predict_log_proba of the final estimator Parameters ---------- X : iterable Data to predict on. Must fulfill input requirements of first step of the pipeline. Returns ------- y_score : array-like, shape = [n_samples, n_class...
def stop(self): """ Stops monitoring the predefined directory. """ with self._status_lock: if self._running: assert self._observer is not None self._observer.stop() self._running = False self._origin_mapped_data ...
Stops monitoring the predefined directory.
def PopupGetFolder(message, title=None, default_path='', no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None, None), initial_fol...
Display popup with text entry field and browse button. Browse for folder :param message: :param default_path: :param no_window: :param size: :param button_color: :param background_color: :param text_color: :param icon: :param font: :param no_titlebar: :param grab_anywhere: ...
def get_check_point(self, project, logstore, consumer_group, shard=-1): """ Get check point :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type consumer_group: string :param consumer_group: co...
Get check point :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type consumer_group: string :param consumer_group: consumer group name :type shard: int :param shard: shard id ...
def passageLoop(parent, new_tree, xpath1, xpath2=None, preceding_siblings=False, following_siblings=False): """ Loop over passages to construct and increment new tree given a parent and XPaths :param parent: Parent on which to perform xpath :param new_tree: Parent on which to add nodes :param xpath1: L...
Loop over passages to construct and increment new tree given a parent and XPaths :param parent: Parent on which to perform xpath :param new_tree: Parent on which to add nodes :param xpath1: List of xpath elements :type xpath1: [str] :param xpath2: List of xpath elements :type xpath2: [str] ...
def refine_peak(tsmap, pix): """Solve for the position and uncertainty of source assuming that you are near the maximum and the errors are parabolic Parameters ---------- tsmap : `~numpy.ndarray` Array with the TS data. Returns ------- The position and uncertainty of the source,...
Solve for the position and uncertainty of source assuming that you are near the maximum and the errors are parabolic Parameters ---------- tsmap : `~numpy.ndarray` Array with the TS data. Returns ------- The position and uncertainty of the source, in pixel units w.r.t. the cente...
def isxmap(xmethod, opt): """Return ``isxmap`` argument for ``.IterStatsConfig`` initialiser. """ if xmethod == 'admm': isx = {'XPrRsdl': 'PrimalRsdl', 'XDlRsdl': 'DualRsdl', 'XRho': 'Rho'} else: isx = {'X_F_Btrack': 'F_Btrack', 'X_Q_Btrack': 'Q_Btrack', 'X...
Return ``isxmap`` argument for ``.IterStatsConfig`` initialiser.
def get_overlay_spec(o, k, v): """ Gets the type.group.label + key spec from an Element in an Overlay. """ k = wrap_tuple(k) return ((type(v).__name__, v.group, v.label) + k if len(o.kdims) else (type(v).__name__,) + k)
Gets the type.group.label + key spec from an Element in an Overlay.
def all_other_enabled_satchels(self): """ Returns a dictionary of satchels used in the current configuration, excluding ourselves. """ return dict( (name, satchel) for name, satchel in self.all_satchels.items() if name != self.name.upper() and name.low...
Returns a dictionary of satchels used in the current configuration, excluding ourselves.
def json_response(obj): """ returns a json response from a json serializable python object """ return Response( response=json.dumps( obj, indent=4, cls=AirflowJsonEncoder), status=200, mimetype="application/json")
returns a json response from a json serializable python object
def attention_lm_moe_24b_diet(): """Unnecessarily large model with 24B params - because we can.""" hparams = attention_lm_moe_large_diet() hparams.moe_hidden_sizes = "12288" hparams.moe_num_experts = 1024 hparams.batch_size = 4096 return hparams
Unnecessarily large model with 24B params - because we can.
def name(self): """Concatenates the names of the given criteria in alphabetical order. If a sub-criterion is itself a combined criterion, its name is first split into the individual names and the names of the sub-sub criteria is used instead of the name of the sub-criterion. Thi...
Concatenates the names of the given criteria in alphabetical order. If a sub-criterion is itself a combined criterion, its name is first split into the individual names and the names of the sub-sub criteria is used instead of the name of the sub-criterion. This is done recursively to en...
def reduce_sequences(object_a, object_b): """Performs an element-wise addition of sequences into a new list. Both sequences must have the same length, and the addition operator must be defined for each element of the sequence. """ def is_seq(obj): """Returns true if the object passed is a s...
Performs an element-wise addition of sequences into a new list. Both sequences must have the same length, and the addition operator must be defined for each element of the sequence.
def run(cmd, input=None, capture_output=False, check=False, quiet=False, **kwargs): """Run the command described by cmd and return its (stdout, stderr) tuple.""" if input is not None: kwargs['stdin'] = subprocess.PIPE if capture_output: kwargs['stdout'] = kwargs['stderr'] = subprocess.PIPE ...
Run the command described by cmd and return its (stdout, stderr) tuple.
def verify_resource_dict(res_dict, is_create, attr_info): """Verifies required attributes are in resource dictionary, res_dict. Also checking that an attribute is only specified if it is allowed for the given operation (create/update). Attribute with default values are considered to be optional. ...
Verifies required attributes are in resource dictionary, res_dict. Also checking that an attribute is only specified if it is allowed for the given operation (create/update). Attribute with default values are considered to be optional. This function contains code taken from function 'prepare_request_...
def load_alleles_dict(): """Create a dictionary mapping each unique allele name to a namedtuple containing information about that alleles class, locus, species, &c. """ alleles = load_alleles() result = {} for allele in alleles: for name in {allele.name}.union(allele.synonyms): ...
Create a dictionary mapping each unique allele name to a namedtuple containing information about that alleles class, locus, species, &c.
def ordered_repr(obj: object, attrlist: Iterable[str], joiner: str = COMMA_SPACE) -> str: """ Shortcut to make :func:`repr` functions ordered. Define your :func:`__repr__` like this: .. code-block:: python def __repr__(self): return ordered_repr(self, ["field1", "f...
Shortcut to make :func:`repr` functions ordered. Define your :func:`__repr__` like this: .. code-block:: python def __repr__(self): return ordered_repr(self, ["field1", "field2", "field3"]) Args: obj: object to display attrlist: iterable of attribute names join...
def delete_client(self, identifier): """Delete client.""" params = {'id': identifier} response = yield from self._transact(SERVER_DELETECLIENT, params) self.synchronize(response)
Delete client.
def distribute(self, func, partitioned_chunks, kwargs): """ Calculates the features in a parallel fashion by distributing the map command to the dask workers on a local machine :param func: the function to send to each worker. :type func: callable :param partitioned_chun...
Calculates the features in a parallel fashion by distributing the map command to the dask workers on a local machine :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again a list of ch...
def iters(cls, batch_size=32, device=0, root='.data', vectors=None, **kwargs): """Create iterator objects for splits of the SST dataset. Arguments: batch_size: Batch_size device: Device to create batches on. Use - 1 for CPU and None for the currently active GPU d...
Create iterator objects for splits of the SST dataset. Arguments: batch_size: Batch_size device: Device to create batches on. Use - 1 for CPU and None for the currently active GPU device. root: The root directory that the dataset's zip archive will be ...
def setup_groups(portal): """Setup roles and groups for BECHEM """ logger.info("*** Setup Roles and Groups ***") portal_groups = api.get_tool("portal_groups") for gdata in GROUPS: group_id = gdata["id"] # create the group and grant the roles if group_id not in portal_groups...
Setup roles and groups for BECHEM
def add_series(self, series): """Adds a :py:class:`.Series` to the chart. :param Series series: The :py:class:`.Series` to add.""" if not isinstance(series, Series): raise TypeError("'%s' is not a Series" % str(series)) self._all_series.append(series) series._chart ...
Adds a :py:class:`.Series` to the chart. :param Series series: The :py:class:`.Series` to add.
def _rotate_to_arbitrary_vector(v,a,inv=False,_dontcutsmall=False): """ Return a rotation matrix that rotates v to align with unit vector a i.e. R . v = |v|\hat{a} """ normv= v/numpy.tile(numpy.sqrt(numpy.sum(v**2.,axis=1)),(3,1)).T rotaxis= numpy.cross(normv,a) rotaxis/= numpy.tile(numpy.sqrt(n...
Return a rotation matrix that rotates v to align with unit vector a i.e. R . v = |v|\hat{a}
def find_primitive(cell, symprec=1e-5, angle_tolerance=-1.0): """Primitive cell is searched in the input cell. The primitive cell is returned by a tuple of (lattice, positions, numbers). If it fails, None is returned. """ _set_no_error() lattice, positions, numbers, _ = _expand_cell(cell) ...
Primitive cell is searched in the input cell. The primitive cell is returned by a tuple of (lattice, positions, numbers). If it fails, None is returned.
def page(self, value): """ Set the page which will be returned. :param value: 'page' parameter value for the rest api call :type value: str Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object """ instance = copy(self) ins...
Set the page which will be returned. :param value: 'page' parameter value for the rest api call :type value: str Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object
def def_variables(s): """ blabla """ frame = inspect.currentframe().f_back try: if isinstance(s,str): s = re.split('\s|,', s) res = [] for t in s: # skip empty stringG if not t: continue if t.count("@") > 0: ...
blabla
def charset_to_int(s, charset): """ Turn a string into a non-negative integer. >>> charset_to_int('0', B40_CHARS) 0 >>> charset_to_int('10', B40_CHARS) 40 >>> charset_to_int('abcd', B40_CHARS) 658093 >>> charset_to_int('', B40_CHARS) 0 >>> charset_to_int('muneeb.id', B40_CHARS) ...
Turn a string into a non-negative integer. >>> charset_to_int('0', B40_CHARS) 0 >>> charset_to_int('10', B40_CHARS) 40 >>> charset_to_int('abcd', B40_CHARS) 658093 >>> charset_to_int('', B40_CHARS) 0 >>> charset_to_int('muneeb.id', B40_CHARS) 149190078205533 >>> charset_to_i...
def read(self, user=True, defaults=True): """Find and read the files for this configuration and set them as the sources for this configuration. To disable either discovered user configuration files or the in-package defaults, set `user` or `defaults` to `False`. """ if us...
Find and read the files for this configuration and set them as the sources for this configuration. To disable either discovered user configuration files or the in-package defaults, set `user` or `defaults` to `False`.
def training(loss_op): """Calculates the loss from the logits and the labels. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor of type float. """ global_step = tf.Variable(0, name='global_step', trainable=False...
Calculates the loss from the logits and the labels. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor of type float.
def sha1_digest(instr): ''' Generate an sha1 hash of a given string. ''' if six.PY3: b = salt.utils.stringutils.to_bytes(instr) return hashlib.sha1(b).hexdigest() return hashlib.sha1(instr).hexdigest()
Generate an sha1 hash of a given string.
def mod_sys_path(paths): """ A context manager that will append the specified paths to Python's ``sys.path`` during the execution of the block. :param paths: the paths to append :type paths: list(str) """ old_path = sys.path sys.path = paths + sys.path try: yield finall...
A context manager that will append the specified paths to Python's ``sys.path`` during the execution of the block. :param paths: the paths to append :type paths: list(str)
def simxGetDialogResult(clientID, dialogHandle, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' result = ct.c_int() return c_GetDialogResult(clientID, dialogHandle, ct.byref(result), operationMode), result.value
Please have a look at the function description/documentation in the V-REP user manual
def set_client(self, *args, **kwargs): ''' Se você possui informações cadastradas sobre o comprador você pode utilizar este método para enviar estas informações para o PagSeguro. É uma boa prática pois evita que seu cliente tenha que preencher estas informações novamente na página do Pag...
Se você possui informações cadastradas sobre o comprador você pode utilizar este método para enviar estas informações para o PagSeguro. É uma boa prática pois evita que seu cliente tenha que preencher estas informações novamente na página do PagSeguro. Args: name (str): (opc...
def get_facet_keys_as_list(self,field): ''' :param str field: Name of facet field to retrieve keys from. Similar to get_facet_values_as_list but returns the list of keys as a list instead. Example:: >>> r.get_facet_keys_as_list('facet_test') ['Lorem', 'ipsum', '...
:param str field: Name of facet field to retrieve keys from. Similar to get_facet_values_as_list but returns the list of keys as a list instead. Example:: >>> r.get_facet_keys_as_list('facet_test') ['Lorem', 'ipsum', 'amet,', 'dolor', 'sit']
def init_benchmarks(n_values=None): """Initialize the strings we'll run the regexes against. The strings used in the benchmark are prefixed and suffixed by strings that are repeated n times. The sequence n_values contains the values for n. If n_values is None the values of n from the original benc...
Initialize the strings we'll run the regexes against. The strings used in the benchmark are prefixed and suffixed by strings that are repeated n times. The sequence n_values contains the values for n. If n_values is None the values of n from the original benchmark are used. The generated list...
def sqlmany(self, stringname, *args): """Wrapper for executing many SQL calls on my connection. First arg is the name of a query, either a key in the precompiled JSON or a method name in ``allegedb.alchemy.Alchemist``. Remaining arguments should be tuples of argument sequences t...
Wrapper for executing many SQL calls on my connection. First arg is the name of a query, either a key in the precompiled JSON or a method name in ``allegedb.alchemy.Alchemist``. Remaining arguments should be tuples of argument sequences to be passed to the query.
def compile_state_action_constraints(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor]) -> List[TensorFluent]: '''Compiles the state-action constraints given current `state` and `action` fluents. Args: state (Sequence[tf.Tensor]): The current state fluent...
Compiles the state-action constraints given current `state` and `action` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A list of :obj:`rddl2tf.fluent.TensorFluent`.
def get_help_msg(self, dotspace_ending=False, # type: bool **kwargs): # type: (...) -> str """ The method used to get the formatted help message according to kwargs. By default it returns the 'help_msg' attribute, whether it is defined at the in...
The method used to get the formatted help message according to kwargs. By default it returns the 'help_msg' attribute, whether it is defined at the instance level or at the class level. The help message is formatted according to help_msg.format(**kwargs), and may be terminated with a dot and a ...
def add_userids_for_address(self, address: Address, user_ids: Iterable[str]): """ Add multiple ``user_ids`` for the given ``address``. Implicitly adds any addresses if they were unknown before. """ self._address_to_userids[address].update(user_ids)
Add multiple ``user_ids`` for the given ``address``. Implicitly adds any addresses if they were unknown before.
def get_package_filename(filename, package_dir=None): '''Return the filename of the data file.''' if getattr(sys, 'frozen', False): package_dir = os.path.join( sys._MEIPASS, os.path.basename(os.path.dirname(__file__)) ) elif not package_dir: package_dir = os.p...
Return the filename of the data file.
def create_stack(self, stack_name, template_body=None, template_url=None, parameters=[], notification_arns=[], disable_rollback=False, timeout_in_minutes=None, capabilities=None): """ Creates a CloudFormation Stack as specified by the template. :type stack_name: string ...
Creates a CloudFormation Stack as specified by the template. :type stack_name: string :param stack_name: The name of the Stack, must be unique amoung running Stacks :type template_body: string :param template_body: The template body (JSON string) :t...
def print_build_info(zipped_pex=False): """Print build_info from release.yaml :param zipped_pex: True if the PEX file is built with flag `zip_safe=False'. """ if zipped_pex: release_file = get_zipped_heron_release_file() else: release_file = get_heron_release_file() with open(release_file) as rele...
Print build_info from release.yaml :param zipped_pex: True if the PEX file is built with flag `zip_safe=False'.
def rewire_inputs(data_list): """Rewire inputs of provided data objects. Input parameter is a list of original and copied data object model instances: ``[{'original': original, 'copy': copy}]``. This function finds which objects reference other objects (in the list) on the input and replaces origin...
Rewire inputs of provided data objects. Input parameter is a list of original and copied data object model instances: ``[{'original': original, 'copy': copy}]``. This function finds which objects reference other objects (in the list) on the input and replaces original objects with the copies (mutates ...
def get_clients_groups(self) -> typing.Iterator['Group']: """ Gets all clients groups Returns: generator of Groups """ for group in self.groups: if group.group_is_client_group: yield group
Gets all clients groups Returns: generator of Groups
def _set_signed_in(self): """Populate the signed_in list with the names of currently signed in users. """ names = [ controller.get_user_name(user, full_name=CONFIG['FULL_USER_NAMES']) for user in controller.signed_in_users() ] self.lbl_signedin_lis...
Populate the signed_in list with the names of currently signed in users.
def cleanup(self): """ Clean up the saved state. """ if os.path.exists(self.path): os.remove(self.path)
Clean up the saved state.
def download_file(self, response, outfile, quiet=True, chunk_size=1048576): """ download a file to an output file based on a chunk size Parameters ========== response: the response to download outfile: the output file to download to quiet: suppress ve...
download a file to an output file based on a chunk size Parameters ========== response: the response to download outfile: the output file to download to quiet: suppress verbose output (default is True) chunk_size: the size of the chunk to stream
def node_has_namespace(self, node: BaseEntity, namespace: str) -> bool: """Check if the node have the given namespace. This also should look in the equivalent nodes. """ return any( self._node_has_namespace_helper(n, namespace) for n in self.iter_equivalent_nodes...
Check if the node have the given namespace. This also should look in the equivalent nodes.
def user_stats_api(request, provider): """ Get statistics for selected Edookit users key: api key since: time as timestamp - get stats changed since """ if 'key' not in request.GET or provider not in settings.USER_STATS_API_KEY \ or request.GET['key'] != settings.USER_S...
Get statistics for selected Edookit users key: api key since: time as timestamp - get stats changed since
def between(self, low, high): """ Sets the operator type to Query.Op.Between and sets the value to a tuple of the two inputted values. :param low | <variant> :param high | <variant> :return <Query> :usage |>>> from orb...
Sets the operator type to Query.Op.Between and sets the value to a tuple of the two inputted values. :param low | <variant> :param high | <variant> :return <Query> :usage |>>> from orb import Query as Q |>>> query ...
def Hi(self, str_, salt, i): """The Hi(str, salt, i) function.""" # pylint: disable=C0103 Uj = self.HMAC(str_, salt + b"\000\000\000\001") # U1 result = Uj for _ in range(2, i + 1): Uj = self.HMAC(str_, Uj) # Uj = HMAC(str, Uj-1) result = sel...
The Hi(str, salt, i) function.
def _create_network_config(self): """ If network config is empty we create a sample config """ path = os.path.join(self.working_dir, "etc", "network") os.makedirs(path, exist_ok=True) open(os.path.join(path, ".gns3_perms"), 'a').close() os.makedirs(os.path.join(pa...
If network config is empty we create a sample config
def get_section_path(section): """Return a list with keys to access the section from root :param section: A Section :type section: Section :returns: list of strings in the order to access the given section from root :raises: None """ keys = [] p = section for i in range(section.dept...
Return a list with keys to access the section from root :param section: A Section :type section: Section :returns: list of strings in the order to access the given section from root :raises: None