code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_app_data(app_id): """ get app data ( include name and app_data ) """ try: conn = get_conn() c = conn.cursor() c.execute("SELECT id,name,app_data FROM app WHERE id='{0}' ".format(app_id)) result = c.fetchone() conn.close() if result: ap...
get app data ( include name and app_data )
def find_parents(self): """Take a tree and set the parents according to the children Takes a tree structure which lists the children of each vertex and computes the parents for each vertex and places them in.""" for i in range(len(self.vertices)): self.vertices[i].parents = ...
Take a tree and set the parents according to the children Takes a tree structure which lists the children of each vertex and computes the parents for each vertex and places them in.
def _configuration(self, kwargs, config_item): """Combine configuration-related keyworded arguments into notification_configuration. """ if 'notification_configuration' not in config_item: if 'notification_type' not in kwargs: return nc = kwargs['n...
Combine configuration-related keyworded arguments into notification_configuration.
def read_env(cls, env_file=None, **overrides): """Read a .env file into os.environ. If not given a path to a dotenv path, does filthy magic stack backtracking to find manage.py and then find the dotenv. http://www.wellfireinteractive.com/blog/easier-12-factor-django/ https://g...
Read a .env file into os.environ. If not given a path to a dotenv path, does filthy magic stack backtracking to find manage.py and then find the dotenv. http://www.wellfireinteractive.com/blog/easier-12-factor-django/ https://gist.github.com/bennylope/2999704
def run(self): """Run the process. Iterate the GLib main loop and process the task queue. """ loop = GLib.MainLoop() context = loop.get_context() while True: time.sleep(0.1) if context.pending(): context.iteration() ...
Run the process. Iterate the GLib main loop and process the task queue.
def init_app(self, app): ''' Initialize this Flask extension for given app. ''' self.app = app if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['plugin_manager'] = self self.reload()
Initialize this Flask extension for given app.
def python(source): r""" >>> python('def add(a, b): return a + b').add(40, 2) 42 """ obj = type('', (object,), {})() _exec(source, obj.__dict__, obj.__dict__) return obj
r""" >>> python('def add(a, b): return a + b').add(40, 2) 42
def grains_dict(self): """Allowing to lookup grain by either label or duration For backward compatibility""" d = {grain.duration: grain for grain in self.grains()} d.update({grain.label: grain for grain in self.grains()}) return d
Allowing to lookup grain by either label or duration For backward compatibility
def update_metric_tags(self, metric_type, metric_id, **tags): """ Replace the metric_id's tags with given **tags :param metric_type: MetricType to be matched (required) :param metric_id: Exact string matching metric id :param tags: Updated key/value tag values of the metric ...
Replace the metric_id's tags with given **tags :param metric_type: MetricType to be matched (required) :param metric_id: Exact string matching metric id :param tags: Updated key/value tag values of the metric
def _setup_output_file(self, output_filename, args, write_header=True): """Open and prepare output file.""" # write command line into outputFile # (without environment variables, they are documented by benchexec) try: output_file = open(output_filename, 'w') # override existi...
Open and prepare output file.
def run_config_diagnostics(config_path=CONFIG_PATH): """Run diagnostics on the configuration file. Args: config_path (str): Path to the configuration file. Returns: str, Set[str], dict(str, Set[str]): The path to the configuration file, a set of missing sections and a dict that maps...
Run diagnostics on the configuration file. Args: config_path (str): Path to the configuration file. Returns: str, Set[str], dict(str, Set[str]): The path to the configuration file, a set of missing sections and a dict that maps each section to the entries that have either missing or emp...
def handle_document_error(self, item_session: ItemSession) -> Actions: '''Callback for when the document only describes an server error. Returns: A value from :class:`.hook.Actions`. ''' self._waiter.increment() self._statistics.errors[ServerError] += 1 act...
Callback for when the document only describes an server error. Returns: A value from :class:`.hook.Actions`.
def handle_result(self, idents, parent, raw_msg, success=True): """handle a real task result, either success or failure""" # first, relay result to client engine = idents[0] client = idents[1] # swap_ids for ROUTER-ROUTER mirror raw_msg[:2] = [client,engine] # pri...
handle a real task result, either success or failure
def plot_histogram(self, filename=None): """ Plot a histogram of data values """ header, data = self.read_next_data_block() data = data.view('float32') plt.figure("Histogram") plt.hist(data.flatten(), 65, facecolor='#cc0000') if filename: plt.savefig(filename...
Plot a histogram of data values
def _fill_syns(self, new_syns, rpacketlists_per_worker): """ rpacket_per_worker is a list of packetlists as returned by _run_chunk """ # TODO: move to BaseBackendByDataset or BaseBackend? logger.debug("rank:{}/{} {}._fill_syns".format(mpi.myrank, mpi.nprocs, self.__class__.__name...
rpacket_per_worker is a list of packetlists as returned by _run_chunk
def inline(text, data=None): """ Creates a new inline button. If `data` is omitted, the given `text` will be used as `data`. In any case `data` should be either ``bytes`` or ``str``. Note that the given `data` must be less or equal to 64 bytes. If more than 64 bytes are...
Creates a new inline button. If `data` is omitted, the given `text` will be used as `data`. In any case `data` should be either ``bytes`` or ``str``. Note that the given `data` must be less or equal to 64 bytes. If more than 64 bytes are passed as data, ``ValueError`` is raised.
def error(self, fail=True, action=''): """ SHOULD BE PRIVATE METHOD """ e = 'There was an unknown error communicating with the device.' if action: e = 'While %s: %s' % (action, e) log.error(e) if fail: raise IOError(e)
SHOULD BE PRIVATE METHOD
def best_diff(img1, img2, opts): """Find the best alignment of two images that minimizes the differences. Returns (diff, alignments) where ``diff`` is a difference map, and ``alignments`` is a tuple ((x1, y2), (x2, y2)). See ``diff()`` for the description of the alignment numbers. """ w1, h1 =...
Find the best alignment of two images that minimizes the differences. Returns (diff, alignments) where ``diff`` is a difference map, and ``alignments`` is a tuple ((x1, y2), (x2, y2)). See ``diff()`` for the description of the alignment numbers.
def exciter(self, Xexc, Pexc, Vexc): """ Exciter model. Based on Exciter.m from MatDyn by Stijn Cole, developed at Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/electa/teaching/ matdyn/} for more information. """ exciters = self.exciters F = ...
Exciter model. Based on Exciter.m from MatDyn by Stijn Cole, developed at Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/electa/teaching/ matdyn/} for more information.
def build_network(self, network=None, *args, **kwargs): """ Core method to construct PyPSA Network object. """ # TODO: build_network takes care of divergences in database design and # future PyPSA changes from PyPSA's v0.6 on. This concept should be # replaced, when the oedb has...
Core method to construct PyPSA Network object.
def random_box(molecules, total=None, proportions=None, size=[1.,1.,1.], maxtries=100): '''Create a System made of a series of random molecules. Parameters: total: molecules: proportions: ''' # Setup proportions to be right if proportions is None: proportions = np....
Create a System made of a series of random molecules. Parameters: total: molecules: proportions:
def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): """Look for any references, without object type This always searches in "refspecific" mode """ prefix = node.get('dn:prefix') results = [] match = self.find_obj(env, ...
Look for any references, without object type This always searches in "refspecific" mode
def PwDecrypt(self, password): """Unobfuscate a RADIUS password. RADIUS hides passwords in packets by using an algorithm based on the MD5 hash of the packet authenticator and RADIUS secret. This function reverses the obfuscation process. :param password: obfuscated form of password ...
Unobfuscate a RADIUS password. RADIUS hides passwords in packets by using an algorithm based on the MD5 hash of the packet authenticator and RADIUS secret. This function reverses the obfuscation process. :param password: obfuscated form of password :type password: binary string ...
def create(cls, name, ne_ref=None, operator='exclusion', sub_expression=None, comment=None): """ Create the expression :param str name: name of expression :param list ne_ref: network element references for expression :param str operator: 'exclusion' (negation), 'u...
Create the expression :param str name: name of expression :param list ne_ref: network element references for expression :param str operator: 'exclusion' (negation), 'union', 'intersection' (default: exclusion) :param dict sub_expression: sub expression used :param...
def get_corpus(self): """获取语料库 Return: corpus -- 语料库,str类型 """ # 正向判定 corpus = [] cd = 0 tag = None for i in range(0, self.init_corpus[0][0]): init_unit = self.unit_raw[self.init_corpus[0][0] - i] cdm = CDM(i...
获取语料库 Return: corpus -- 语料库,str类型
def get_working_login(self, database, username=None, password=None): """ authenticate to the specified database starting with specified username/password (if present), try to return a successful login within 3 attempts """ login_user = None # this w...
authenticate to the specified database starting with specified username/password (if present), try to return a successful login within 3 attempts
def reboot_autopilot(self, hold_in_bootloader=False): '''reboot the autopilot''' if self.mavlink10(): if hold_in_bootloader: param1 = 3 else: param1 = 1 self.mav.command_long_send(self.target_system, self.target_component, ...
reboot the autopilot
def create_session(docker_image=None, docker_rm=None, echo=False, loglevel='WARNING', nocolor=False, session_type='bash', vagrant_session_name=None, vagrant_image='ubuntu/xenial64', ...
Creates a distinct ShutIt session. Sessions can be of type: bash - a bash shell is spawned and vagrant - a Vagrantfile is created and 'vagrant up'ped
def _ip_int_from_string(self, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: A long, the IPv6 ip_str. Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ parts = i...
Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: A long, the IPv6 ip_str. Raises: AddressValueError: if ip_str isn't a valid IPv6 Address.
def write_graph(self, filename): """ Write raw graph data which can be post-processed using graphviz. """ f = open(filename, 'w') f.write(self._get_graphviz_data()) f.close()
Write raw graph data which can be post-processed using graphviz.
def to_timedelta(value, strict=True): """ converts duration string to timedelta strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration string exceed allowed values """ if isinstance(value, int): return timedelta(seconds=value) # assuming it's se...
converts duration string to timedelta strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration string exceed allowed values
def acceptNavigationRequest(self, url, navigation_type, isMainFrame): """ Overloaded method to handle links ourselves """ if navigation_type == QWebEnginePage.NavigationTypeLinkClicked: self.linkClicked.emit(url) return False return True
Overloaded method to handle links ourselves
def serialize(self, o): ''' Returns a safe serializable object that can be serialized into JSON. @param o Python object to serialize ''' if isinstance(o, (list, tuple)): return [self.serialize(i) for i in o] if isinstance(o, dict): return {k: self...
Returns a safe serializable object that can be serialized into JSON. @param o Python object to serialize
def timeout(timeout_time, default): ''' Decorate a method so it is required to execute in a given time period, or return a default value. ''' def timeout_function(f): def f2(*args): def timeout_handler(signum, frame): raise MethodTi...
Decorate a method so it is required to execute in a given time period, or return a default value.
def load_secret(self, secret): """ Ask YubiHSM to load a pre-existing YubiKey secret. The data is stored internally in the YubiHSM in temporary memory - this operation would typically be followed by one or more L{generate_aead} commands to actually retreive the generated secret ...
Ask YubiHSM to load a pre-existing YubiKey secret. The data is stored internally in the YubiHSM in temporary memory - this operation would typically be followed by one or more L{generate_aead} commands to actually retreive the generated secret (in encrypted form). @param secret: YubiKe...
def output_file_job(job, filename, file_id, output_dir, s3_key_path=None): """ Uploads a file from the FileStore to an output directory on the local filesystem or S3. :param JobFunctionWrappingJob job: passed automatically by Toil :param str filename: basename for file :param str file_id: FileStore...
Uploads a file from the FileStore to an output directory on the local filesystem or S3. :param JobFunctionWrappingJob job: passed automatically by Toil :param str filename: basename for file :param str file_id: FileStoreID :param str output_dir: Amazon S3 URL or local path :param str s3_key_path: (...
def get_fit_failed_candidate_model(model_type, formula): """ Return a Candidate model that indicates the fitting routine failed. Parameters ---------- model_type : :any:`str` Model type (e.g., ``'cdd_hdd'``). formula : :any:`float` The candidate model formula. Returns -----...
Return a Candidate model that indicates the fitting routine failed. Parameters ---------- model_type : :any:`str` Model type (e.g., ``'cdd_hdd'``). formula : :any:`float` The candidate model formula. Returns ------- candidate_model : :any:`eemeter.CalTRACKUsagePerDayCandida...
def fetch_all_records(self): r""" Returns a generator that yields all of the DNS records for the domain :rtype: generator of `DomainRecord`\ s :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager return map(self._record, api....
r""" Returns a generator that yields all of the DNS records for the domain :rtype: generator of `DomainRecord`\ s :raises DOAPIError: if the API endpoint replies with an error
def _initialize(self, funs_to_tally, length): """Create a group named ``chain#`` to store all data for this chain.""" chain = self.nchains self._chains[chain] = self._h5file.create_group( '/', 'chain%d' % chain, 'chain #%d' % chain) for name, fun in six.iteritems(funs_to_ta...
Create a group named ``chain#`` to store all data for this chain.
def set_type(self, value): """Setter for type attribute""" if value not in self.types_available: log = "Sources field 'type' should be in one of %s" % ( self.types_available ) raise MalFormattedSource(log) self._type = value
Setter for type attribute
def isdir(self, path): """ Return `True` if directory at `path` exist, False otherwise. """ try: self.remote_context.check_output(["test", "-d", path]) except subprocess.CalledProcessError as e: if e.returncode == 1: return False ...
Return `True` if directory at `path` exist, False otherwise.
def get_best_local_timezone(): """ Compares local timezone offset to pytz's timezone db, to determine a matching timezone name to use when TIME_ZONE is not set. """ zone_name = tzlocal.get_localzone().zone if zone_name in pytz.all_timezones: return zone_name if time.daylight: ...
Compares local timezone offset to pytz's timezone db, to determine a matching timezone name to use when TIME_ZONE is not set.
def data_objet_class(data_mode='value', time_mode='framewise'): """ Factory function for Analyzer result """ classes_table = {('value', 'global'): GlobalValueObject, ('value', 'event'): EventValueObject, ('value', 'segment'): SegmentValueObject, ...
Factory function for Analyzer result
def unitary(self, obj, qubits, label=None): """Apply u2 to q.""" if isinstance(qubits, QuantumRegister): qubits = qubits[:] return self.append(UnitaryGate(obj, label=label), qubits, [])
Apply u2 to q.
def _handle_dbproc_call(self, parts, parameters_metadata): """Handle reply messages from STORED PROCEDURE statements""" for part in parts: if part.kind == part_kinds.ROWSAFFECTED: self.rowcount = part.values[0] elif part.kind == part_kinds.TRANSACTIONFLAGS: ...
Handle reply messages from STORED PROCEDURE statements
def get_scales(self, aesthetic): """ Return the scale for the aesthetic or None if there isn't one. These are the scales specified by the user e.g `ggplot() + scale_x_continuous()` or those added by default during the plot building process """ ...
Return the scale for the aesthetic or None if there isn't one. These are the scales specified by the user e.g `ggplot() + scale_x_continuous()` or those added by default during the plot building process
def javadoc_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """ Role for linking to external Javadoc """ has_explicit_title, title, target = split_explicit_title(text) title = utils.unescape(title) target = utils.unescape(target) if not has_explicit_title: target = targ...
Role for linking to external Javadoc
def loadRule(rule_json_object): """ Method to load the rules - when adding a new rule it must be added to the if statement within this method. """ name = rule_json_object['name'] rule_type = rule_json_object['rule_type'] validation_regex = None required = False removehtml = False include_end...
Method to load the rules - when adding a new rule it must be added to the if statement within this method.
def best_model(seq2hmm): """ determine the best model: archaea, bacteria, eukarya (best score) """ for seq in seq2hmm: best = [] for model in seq2hmm[seq]: best.append([model, sorted([i[-1] for i in seq2hmm[seq][model]], reverse = True)[0]]) best_model = sorted(best, ...
determine the best model: archaea, bacteria, eukarya (best score)
def get_used_entities(self,use_specs): """ Returns the entities which are imported by a use statement. These are contained in dicts. """ if len(use_specs.strip()) == 0: return (self.pub_procs, self.pub_absints, self.pub_types, self.pub_vars) only = bool(self.O...
Returns the entities which are imported by a use statement. These are contained in dicts.
def reset_object(self, driver_wrapper=None): """Reset each page element object :param driver_wrapper: driver wrapper instance """ from toolium.pageelements.page_elements import PageElements if driver_wrapper: self.driver_wrapper = driver_wrapper self._web_ele...
Reset each page element object :param driver_wrapper: driver wrapper instance
def plot_h(data, cols, wspace=.1, plot_kw=None, **kwargs): """ Plot horizontally Args: data: DataFrame of data cols: columns to be plotted wspace: spacing between plots plot_kw: kwargs for each plot **kwargs: kwargs for the whole plot Returns: axes for p...
Plot horizontally Args: data: DataFrame of data cols: columns to be plotted wspace: spacing between plots plot_kw: kwargs for each plot **kwargs: kwargs for the whole plot Returns: axes for plots Examples: >>> import pandas as pd >>> import ...
def _compute_nfp_uniform(l, u, cum_counts, sizes): """Computes the expected number of false positives caused by using u to approximate set sizes in the interval [l, u], assuming uniform distribution of set sizes within the interval. Args: l: the lower bound on set sizes. u: the upper bo...
Computes the expected number of false positives caused by using u to approximate set sizes in the interval [l, u], assuming uniform distribution of set sizes within the interval. Args: l: the lower bound on set sizes. u: the upper bound on set sizes. cum_counts: the complete cummula...
def disallow(nodes): """Decorator to disallow certain nodes from parsing. Raises a NotImplementedError instead. Returns ------- disallowed : callable """ def disallowed(cls): cls.unsupported_nodes = () for node in nodes: new_method = _node_not_implemented(node, c...
Decorator to disallow certain nodes from parsing. Raises a NotImplementedError instead. Returns ------- disallowed : callable
def is_email_simple(value): """Return True if value looks like an email address.""" # An @ must be in the middle of the value. if '@' not in value or value.startswith('@') or value.endswith('@'): return False try: p1, p2 = value.split('@') except ValueErro...
Return True if value looks like an email address.
def right_join_where(self, table, one, operator, two): """ Add a "right join where" clause to the query :param table: The table to join with, can also be a JoinClause instance :type table: str or JoinClause :param one: The first column of the join condition :type one: s...
Add a "right join where" clause to the query :param table: The table to join with, can also be a JoinClause instance :type table: str or JoinClause :param one: The first column of the join condition :type one: str :param operator: The operator of the join condition :ty...
def get_rt_data(self, code): """ 获取指定股票的分时数据 :param code: 股票代码,例如,HK.00700,US.APPL :return: (ret, data) ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下 ret != RET_OK 返回错误字符串 ===================== =========== ===============...
获取指定股票的分时数据 :param code: 股票代码,例如,HK.00700,US.APPL :return: (ret, data) ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下 ret != RET_OK 返回错误字符串 ===================== =========== ================================================================...
def scale_cb(self, setting, value): """Handle callback related to image scaling.""" zoomlevel = self.zoom.calc_level(value) self.t_.set(zoomlevel=zoomlevel) self.redraw(whence=0)
Handle callback related to image scaling.
def lnprior(x): """Return the log prior given parameter vector `x`.""" per, t0, b = x if b < -1 or b > 1: return -np.inf elif per < 7 or per > 10: return -np.inf elif t0 < 1978 or t0 > 1979: return -np.inf else: return 0.
Return the log prior given parameter vector `x`.
def getNodeRefs(self): ''' Return a list of (prop, (form, valu)) refs out for the node. ''' retn = [] for name, valu in self.props.items(): pobj = self.form.props.get(name) if isinstance(pobj.type, s_types.Ndef): retn.append((name, valu)...
Return a list of (prop, (form, valu)) refs out for the node.
def addSubsumableToGroups(self, proteinIds, groupIds): """Add one or multiple subsumable proteins to one or multiple protein groups. :param proteinIds: a proteinId or a list of proteinIds, a proteinId must be a string. :param groupIds: a groupId or a list of groupIds, a grou...
Add one or multiple subsumable proteins to one or multiple protein groups. :param proteinIds: a proteinId or a list of proteinIds, a proteinId must be a string. :param groupIds: a groupId or a list of groupIds, a groupId must be a string.
def _pop_api_call(self, method, _url, kwargs): """ This will initialize an api_call or pop one that has already been initialized with the endpoint parameters :param method: str of the html method ['GET','POST','PUT','DELETE'] :param _url: str of the sub url of the api call (e...
This will initialize an api_call or pop one that has already been initialized with the endpoint parameters :param method: str of the html method ['GET','POST','PUT','DELETE'] :param _url: str of the sub url of the api call (ex. g/device/list) :param kwargs: dict of additional argume...
def parent_ids(self): """ Returns an array of parent Biosample IDs. If the current Biosample has a part_of relationship, the Biosampled referenced there will be returned. Otherwise, if the current Biosample was generated from a pool of Biosamples (pooled_from_biosample_ids), then those w...
Returns an array of parent Biosample IDs. If the current Biosample has a part_of relationship, the Biosampled referenced there will be returned. Otherwise, if the current Biosample was generated from a pool of Biosamples (pooled_from_biosample_ids), then those will be returned. Otherwise, the re...
def to_bytes(s, encoding="utf-8"): """ Converts the string to a bytes type, if not already. :s: the string to convert to bytes :returns: `str` on Python2 and `bytes` on Python3. """ if isinstance(s, six.binary_type): return s else: return six.text_type(s).encode(encoding)
Converts the string to a bytes type, if not already. :s: the string to convert to bytes :returns: `str` on Python2 and `bytes` on Python3.
def make_stats(data, perfile, fsamplehits, fbarhits, fmisses, fdbars): """ Write stats and stores to Assembly object. """ ## out file outhandle = os.path.join(data.dirs.fastqs, 's1_demultiplex_stats.txt') outfile = open(outhandle, 'w') ## write the header for file stats -------------------...
Write stats and stores to Assembly object.
def delay(self, dl=0): """Delay for ``dl`` seconds. """ if dl is None: time.sleep(self.dl) elif dl < 0: sys.stderr.write( "delay cannot less than zero, this takes no effects.\n") else: time.sleep(dl)
Delay for ``dl`` seconds.
def set(self, *components): """ Set the possible components of the block :param components: components to append Optionables or Composables """ self.reset() if len(components) == 1: self.append(components[0]) else: for comp in components: ...
Set the possible components of the block :param components: components to append Optionables or Composables
def _read_metrics(repo, metrics, branch): """Read the content of each metric file and format it. Args: metrics (list): List of metric touples branch (str): Branch to look up for metrics. Returns: A dict mapping keys with metrics path name and content. For example: ...
Read the content of each metric file and format it. Args: metrics (list): List of metric touples branch (str): Branch to look up for metrics. Returns: A dict mapping keys with metrics path name and content. For example: {'metric.csv': ("value_mse deviation_mse data_...
def tags_getrelated(tag): """Gets the related tags for given tag.""" method = 'flickr.tags.getRelated' data = _doget(method, auth=False, tag=tag) if isinstance(data.rsp.tags.tag, list): return [tag.text for tag in data.rsp.tags.tag] else: return [data.rsp.tags.tag.text]
Gets the related tags for given tag.
def AddArguments(cls, argument_group): """Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser...
Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group.
def transform(self, X, y=None, **params): """ Transforms *X* from phase-space to Fourier-space, returning the design matrix produced by :func:`Fourier.design_matrix` for input to a regressor. **Parameters** X : array-like, shape = [n_samples, 1] Column vecto...
Transforms *X* from phase-space to Fourier-space, returning the design matrix produced by :func:`Fourier.design_matrix` for input to a regressor. **Parameters** X : array-like, shape = [n_samples, 1] Column vector of phases. y : None, optional Unused arg...
def precision_score(df, col_true=None, col_pred='precision_result', pos_label=1, average=None): r""" Compute precision of a predicted DataFrame. Precision is defined as :math:`\frac{TP}{TP + TN}` :Parameters: - **df** - predicted data frame - **col_true** - column name of true label ...
r""" Compute precision of a predicted DataFrame. Precision is defined as :math:`\frac{TP}{TP + TN}` :Parameters: - **df** - predicted data frame - **col_true** - column name of true label - **col_pred** - column name of predicted label, 'prediction_result' by default. - **pos_la...
async def trigger(self, event, kwargs): """ Enqueue an event for processing """ await self._queue.put((event, kwargs)) self._resume_processing.set()
Enqueue an event for processing
def active_joined_organisations(doc): """View for getting organisations associated with a user""" if doc.get('type') == 'user' and doc.get('state') != 'deactivated': for org_id, state in doc.get('organisations', {}).items(): if state['state'] == 'deactivated': continue ...
View for getting organisations associated with a user
def get_proteome_counts_impute_missing(prots_filtered_feathers, outpath, length_filter_pid=None, copynum_scale=False, copynum_df=None, force_rerun=False): """Get counts, uses the mean feature vector to fill in missing proteins for a strai...
Get counts, uses the mean feature vector to fill in missing proteins for a strain
def get_time_remaining_estimate(self): """ Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() if POWER_TYPE_MAP[powe...
Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime
def _init_glyph(self, plot, mapping, properties): """ Returns a Bokeh glyph object. """ box = Span(level=properties.get('level', 'glyph'), **mapping) plot.renderers.append(box) return None, box
Returns a Bokeh glyph object.
def convert(self, *args, **kwargs): """ Yes it is, thanks captain. """ self.strings() self.metadata() # save file self.result.save(self.output())
Yes it is, thanks captain.
def _prepare_value(val, maxlen=50, notype=False): """ Stringify value `val`, ensuring that it is not too long. """ if val is None or val is True or val is False: return str(val) sval = repr(val) sval = sval.replace("\n", " ").replace("\t", " ").replace("`", "'") if len(sval) > maxlen...
Stringify value `val`, ensuring that it is not too long.
def _create_group_assignment(self, mesh_axes): """Create group assignment for XLA cross replica ops (physical pnums).""" partitioning = {} for logical_pnum in xrange(self.size): group = mtf.pnum_to_group(self.shape, mesh_axes, logical_pnum) if group not in partitioning: partitioning[gro...
Create group assignment for XLA cross replica ops (physical pnums).
def show(self, baseAppInstance): """Allows to show the widget as root window""" self.from_dict_to_fields(self.configDict) super(ProjectConfigurationDialog, self).show(baseAppInstance)
Allows to show the widget as root window
def share_column_widths(self, tables, shared_limit=None): """ To have this table use sync with the columns in tables Note, this will need to be called on the other tables to be fully synced. :param tables: list of SeabornTables to share column widths :param sh...
To have this table use sync with the columns in tables Note, this will need to be called on the other tables to be fully synced. :param tables: list of SeabornTables to share column widths :param shared_limit: int if diff is greater than this than ignore it. :return: None
def get_location_observation(lat, lng, token): """Lookup observations by geo coordinates.""" req = requests.get( API_ENDPOINT_GEO % (lat, lng), params={ 'token': token }) if req.status_code == 200 and req.json()["status"] == "ok": return parse_observation_respons...
Lookup observations by geo coordinates.
def get_absolute_url_with_date(self): """URL based on the entry's date & slug.""" pub_date = self.published_on if pub_date and settings.USE_TZ: # If TZ is enabled, convert all of these dates from UTC to whatever # the project's timezone is set as. Ideally, we'd pull this...
URL based on the entry's date & slug.
def queryResponse(self, queryEngine, query=None, vendorSpecific=None, **kwargs): """CNRead.query(session, queryEngine, query) → OctetStream https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNRead.query. Args: queryEngine: query: ...
CNRead.query(session, queryEngine, query) → OctetStream https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNRead.query. Args: queryEngine: query: vendorSpecific: **kwargs: Returns:
def draw_cloud_tree(self, axes=None, html=False, fixed_order=True, **kwargs): """ Draw a series of trees overlapping each other in coordinate space. The order of tip_labels is fixed in cloud trees so that trees with discordant relationships can be seen ...
Draw a series of trees overlapping each other in coordinate space. The order of tip_labels is fixed in cloud trees so that trees with discordant relationships can be seen in conflict. To change the tip order use the 'fixed_order' argument in toytree.mtree() when creating the MultiTree o...
def warn_startup_with_shell_off(platform, gdb_args): """return True if user may need to turn shell off if mac OS version is 16 (sierra) or higher, may need to set shell off due to os's security requirements http://stackoverflow.com/questions/39702871/gdb-kind-of-doesnt-work-on-macos-sierra """ d...
return True if user may need to turn shell off if mac OS version is 16 (sierra) or higher, may need to set shell off due to os's security requirements http://stackoverflow.com/questions/39702871/gdb-kind-of-doesnt-work-on-macos-sierra
def lines_table(html_doc, tofloat=True): """return a list of [(lines, table), .....] lines = all the significant lines before the table. These are lines between this table and the previous table or 'hr' tag table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..] The lines act as a...
return a list of [(lines, table), .....] lines = all the significant lines before the table. These are lines between this table and the previous table or 'hr' tag table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..] The lines act as a description for what is in the table
def getInstance(self, aLocation, axisOnly=False, getFactors=False): """ Calculate the delta at aLocation. * aLocation: a Location object, expected to be in bent space * axisOnly: * True: calculate an instance only with the on-axis masters. * Fals...
Calculate the delta at aLocation. * aLocation: a Location object, expected to be in bent space * axisOnly: * True: calculate an instance only with the on-axis masters. * False: calculate an instance with on-axis and off-axis masters. * getFa...
def stop_threadsafe(self): """Stop this task from another thread and wait for it to finish. This method must not be called from within the BackgroundEventLoop but will inject self.stop() into the event loop and block until it returns. Raises: TimeoutExpiredError: If...
Stop this task from another thread and wait for it to finish. This method must not be called from within the BackgroundEventLoop but will inject self.stop() into the event loop and block until it returns. Raises: TimeoutExpiredError: If the task does not stop in the given ...
def render_customizations(self): """ Customize template for site user specified customizations """ disable_plugins = self.pt.customize_conf.get('disable_plugins', []) if not disable_plugins: logger.debug('No site-user specified plugins to disable') else: ...
Customize template for site user specified customizations
def skewvT(self,R,romberg=False,nsigma=None,phi=0.): """ NAME: skewvT PURPOSE: calculate skew in vT at R by marginalizing over velocity INPUT: R - radius at which to calculate <vR> (can be Quantity) OPTIONAL INPUT: nsigma - numbe...
NAME: skewvT PURPOSE: calculate skew in vT at R by marginalizing over velocity INPUT: R - radius at which to calculate <vR> (can be Quantity) OPTIONAL INPUT: nsigma - number of sigma to integrate the velocities over KEYWORDS: ...
def format_list(self, at_char, user, list_name): '''Return formatted HTML for a list.''' return '<a href="https://twitter.com/%s/lists/%s">%s%s/%s</a>' \ % (user, list_name, at_char, user, list_name)
Return formatted HTML for a list.
def add_logging(parser, log_format=LOG_FORMAT, log_level=LOG_LEVEL, color=True): """Configures the `argparse.ArgumentParser` with arguments to configure logging. This adds arguments: * ``-v`` to increase the log level * ``-q`` to decrease the log level * ``--color`` to enable color logging whe...
Configures the `argparse.ArgumentParser` with arguments to configure logging. This adds arguments: * ``-v`` to increase the log level * ``-q`` to decrease the log level * ``--color`` to enable color logging when available * ``--no-color`` to disable color logging The root logger is config...
def validate_dict(in_dict, **kwargs): """ Returns Boolean of whether given dict conforms to type specifications given in kwargs. """ if not isinstance(in_dict, dict): raise ValueError('requires a dictionary') for key, value in kwargs.iteritems(): if key == 'required': for ...
Returns Boolean of whether given dict conforms to type specifications given in kwargs.
def grid_at_redshift_from_image_plane_grid_and_redshift(self, image_plane_grid, redshift): """For an input grid of (y,x) arc-second image-plane coordinates, ray-trace the coordinates to any redshift in \ the strong lens configuration. This is performed using multi-plane ray-tracing and the exis...
For an input grid of (y,x) arc-second image-plane coordinates, ray-trace the coordinates to any redshift in \ the strong lens configuration. This is performed using multi-plane ray-tracing and the existing redshifts and planes of the tracer. However, \ any redshift can be input even if a plane ...
def get_group(self, group_id): """Get a single group. :param str group_id: group ID :returns: group :rtype: :class:`marathon.models.group.MarathonGroup` """ response = self._do_request( 'GET', '/v2/groups/{group_id}'.format(group_id=group_id)) return...
Get a single group. :param str group_id: group ID :returns: group :rtype: :class:`marathon.models.group.MarathonGroup`
def _execute_command(self, command, sql): """ :raise InterfaceError: If the connection is closed. :raise ValueError: If no username was specified. """ if not self._sock: raise err.InterfaceError("(0, '')") # If the last query was unbuffered, make sure it fini...
:raise InterfaceError: If the connection is closed. :raise ValueError: If no username was specified.
def operator(self): """Supported Filter Operators + EQ - Equal To + NE - Not Equal To + GT - Greater Than + GE - Greater Than or Equal To + LT - Less Than + LE - Less Than or Equal To + SW - Starts With + IN - In String or Array + NI - Not...
Supported Filter Operators + EQ - Equal To + NE - Not Equal To + GT - Greater Than + GE - Greater Than or Equal To + LT - Less Than + LE - Less Than or Equal To + SW - Starts With + IN - In String or Array + NI - Not in String or Array
def median_slitlets_rectified( input_image, mode=0, minimum_slitlet_width_mm=EMIR_MINIMUM_SLITLET_WIDTH_MM, maximum_slitlet_width_mm=EMIR_MAXIMUM_SLITLET_WIDTH_MM, debugplot=0 ): """Compute median spectrum for each slitlet. Parameters ---------- input_image :...
Compute median spectrum for each slitlet. Parameters ---------- input_image : HDUList object Input 2D image. mode : int Indicate desired result: 0 : image with the same size as the input image, with the median spectrum of each slitlet spanning all the spectra ...