code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def token(name): def wrap(f): tokenizers.append((name, f)) return f return wrap
Marker for a token :param str name: Name of tokenizer
def complement(color): r (r, g, b) = parse_color(color) gcolor = grapefruit.Color((r / 255.0, g / 255.0, b / 255.0)) complement = gcolor.ComplementaryColor() (r, g, b) = [int(c * 255.0) for c in complement.rgb] return (r, g, b)
r"""Calculates polar opposite of color This isn't guaranteed to look good >_> (especially with brighter, higher intensity colors.) This will be replaced with a formula that produces better looking colors in the future. >>> complement('red') (0, 255, 76) >>> complement((0, 100, 175)) (175, ...
def all(self, value, pos=None): value = bool(value) length = self.len if pos is None: pos = xrange(self.len) for p in pos: if p < 0: p += length if not 0 <= p < length: raise IndexError("Bit position {0} out of range.".f...
Return True if one or many bits are all set to value. value -- If value is True then checks for bits set to 1, otherwise checks for bits set to 0. pos -- An iterable of bit positions. Negative numbers are treated in the same way as slice indices. Defaults to the whole bi...
def toggle_bit(self, position: int): if position > (self._bit_width - 1): raise ValueError('position greater than the bit width') self._value ^= (1 << position) self._text_update()
Toggles the value at position :param position: integer between 0 and 7, inclusive :return: None
def get_tmp_file(dir=None): "Create and return a tmp filename, optionally at a specific path. `os.remove` when done with it." with tempfile.NamedTemporaryFile(delete=False, dir=dir) as f: return f.name
Create and return a tmp filename, optionally at a specific path. `os.remove` when done with it.
def create(cls, zmq_context, endpoint): socket = zmq_context.socket(zmq.REQ) socket.connect(endpoint) return cls(socket)
Create new client transport. Instead of creating the socket yourself, you can call this function and merely pass the :py:class:`zmq.core.context.Context` instance. By passing a context imported from :py:mod:`zmq.green`, you can use green (gevent) 0mq sockets as well. :param zm...
def wait_all(jobs, timeout=None): return Job._wait(jobs, timeout, concurrent.futures.ALL_COMPLETED)
Return when at all of the specified jobs have completed or timeout expires. Args: jobs: a Job or list of Jobs to wait on. timeout: a timeout in seconds to wait for. None (the default) means no timeout. Returns: A list of the jobs that have now completed or None if there were no jobs.
async def cursor_async(self): await self.connect_async(loop=self._loop) if self.transaction_depth_async() > 0: conn = self.transaction_conn_async() else: conn = None try: return (await self._async_conn.cursor(conn=conn)) except: awa...
Acquire async cursor.
def on_excepthandler(self, node): return (self.run(node.type), node.name, node.body)
Exception handler...
def rename(self, new_name, range=None): self.log.debug('rename: in') if not new_name: new_name = self.editor.ask_input("Rename to:") self.editor.write(noautocmd=True) b, e = self.editor.word_under_cursor_pos() current_file = self.editor.path() self.editor.raw_...
Request a rename to the server.
def _get_upserts_distinct(queryset, model_objs_updated, model_objs_created, unique_fields): created_models = [] if model_objs_created: created_models.extend( queryset.extra( where=['({unique_fields_sql}) in %s'.format( unique_fields_sql=', '.join(unique_fi...
Given a list of model objects that were updated and model objects that were created, fetch the pks of the newly created models and return the two lists in a tuple
def _initialize_application(): RuntimeGlobals.application = umbra.ui.common.get_application_instance() umbra.ui.common.set_window_default_icon(RuntimeGlobals.application) RuntimeGlobals.reporter = umbra.reporter.install_exception_reporter()
Initializes the Application.
def delete(self, port, qos_policy=None): LOG.info("Deleting QoS policy %(qos_policy)s on port %(port)s", dict(qos_policy=qos_policy, port=port)) self._utils.remove_port_qos_rule(port["port_id"])
Remove QoS rules from port. :param port: port object. :param qos_policy: the QoS policy to be removed from port.
def get_attention(config: AttentionConfig, max_seq_len: int, prefix: str = C.ATTENTION_PREFIX) -> 'Attention': att_cls = Attention.get_attention_cls(config.type) params = config.__dict__.copy() params.pop('_frozen') params['max_seq_len'] = max_seq_len params['prefix'] = prefix return _instantiat...
Returns an Attention instance based on attention_type. :param config: Attention configuration. :param max_seq_len: Maximum length of source sequences. :param prefix: Name prefix. :return: Instance of Attention.
def imagedatadict_to_ndarray(imdict): arr = imdict['Data'] im = None if isinstance(arr, parse_dm3.array.array): im = numpy.asarray(arr, dtype=arr.typecode) elif isinstance(arr, parse_dm3.structarray): t = tuple(arr.typecodes) im = numpy.frombuffer( arr.raw_data, ...
Converts the ImageData dictionary, imdict, to an nd image.
def read_feather(path, columns=None, use_threads=True): feather, pyarrow = _try_import() path = _stringify_path(path) if LooseVersion(pyarrow.__version__) < LooseVersion('0.11.0'): int_use_threads = int(use_threads) if int_use_threads < 1: int_use_threads = 1 return feath...
Load a feather-format object from the file path .. versionadded 0.20.0 Parameters ---------- path : string file path, or file-like object columns : sequence, default None If not provided, all columns are read .. versionadded 0.24.0 nthreads : int, default 1 Number of C...
def _remove_data_dir_path(self, inp=None): if inp is not None: split_str = os.path.join(self.data_path, '') return inp.apply(lambda x: x.split(split_str)[-1])
Remove the data directory path from filenames
def rand_block(minimum, scale, maximum=1): t = min(rand_pareto_float(minimum, scale), maximum) time.sleep(t) return t
block current thread at random pareto time ``minimum < block < 15`` and return the sleep time ``seconds`` :param minimum: :type minimum: :param scale: :type scale: :param slow_mode: a tuple e.g.(2, 5) :type slow_mode: tuple :return:
def has_chosen(state, correct, msgs): ctxt = {} exec(state.student_code, globals(), ctxt) sel_indx = ctxt["selected_option"] if sel_indx != correct: state.report(Feedback(msgs[sel_indx - 1])) else: state.reporter.success_msg = msgs[correct - 1] return state
Verify exercises of the type MultipleChoiceExercise Args: state: State instance describing student and solution code. Can be omitted if used with Ex(). correct: index of correct option, where 1 is the first option. msgs : list of feedback messages corresponding to each option. ...
def main(): if "--help" in sys.argv or "-h" in sys.argv or len(sys.argv) > 3: raise SystemExit(__doc__) try: discordian_calendar(*sys.argv[1:]) except ValueError as error: raise SystemExit("Error: {}".format("\n".join(error.args)))
Command line entry point for dcal.
def from_taxtable(cls, taxtable_fp): r = csv.reader(taxtable_fp) headers = next(r) rows = (collections.OrderedDict(list(zip(headers, i))) for i in r) row = next(rows) root = cls(rank=row['rank'], tax_id=row[ 'tax_id'], name=row['tax_name']) path_root = ...
Generate a node from an open handle to a taxtable, as generated by ``taxit taxtable``
async def save(self, db=None): self._db = db or self.db data = self.prepare_data() self.validate() for i in self.connection_retries(): try: created = False if '_id' in data else True result = await self.db[self.get_collection_name()].insert_one...
If object has _id, then object will be created or fully rewritten. If not, object will be inserted and _id will be assigned.
def _do_help(self, cmd, args): print(self.doc_string()) print() data_unsorted = [] cls = self.__class__ for name in dir(cls): obj = getattr(cls, name) if iscommand(obj): cmds = [] for cmd in getcommands(obj): ...
Display doc strings of the shell and its commands.
def order_target_value(self, asset, target, limit_price=None, stop_price=None, style=None): if not self._can_order_asset(asset): return None target_amount = ...
Place an order to adjust a position to a target value. If the position doesn't already exist, this is equivalent to placing a new order. If the position does exist, this is equivalent to placing an order for the difference between the target value and the current value. If the As...
def export_xlsx(self, key): spreadsheet_file = self.client.files().get(fileId=key).execute() links = spreadsheet_file.get('exportLinks') downloadurl = links.get('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') resp, content = self.client._http.request(downloadurl) ...
Download xlsx version of spreadsheet.
def _get_ssh_config(config_path='~/.ssh/config'): ssh_config = paramiko.SSHConfig() try: with open(os.path.realpath(os.path.expanduser(config_path))) as f: ssh_config.parse(f) except IOError: pass return ssh_config
Extract the configuration located at ``config_path``. Returns: paramiko.SSHConfig: the configuration instance.
def load_gffutils_db(f): import gffutils db = gffutils.FeatureDB(f, keep_order=True) return db
Load database for gffutils. Parameters ---------- f : str Path to database. Returns ------- db : gffutils.FeatureDB gffutils feature database.
async def write(self, data): if type(data) != bytes: data = self._encode_body(data) self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data)) await self.protocol.drain()
Writes a chunk of data to the streaming response. :param data: bytes-ish data to be written.
def sanitize_html(value, valid_tags=VALID_TAGS, strip=True): return bleach.clean(value, tags=list(VALID_TAGS.keys()), attributes=VALID_TAGS, strip=strip)
Strips unwanted markup out of HTML.
def escape( text, newline=False ): if isinstance( text, basestring ): if '&' in text: text = text.replace( '&', '&amp;' ) if '>' in text: text = text.replace( '>', '&gt;' ) if '<' in text: text = text.replace( '<', '&lt;' ) if '\"' in text: ...
Escape special html characters.
def cancelled(self): return self._state == self.S_EXCEPTION and isinstance(self._result, Cancelled)
Return whether this future was successfully cancelled.
def _padding(self, image, geometry, options): image['options']['background'] = options.get('padding_color') image['options']['gravity'] = 'center' image['options']['extent'] = '%sx%s' % (geometry[0], geometry[1]) return image
Pads the image
def __execute_bisz(self, instr): op0_val = self.read_operand(instr.operands[0]) op2_val = 1 if op0_val == 0 else 0 self.write_operand(instr.operands[2], op2_val) return None
Execute BISZ instruction.
def getJson(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): if not 'Content-Type' in headers: headers['Content-Type'] = ['application/json'] body = yield cls().getBody(url, method, headers, data, socket, timeout) defer.returnValue(json.loads(body))
Fetch a JSON result via HTTP
def set_PLOS_2column_fig_style(self, ratio=1): plt.rcParams.update({ 'figure.figsize' : [self.PLOSwidth2Col, self.PLOSwidth2Col*ratio], })
figure size corresponding to Plos 2 columns
def queue(p_queue, host=None): if host is not None: return _path(_c.FSQ_QUEUE, root=_path(host, root=hosts(p_queue))) return _path(p_queue, _c.FSQ_QUEUE)
Construct a path to the queue dir for a queue
def __expr_str(cls, expr, level): ident = ' ' * level * 4 if isinstance(expr, tuple): return '{}{}'.format(ident, str(expr)) if expr.etype[0] in ['pvar', 'constant']: return '{}Expression(etype={}, args={})'.format(ident, expr.etype, expr.args) if not isinstance(e...
Returns string representing the expression.
def next_frame_l2(): hparams = next_frame_basic_deterministic() hparams.loss["targets"] = modalities.video_l2_loss hparams.top["targets"] = modalities.video_l1_top hparams.video_modality_loss_cutoff = 2.4 return hparams
Basic conv model with L2 modality.
def _dedup_index(self, df_a): pairs = self._link_index(df_a, df_a) pairs = pairs[pairs.labels[0] > pairs.labels[1]] return pairs
Build an index for deduplicating a dataset. Parameters ---------- df_a : (tuple of) pandas.Series The data of the DataFrame to build the index with. Returns ------- pandas.MultiIndex A pandas.MultiIndex with record pairs. Each record pair ...
def join_sources(source_module: DeploymentModule, contract_name: str): joined_file = Path(__file__).parent.joinpath('joined.sol') remapping = {module: str(path) for module, path in contracts_source_path().items()} command = [ './utils/join-contracts.py', '--import-map', json.dumps(re...
Use join-contracts.py to concatenate all imported Solidity files. Args: source_module: a module name to look up contracts_source_path() contract_name: 'TokenNetworkRegistry', 'SecretRegistry' etc.
def debug(method): def new_method(*args, **kwargs): import pdb try: import pudb except ImportError: pudb = pdb try: pudb.runcall(method, *args, **kwargs) except pdb.bdb.BdbQuit: sys.exit('Normal quit from debugger') new_meth...
Decorator to debug the given method
def memoize(fun): argspec = inspect2.getfullargspec(fun) arg_names = argspec.args + argspec.kwonlyargs kwargs_defaults = get_kwargs_defaults(argspec) def cache_key(args, kwargs): return get_args_tuple(args, kwargs, arg_names, kwargs_defaults) @functools.wraps(fun) def new_fun(*args, **kw...
Memoizes return values of the decorated function. Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache() is called on the function.
def delete(ids, yes): failures = False for id in ids: data_source = get_data_object(id, use_data_config=True) if not data_source: failures = True continue data_name = normalize_data_name(data_source.name) suffix = data_name.split('/')[-1] if not su...
Delete datasets.
def extract_formats(config_handle): configurations = dict(config_handle) formats = dict(configurations.get('formats', {})) return formats
Get application formats. See :class:`gogoutils.Formats` for available options. Args: config_handle (configparser.ConfigParser): Instance of configurations. Returns: dict: Formats in ``{$format_type: $format_pattern}``.
def get(self, slug): kb = api.get_kb_by_slug(slug) check_knowledge_access(kb) parser = reqparse.RequestParser() parser.add_argument( 'from', type=str, help="Return only entries where key matches this.") parser.add_argument( 'to', type=str, ...
Get KnwKB. Url parameters: - from: filter "mappings from" - to: filter "mappings to" - page - per_page - match_type: s=substring, e=exact, sw=startswith - sortby: 'from' or 'to'
def create_shot(self, sequence): dialog = ShotCreatorDialog(sequence=sequence, parent=self) dialog.exec_() shot = dialog.shot return shot
Create and return a new shot :param sequence: the sequence for the shot :type sequence: :class:`jukeboxcore.djadapter.models.Sequence` :returns: The created shot or None :rtype: None | :class:`jukeboxcore.djadapter.models.Shot` :raises: None
def from_charmm(cls, path, positions=None, forcefield=None, strict=True, **kwargs): psf = CharmmPsfFile(path) if strict and forcefield is None: raise ValueError('PSF files require key `forcefield`.') if strict and positions is None: raise ValueError('PSF files require key...
Loads PSF Charmm structure from `path`. Requires `charmm_parameters`. Parameters ---------- path : str Path to PSF file forcefield : list of str Paths to Charmm parameters files, such as *.par or *.str. REQUIRED Returns ------- psf : Syst...
def rawselect(message: Text, choices: List[Union[Text, Choice, Dict[Text, Any]]], default: Optional[Text] = None, qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: return select.select(message, choi...
Ask the user to select one item from a list of choices using shortcuts. The user can only select one option. Args: message: Question text choices: Items shown in the selection, this can contain `Choice` or or `Separator` objects or simple items as strings. Pass...
def parse_date(value): if not value: return None if isinstance(value, datetime.date): return value return parse_datetime(value).date()
Attempts to parse `value` into an instance of ``datetime.date``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string, datetime.date, or datetime.datetime value.
def configure_error_handlers(app): def render_error(error): return (render_template('errors/%s.html' % error.code, title=error_messages[error.code], code=error.code), error.code) for (errcode, title) in error_messages.iteritems(): app.errorhandler(errcode)(render_error)
Configure application error handlers
def get_renderers(self): renderers = super(WithDynamicViewSetMixin, self).get_renderers() if settings.ENABLE_BROWSABLE_API is False: return [ r for r in renderers if not isinstance(r, BrowsableAPIRenderer) ] else: return renderers
Optionally block Browsable API rendering.
def create_account(self, **kwargs): response = self.__requester.request( 'POST', 'accounts', _kwargs=combine_kwargs(**kwargs) ) return Account(self.__requester, response.json())
Create a new root account. :calls: `POST /api/v1/accounts \ <https://canvas.instructure.com/doc/api/accounts.html#method.accounts.create>`_ :rtype: :class:`canvasapi.account.Account`
def pull(self): repo_root = settings.REPO_ROOT pull_from_origin(join(repo_root, self.name))
Pull from the origin.
def check_smart_storage_config_ids(self): if self.smart_storage_config_identities is None: msg = ('The Redfish controller failed to get the ' 'SmartStorageConfig controller configurations.') LOG.debug(msg) raise exception.IloError(msg)
Check SmartStorageConfig controllers is there in hardware. :raises: IloError, on an error from iLO.
def detect_interval( self, min_head_length=None, max_head_length=None, min_tail_length=None, max_tail_length=None ): head = self.detect_head(min_head_length, max_head_length) tail = self.detect_tail(min_tail_length, max_tail_length) ...
Detect the interval of the audio file containing the fragments in the text file. Return the audio interval as a tuple of two :class:`~aeneas.exacttiming.TimeValue` objects, representing the begin and end time, in seconds, with respect to the full wave duration. If one o...
def login_required(func): @wraps(func) def wrapped(*args, **kwargs): if g.user is None: return redirect(url_for(current_app.config['LDAP_LOGIN_VIEW'], next=request.path)) return func(*args, **kwargs) return wrapped
When applied to a view function, any unauthenticated requests will be redirected to the view named in LDAP_LOGIN_VIEW. Authenticated requests do NOT require membership from a specific group. The login view is responsible for asking for credentials, checking them, and setting ``flask.g.u...
def rsync_git(local_path, remote_path, exclude=None, extra_opts=None, version_file='version.txt'): with settings(hide('output', 'running'), warn_only=True): print(green('Version On Server: ' + run('cat ' + '{}/{}'.format( remote_path, version_file)).strip())) print(green('Now...
Rsync deploy a git repo. Write and compare version.txt
def wrap(tensor, books=None, tensor_shape=None): if books is None: books = bookkeeper.for_default_graph() if isinstance(tensor, PrettyTensor): return tensor.as_layer() elif isinstance(tensor, UnboundVariable): def set_input_from_unbound_var(data): if data is not None: return wrap(data, b...
Creates an input layer representing the given tensor. Args: tensor: The tensor. books: The bookkeeper; this is usually not required unless you are building multiple `tf.Graphs.` tensor_shape: An optional shape that will be set on the Tensor or verified to match the tensor. Returns: A la...
def _build_schema(self, s): w = self._whatis(s) if w == self.IS_LIST: w0 = self._whatis(s[0]) js = {"type": "array", "items": {"type": self._jstype(w0, s[0])}} elif w == self.IS_DICT: js = {"type": "object", "properties": {k...
Recursive schema builder, called by `json_schema`.
def make_python_name(self, name): for k, v in [('<', '_'), ('>', '_'), ('::', '__'), (',', ''), (' ', ''), ("$", "DOLLAR"), (".", "DOT"), ("@", "_"), (":", "_"), ('-', '_')]: if k in name: name = name.replace(k, v) if name.startsw...
Transforms an USR into a valid python name.
def zip_currentdir(self) -> None: with zipfile.ZipFile(f'{self.currentpath}.zip', 'w') as zipfile_: for filepath, filename in zip(self.filepaths, self.filenames): zipfile_.write(filename=filepath, arcname=filename) del self.currentdir
Pack the current working directory in a `zip` file. |FileManager| subclasses allow for manual packing and automatic unpacking of working directories. The only supported format is `zip`. To avoid possible inconsistencies, origin directories and zip files are removed after packing or unp...
def parse_year_days(year_info): leap_month, leap_days = _parse_leap(year_info) res = leap_days for month in range(1, 13): res += (year_info >> (16 - month)) % 2 + 29 return res
Parse year days from a year info.
def interactive_server(port=27017, verbose=True, all_ok=False, name='MockupDB', ssl=False, uds_path=None): if uds_path is not None: port = None server = MockupDB(port=port, verbose=verbose, request_timeout=int(1e6), ...
A `MockupDB` that the mongo shell can connect to. Call `~.MockupDB.run` on the returned server, and clean it up with `~.MockupDB.stop`. If ``all_ok`` is True, replies {ok: 1} to anything unmatched by a specific responder.
def to_shcoeffs(self, itaper, normalization='4pi', csphase=1): if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not ...
Return the spherical harmonic coefficients of taper i as a SHCoeffs class instance. Usage ----- clm = x.to_shcoeffs(itaper, [normalization, csphase]) Returns ------- clm : SHCoeffs class instance Parameters ---------- itaper : int ...
def finish(self): stylesheet = ''.join(self._buffer) parser = CSSParser() css = parser.parseString(stylesheet) replaceUrls(css, self._replace) self.request.write(css.cssText) return self.request.finish()
Parse the buffered response body, rewrite its URLs, write the result to the wrapped request, and finish the wrapped request.
def send_confirmation_email(self): context= {'user': self, 'new_email': self.email_unconfirmed, 'protocol': get_protocol(), 'confirmation_key': self.email_confirmation_key, 'site': Site.objects.get_current()} subject_old = ''.join(r...
Sends an email to confirm the new email address. This method sends out two emails. One to the new email address that contains the ``email_confirmation_key`` which is used to verify this this email address with :func:`User.objects.confirm_email`. The other email is to the old email addr...
def from_moment_relative_to_crystal_axes(cls, moment, lattice): unit_m = lattice.matrix / np.linalg.norm(lattice.matrix, axis=1)[:, None] moment = np.matmul(list(moment), unit_m) moment[np.abs(moment) < 1e-8] = 0 return cls(moment)
Obtaining a Magmom object from a magnetic moment provided relative to crystal axes. Used for obtaining moments from magCIF file. :param magmom: list of floats specifying vector magmom :param lattice: Lattice :return: Magmom
def data_to_imagesurface (data, **kwargs): import cairo data = np.atleast_2d (data) if data.ndim != 2: raise ValueError ('input array may not have more than 2 dimensions') argb32 = data_to_argb32 (data, **kwargs) format = cairo.FORMAT_ARGB32 height, width = argb32.shape stride = cair...
Turn arbitrary data values into a Cairo ImageSurface. The method and arguments are the same as data_to_argb32, except that the data array will be treated as 2D, and higher dimensionalities are not allowed. The return value is a Cairo ImageSurface object. Combined with the write_to_png() method on Imag...
def blueprint(self) -> Optional[str]: if self.endpoint is not None and '.' in self.endpoint: return self.endpoint.rsplit('.', 1)[0] else: return None
Returns the blueprint the matched endpoint belongs to. This can be None if the request has not been matched or the endpoint is not in a blueprint.
def is_third_friday(day=None): day = day if day is not None else datetime.datetime.now() defacto_friday = (day.weekday() == 4) or ( day.weekday() == 3 and day.hour() >= 17) return defacto_friday and 14 < day.day < 22
check if day is month's 3rd friday
def get_zorder(self, overlay, key, el): spec = util.get_overlay_spec(overlay, key, el) return self.ordering.index(spec)
Computes the z-order of element in the NdOverlay taking into account possible batching of elements.
def parseLines(self): inAst = parse(''.join(self.lines), self.inFilename) self.visit(inAst)
Form an AST for the code and produce a new version of the source.
def truncated_normal_log_likelihood(params, low, high, data): mu = params[0] sigma = params[1] if sigma == 0: return np.inf ll = np.sum(norm.logpdf(data, mu, sigma)) ll -= len(data) * np.log((norm.cdf(high, mu, sigma) - norm.cdf(low, mu, sigma))) return -ll
Calculate the log likelihood of the truncated normal distribution. Args: params: tuple with (mean, std), the parameters under which we evaluate the model low (float): the lower truncation bound high (float): the upper truncation bound data (ndarray): the one dime...
def _heartbeat_loop(self): self.logger.debug("running main heartbeat thread") while not self.closed: time.sleep(self.settings['SLEEP_TIME']) self._report_self()
A main run loop thread to do work
def _get_atomsection(mol2_lst): started = False for idx, s in enumerate(mol2_lst): if s.startswith('@<TRIPOS>ATOM'): first_idx = idx + 1 started = True elif started and s.startswith('@<TRIPOS>'): last_idx_plus1 = idx ...
Returns atom section from mol2 provided as list of strings
def partition_list(pred, iterable): left, right = partition_iter(pred, iterable) return list(left), list(right)
Partitions an iterable with a predicate into two lists, one with elements satisfying the predicate and one with elements that do not satisfy it. .. note: this just converts the results of partition_iter to a list for you so that you don't have to in most cases using `partition_iter` is a better option. ...
def upload_file_and_send_file_offer(self, file_name, user_id, data=None, input_file_path=None, content_type='application/octet-stream', auto_open=False, prevent_share=False, scope='content/send'): if input_file_path: wit...
Upload a file of any type to store and return a FileId once file offer has been sent. No user authentication required
def task_annotate(self, task, annotation): self._execute( task['uuid'], 'annotate', '--', annotation ) id, annotated_task = self.get_task(uuid=task[six.u('uuid')]) return annotated_task
Annotates a task.
def colors(self, color_code): if color_code is None: color_code = WINDOWS_CODES['/all'] current_fg, current_bg = self.colors if color_code == WINDOWS_CODES['/fg']: final_color_code = self.default_fg | current_bg elif color_code == WINDOWS_CODES['/bg']: ...
Change the foreground and background colors for subsequently printed characters. None resets colors to their original values (when class was instantiated). Since setting a color requires including both foreground and background codes (merged), setting just the foreground color resets the backg...
def process_nxml_file(file_name, citation=None, offline=False, output_fname=default_output_fname): with open(file_name, 'rb') as f: nxml_str = f.read().decode('utf-8') return process_nxml_str(nxml_str, citation, False, output_fname)
Return a ReachProcessor by processing the given NXML file. NXML is the format used by PubmedCentral for papers in the open access subset. Parameters ---------- file_name : str The name of the NXML file to be processed. citation : Optional[str] A PubMed ID passed to be used in t...
def f1_score(df, col_true=None, col_pred='precision_result', pos_label=1, average=None): r if not col_pred: col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS) return fbeta_score(df, col_true, col_pred, pos_label=pos_label, average=average)
r""" Compute f-1 score of a predicted DataFrame. f-1 is defined as .. math:: \frac{2 \cdot precision \cdot recall}{precision + recall} :Parameters: - **df** - predicted data frame - **col_true** - column name of true label - **col_pred** - column name of predicted label, ...
def pasa(args): p = OptionParser(pasa.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) pasa_db, fastafile = args termexons = "pasa.terminal_exons.gff3" if need_update(fastafile, termexons): cmd = "$ANNOT_DEVEL/PASA2/scripts/pasa_asmbls_to_t...
%prog pasa pasa_db fastafile Run EVM in TIGR-only mode.
def _show_stat(self): _show_stat_wrapper_multi_Progress(self.count, self.last_count, self.start_time, self.max_count, self.speed_calc_cycles,...
convenient functions to call the static show_stat_wrapper_multi with the given class members
def check_script(vouts): for vout in [v for v in vouts[::-1] if v['hex'].startswith('6a')]: verb = BlockchainSpider.decode_op_return(vout['hex']) action = Spoolverb.from_verb(verb).action if action in Spoolverb.supported_actions: return verb raise Exce...
Looks into the vouts list of a transaction and returns the ``op_return`` if one exists. Args; vouts (list): List of outputs of a transaction. Returns: str: String representation of the ``op_return``. Raises: Exception: If no ``vout`` having a suppor...
def if_sqlserver_disable_constraints_triggers(session: SqlASession, tablename: str) -> None: with if_sqlserver_disable_constraints(session, tablename): with if_sqlserver_disable_triggers(session, tablename): yield
If we're running under SQL Server, disable triggers AND constraints for the specified table while the resource is held. Args: session: SQLAlchemy :class:`Session` tablename: table name
def set(self, key, val, time=0, min_compress_len=0): return self._set("set", key, val, time, min_compress_len)
Unconditionally sets a key to a given value in the memcache. The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. If you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all o...
def _restore_backup(self): input_filename, input_file = self._get_backup_file(database=self.database_name, servername=self.servername) self.logger.info("Restoring backup for database '%s' and server '%s'", self.database_...
Restore the specified database.
def email(anon, obj, field, val): return anon.faker.email(field=field)
Generates a random email address.
def _parse_dav_element(self, dav_response): href = parse.unquote( self._strip_dav_path(dav_response.find('{DAV:}href').text) ) if six.PY2: href = href.decode('utf-8') file_type = 'file' if href[-1] == '/': file_type = 'dir' file_attrs =...
Parses a single DAV element :param dav_response: DAV response :returns :class:`FileInfo`
def pelix_services(self): return { svc_ref.get_property(pelix.constants.SERVICE_ID): { "specifications": svc_ref.get_property( pelix.constants.OBJECTCLASS ), "ranking": svc_ref.get_property( pelix.constants.SERVI...
List of registered services
def gameloop(self): try: while True: self.handle_events() self.update() self.render() except KeyboardInterrupt: pass
A game loop that circles through the methods.
def _make_mask(self, data, lon_str=LON_STR, lat_str=LAT_STR): mask = False for west, east, south, north in self.mask_bounds: if west < east: mask_lon = (data[lon_str] > west) & (data[lon_str] < east) else: mask_lon = (data[lon_str] < west) | (data[...
Construct the mask that defines a region on a given data's grid.
def get_database_configuration(): db_config = get_database_config_file() if db_config is None: return None with open(db_config, 'r') as ymlfile: cfg = yaml.load(ymlfile) return cfg
Get database configuration as dictionary.
def _construct(self, context): with self.g.as_default(): if self._pass_through: return self._pass_through._construct(context) current_value = context.get(self, None) assert current_value is not _unspecified, 'Circular dependency' if current_value is not None: return current_v...
Constructs this by calling the deferred method. This assumes that all unbound_vars have been specified in context and if this layer has already been computed in this context, then the previously constructed value will be returned. Args: context: A dict of UnboundVariables/_DeferredLayers to thei...
def get_qualification_type_by_name(self, name): max_fuzzy_matches_to_check = 100 query = name.upper() start = time.time() args = { "Query": query, "MustBeRequestable": False, "MustBeOwnedByCaller": True, "MaxResults": max_fuzzy_matches_to_c...
Return a Qualification Type by name. If the provided name matches more than one Qualification, check to see if any of the results match the provided name exactly. If there's an exact match, return that Qualification. Otherwise, raise an exception.
def get_list_w_id2nts(ids, id2nts, flds, dflt_null=""): combined_nt_list = [] ntobj = cx.namedtuple("Nt", " ".join(flds)) for item_id in ids: nts = [id2nt.get(item_id) for id2nt in id2nts] vals = _combine_nt_vals(nts, flds, dflt_null) combined_nt_list.append(ntobj._make(vals)) re...
Return a new list of namedtuples by combining "dicts" of namedtuples or objects.
def get_pending_domain_join(): base_key = r'SYSTEM\CurrentControlSet\Services\Netlogon' avoid_key = r'{0}\AvoidSpnSet'.format(base_key) join_key = r'{0}\JoinDomain'.format(base_key) if __utils__['reg.key_exists']('HKLM', avoid_key): log.debug('Key exists: %s', avoid_key) return True ...
Determine whether there is a pending domain join action that requires a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there is a pending domain join action, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_domain_join
def check_dupl_sources(self): dd = collections.defaultdict(list) for src_group in self.src_groups: for src in src_group: try: srcid = src.source_id except AttributeError: srcid = src['id'] dd[srcid].appen...
Extracts duplicated sources, i.e. sources with the same source_id in different source groups. Raise an exception if there are sources with the same ID which are not duplicated. :returns: a list of list of sources, ordered by source_id
def write(self): with open(self.log_path, "w") as f: json.dump(self.log_dict, f, indent=1)
Dump JSON to file
def has_hlu(self, lun_or_snap, cg_member=None): hlu = self.get_hlu(lun_or_snap, cg_member=cg_member) return hlu is not None
Returns True if `lun_or_snap` is attached to the host. :param lun_or_snap: can be lun, lun snap, cg snap or a member snap of cg snap. :param cg_member: the member lun of cg if `lun_or_snap` is cg snap. :return: True - if `lun_or_snap` is attached, otherwise False.