code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def findall(dir = os.curdir): """Find all files under 'dir' and return the list of full filenames (relative to 'dir'). """ all_files = [] for base, dirs, files in os.walk(dir, followlinks=True): if base==os.curdir or base.startswith(os.curdir+os.sep): base = base[2:] if b...
Find all files under 'dir' and return the list of full filenames (relative to 'dir').
def unit_vector_game(n, avoid_pure_nash=False, random_state=None): """ Return a NormalFormGame instance of the 2-player game "unit vector game" (Savani and von Stengel, 2016). Payoffs for player 1 are chosen randomly from the [0, 1) range. For player 0, each column contains exactly one 1 payoff and ...
Return a NormalFormGame instance of the 2-player game "unit vector game" (Savani and von Stengel, 2016). Payoffs for player 1 are chosen randomly from the [0, 1) range. For player 0, each column contains exactly one 1 payoff and the rest is 0. Parameters ---------- n : scalar(int) Numbe...
def contains(self, key): """Does this configuration contain a given key?""" if self._jconf is not None: return self._jconf.contains(key) else: return key in self._conf
Does this configuration contain a given key?
def get_queryset(self): """ Implements before date filtering on ``date_field`` """ kwargs = {} if self.ends_at: kwargs.update({'%s__lt' % self.date_field: self.ends_at}) return super(BeforeMixin, self).get_queryset().filter(**kwargs)
Implements before date filtering on ``date_field``
def remove_unreferenced_items(self, stale_cts): """ See if there are items that no longer point to an existing parent. """ stale_ct_ids = list(stale_cts.keys()) parent_types = (ContentItem.objects.order_by() .exclude(polymorphic_ctype__in=stale_ct_ids) ...
See if there are items that no longer point to an existing parent.
def get_organizer(self, id, **data): """ GET /organizers/:id/ Gets an :format:`organizer` by ID as ``organizer``. """ return self.get("/organizers/{0}/".format(id), data=data)
GET /organizers/:id/ Gets an :format:`organizer` by ID as ``organizer``.
def _copy_from(self, node, copy_leaves=True, overwrite=False, with_links=True): """Pass a ``node`` to insert the full tree to the trajectory. Considers all links in the given node! Ignored nodes already found in the c...
Pass a ``node`` to insert the full tree to the trajectory. Considers all links in the given node! Ignored nodes already found in the current trajectory. :param node: The node to insert :param copy_leaves: If leaves should be **shallow** copied or simply referred to by bot...
def clear_modules(self): """ Clears the modules snapshot. """ for aModule in compat.itervalues(self.__moduleDict): aModule.clear() self.__moduleDict = dict()
Clears the modules snapshot.
def add(self, name, path): """Add a workspace entry in user config file.""" if not (os.path.exists(path)): raise ValueError("Workspace path `%s` doesn't exists." % path) if (self.exists(name)): raise ValueError("Workspace `%s` already exists." % name) self.confi...
Add a workspace entry in user config file.
def read_raw_parser_conf(data: str) -> dict: """We expect to have a section like this ``` [commitizen] name = cz_jira files = [ "commitizen/__version__.py", "pyproject.toml" ] # this tab at the end is important ``` """ config = configparser.ConfigParser(allow_no...
We expect to have a section like this ``` [commitizen] name = cz_jira files = [ "commitizen/__version__.py", "pyproject.toml" ] # this tab at the end is important ```
async def close(self): """Attempt to gracefully close all connections in the pool. Wait until all pool connections are released, close them and shut down the pool. If any error (including cancellation) occurs in ``close()`` the pool will terminate by calling :meth:`Pool.termina...
Attempt to gracefully close all connections in the pool. Wait until all pool connections are released, close them and shut down the pool. If any error (including cancellation) occurs in ``close()`` the pool will terminate by calling :meth:`Pool.terminate() <pool.Pool.terminate>`. ...
def solvent_per_layer(self): """Determine the number of solvent molecules per single layer. """ if self._solvent_per_layer: return self._solvent_per_layer assert not (self.solvent_per_lipid is None and self.n_solvent is None) if self.solvent_per_lipid is not None: ...
Determine the number of solvent molecules per single layer.
def bulk_insert(self, rows, return_model=False): """Creates multiple new records in the database. This allows specifying custom conflict behavior using .on_conflict(). If no special behavior was specified, this uses the normal Django create(..) Arguments: rows: ...
Creates multiple new records in the database. This allows specifying custom conflict behavior using .on_conflict(). If no special behavior was specified, this uses the normal Django create(..) Arguments: rows: An array of dictionaries, where each dictionary ...
def add(self, iocb): """Add an IOCB to the group, you can also add other groups.""" if _debug: IOGroup._debug("add %r", iocb) # add this to our members self.ioMembers.append(iocb) # assume all of our members have not completed yet self.ioState = PENDING self.ioC...
Add an IOCB to the group, you can also add other groups.
def labels(self): """ Return the unique labels assigned to the documents. """ return [ name for name in os.listdir(self.root) if os.path.isdir(os.path.join(self.root, name)) ]
Return the unique labels assigned to the documents.
def add_url(self, url, description=None): """Add a personal website. Args: :param url: url to the person's website. :type url: string :param description: short description of the website. :type description: string """ url = { ...
Add a personal website. Args: :param url: url to the person's website. :type url: string :param description: short description of the website. :type description: string
def encode_all_features(dataset, vocabulary): """Encode all features. Args: dataset: a tf.data.Dataset vocabulary: a vocabulary.Vocabulary Returns: a tf.data.Dataset """ def my_fn(features): ret = {} for k, v in features.items(): v = vocabulary.encode_tf(v) v = tf.concat([tf.t...
Encode all features. Args: dataset: a tf.data.Dataset vocabulary: a vocabulary.Vocabulary Returns: a tf.data.Dataset
def create(cls, env, filenames, trim=False): """Create and return a final graph. Args: env: An environment.Environment object filenames: A list of filenames trim: Whether to trim the dependencies of builtin and system files. Returns: An immutable ImportG...
Create and return a final graph. Args: env: An environment.Environment object filenames: A list of filenames trim: Whether to trim the dependencies of builtin and system files. Returns: An immutable ImportGraph with the recursive dependencies of all the ...
def check_exists(path, type='file'): """ Check if a file or a folder exists """ if type == 'file': if not os.path.isfile(path): raise RuntimeError('The file `%s` does not exist.' % path) else: if not os.path.isdir(path): raise RuntimeError('The folder `%s` does not e...
Check if a file or a folder exists
def api_walk(uri, per_page=100, key="login"): """ For a GitHub URI, walk all the pages until there's no more content """ page = 1 result = [] while True: response = get_json(uri + "?page=%d&per_page=%d" % (page, per_page)) if len(response) == 0: break else: ...
For a GitHub URI, walk all the pages until there's no more content
def terminate_ex(self, nodes, threads=False, attempts=3): """Wrapper method for terminate. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :param attempts: The amount of attempts for retrying to terminate failed instances. :type attempts: ``int`` :...
Wrapper method for terminate. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :param attempts: The amount of attempts for retrying to terminate failed instances. :type attempts: ``int`` :param threads: Whether to use the threaded approach or not. ...
def main(self): """ Scheduler steps: - run ready until exhaustion - if there's something scheduled - run overdue scheduled immediately - or if there's nothing registered, sleep until next scheduled and then go back to ready ...
Scheduler steps: - run ready until exhaustion - if there's something scheduled - run overdue scheduled immediately - or if there's nothing registered, sleep until next scheduled and then go back to ready - if there's nothing registe...
def page(self, number): """ Returns a Page object for the given 1-based page number. """ number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page page_items = self.object_list[bottom:top] # check moved from v...
Returns a Page object for the given 1-based page number.
async def update_data_status(self, **kwargs): """Update (PATCH) Data object. :param kwargs: The dictionary of :class:`~resolwe.flow.models.Data` attributes to be changed. """ await self._send_manager_command(ExecutorProtocol.UPDATE, extra_fields={ ExecutorProtoco...
Update (PATCH) Data object. :param kwargs: The dictionary of :class:`~resolwe.flow.models.Data` attributes to be changed.
def get_neighbor_ip(ip_addr, cidr="30"): """ Function to figure out the IP's between neighbors address Args: ip_addr: Unicast IP address in the following format 192.168.1.1 cidr: CIDR value of 30, or 31 Returns: returns Our IP and the Neighbor IP in a tuple """ our_octet = None...
Function to figure out the IP's between neighbors address Args: ip_addr: Unicast IP address in the following format 192.168.1.1 cidr: CIDR value of 30, or 31 Returns: returns Our IP and the Neighbor IP in a tuple
def get_state_variable_from_storage( self, address: str, params: Optional[List[str]] = None ) -> str: """ Get variables from the storage :param address: The contract address :param params: The list of parameters param types: [position, length] or ["map...
Get variables from the storage :param address: The contract address :param params: The list of parameters param types: [position, length] or ["mapping", position, key1, key2, ... ] or [position, length, array] :return: The corresponding storage sl...
def parse_argv(self, argv=None, location='Command line.'): """Parse command line arguments. args <list str> or None: The argument list to parse. None means use a copy of sys.argv. argv[0] is ignored. location = '' <str>: A user friendly string describ...
Parse command line arguments. args <list str> or None: The argument list to parse. None means use a copy of sys.argv. argv[0] is ignored. location = '' <str>: A user friendly string describing where the parser got this data from. '' means use "Com...
async def close_authenticator_async(self): """Close the CBS auth channel and session asynchronously.""" _logger.info("Shutting down CBS session on connection: %r.", self._connection.container_id) try: self._cbs_auth.destroy() _logger.info("Auth closed, destroying session ...
Close the CBS auth channel and session asynchronously.
def formula_dual(input_formula: str) -> str: """ Returns the dual of the input formula. The dual operation on formulas in :math:`B^+(X)` is defined as: the dual :math:`\overline{θ}` of a formula :math:`θ` is obtained from θ by switching :math:`∧` and :math:`∨`, and by switching :math:`true` and :ma...
Returns the dual of the input formula. The dual operation on formulas in :math:`B^+(X)` is defined as: the dual :math:`\overline{θ}` of a formula :math:`θ` is obtained from θ by switching :math:`∧` and :math:`∨`, and by switching :math:`true` and :math:`false`. :param str input_formula: original s...
def get_total_contributors(self, repo): """ Retrieves the number of contributors to a repo in the organization. Also adds to unique contributor list. """ repo_contributors = 0 for contributor in repo.iter_contributors(): repo_contributors += 1 self...
Retrieves the number of contributors to a repo in the organization. Also adds to unique contributor list.
def wait_until_done(self, timeout=None): """Wait for the background load to complete.""" start = datetime.now() if not self.__th: raise IndraDBRestResponseError("There is no thread waiting to " "complete.") self.__th.join(timeout) ...
Wait for the background load to complete.
def manage_recurring_payments_profile_status(self, profileid, action, note=None): """Shortcut to the ManageRecurringPaymentsProfileStatus method. ``profileid`` is the same profile id used for getting profile details. ``action`` should be either '...
Shortcut to the ManageRecurringPaymentsProfileStatus method. ``profileid`` is the same profile id used for getting profile details. ``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'. ``note`` is optional and is visible to the user. It contains the reason for the chang...
def set_write_bit(fn): # type: (str) -> None """ Set read-write permissions for the current user on the target path. Fail silently if the path doesn't exist. :param str fn: The target filename or path :return: None """ fn = fs_encode(fn) if not os.path.exists(fn): return ...
Set read-write permissions for the current user on the target path. Fail silently if the path doesn't exist. :param str fn: The target filename or path :return: None
def distance_to_interval(self, start, end): """ Find the distance between intervals [start1, end1] and [start2, end2]. If the intervals overlap then the distance is 0. """ if self.start > end: # interval is before this exon return self.start - end ...
Find the distance between intervals [start1, end1] and [start2, end2]. If the intervals overlap then the distance is 0.
def expanded_counts_map(self): """ return the full counts map """ if self.hpx._ipix is None: return self.counts output = np.zeros( (self.counts.shape[0], self.hpx._maxpix), self.counts.dtype) for i in range(self.counts.shape[0]): output[i][self.hpx._i...
return the full counts map
def output(self, resource): """Wrap a resource (as a flask view function). This is for cases where the resource does not directly return a response object. Now everything should be a Response object. :param resource: The resource as a flask view function """ @wraps(reso...
Wrap a resource (as a flask view function). This is for cases where the resource does not directly return a response object. Now everything should be a Response object. :param resource: The resource as a flask view function
def record_launch(self, queue_id): # retcode): """Save submission""" self.launches.append( AttrDict(queue_id=queue_id, mpi_procs=self.mpi_procs, omp_threads=self.omp_threads, mem_per_proc=self.mem_per_proc, timelimit=self.timelimit)) return len(self.launches)
Save submission
def safe_print(msg): """ Safely print a given Unicode string to stdout, possibly replacing characters non-printable in the current stdout encoding. :param string msg: the message """ try: print(msg) except UnicodeEncodeError: try: # NOTE encoding and decoding...
Safely print a given Unicode string to stdout, possibly replacing characters non-printable in the current stdout encoding. :param string msg: the message
def data_size(self, live_data=None): """Uses `nodetool info` to get the size of a node's data in KB.""" if live_data is not None: warnings.warn("The 'live_data' keyword argument is deprecated.", DeprecationWarning) output = self.nodetool('info')[0] r...
Uses `nodetool info` to get the size of a node's data in KB.
def make_simple_equity_info(sids, start_date, end_date, symbols=None, names=None, exchange='TEST'): """ Create a DataFrame representing assets that exist for the full durat...
Create a DataFrame representing assets that exist for the full duration between `start_date` and `end_date`. Parameters ---------- sids : array-like of int start_date : pd.Timestamp, optional end_date : pd.Timestamp, optional symbols : list, optional Symbols to use for the assets. ...
def set_usage_rights_courses(self, file_ids, course_id, usage_rights_use_justification, folder_ids=None, publish=None, usage_rights_legal_copyright=None, usage_rights_license=None): """ Set usage rights. Sets copyright and license information for one or more files """ path...
Set usage rights. Sets copyright and license information for one or more files
def tcounts(self): """ :return: a data frame containing the names and sizes for all tables """ df = pd.DataFrame([[t.name(), t.size()] for t in self.tables()], columns=["name", "size"]) df.index = df.name return df
:return: a data frame containing the names and sizes for all tables
def _npy2fits(d, table_type='binary', write_bitcols=False): """ d is the full element from the descr """ npy_dtype = d[1][1:] if npy_dtype[0] == 'S' or npy_dtype[0] == 'U': name, form, dim = _npy_string2fits(d, table_type=table_type) else: name, form, dim = _npy_num2fits( ...
d is the full element from the descr
def delay_on(self): """ The `timer` trigger will periodically change the LED brightness between 0 and the current brightness setting. The `on` time can be specified via `delay_on` attribute in milliseconds. """ # Workaround for ev3dev/ev3dev#225. # 'delay_on' and...
The `timer` trigger will periodically change the LED brightness between 0 and the current brightness setting. The `on` time can be specified via `delay_on` attribute in milliseconds.
def import_from_api(request): """ Import a part of a source site's page tree via a direct API request from this Wagtail Admin to the source site The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines wh...
Import a part of a source site's page tree via a direct API request from this Wagtail Admin to the source site The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to.
async def setex(self, name, time, value): """ Set the value of key ``name`` to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object. """ if isinstance(time, datetime.timedelta): time = time.seconds ...
Set the value of key ``name`` to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object.
def copy(self): """ Create a copy of the mapping, including formatting information """ dup = type(self)() dup._indices = OrderedDict( (k, list(v)) for k,v in six.iteritems(self._indices) ) dup._lines = self._lines.copy() return dup
Create a copy of the mapping, including formatting information
def set_figure(self, figure, handle=None): """Call this with the Bokeh figure object.""" self.figure = figure self.bkimage = None self._push_handle = handle wd = figure.plot_width ht = figure.plot_height self.configure_window(wd, ht) doc = curdoc() ...
Call this with the Bokeh figure object.
def get(key, default=None): """Retrieves env vars and makes Python boolean replacements""" val = os.environ.get(key, default) if val == 'True': val = True elif val == 'False': val = False return val
Retrieves env vars and makes Python boolean replacements
def substitution(self, substitution): """Add substitutions to the email :param value: Add substitutions to the email :type value: Substitution, list(Substitution) """ if isinstance(substitution, list): for s in substitution: self.add_substitution(s) ...
Add substitutions to the email :param value: Add substitutions to the email :type value: Substitution, list(Substitution)
def check_requirements(dist, attr, value): """Verify that install_requires is a valid requirements list""" try: list(pkg_resources.parse_requirements(value)) except (TypeError, ValueError) as error: tmpl = ( "{attr!r} must be a string or list of strings " "containing ...
Verify that install_requires is a valid requirements list
def _check_algorithm_values(item): """Check for misplaced inputs in the algorithms. - Identify incorrect boolean values where a choice is required. """ problems = [] for k, v in item.get("algorithm", {}).items(): if v is True and k not in ALG_ALLOW_BOOLEANS: problems.append("%s ...
Check for misplaced inputs in the algorithms. - Identify incorrect boolean values where a choice is required.
def load(self, table_names=None, table_schemas=None, table_rowgens=None): ''' Initiates the tables, schemas and record generators for this database. Parameters ---------- table_names : list of str, str or None List of tables to load into this database. If `auto_load`...
Initiates the tables, schemas and record generators for this database. Parameters ---------- table_names : list of str, str or None List of tables to load into this database. If `auto_load` is true, inserting a record into a new table not provided here will automatically...
def filter_reads(self, input_bam, output_bam, metrics_file, paired=False, cpus=16, Q=30): """ Remove duplicates, filter for >Q, remove multiple mapping reads. For paired-end reads, keep only proper pairs. """ nodups = re.sub("\.bam$", "", output_bam) + ".nodups.nofilter.bam" ...
Remove duplicates, filter for >Q, remove multiple mapping reads. For paired-end reads, keep only proper pairs.
def _from_dict(cls, _dict): """Initialize a TopHitsResults object from a json dictionary.""" args = {} if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'hits' in _dict: args['hits'] = [ QueryResult._from_d...
Initialize a TopHitsResults object from a json dictionary.
def call_rpc(*inputs, **kwargs): """Call an RPC based on the encoded value read from input b. The response of the RPC must be a 4 byte value that is used as the output of this call. The encoded RPC must be a 32 bit value encoded as "BBH": B: ignored, should be 0 B: the address of the t...
Call an RPC based on the encoded value read from input b. The response of the RPC must be a 4 byte value that is used as the output of this call. The encoded RPC must be a 32 bit value encoded as "BBH": B: ignored, should be 0 B: the address of the tile that we should call H: The i...
def init(plugin_manager, _, _2, _3): """ Init the plugin. Available configuration in configuration.yaml: :: - plugin_module: "inginious.frontend.plugins.scoreboard" Available configuration in course.yaml: :: - scoreboard: #you can define multiple sc...
Init the plugin. Available configuration in configuration.yaml: :: - plugin_module: "inginious.frontend.plugins.scoreboard" Available configuration in course.yaml: :: - scoreboard: #you can define multiple scoreboards - content: "taskid1" #creat...
def cite(self, max_authors=5): """ Return string with a citation for the record, formatted as: '{authors} ({year}). {title} {journal} {volume}({issue}): {pages}.' """ citation_data = { 'title': self.title, 'authors': self.authors_et_al(max_authors), ...
Return string with a citation for the record, formatted as: '{authors} ({year}). {title} {journal} {volume}({issue}): {pages}.'
def news(symbol, count=10, token='', version=''): '''News about company https://iexcloud.io/docs/api/#news Continuous Args: symbol (string); Ticker to request count (int): limit number of results token (string); Access token version (string); API version Returns: ...
News about company https://iexcloud.io/docs/api/#news Continuous Args: symbol (string); Ticker to request count (int): limit number of results token (string); Access token version (string); API version Returns: dict: result
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs): """ {_gate_plot_doc} """ if ax == None: ax = pl.gca() kwargs.setdefault('color', 'black') if ax_channels is not None: flip = self._find_orientation(ax_channels) if n...
{_gate_plot_doc}
def pow(self, other, axis="columns", level=None, fill_value=None): """Pow this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the pow against this. axis: The axis to pow over. level: The Multilevel index level to appl...
Pow this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the pow against this. axis: The axis to pow over. level: The Multilevel index level to apply pow over. fill_value: The value to fill NaNs with. Re...
def from_string(cls, string): """ Parse ``string`` into a CPPType instance """ cls.TYPE.setParseAction(cls.make) try: return cls.TYPE.parseString(string, parseAll=True)[0] except ParseException: log.error("Failed to parse '{0}'".format(string)) ...
Parse ``string`` into a CPPType instance
def cublasSger(handle, m, n, alpha, x, incx, y, incy, A, lda): """ Rank-1 operation on real general matrix. """ status = _libcublas.cublasSger_v2(handle, m, n, ctypes.byref(ctypes.c_float(alpha)), ...
Rank-1 operation on real general matrix.
def set_quota_volume(name, path, size, enable_quota=False): ''' Set quota to glusterfs volume. name Name of the gluster volume path Folder path for restriction in volume ("/") size Hard-limit size of the volume (MB/GB) enable_quota Enable quota before set up r...
Set quota to glusterfs volume. name Name of the gluster volume path Folder path for restriction in volume ("/") size Hard-limit size of the volume (MB/GB) enable_quota Enable quota before set up restriction CLI Example: .. code-block:: bash salt '*'...
def follow_bytes(self, s, index): "Follows transitions." for ch in s: index = self.follow_char(int_from_byte(ch), index) if index is None: return None return index
Follows transitions.
def removeTab(self, index): """ Removes the tab at the inputed index. :param index | <int> """ curr_index = self.currentIndex() items = list(self.items()) item = items[index] item.close() if index <= curr_index: self._currentInde...
Removes the tab at the inputed index. :param index | <int>
def simxStart(connectionAddress, connectionPort, waitUntilConnected, doNotReconnectOnceDisconnected, timeOutInMs, commThreadCycleInMs): ''' Please have a look at the function description/documentation in the V-REP user manual ''' if (sys.version_info[0] == 3) and (type(connectionAddress) is str): ...
Please have a look at the function description/documentation in the V-REP user manual
def hasReaders(self, ulBuffer): """inexpensively checks for readers to allow writers to fast-fail potentially expensive copies and writes.""" fn = self.function_table.hasReaders result = fn(ulBuffer) return result
inexpensively checks for readers to allow writers to fast-fail potentially expensive copies and writes.
def apply_mask(self, x=None): ''' Returns the outlier mask, an array of indices corresponding to the non-outliers. :param numpy.ndarray x: If specified, returns the masked version of \ :py:obj:`x` instead. Default :py:obj:`None` ''' if x is None: ...
Returns the outlier mask, an array of indices corresponding to the non-outliers. :param numpy.ndarray x: If specified, returns the masked version of \ :py:obj:`x` instead. Default :py:obj:`None`
def command_x(self, x, to=None): """ Sends a character to the currently active element with Command pressed. This method takes care of pressing and releasing Command. """ if to is None: ActionChains(self.driver) \ .send_keys([Keys.COMMAND, x, K...
Sends a character to the currently active element with Command pressed. This method takes care of pressing and releasing Command.
def crop_frequencies(self, low=None, high=None, copy=False): """Crop this `Spectrogram` to the specified frequencies Parameters ---------- low : `float` lower frequency bound for cropped `Spectrogram` high : `float` upper frequency bound for cropped `Spec...
Crop this `Spectrogram` to the specified frequencies Parameters ---------- low : `float` lower frequency bound for cropped `Spectrogram` high : `float` upper frequency bound for cropped `Spectrogram` copy : `bool` if `False` return a view of t...
def format_choices(self): """Return the choices in string form.""" ce = enumerate(self.choices) f = lambda i, c: '%s (%d)' % (c, i+1) # apply formatter and append help token toks = [f(i,c) for i, c in ce] + ['Help (?)'] return ' '.join(toks)
Return the choices in string form.
def set_current_thumbnail(self, thumbnail): """Set the currently selected thumbnail.""" self.current_thumbnail = thumbnail self.figure_viewer.load_figure( thumbnail.canvas.fig, thumbnail.canvas.fmt) for thumbnail in self._thumbnails: thumbnail.highlight_canvas...
Set the currently selected thumbnail.
def text_entry(self): """ Relay literal text entry from user to Roku until <Enter> or <Esc> pressed. """ allowed_sequences = set(['KEY_ENTER', 'KEY_ESCAPE', 'KEY_DELETE']) sys.stdout.write('Enter text (<Esc> to abort) : ') sys.stdout.flush() # Track start column to ens...
Relay literal text entry from user to Roku until <Enter> or <Esc> pressed.
def get_dict(self): """ Returns a dict containing the host's attributes. The following keys are contained: - hostname - address - protocol - port :rtype: dict :return: The resulting dictionary. """ return {'hostna...
Returns a dict containing the host's attributes. The following keys are contained: - hostname - address - protocol - port :rtype: dict :return: The resulting dictionary.
def clear_graph(identifier=None): """ Clean up a graph by removing it :param identifier: Root identifier of the graph :return: """ graph = get_graph() if identifier: graph.destroy(identifier) try: graph.close() except: warn("Unable to close the Graph")
Clean up a graph by removing it :param identifier: Root identifier of the graph :return:
def local_global_attention(x, self_attention_bias, hparams, q_padding="LEFT", kv_padding="LEFT"): """Local and global 1d self attention.""" with tf.variable_scope("self_local_global_att"): [x_global, x_lo...
Local and global 1d self attention.
def compute(self, inputs, outputs): """ Run one iteration of TM's compute. """ # Handle reset first (should be sent with an empty signal) if "resetIn" in inputs: assert len(inputs["resetIn"]) == 1 if inputs["resetIn"][0] != 0: # send empty output self._tm.reset() ...
Run one iteration of TM's compute.
def root_manifest_id(self, root_manifest_id): """ Sets the root_manifest_id of this UpdateCampaignPutRequest. :param root_manifest_id: The root_manifest_id of this UpdateCampaignPutRequest. :type: str """ if root_manifest_id is not None and len(root_manifest_id) > 32: ...
Sets the root_manifest_id of this UpdateCampaignPutRequest. :param root_manifest_id: The root_manifest_id of this UpdateCampaignPutRequest. :type: str
def list_namespaced_stateful_set(self, namespace, **kwargs): # noqa: E501 """list_namespaced_stateful_set # noqa: E501 list or watch objects of kind StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asy...
list_namespaced_stateful_set # noqa: E501 list or watch objects of kind StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_stateful_set(namespace, async_req...
def create_wsgi_request(event, server_name='apigw'): """Create a wsgi environment from an apigw request. """ path = urllib.url2pathname(event['path']) script_name = ( event['headers']['Host'].endswith('.amazonaws.com') and event['requestContext']['stage'] or '').encode('utf8') query ...
Create a wsgi environment from an apigw request.
def flatten(text): """ Flatten the text: * make sure each record is on one line. * remove parenthesis """ lines = text.split("\n") # tokens: sequence of non-whitespace separated by '' where a newline was tokens = [] for l in lines: if len(l) == 0: continue ...
Flatten the text: * make sure each record is on one line. * remove parenthesis
def wishart_pairwise_pvals(self, axis=0): """Return square symmetric matrix of pairwise column-comparison p-values. Square, symmetric matrix along *axis* of pairwise p-values for the null hypothesis that col[i] = col[j] for each pair of columns. *axis* (int): axis along which to perfor...
Return square symmetric matrix of pairwise column-comparison p-values. Square, symmetric matrix along *axis* of pairwise p-values for the null hypothesis that col[i] = col[j] for each pair of columns. *axis* (int): axis along which to perform comparison. Only columns (0) are implemente...
def parse_binary_descriptor(bindata): """Convert a binary node descriptor into a string descriptor. Binary node descriptor are 20-byte binary structures that encode all information needed to create a graph node. They are used to communicate that information to an embedded device in an efficent format....
Convert a binary node descriptor into a string descriptor. Binary node descriptor are 20-byte binary structures that encode all information needed to create a graph node. They are used to communicate that information to an embedded device in an efficent format. This function exists to turn such a com...
def split_header(fp): """ Read file pointer and return pair of lines lists: first - header, second - the rest. """ body_start, header_ended = 0, False lines = [] for line in fp: if line.startswith('#') and not header_ended: # Header tex...
Read file pointer and return pair of lines lists: first - header, second - the rest.
def moment_sequence(self): r""" Create a generator to calculate the population mean and variance-convariance matrix for both :math:`x_t` and :math:`y_t` starting at the initial condition (self.mu_0, self.Sigma_0). Each iteration produces a 4-tuple of items (mu_x, mu_y, Sigma_x, ...
r""" Create a generator to calculate the population mean and variance-convariance matrix for both :math:`x_t` and :math:`y_t` starting at the initial condition (self.mu_0, self.Sigma_0). Each iteration produces a 4-tuple of items (mu_x, mu_y, Sigma_x, Sigma_y) for the next period...
def example_yaml(cls, skip=()): """ Generate an example yaml string for a Serializable subclass. If traits have been tagged with an `example` value, then we use that value. Otherwise we fall back the default_value for the instance. """ return cls.example_instance(skip=s...
Generate an example yaml string for a Serializable subclass. If traits have been tagged with an `example` value, then we use that value. Otherwise we fall back the default_value for the instance.
def get_available_tokens(self, count=10, token_length=15, **kwargs): """Gets a list of available tokens. :param count: the number of tokens to return. :param token_length: the length of the tokens. The higher the number the easier it will be to return a list. If token_length == 1 ...
Gets a list of available tokens. :param count: the number of tokens to return. :param token_length: the length of the tokens. The higher the number the easier it will be to return a list. If token_length == 1 there's a strong probability that the enough tokens will exist in ...
def _bulk_to_linear(M, N, L, qubits): "Converts a list of chimera coordinates to linear indices." return [2 * L * N * x + 2 * L * y + L * u + k for x, y, u, k in qubits]
Converts a list of chimera coordinates to linear indices.
def _get_user_agent(): """Construct the user-agent header with the package info, Python version and OS version. Returns: The user agent string. e.g. 'Python/3.6.7 slack/2.0.0 Darwin/17.7.0' """ # __name__ returns all classes, we only want the client ...
Construct the user-agent header with the package info, Python version and OS version. Returns: The user agent string. e.g. 'Python/3.6.7 slack/2.0.0 Darwin/17.7.0'
def channels_set_topic(self, room_id, topic, **kwargs): """Sets the topic for the channel.""" return self.__call_api_post('channels.setTopic', roomId=room_id, topic=topic, kwargs=kwargs)
Sets the topic for the channel.
def dateindex(self, col: str): """ Set a datetime index from a column :param col: column name where to index the date from :type col: str :example: ``ds.dateindex("mycol")`` """ df = self._dateindex(col) if df is None: self.err("Can not creat...
Set a datetime index from a column :param col: column name where to index the date from :type col: str :example: ``ds.dateindex("mycol")``
def _parse_textgroup_wrapper(self, cts_file): """ Wraps with a Try/Except the textgroup parsing from a cts file :param cts_file: Path to the CTS File :type cts_file: str :return: CtsTextgroupMetadata """ try: return self._parse_textgroup(cts_file) exc...
Wraps with a Try/Except the textgroup parsing from a cts file :param cts_file: Path to the CTS File :type cts_file: str :return: CtsTextgroupMetadata
def _gradient_penalty(self, real_samples, fake_samples, kwargs): """ Compute the norm of the gradients for each sample in a batch, and penalize anything on either side of unit norm """ import torch from torch.autograd import Variable, grad real_samples = real_sam...
Compute the norm of the gradients for each sample in a batch, and penalize anything on either side of unit norm
def min(self): """ :returns the minimum of the column """ res = self._qexec("min(%s)" % self._name) if len(res) > 0: self._min = res[0][0] return self._min
:returns the minimum of the column
def unit(w, sparsity): """Unit-level magnitude pruning.""" w_shape = common_layers.shape_list(w) count = tf.to_int32(w_shape[-1] * sparsity) mask = common_layers.unit_targeting(w, count) return (1 - mask) * w
Unit-level magnitude pruning.
def new(image): """Make a region on an image. Returns: A new :class:`.Region`. Raises: :class:`.Error` """ pointer = vips_lib.vips_region_new(image.pointer) if pointer == ffi.NULL: raise Error('unable to make region') retur...
Make a region on an image. Returns: A new :class:`.Region`. Raises: :class:`.Error`
def pipeline_launchpad(job, fastqs, univ_options, tool_options): """ The precision immuno pipeline begins at this module. The DAG can be viewed in Flowchart.txt This module corresponds to node 0 on the tree """ # Add Patient id to univ_options as is is passed to every major node in the DAG and can ...
The precision immuno pipeline begins at this module. The DAG can be viewed in Flowchart.txt This module corresponds to node 0 on the tree
def todict(self, exclude_cache=False): '''Return a dictionary of serialised scalar field for pickling. If the *exclude_cache* flag is ``True``, fields with :attr:`Field.as_cache` attribute set to ``True`` will be excluded.''' odict = {} for field, value in self.fieldvalue_pairs(exclude_cache=exc...
Return a dictionary of serialised scalar field for pickling. If the *exclude_cache* flag is ``True``, fields with :attr:`Field.as_cache` attribute set to ``True`` will be excluded.
def parse_xmlsec_output(output): """ Parse the output from xmlsec to try to find out if the command was successfull or not. :param output: The output from Popen :return: A boolean; True if the command was a success otherwise False """ for line in output.splitlines(): if line == 'OK': ...
Parse the output from xmlsec to try to find out if the command was successfull or not. :param output: The output from Popen :return: A boolean; True if the command was a success otherwise False