positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def consistency_check(model, subset, epsilon, tfba, solver): """Check that reaction subset of model is consistent using FBA. Yields all reactions that are *not* flux consistent. A reaction is consistent if there is at least one flux solution to the model that both respects the model constraints and als...
Check that reaction subset of model is consistent using FBA. Yields all reactions that are *not* flux consistent. A reaction is consistent if there is at least one flux solution to the model that both respects the model constraints and also allows the reaction in question to have non-zero flux. Th...
def range(self): """Returns the range for N""" match = self._match(in_comment( 'n[ \t]+in[ \t]*\\[([0-9]+)\\.\\.([0-9]+)\\),[ \t]+' 'step[ \t]+([0-9]+)' )) return range( int(match.group(1)), int(match.group(2)), int(match.group(...
Returns the range for N
def create_process(self, command, shell=True, stdout=None, stderr=None, env=None): """ Execute a process using subprocess.Popen, setting the backend's DISPLAY """ env = env if env is not None else dict(os.environ) env['DISPLAY'] = self.display retur...
Execute a process using subprocess.Popen, setting the backend's DISPLAY
def fetch(self, start=None, stop=None): """ Fetch log records and return them as a list. |Args| * ``start`` (**int**): non-negative index of the first log record to return. * ``stop`` (**int**): non-negative index of the last log record to return. ...
Fetch log records and return them as a list. |Args| * ``start`` (**int**): non-negative index of the first log record to return. * ``stop`` (**int**): non-negative index of the last log record to return. |Returns| * **list**: list of log records (see ``lo...
def indent_text(string, indent_level=2): """Indent every line of text in a newline-delimited string""" indented_lines = [] indent_spaces = ' ' * indent_level for line in string.split('\n'): indented_lines.append(indent_spaces + line) return '\n'.join(indented_lines)
Indent every line of text in a newline-delimited string
def _fill_parameters(self): """ Fill in the _parameters dict from the properties file. Args: None Returns: True Todo: Figure out what could go wrong and at least acknowledge the the fact that Murphy was an optimist. """ ...
Fill in the _parameters dict from the properties file. Args: None Returns: True Todo: Figure out what could go wrong and at least acknowledge the the fact that Murphy was an optimist.
def add_console_message(self, message_type, message): """add messages in the console_messages list """ for m in message.split("\n"): if m.strip(): self.console_messages.append((message_type, m))
add messages in the console_messages list
def unpack(self, value): """Unpack the parameter using its kattype. Parameters ---------- packed_value : str The unescaped KATCP string to unpack. Returns ------- value : object The unpacked value. """ # Wrap errors in Fa...
Unpack the parameter using its kattype. Parameters ---------- packed_value : str The unescaped KATCP string to unpack. Returns ------- value : object The unpacked value.
def _cutadapt_se_cmd(fastq_files, out_files, base_cmd, data): """ this has to use the -o option, not redirect to stdout in order for gzipping to be supported """ min_length = dd.get_min_read_length(data) cmd = base_cmd + " --minimum-length={min_length} ".format(**locals()) fq1 = objectstore....
this has to use the -o option, not redirect to stdout in order for gzipping to be supported
def sequence_quality_plot (self): """ Create the HTML for the phred quality score plot """ data = dict() for s_name in self.fastqc_data: try: data[s_name] = {self.avg_bp_from_range(d['base']): d['mean'] for d in self.fastqc_data[s_name]['per_base_sequence_quality']} ...
Create the HTML for the phred quality score plot
def _normalize_index(self, index, pipe=None): """Convert negative indexes into their positive equivalents.""" pipe = self.redis if pipe is None else pipe len_self = self.__len__(pipe) positive_index = index if index >= 0 else len_self + index return len_self, positive_index
Convert negative indexes into their positive equivalents.
def sign_up(self, username=None, password=None): """ 创建一个新用户。新创建的 User 对象,应该使用此方法来将数据保存至服务器,而不是使用 save 方法。 用户对象上必须包含 username 和 password 两个字段 """ if username: self.set('username', username) if password: self.set('password', password) usern...
创建一个新用户。新创建的 User 对象,应该使用此方法来将数据保存至服务器,而不是使用 save 方法。 用户对象上必须包含 username 和 password 两个字段
def load(self, filename): """Load proxies from file""" with open(filename, 'r') as fin: proxies = json.load(fin) for protocol in proxies: for proxy in proxies[protocol]: self.proxies[protocol][proxy['addr']] = Proxy( proxy['addr'], prox...
Load proxies from file
def style(self): """Function to apply some styles to the layers.""" LOGGER.info('ANALYSIS : Styling') classes = generate_classified_legend( self.analysis_impacted, self.exposure, self.hazard, self.use_rounding, self.debug_mode) ...
Function to apply some styles to the layers.
def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret
Return a list of all job ids
def validate(self, value, add_comments=False, schema_name="map"): """ verbose - also return the jsonschema error details """ validator = self.get_schema_validator(schema_name) error_messages = [] if isinstance(value, list): for d in value: er...
verbose - also return the jsonschema error details
def copy(self): """Return a copy of ourself.""" new_dict = IDict(std=self._std) new_dict.update(self.store) return new_dict
Return a copy of ourself.
def setactive(self, scriptname): """Define the active script See MANAGESIEVE specifications, section 2.8 If scriptname is empty, the current active script is disabled, ie. there will be no active script anymore. :param scriptname: script's name :rtype: boolean ...
Define the active script See MANAGESIEVE specifications, section 2.8 If scriptname is empty, the current active script is disabled, ie. there will be no active script anymore. :param scriptname: script's name :rtype: boolean
def on_trial_result(self, trial_runner, trial, result): """Callback for early stopping. This stopping rule stops a running trial if the trial's best objective value by step `t` is strictly worse than the median of the running averages of all completed trials' objectives reported up to s...
Callback for early stopping. This stopping rule stops a running trial if the trial's best objective value by step `t` is strictly worse than the median of the running averages of all completed trials' objectives reported up to step `t`.
def lgammln(xx): """ Returns the gamma function of xx. Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt. (Adapted from: Numerical Recipies in C.) Usage: lgammln(xx) """ coeff = [76.18009173, -86.50532033, 24.01409822, -1.231739516, 0.120858003e-2, -0.536382e-5] x = xx - 1.0 tmp ...
Returns the gamma function of xx. Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt. (Adapted from: Numerical Recipies in C.) Usage: lgammln(xx)
def mask_by_linear_ind(self, linear_inds): """Create a new image by zeroing out data at locations not in the given indices. Parameters ---------- linear_inds : :obj:`numpy.ndarray` of int A list of linear coordinates. Returns ------- :obj:`Im...
Create a new image by zeroing out data at locations not in the given indices. Parameters ---------- linear_inds : :obj:`numpy.ndarray` of int A list of linear coordinates. Returns ------- :obj:`Image` A new Image of the same type, with da...
def adev_from_qd(self, tau0=1.0, tau=1.0): """ prefactor for Allan deviation for noise type defined by (qd, b, tau0) Colored noise generated with (qd, b, tau0) parameters will show an Allan variance of: AVAR = prefactor * h_a * tau^c where a = b + 2...
prefactor for Allan deviation for noise type defined by (qd, b, tau0) Colored noise generated with (qd, b, tau0) parameters will show an Allan variance of: AVAR = prefactor * h_a * tau^c where a = b + 2 is the slope of the frequency PSD. and h_a...
def write(bar, offset, data): """Write data to PCI board. Parameters ---------- bar : BaseAddressRegister BAR to write. offset : int Address offset in BAR to write. data : bytes Data to write. Returns ------- None Examples ...
Write data to PCI board. Parameters ---------- bar : BaseAddressRegister BAR to write. offset : int Address offset in BAR to write. data : bytes Data to write. Returns ------- None Examples -------- >>> b = pypci.lspci(vend...
def update_intent(self, workspace_id, intent, new_intent=None, new_description=None, new_examples=None, **kwargs): """ Update intent. Update an existing intent wit...
Update intent. Update an existing intent with new or modified data. You must provide component objects defining the content of the updated intent. This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate limiting**. :param str workspace_id: Un...
def _group_sql(self, quote_char=None, groupby_alias=True, **kwargs): """ Produces the GROUP BY part of the query. This is a list of fields. The clauses are stored in the query under self._groupbys as a list fields. If an groupby field is used in the select clause, determined by...
Produces the GROUP BY part of the query. This is a list of fields. The clauses are stored in the query under self._groupbys as a list fields. If an groupby field is used in the select clause, determined by a matching alias, and the groupby_alias is set True then the GROUP BY clause wil...
def simulate(s0, transmat, steps=1): """Simulate the next state Parameters ---------- s0 : ndarray Vector with state variables at t=0 transmat : ndarray The estimated transition/stochastic matrix. steps : int (Default: 1) The number of steps to simulate model outputs a...
Simulate the next state Parameters ---------- s0 : ndarray Vector with state variables at t=0 transmat : ndarray The estimated transition/stochastic matrix. steps : int (Default: 1) The number of steps to simulate model outputs ahead. If steps>1 the a Mult-Step Sim...
def name2marc(self, key, value): """Populates the ``100`` field. Also populates the ``400``, ``880``, and ``667`` fields through side effects. """ result = self.get('100', {}) result['a'] = value.get('value') result['b'] = value.get('numeration') result['c'] = value.get('title') re...
Populates the ``100`` field. Also populates the ``400``, ``880``, and ``667`` fields through side effects.
def get_gradebook(self): """Gets the ``Gradebook`` at this node. return: (osid.grading.Gradebook) - the gradebook represented by this node *compliance: mandatory -- This method must be implemented.* """ if self._lookup_session is None: mgr = get_prov...
Gets the ``Gradebook`` at this node. return: (osid.grading.Gradebook) - the gradebook represented by this node *compliance: mandatory -- This method must be implemented.*
def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr ini...
Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', '...
def align_transcriptome(fastq_file, pair_file, ref_file, data): """ bowtie2 with settings for aligning to the transcriptome for eXpress/RSEM/etc """ work_bam = dd.get_work_bam(data) base, ext = os.path.splitext(work_bam) out_file = base + ".transcriptome" + ext if utils.file_exists(out_file)...
bowtie2 with settings for aligning to the transcriptome for eXpress/RSEM/etc
async def open_websocket_server(sock, filter=None): # pylint: disable=W0622 """ A context manager which serves this websocket. :param filter: an async callback which accepts the connection request and returns a bool, or an explicit Accept/Reject message. """ ws = await create_websocket_server(...
A context manager which serves this websocket. :param filter: an async callback which accepts the connection request and returns a bool, or an explicit Accept/Reject message.
def fit(self, X, y, Z): """Compute the Semi-Supervised Shared Response Model Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, n_align] Each element in the list contains the fMRI data for alignment of one subject. There are n_align samp...
Compute the Semi-Supervised Shared Response Model Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, n_align] Each element in the list contains the fMRI data for alignment of one subject. There are n_align samples for each subject. y : ...
def wait_for(self, new_state): """ Wait for an exact state `new_state` to be reached by the state machine. If the state is skipped, that is, if a state which is greater than `new_state` is written to :attr:`state`, the coroutine raises :class:`OrderedStateSkipped` except...
Wait for an exact state `new_state` to be reached by the state machine. If the state is skipped, that is, if a state which is greater than `new_state` is written to :attr:`state`, the coroutine raises :class:`OrderedStateSkipped` exception as it is not possible anymore that it c...
def cmd_touch_note(args): """Create a note""" major = args.get(0) minor = args.get(1) if major in penStore.data: if minor is None: # show items in list for note in penStore.data[major]: puts(note) elif minor in penStore.data[major]: penStore.openN...
Create a note
def gslib_2_dataframe(filename,attr_name=None,x_idx=0,y_idx=1): """ function to read a GSLIB point data file into a pandas.DataFrame Parameters ---------- filename : (str) GSLIB file attr_name : (str) the column name in the dataframe for the attribute. If None, GSLIB file c...
function to read a GSLIB point data file into a pandas.DataFrame Parameters ---------- filename : (str) GSLIB file attr_name : (str) the column name in the dataframe for the attribute. If None, GSLIB file can have only 3 columns. attr_name must be in the GSLIB file header ...
def rgb_to_yiq(r, g=None, b=None): """Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1],...
Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1], q[0...1] >>> '(%g, %g, %g)' % rg...
def expand_path(path): ''' Given a compressed path, return a new path that has all the segments in it interpolated. ''' expanded = [] if len(path) < 2: return expanded for i in range(len(path)-1): expanded += bresenham(path[i], path[i + 1]) expanded += [path[:-1]] ret...
Given a compressed path, return a new path that has all the segments in it interpolated.
def work(): """Implement a worker for write-math.com.""" global n cmd = utils.get_project_configuration() if 'worker_api_key' not in cmd: return ("You need to define a 'worker_api_key' in your ~/") chunk_size = 1000 logging.info("Start working with n=%i", n) for _ in range(chunk_s...
Implement a worker for write-math.com.
def _generate_filenames(sources): """Generate filenames. :param tuple sources: Sequence of strings representing path to file(s). :return: Path to file(s). :rtype: :py:class:`str` """ for source in sources: if os.path.isdir(source): for path, dirlist, filelist in os.walk(sour...
Generate filenames. :param tuple sources: Sequence of strings representing path to file(s). :return: Path to file(s). :rtype: :py:class:`str`
def get_expanded_path(path): """Expand ~ and variables in a path. If path is not truthy, return None.""" if path: result = path result = os.path.expanduser(result) result = os.path.expandvars(result) return result else: return None
Expand ~ and variables in a path. If path is not truthy, return None.
def mkdir(self, src, extra_args=[]): '''Create a directory''' return self._getStdOutCmd([self._hadoop_cmd, 'fs', '-mkdir'] + extra_args + [self._full_hdfs_path(src)], True)
Create a directory
def nic_v1(msg, NICs): """Calculate NIC, navigation integrity category, for ADS-B version 1 Args: msg (string): 28 bytes hexadecimal message string NICs (int or string): NIC supplement Returns: int or string: Horizontal Radius of Containment int or string: Vertical Protecti...
Calculate NIC, navigation integrity category, for ADS-B version 1 Args: msg (string): 28 bytes hexadecimal message string NICs (int or string): NIC supplement Returns: int or string: Horizontal Radius of Containment int or string: Vertical Protection Limit
def get_template(file): ''' Lookup a template class for the given filename or file extension. Return nil when no implementation is found. ''' pattern = str(file).lower() while len(pattern) and not Lean.is_registered(pattern): pattern = os.path.basename(pattern) pattern = re.sub(r'^[...
Lookup a template class for the given filename or file extension. Return nil when no implementation is found.
def labels(self): """ Get list of labels from the target instance. :return: [str] """ if self._labels is None: self._labels = self.instance.labels return self._labels
Get list of labels from the target instance. :return: [str]
def check_that_operator_can_be_applied_to_produces_items(op, g1, g2): """ Helper function to check that the operator `op` can be applied to items produced by g1 and g2. """ g1_tmp_copy = g1.spawn() g2_tmp_copy = g2.spawn() sample_item_1 = next(g1_tmp_copy) sample_item_2 = next(g2_tmp_copy) ...
Helper function to check that the operator `op` can be applied to items produced by g1 and g2.
def extract_subjects(bill): """ Return a list subject for legislation. """ logger.debug("Extracting Subjects") subject_map = [] subjects = bill.get('subjects', []) bill_id = bill.get('bill_id', None) bill_type = bill.get('bill_type', None) for sub in subjects: subject_map.ap...
Return a list subject for legislation.
def bulk_delete(self, ids=None, filter=None, type=None, all=False): # pylint: disable=redefined-builtin """Bulk delete a set of configs. :param ids: (optional) Int list of config IDs. :param filter: (optional) String list of filters. :param type: (optional) `union` or `inter` as string....
Bulk delete a set of configs. :param ids: (optional) Int list of config IDs. :param filter: (optional) String list of filters. :param type: (optional) `union` or `inter` as string. :param all: (optional) Apply to all if bool `True`.
def get(self, col1, col2, method, channel_width, flow_rate=None, viscosity=None, add_px_err=False, px_um=None): """Get isoelastics Parameters ---------- col1: str Name of the first feature of all isoelastics (e.g. isoel[0][:,0]) col2: str ...
Get isoelastics Parameters ---------- col1: str Name of the first feature of all isoelastics (e.g. isoel[0][:,0]) col2: str Name of the second feature of all isoelastics (e.g. isoel[0][:,1]) method: str The method used ...
def is_zombie(self, path): '''Is the node pointed to by @ref path a zombie object?''' node = self.get_node(path) if not node: return False return node.is_zombie
Is the node pointed to by @ref path a zombie object?
def join_gates(*gates: Gate) -> Gate: """Direct product of two gates. Qubit count is the sum of each gate's bit count.""" vectors = [gate.vec for gate in gates] vec = reduce(outer_product, vectors) return Gate(vec.tensor, vec.qubits)
Direct product of two gates. Qubit count is the sum of each gate's bit count.
def get_formatted_rule(rule=None): """Helper to format the rule into a user friendly format. :param dict rule: A dict containing one rule of the firewall :returns: a formatted string that get be pushed into the editor """ rule = rule or {} return ('action: %s\n' 'protocol: %s\n' ...
Helper to format the rule into a user friendly format. :param dict rule: A dict containing one rule of the firewall :returns: a formatted string that get be pushed into the editor
def translate(self, text, model_id=None, source=None, target=None, **kwargs): """ Translate. Translates the input text from the source language to the target language. :param list[str] text: Input text in UTF-8 encoding. Multiple entries will result in multipl...
Translate. Translates the input text from the source language to the target language. :param list[str] text: Input text in UTF-8 encoding. Multiple entries will result in multiple translations in the response. :param str model_id: A globally unique string that identifies the underlying...
def get_for(self, query_type, value): """ Create a query and run it for the given arg if it doesn't exist, and return the tweets for the query. """ from yacms.twitter.models import Query lookup = {"type": query_type, "value": value} query, created = Query.objects....
Create a query and run it for the given arg if it doesn't exist, and return the tweets for the query.
def open(store=None, mode='a', **kwargs): """Convenience function to open a group or array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, opti...
Convenience function to open a group or array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read onl...
def independent_interdomain_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False): """ The inducing outputs live in the g-space (R^L). Interdomain conditional calculation. :param Kmn: M x L x N x P :param Kmm: L x M...
The inducing outputs live in the g-space (R^L). Interdomain conditional calculation. :param Kmn: M x L x N x P :param Kmm: L x M x M :param Knn: N x P or N x N or P x N x N or N x P x N x P :param f: data matrix, M x L :param q_sqrt: L x M x M or M x L :param full_cov: calculate cov...
def fraction_visited(source, sink, waypoint, msm): """ Calculate the fraction of times a walker on `tprob` going from `sources` to `sinks` will travel through the set of states `waypoints` en route. Computes the conditional committors q^{ABC^+} and uses them to find the fraction of paths mentioned ...
Calculate the fraction of times a walker on `tprob` going from `sources` to `sinks` will travel through the set of states `waypoints` en route. Computes the conditional committors q^{ABC^+} and uses them to find the fraction of paths mentioned above. Note that in the notation of Dickson et. al. this c...
def status_for_order(self, order_id, stock): """Status For An Existing Order https://starfighter.readme.io/docs/status-for-an-existing-order """ url_fragment = 'venues/{venue}/stocks/{stock}/orders/{order_id}'.format( venue=self.venue, stock=stock, or...
Status For An Existing Order https://starfighter.readme.io/docs/status-for-an-existing-order
def connect(self): """Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails. """ attempt = 0 for i in self.max_tries_counter: attempt += 1 try: self._conn = se...
Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails.
def log(self, output, exit_status): """Log given CompletedProcess and return exit status code.""" if exit_status != 0: self.logger.error(f'Error running command! Exit status: {exit_status}, {output}') return exit_status
Log given CompletedProcess and return exit status code.
def graph(self, stages=None, from_directory=None): """Generate a graph by using the given stages on the given directory The nodes of the graph are the stage's path relative to the root. Edges are created when the output of one stage is used as a dependency in other stage. The ...
Generate a graph by using the given stages on the given directory The nodes of the graph are the stage's path relative to the root. Edges are created when the output of one stage is used as a dependency in other stage. The direction of the edges goes from the stage to its dependency: ...
def authenticate_connection(username, password, db=None): """ Authenticates the current database connection with the passed username and password. If the database connection uses all default parameters, this can be called without connect_to_database. Otherwise, it should be preceded by a connect_t...
Authenticates the current database connection with the passed username and password. If the database connection uses all default parameters, this can be called without connect_to_database. Otherwise, it should be preceded by a connect_to_database call. @param username: the username with which you...
def to_json(value): """ Converts a value to a jsonable type. """ if type(value) in JSON_TYPES: return value elif hasattr(value, "to_json"): return value.to_json() elif isinstance(value, list) or isinstance(value, set) or \ isinstance(value, deque) or isinstance(value,...
Converts a value to a jsonable type.
def rename(self, from_symbol, to_symbol, audit=None): """ Rename a symbol Parameters ---------- from_symbol: str the existing symbol that will be renamed to_symbol: str the new symbol name audit: dict audit information ...
Rename a symbol Parameters ---------- from_symbol: str the existing symbol that will be renamed to_symbol: str the new symbol name audit: dict audit information
def add_middleware(middleware: EFBMiddleware): """ Register a middleware with the coordinator. Args: middleware (EFBMiddleware): Middleware to register """ global middlewares if isinstance(middleware, EFBMiddleware): middlewares.append(middleware) else: raise TypeErr...
Register a middleware with the coordinator. Args: middleware (EFBMiddleware): Middleware to register
def split(input_layer, split_dim=0, num_splits=2): """Splits this Tensor along the split_dim into num_splits Equal chunks. Examples: * `[1, 2, 3, 4] -> [1, 2], [3, 4]` * `[[1, 1], [2, 2], [3, 3], [4, 4]] -> [[1, 1], [2, 2]], [[3, 3], [4, 4]]` Args: input_layer: The chainable object, supplied. split...
Splits this Tensor along the split_dim into num_splits Equal chunks. Examples: * `[1, 2, 3, 4] -> [1, 2], [3, 4]` * `[[1, 1], [2, 2], [3, 3], [4, 4]] -> [[1, 1], [2, 2]], [[3, 3], [4, 4]]` Args: input_layer: The chainable object, supplied. split_dim: The dimension to split along. Defaults to batch. ...
def run(): """Display the arguments as a braille graph on standard output.""" # We override the program name to reflect that this script must be run with # the python executable. parser = argparse.ArgumentParser( prog='python -m braillegraph', description='Print a braille bar graph of t...
Display the arguments as a braille graph on standard output.
def set_right_to_left(self): """Set text direction right to left.""" self.displaymode &= ~LCD_ENTRYLEFT self.write8(LCD_ENTRYMODESET | self.displaymode)
Set text direction right to left.
def publish_if_new(cls): """If the station map has changed, publish the new information.""" message = cls.make_message() if message != cls.last_message: super(DashboardPubSub, cls).publish(message) cls.last_message = message
If the station map has changed, publish the new information.
def _example_short_number_for_cost(region_code, cost): """Gets a valid short number for the specified cost category. Arguments: region_code -- the region for which an example short number is needed. cost -- the cost category of number that is needed. Returns a valid short number for the specified ...
Gets a valid short number for the specified cost category. Arguments: region_code -- the region for which an example short number is needed. cost -- the cost category of number that is needed. Returns a valid short number for the specified region and cost category. Returns an empty string when the...
def append_field(self, path, name, value): """ Appends the field to the container at the specified path. :param path: str or Path instance :param name: :type name: str :param value: :type value: str """ path = make_path(path) container = s...
Appends the field to the container at the specified path. :param path: str or Path instance :param name: :type name: str :param value: :type value: str
def filter_source(self, source): # pylint: disable=R0911,R0912 """ Apply filters to ``source`` and return ``True`` if uncertainty should be applied to it. """ for key, value in self.filters.items(): if key == 'applyToTectonicRegionType': if val...
Apply filters to ``source`` and return ``True`` if uncertainty should be applied to it.
def get_soap_client(db_alias, client_class=None): """ Create the SOAP client for the current user logged in the db_alias The default created client is "beatbox.PythonClient", but an alternative client is possible. (i.e. other subtype of beatbox.XMLClient) """ if not beatbox: raise Inter...
Create the SOAP client for the current user logged in the db_alias The default created client is "beatbox.PythonClient", but an alternative client is possible. (i.e. other subtype of beatbox.XMLClient)
def record_markdown(text, cellid): """Records the specified markdown text to the acorn database. Args: text (str): the *raw* markdown text entered into the cell in the ipython notebook. """ from acorn.logging.database import record from time import time ekey = "nb-{}".format(c...
Records the specified markdown text to the acorn database. Args: text (str): the *raw* markdown text entered into the cell in the ipython notebook.
def port_profile_restrict_flooding_container_restrict_flooding(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") name_key = ET.SubElement(port_profile, ...
Auto Generated Code
def connect_euca(host=None, aws_access_key_id=None, aws_secret_access_key=None, port=8773, path='/services/Eucalyptus', is_secure=False, **kwargs): """ Connect to a Eucalyptus service. :type host: string :param host: the host name or ip address of the Eucalyptus server...
Connect to a Eucalyptus service. :type host: string :param host: the host name or ip address of the Eucalyptus server :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 ...
def create(self, notification_type, label=None, name=None, details=None): """ Defines a notification for handling an alarm. """ uri = "/%s" % self.uri_base body = {"label": label or name, "type": utils.get_id(notification_type), "details": details,...
Defines a notification for handling an alarm.
def _conn_string_adodbapi(self, db_key, instance=None, conn_key=None, db_name=None): ''' Return a connection string to use with adodbapi ''' if instance: _, host, username, password, database, _ = self._get_access_info(instance, db_key, db_name) elif conn_key: _, ...
Return a connection string to use with adodbapi
def load_tree(self): """ method iterates thru all objects older than synergy_start_timeperiod parameter in job collections and loads them into this timetable""" timeperiod = settings.settings['synergy_start_timeperiod'] yearly_timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_YEA...
method iterates thru all objects older than synergy_start_timeperiod parameter in job collections and loads them into this timetable
def getFileNameMime(self, requestedUrl, *args, **kwargs): ''' Give a requested page (note: the arguments for this call are forwarded to getpage()), return the content at the target URL, the filename for the target content, and the mimetype for the content at the target URL, as a 3-tuple (pgctnt, hName, mime). ...
Give a requested page (note: the arguments for this call are forwarded to getpage()), return the content at the target URL, the filename for the target content, and the mimetype for the content at the target URL, as a 3-tuple (pgctnt, hName, mime). The filename specified in the content-disposition header is used...
def this_month(today: datetime=None, tz=None): """ Returns current month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: t...
Returns current month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
def tabfile2doefile(tabfile, doefile): """tabfile2doefile""" alist = tabfile2list(tabfile) astr = list2doe(alist) mylib1.write_str2file(doefile, astr)
tabfile2doefile
def get_country_by_id(cls, country_id, **kwargs): """Find Country Return single instance of Country by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_country_by_id(country_id, asy...
Find Country Return single instance of Country by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_country_by_id(country_id, async=True) >>> result = thread.get() :param as...
def set_thumbnail(self, **kwargs): """ set thumbnail of embed :keyword url: source url of thumbnail (only supports http(s) and attachments) :keyword proxy_url: a proxied thumbnail of the image :keyword height: height of thumbnail :keyword width: width of thumbnail ...
set thumbnail of embed :keyword url: source url of thumbnail (only supports http(s) and attachments) :keyword proxy_url: a proxied thumbnail of the image :keyword height: height of thumbnail :keyword width: width of thumbnail
def multi_send(self, template, emails, _vars=None, evars=None, schedule_time=None, options=None): """ Remotely send an email template to multiple email addresses. http://docs.sailthru.com/api/send @param template: template string @param emails: List with email values or comma sep...
Remotely send an email template to multiple email addresses. http://docs.sailthru.com/api/send @param template: template string @param emails: List with email values or comma separated email string @param _vars: a key/value hash of the replacement vars to use in the send. Each var may be...
def _relative_path_to(path_list, filename): """Get a neat relative path to files relative to the CWD""" return os.path.join( os.path.relpath(os.path.join(*path_list), os.getcwd()), filename )
Get a neat relative path to files relative to the CWD
def lock_context(self, timeout='default', requested_key='exclusive'): """A context that locks :param timeout: Absolute time period (in milliseconds) that a resource waits to get unlocked by the locking session before returning an error. (Defaults to self....
A context that locks :param timeout: Absolute time period (in milliseconds) that a resource waits to get unlocked by the locking session before returning an error. (Defaults to self.timeout) :param requested_key: When using default of 'exclusive' the lock...
def render(self, text, auth=None): """ Renders the specified markdown content and embedded styles. """ if markdown is None: import markdown if UrlizeExtension is None: from .mdx_urlize import UrlizeExtension return markdown.markdown(text, extension...
Renders the specified markdown content and embedded styles.
def _utilized(n, node, other_attrs, unsuppressedPrefixes): '''_utilized(n, node, other_attrs, unsuppressedPrefixes) -> boolean Return true if that nodespace is utilized within the node''' if n.startswith('xmlns:'): n = n[6:] elif n.startswith('xmlns'): n = n[5:] if (n=="" and node.pr...
_utilized(n, node, other_attrs, unsuppressedPrefixes) -> boolean Return true if that nodespace is utilized within the node
def from_name(clz, name): """ Instantiates the object from a known name """ if isinstance(name, list) and "green" in name: name = "teal" assert name in COLOR_NAMES, 'Unknown color name' r, b, g = COLOR_NAMES[name] return clz(r, b, g)
Instantiates the object from a known name
def run(self): """ Main thread listen to socket and send any commands to the CommandRunner. """ while True: try: data = None # Wait for a connection if self.debug: self.py3_wrapper.log("waiting for a ...
Main thread listen to socket and send any commands to the CommandRunner.
def add_report_data(list_all=[], module_name="TestModule", **kwargs): ''' add report data to a list @param list_all: a list which save the report data @param module_name: test set name or test module name @param kwargs: such as case_name: testcase name ...
add report data to a list @param list_all: a list which save the report data @param module_name: test set name or test module name @param kwargs: such as case_name: testcase name status: test result, Pass or Fail resp_teste...
def _attachToObject(self, anchorObj, relationName) : "dummy fct for compatibility reasons, a RabaListPupa is attached by default" #MutableSequence.__getattribute__(self, "develop")() self.develop() self._attachToObject(anchorObj, relationName)
dummy fct for compatibility reasons, a RabaListPupa is attached by default
def runSearchVariantAnnotationSets(self, request): """ Runs the specified SearchVariantAnnotationSetsRequest. """ return self.runSearchRequest( request, protocol.SearchVariantAnnotationSetsRequest, protocol.SearchVariantAnnotationSetsResponse, self.var...
Runs the specified SearchVariantAnnotationSetsRequest.
def compute(self, config, budget, working_directory, *args, **kwargs): """ Simple example for a compute function using a feed forward network. It is trained on the MNIST dataset. The input parameter "config" (dictionary) contains the sampled configurations passed by the bohb optimizer """ # device = torch....
Simple example for a compute function using a feed forward network. It is trained on the MNIST dataset. The input parameter "config" (dictionary) contains the sampled configurations passed by the bohb optimizer
def show_slug_with_level(context, page, lang=None, fallback=True): """Display slug with level by language.""" if not lang: lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) page = get_page_from_string_or_id(page, lang) if not page: return '' return {'content': page.s...
Display slug with level by language.
def lfu_cache(maxsize=128, typed=False): """Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Least Frequently Used (LFU) algorithm. """ if maxsize is None: return _cache(_UnboundCache(), typed) else: return _cache(LFUCache(maxs...
Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Least Frequently Used (LFU) algorithm.
def parse_cl_args(arg_vector): '''Parses the command line arguments''' parser = argparse.ArgumentParser(description='Compiles markdown files into html files for remark.js') parser.add_argument('source', metavar='source', help='the source to compile. If a directory is provided, all markdown files in that directory...
Parses the command line arguments
def db_import_xml(self, url=None, force_download=False, taxids=None, silent=False): """Updates the CTD database 1. downloads gzipped XML 2. drops all tables in database 3. creates all tables in database 4. import XML 5. close session :param Optional[list...
Updates the CTD database 1. downloads gzipped XML 2. drops all tables in database 3. creates all tables in database 4. import XML 5. close session :param Optional[list[int]] taxids: list of NCBI taxonomy identifier :param str url: iterable of URL strings...
def find_object(self, obj, search_dirs, file_name=None): """ Return the path to a template associated with the given object. """ if file_name is None: # TODO: should we define a make_file_name() method? template_name = self.make_template_name(obj) fil...
Return the path to a template associated with the given object.
def get_data(self): """Gets data from the given url""" url = self.build_url() self.incidents_data = requests.get(url) if not self.incidents_data.status_code == 200: raise self.incidents_data.raise_for_status()
Gets data from the given url