text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def insert_with_id(obj):
"""
Generates a unique ID for the supplied legislator/committee/bill
and inserts it into the appropriate collection.
"""
if '_id' in obj:
raise ValueError("object already has '_id' field")
# add created_at/updated_at on insert
obj['created_at'] = datetime.da... | 0.000632 |
def do_switch(self, subcmd, opts, *args):
"""Update the working copy to a different URL.
usage:
1. switch URL [PATH]
2. switch --relocate FROM TO [PATH...]
1. Update the working copy to mirror a new URL within the repository.
This behaviour is similar... | 0.00576 |
def _rainbow_rgb_chars(self, s, freq=0.1, spread=3.0, offset=0):
""" Iterate over characters in a string to build data needed for a
rainbow effect.
Yields tuples of (char, (r, g, b)).
Arguments:
s : String to colorize.
freq : Frequency/"... | 0.002584 |
def detect(self, filename, offset, standalone=False):
"""Verifies NTFS filesystem signature.
Returns:
bool: True if filesystem signature at offset 0x03 \
matches 'NTFS ', False otherwise.
"""
r = RawStruct(
filename=filename,
offset=off... | 0.004237 |
def read_config_files(files):
"""Read and merge a list of config files."""
config = ConfigObj()
for _file in files:
_config = read_config_file(_file)
if bool(_config) is True:
config.merge(_config)
config.filename = _config.filename
return config | 0.003279 |
def aggregate(self, zeroValue, seqOp, combOp):
"""
Aggregate the elements of each partition, and then the results for all
the partitions, using a given combine functions and a neutral "zero
value."
The functions C{op(t1, t2)} is allowed to modify C{t1} and return it
as i... | 0.001384 |
def t_TEXT(self, token):
ur'(?P<text>[^<#\n ].+?[^ ])(?=\n)'
text = token.lexer.lexmatch.group("text").decode("utf8")
token.value = text
return token | 0.01105 |
def calling(data):
"""Main function to parallelize peak calling."""
chip_bam = data.get("work_bam")
input_bam = data.get("work_bam_input", None)
caller_fn = get_callers()[data["peak_fn"]]
name = dd.get_sample_name(data)
out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), data["peak_... | 0.004286 |
def fix_variables(bqm, sampling_mode=True):
"""Determine assignments for some variables of a binary quadratic model.
Roof duality finds a lower bound for the minimum of a quadratic polynomial. It
can also find minimizing assignments for some of the polynomial's variables;
these fixed variables take the... | 0.004677 |
def elapsed_time(self):
"""To know the duration of the function.
This property might return None if the function is still running.
"""
if self._end_time:
elapsed_time = round(self._end_time - self._start_time, 3)
return elapsed_time
else:
retu... | 0.006116 |
def getExtraIncludes(self):
''' Some components must export whole directories full of headers into
the search path. This is really really bad, and they shouldn't do
it, but support is provided as a concession to compatibility.
'''
if 'extraIncludes' in self.description:
... | 0.006849 |
def convert(ids, from_type):
'''Uses the NCBI IP Converter API to converts a list of publication IDs in the same format e.g. DOI identifiers to
another format e.g. PubMed identifiers.
ids is a list of IDs of the type from_type e.g. a from_type of 'doi' specifies DOI identifiers.
The function ret... | 0.004055 |
def rshift_logical(self, shift_amount):
"""
Logical shift right.
:param StridedInterval shift_amount: The amount of shifting
:return: The shifted StridedInterval
:rtype: StridedInterval
"""
lower, upper = self._pre_shift(shift_amount)
# Shift the lower_... | 0.004532 |
def conv_layer(x,
hidden_size,
kernel_size,
stride,
pooling_window,
dropout_rate,
dilation_rate,
name="conv"):
"""Single conv layer with relu, optional pooling, and dropout."""
with tf.variable_scope(name):
... | 0.005587 |
def _set_secondary_path(self, v, load=False):
"""
Setter method for secondary_path, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_secondary_path is considered as a private
... | 0.003766 |
def _splitGenoGeneWindow(self,annotation_file=None,cis=1e4,funct='protein_coding',minSnps=1.,maxSnps=SP.inf):
"""
split into windows based on genes
"""
#1. load annotation
assert annotation_file is not None, 'Splitter:: specify annotation file'
try:
f = h5py.... | 0.017516 |
def _model(self, data, beta):
""" Creates the structure of the model
Parameters
----------
data : np.array
Contains the time series
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
a,... | 0.018553 |
def _do_functions(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr, code, name):
"""
Implements @mixin and @function
"""
if name:
funct, params, _ = name.partition('(')
funct = funct.strip()
params = split_p... | 0.001934 |
def curtailment(network, carrier='solar', filename=None):
"""
Plot curtailment of selected carrier
Parameters
----------
network : PyPSA network container
Holds topology of grid including results from powerflow analysis
carrier: str
Plot curtailemt of this carrier
filename:... | 0.001678 |
def euclidean_distances(a, b, squared=False, to_numpy=True):
"""
Compute the pairwise euclidean distance between matrices a and b.
If the input matrix are in numpy format, they will be uploaded to the
GPU first which can incur significant time overhead.
Parameters
----------
a : np.ndarray... | 0.000978 |
def editContactItem(self, contactType, contactItem, contactInfo):
"""
Edit the given contact item with the given contact type. Broadcast
the edit to all L{IOrganizerPlugin} powerups.
@type contactType: L{IContactType}
@param contactType: The contact type which will be used to e... | 0.002692 |
def find_components_without_annotation(model, components):
"""
Find model components with empty annotation attributes.
Parameters
----------
model : cobra.Model
A cobrapy metabolic model.
components : {"metabolites", "reactions", "genes"}
A string denoting `cobra.Model` componen... | 0.001859 |
def save_gradebook(self, gradebook_form, *args, **kwargs):
"""Pass through to provider GradebookAdminSession.update_gradebook"""
# Implemented from kitosid template for -
# osid.resource.BinAdminSession.update_bin
if gradebook_form.is_for_update():
return self.update_gradeboo... | 0.004525 |
def as_graph(self, depth=0):
"""
Create a graph with self as node, cache it, return it.
Args:
depth (int): depth of the graph.
Returns:
Graph: an instance of Graph.
"""
if depth in self._graph_cache:
return self._graph_cache[depth]
... | 0.004926 |
def connect_combo_text(instance, prop, widget):
"""
Connect a callback property with a QComboBox widget based on the text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget... | 0.001887 |
def iteritems_sorted(dict_):
""" change to iteritems ordered """
if isinstance(dict_, OrderedDict):
return six.iteritems(dict_)
else:
return iter(sorted(six.iteritems(dict_))) | 0.004926 |
def _get_remote_node_url(self, remote_node):
"""Get grid-extras url of a node
:param remote_node: remote node name
:returns: grid-extras url
"""
logging.getLogger("requests").setLevel(logging.WARNING)
gridextras_port = 3000
return 'http://{}:{}'.format(remote_nod... | 0.0059 |
def main(feature_folder, create_learning_curve=False):
"""main function of create_ffiles.py"""
# Read the feature description file
with open(os.path.join(feature_folder, "info.yml"), 'r') as ymlfile:
feature_description = yaml.load(ymlfile)
# Get preprocessed .pickle file from model descriptio... | 0.000303 |
def get_newcommand_macros(tex_source):
r"""Get all ``\newcommand`` macro definition from TeX source.
Parameters
----------
tex_source : `str`
TeX source content.
Returns
-------
macros : `dict`
Keys are macro names (including leading ``\``) and values are the
conten... | 0.001353 |
def getYamlDocument(filePath):
"""
Return a yaml file's contents as a dictionary
"""
with open(filePath) as stream:
doc = yaml.load(stream)
return doc | 0.005495 |
def update_dcnm_partition_static_route(self, tenant_id, arg_dict):
"""Add static route in DCNM's partition.
This gets pushed to the relevant leaf switches.
"""
ip_list = self.os_helper.get_subnet_nwk_excl(tenant_id,
arg_dict.get('excl... | 0.002055 |
async def message_handler(self, event):
"""Callback method for received events.NewMessage"""
# Note that message_handler is called when a Telegram update occurs
# and an event is created. Telegram may not always send information
# about the ``.sender`` or the ``.chat``, so if you *reall... | 0.001561 |
def open_shapefile(shapefile_path, file_geodatabase=None):
"""Opens a shapefile using either a shapefile path
or a file geodatabase
"""
if file_geodatabase:
gdb_driver = ogr.GetDriverByName("OpenFileGDB")
ogr_shapefile = gdb_driver.Open(file_geodatabase)
ogr_shapefile_lyr = o... | 0.001949 |
def set_cache_implementation(self, cache_name, impl_name, maxsize, **kwargs):
"""
Changes the cache implementation for the named cache
"""
self._get_cache(cache_name).set_cache_impl(impl_name, maxsize, **kwargs) | 0.012346 |
def request(self, method, path, query=None, data=None, redirects=True):
"""
Sends HTTP request to LendingClub.
Parameters
----------
method : {GET, POST, HEAD, DELETE}
The HTTP method to use: GET, POST, HEAD or DELETE
path : string
The path that w... | 0.005482 |
def match_filtered_identities(self, fa, fb):
"""Determine if two filtered identities are the same.
This method compares the username and the source of each
identity to check if the given unique identities are the
same. Identities sources have to start with 'github' keyword
(uppe... | 0.002719 |
def expand_to_chunk_size(self, chunk_size, offset=Vec(0,0,0, dtype=int)):
"""
Align a potentially non-axis aligned bbox to the grid by growing it
to the nearest grid lines.
Required:
chunk_size: arraylike (x,y,z), the size of chunks in the
dataset e.g. (64,64,64)
Optional... | 0.007184 |
def add_comment_to_issue(self, issue, comment, visibility=None):
"""
Adds a comment to a specified issue from the current user.
Arguments:
| issue (string) | A JIRA Issue that a watcher needs added to, can be an issue ID or Key |
| comment (string)... | 0.007839 |
def post(self, endpoint, params=None, version='1.1', json_encoded=False):
"""Shortcut for POST requests via :class:`request`"""
return self.request(endpoint, 'POST', params=params, version=version, json_encoded=json_encoded) | 0.0125 |
def wrap_json(cls, json, viewers=None, channels=None):
"""Create a Game instance for the given json
:param json: the dict with the information of the game
:type json: :class:`dict`
:param viewers: The viewer count
:type viewers: :class:`int`
:param channels: The viewer c... | 0.002805 |
def copy_file(file_name):
"""
Copy a given file from the cache storage
"""
remote_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)
current_path = join(getcwd(), file_name)
try:
copyfile(remote_file_path, current_path)
except Exception, e:
raise e | 0.035587 |
def _Liquid(T, P=0.1):
"""Supplementary release on properties of liquid water at 0.1 MPa
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
Although this relation is for P=0.1MPa, can be extrapoled at pressure
0.3 MPa
Returns
-------
... | 0.000163 |
def checklink (form=None, env=os.environ):
"""Validates the CGI form and checks the given links."""
if form is None:
form = {}
try:
checkform(form, env)
except LCFormError as errmsg:
log(env, errmsg)
yield encode(format_error(errmsg))
return
out = ThreadsafeIO... | 0.002999 |
def init(self):
"""init `todo` file
if file exists, then initialization self.todos
and record current max index of todos
: when add a new todo, the `idx` via only `self.current_max_idx + 1`
"""
if os.path.isdir(self.path):
raise InvalidTodoFile
if os.p... | 0.00355 |
def setLevel(self, lvl):
"""
Trim or extend scope
lvl = 1 -> only one scope (global)
"""
while len(self) != lvl:
if len(self) > lvl:
self.pop()
else:
self.append(NameScopeItem(len(self))) | 0.007067 |
def W_min_HS_ratio(self):
"""Calculate the minimum flocculator channel width, given the minimum
ratio between expansion height (H) and baffle spacing (S).
:returns: Minimum channel width given H_e/S
:rtype: float * centimeter
"""
return ((self.HS_RATIO_MIN * self.Q / self... | 0.009901 |
def _interleaved_dtype(
blocks: List[Block]
) -> Optional[Union[np.dtype, ExtensionDtype]]:
"""Find the common dtype for `blocks`.
Parameters
----------
blocks : List[Block]
Returns
-------
dtype : Optional[Union[np.dtype, ExtensionDtype]]
None is returned when `blocks` is ... | 0.002304 |
def RegisterArtifact(self,
artifact_rdfvalue,
source="datastore",
overwrite_if_exists=False,
overwrite_system_artifacts=False):
"""Registers a new artifact."""
artifact_name = artifact_rdfvalue.name
if artifact_name ... | 0.009213 |
def create_widget(self, dim, holomap=None, editable=False):
""""
Given a Dimension creates bokeh widgets to select along that
dimension. For numeric data a slider widget is created which
may be either discrete, if a holomap is supplied or the
Dimension.values are set, or a contin... | 0.003404 |
def unregister(self, namespace, command=None):
"""
Unregisters the given command. If command is None, the whole name space
is unregistered.
:param namespace: The command name space.
:param command: The shell name of the command, or None
:return: True if the command was k... | 0.001621 |
def _document_structure(self):
"""Document the structure of the dataset."""
logger.debug("Documenting dataset structure")
key = self.get_structure_key()
text = json.dumps(self._structure_parameters, indent=2, sort_keys=True)
self.put_text(key, text)
key = self.get_dtool_... | 0.005222 |
def load_tpf(self):
'''
Loads the target pixel file.
'''
if not self.loaded:
if self._data is not None:
data = self._data
else:
data = self._mission.GetData(
self.ID, season=self.season,
... | 0.000953 |
def instruction_list_to_easm(instruction_list: list) -> str:
"""Convert a list of instructions into an easm op code string.
:param instruction_list:
:return:
"""
result = ""
for instruction in instruction_list:
result += "{} {}".format(instruction["address"], instruction["opcode"])
... | 0.002232 |
def map(cls, latitudes, longitudes, labels=None, colors=None, areas=None, **kwargs):
"""Return markers from columns of coordinates, labels, & colors.
The areas column is not applicable to markers, but sets circle areas.
"""
assert len(latitudes) == len(longitudes)
assert areas i... | 0.004202 |
def AddEventSource(self, event_source):
"""Adds an event source.
Args:
event_source (EventSource): an event source.
Raises:
IOError: when the storage writer is closed.
OSError: when the storage writer is closed.
"""
self._RaiseIfNotWritable()
self._storage_file.AddEventSourc... | 0.002681 |
def request(self, request):
"""Sets the request of this V1beta1CertificateSigningRequestSpec.
Base64-encoded PKCS#10 CSR data # noqa: E501
:param request: The request of this V1beta1CertificateSigningRequestSpec. # noqa: E501
:type: str
"""
if request is None:
... | 0.002601 |
def select_single_column(engine, column):
"""
Select data from single column.
Example::
>>> select_single_column(engine, table_user.c.id)
[1, 2, 3]
>>> select_single_column(engine, table_user.c.name)
["Alice", "Bob", "Cathy"]
"""
s = select([column])
return col... | 0.002725 |
def main(argv=None):
"""
Entry point
:param argv: Script arguments (None for sys.argv)
:return: An exit code or None
"""
# Prepare arguments
parser = argparse.ArgumentParser(
prog="pelix.shell.xmpp",
parents=[make_common_parser()],
description="Pelix XMPP Shell",
... | 0.000639 |
def tokenize(s):
# type: (str) -> List[Token]
"""Translate a type comment into a list of tokens."""
original = s
tokens = [] # type: List[Token]
while True:
if not s:
tokens.append(End())
return tokens
elif s[0] == ' ':
s = s[1:]
elif s[0]... | 0.000629 |
def match(self, **kwargs):
"""
Traverse relationships with properties matching the given parameters.
e.g: `.match(price__lt=10)`
:param kwargs: see `NodeSet.filter()` for syntax
:return: self
"""
if kwargs:
if self.definition.get('model') is None... | 0.005137 |
def Histograms(self, run, tag):
"""Retrieve the histogram events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not a... | 0.001946 |
def get_data_ttl(self, use_cached=True):
"""Retrieve the dataTTL for this stream
The dataTtl is the time to live (TTL) in seconds for data points stored in the data stream.
A data point expires after the configured amount of time and is automatically deleted.
:param bool use_cached: If... | 0.008979 |
def get_gene2section2gos(gene2gos, sec2gos):
"""Get a list of section aliases for each gene product ID."""
gene2section2gos = {}
for geneid, gos_gene in gene2gos.items():
section2gos = {}
for section_name, gos_sec in sec2gos.items():
gos_secgene = gos_gene... | 0.003868 |
def write(self, message, autoerase=True):
"""Send something for stdout and erased after delay"""
super(Animation, self).write(message)
self.last_message = message
if autoerase:
time.sleep(self.interval)
self.erase(message) | 0.007194 |
def get_file(path=None, content=None):
"""
:param path: relative path, or None to get from request
:param content: file content, output in data. Used for editfile
"""
if path is None:
path = request.args.get('path')
if path is None:
return error('No path in request')
fi... | 0.002385 |
def str_upper(x):
"""Converts all strings in a column to uppercase.
:returns: an expression containing the converted strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Som... | 0.002577 |
def to_file(self, filepath, codec='utf-8', mode='normal'):
"""Write the object to a file.
:param str filepath: Path of the fil.
:param str codec: Text encoding.
:param string mode: Flag to for write mode, possible modes:
'n'/'normal', 's'/'short' and 'b'/'binary'
"""... | 0.000502 |
def _get_value_opc_attr(self, attr_name, prec_decimals=2):
"""Return sensor attribute with precission, or None if not present."""
try:
value = getattr(self, attr_name)
if value is not None:
return round(value, prec_decimals)
except I2cVariableNotImplemente... | 0.005571 |
def from_dict(data, ctx):
"""
Instantiate a new OrderFillTransaction from a dict (generally from
loading a JSON response). The data used to instantiate the
OrderFillTransaction is a shallow copy of the dict passed in, with any
complex child types instantiated appropriately.
... | 0.000644 |
def any(self, array, role = None):
"""
Return ``True`` if ``array`` is ``True`` for any members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into acc... | 0.016077 |
def get_datatype(object_type, propid, vendor_id=0):
"""Return the datatype for the property of an object."""
if _debug: get_datatype._debug("get_datatype %r %r vendor_id=%r", object_type, propid, vendor_id)
# get the related class
cls = get_object_class(object_type, vendor_id)
if not cls:
r... | 0.006224 |
def can_dict(obj):
"""Can the *values* of a dict."""
if istype(obj, dict):
newobj = {}
for k, v in iteritems(obj):
newobj[k] = can(v)
return newobj
else:
return obj | 0.004545 |
def update_info(self, custom=None):
"""Updates the figure's suptitle.
Calls self.info_string() unless custom is provided.
Args:
custom: Overwrite it with this string, unless None.
"""
self.figure.suptitle(self.info_string() if custom is None else custom) | 0.006494 |
def get_hashed_filename(name, file, suffix=None):
"""
Gets a new filename for the provided file of the form
"oldfilename.hash.ext". If the old filename looks like it already contains a
hash, it will be replaced (so you don't end up with names like
"pic.hash.hash.ext")
"""
basename, hash, ex... | 0.003697 |
def delete(self):
"""
If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions.
"""
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).... | 0.005263 |
def get_fit_auto(self, CentralFreq, MaxWidth=15000, MinWidth=500, WidthIntervals=500, MakeFig=True, show_fig=True, silent=False):
"""
Tries a range of regions to search for peaks and runs the one with the least error
and returns the parameters with the least errors.
Parameters
-... | 0.003999 |
def plot_eps_data_hist(self, dfs):
"""Plot histograms of data residuals and data error weighting
TODO:
* add percentage of data below/above the RMS value
"""
# check if this is a DC inversion
if 'datum' in dfs[0]:
dc_inv = True
else:
d... | 0.00069 |
def graph(self, **kw):
"""Set up a graphviz graph context.
"""
self.name = kw.get('name', 'G')
self.fillcolor = kw.get('fillcolor', '#ffffff')
self.fontcolor = kw.get('fontcolor', '#000000')
self.rankdir = kw.get('rankdir', 'BT' if self.reverse else 'TB')
if kw.ge... | 0.003856 |
def get_project(project_id):
"""Return a PYBOSSA Project for the project_id.
:param project_id: PYBOSSA Project ID
:type project_id: integer
:rtype: PYBOSSA Project
:returns: A PYBOSSA Project object
"""
try:
res = _pybossa_req('get', 'project', project_id)
if res.get('id')... | 0.004587 |
def _plain_authentication(self, login, password, authz_id=b""):
"""SASL PLAIN authentication
:param login: username
:param password: clear password
:return: True on success, False otherwise.
"""
if isinstance(login, six.text_type):
login = login.encode("utf-8... | 0.003125 |
def validate_image_col_row(image , col , row):
"""Basic checks for columns and rows values"""
SPLIT_LIMIT = 99
try:
col = int(col)
row = int(row)
except:
raise ValueError('columns and rows values could not be cast to integer.')
if col < 2:
raise ValueError('Number o... | 0.010221 |
def _groupname():
'''
Grain for the minion groupname
'''
if grp:
try:
groupname = grp.getgrgid(os.getgid()).gr_name
except KeyError:
groupname = ''
else:
groupname = ''
return groupname | 0.003876 |
def guess_format(text):
"""Guess YANG/YIN format
If the first non-whitespace character is '<' then it is XML.
Return 'yang' or 'yin'"""
format = 'yang'
i = 0
while i < len(text) and text[i].isspace():
i += 1
if i < len(text):
if text[i] == '<':
format = 'yin'
... | 0.002994 |
def undisplay(self):
"""Undisplays the top tool.
This actually forces a complete re-render.
"""
self._tools.pop()
self._justClear()
for tool in self._tools:
self._justDisplay(tool) | 0.008299 |
def name_file(lane: int, flowcell: str, sample: str, read: int,
undetermined: bool=False, date: dt.datetime=None, index: str=None) -> str:
"""Name a FASTQ file following MIP conventions."""
flowcell = f"{flowcell}-undetermined" if undetermined else flowcell
date_str = date.strf... | 0.02079 |
def predecesors_pattern(element, root):
"""
Look for `element` by its predecesors.
Args:
element (obj): HTMLElement instance of the object you are looking for.
root (obj): Root of the `DOM`.
Returns:
list: ``[PathCall()]`` - list with one :class:`PathCall` object (to \
... | 0.000952 |
def clearLocalServices(self):
'send Bye messages for the services and remove them'
for service in list(self._localServices.values()):
self._sendBye(service)
self._localServices.clear() | 0.009009 |
def heatmap(args):
"""
%prog heatmap fastafile chr1
Combine stack plot with heatmap to show abundance of various tracks along
given chromosome. Need to give multiple beds to --stacks and --heatmaps
"""
p = OptionParser(heatmap.__doc__)
p.add_option("--stacks",
default="Exon... | 0.000799 |
def plot_variability_thresholds(varthreshpkl,
xmin_lcmad_stdev=5.0,
xmin_stetj_stdev=2.0,
xmin_iqr_stdev=2.0,
xmin_inveta_stdev=2.0,
lcformat='hat-sql',
... | 0.001321 |
def upload_sticker_file(self, user_id, png_sticker):
"""
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
https://core.telegram.org/bots/api#uploadstickerfile... | 0.008319 |
def watch_thread(self):
'''watch for menu events from child'''
from MAVProxy.modules.lib.mp_settings import MPSetting
try:
while True:
msg = self.parent_pipe_recv.recv()
if isinstance(msg, win_layout.WinLayout):
win_layout.set_layou... | 0.003891 |
def metric(self):
"""
Compute a matrix of Hilbert-Schmidt inner products for the basis operators, update
self._metric, and return the value.
:return: The matrix of inner products.
:rtype: numpy.matrix
"""
if self._metric is None:
_log.debug("Computing... | 0.008316 |
def readerWalker(self):
"""Create an xmltextReader for a preparsed document. """
ret = libxml2mod.xmlReaderWalker(self._o)
if ret is None:raise treeError('xmlReaderWalker() failed')
__tmp = xmlTextReader(_obj=ret)
return __tmp | 0.015038 |
def accept(self, key, result):
"""
同步接受确认消息
:param key: correlation_id
:param result 服务端返回的消息
"""
self.data[key]['isAccept'] = True # 设置为已经接受到服务端返回的消息
self.data[key]['result'] = str(result)
self._channel.queue_delete(self.data[key]['reply_queue_name']) | 0.006309 |
def taper(path,
length,
final_width,
final_distance,
direction=None,
layer=0,
datatype=0):
'''
Linear tapers for the lazy.
path : `gdspy.Path` to append the taper
length : total length
final_width : final width of th taper
... | 0.001477 |
def _sim_prediction(self, lmda, Y, scores, h, t_params, simulations):
""" Simulates a h-step ahead mean prediction
Parameters
----------
lmda : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
The past ... | 0.010644 |
def build_tree_from_distance_matrix(matrix, best_tree=False, params={},\
working_dir='/tmp'):
"""Returns a tree from a distance matrix.
matrix: a square Dict2D object (cogent.util.dict2d)
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: ... | 0.005658 |
def setQuery(self, query):
"""
Sets the query for this wigdet to the inputed query instance.
:param query | <orb.Query> || <orb.QueryCompound>
"""
if not self.isNull() and hash(query) == hash(self.query()):
return
# add entries
... | 0.007299 |
def save_image(self, cat, img, data):
"""Saves a new image."""
filename = self.path(cat, img)
mkdir(filename)
if type(data) == np.ndarray:
data = Image.fromarray(data).convert('RGB')
data.save(filename) | 0.007874 |
async def _try_catch_coro(emitter, event, listener, coro):
"""Coroutine wrapper to catch errors after async scheduling.
Args:
emitter (EventEmitter): The event emitter that is attempting to
call a listener.
event (str): The event that triggered the emitter.
listener (async d... | 0.001074 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.