code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def _run_nucmer(self, ref, qry, outfile):
n = pymummer.nucmer.Runner(
ref,
qry,
outfile,
min_id=self.nucmer_min_id,
min_length=self.nucmer_min_length,
diagdiff=self.nucmer_diagdiff,
maxmatch=True,
breaklen=self.nucme... | Run nucmer of new assembly vs original assembly |
def remove_listener(self, registration_id):
try:
self._listeners.pop(registration_id)
return True
except KeyError:
return False | Removes a lifecycle listener.
:param registration_id: (str), the id of the listener to be removed.
:return: (bool), ``true`` if the listener is removed successfully, ``false`` otherwise. |
def first_order_score(y, mean, scale, shape, skewness):
return (y-mean)/float(scale*np.abs(y-mean)) | GAS Laplace Update term using gradient only - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the Laplace distribution
scale : float
scale parameter for the Laplace dis... |
def load(self, filename):
try:
with open(filename, 'rb') as fp:
self.counters = cPickle.load(fp)
except:
logging.debug("can't load counter from file: %s", filename)
return False
return True | Load counters to file |
def get_port_bindings(container_config, client_config):
port_bindings = {}
if_ipv4 = client_config.interfaces
if_ipv6 = client_config.interfaces_ipv6
for exposed_port, ex_port_bindings in itertools.groupby(
sorted(container_config.exposes, key=_get_ex_port), _get_ex_port):
bind_list ... | Generates the input dictionary contents for the ``port_bindings`` argument.
:param container_config: Container configuration.
:type container_config: dockermap.map.config.container.ContainerConfiguration
:param client_config: Client configuration.
:type client_config: dockermap.map.config.client.Client... |
def get(self, transform=None):
if not self.has_expired() and self._cached_copy is not None:
return self._cached_copy, False
return self._refresh_cache(transform), True | Return the JSON defined at the S3 location in the constructor.
The get method will reload the S3 object after the TTL has
expired.
Fetch the JSON object from cache or S3 if necessary |
def _rle(self, a):
ia = np.asarray(a)
n = len(ia)
y = np.array(ia[1:] != ia[:-1])
i = np.append(np.where(y), n - 1)
z = np.diff(np.append(-1, i))
p = np.cumsum(np.append(0, z))[:-1]
return (z, p, ia[i]) | rle implementation credit to Thomas Browne from his SOF post Sept 2015
Parameters
----------
a : array, shape[n,]
input vector
Returns
-------
z : array, shape[nt,]
run lengths
p : array, shape[nt,]
start positions of each run... |
def rand_bivar(X, rho):
import numpy as np
Y = np.empty(X.shape)
Y[:, 0] = X[:, 0]
Y[:, 1] = rho * X[:, 0] + np.sqrt(1.0 - rho**2) * X[:, 1]
return Y | Transform two unrelated random variables into correlated bivariate data
X : ndarray
two univariate random variables
with N observations as <N x 2> matrix
rho : float
The Pearson correlations coefficient
as number between [-1, +1] |
def highlight(str1, str2):
print('------------------------------')
try:
str2 = str2[0]
except IndexError:
str2 = None
if str1 and str2:
return str1.replace(str2, "<b>{}</b>".format(str2))
else:
return str1 | Highlight str1 with the contents of str2. |
def validate(self, value) :
for v in self.validators :
v.validate(value)
return True | checks the validity of 'value' given the lits of validators |
def get_type_name(type_name, sub_type=None):
if type_name in ("string", "enum"):
return "string"
if type_name == "float":
return "float64"
if type_name == "boolean":
return "bool"
if type_name == "list":
st = get_type_name(type_name=sub_type, sub_type=None) if sub_type el... | Returns a go type according to a spec type |
def medium_integer(self, column, auto_increment=False, unsigned=False):
return self._add_column('medium_integer', column,
auto_increment=auto_increment,
unsigned=unsigned) | Create a new medium integer column on the table.
:param column: The column
:type column: str
:type auto_increment: bool
:type unsigned: bool
:rtype: Fluent |
def closest_pair(arr, give="indicies"):
idxs = [idx for idx in np.ndindex(arr.shape)]
outs = []
min_dist = arr.max() - arr.min()
for idxa in idxs:
for idxb in idxs:
if idxa == idxb:
continue
dist = abs(arr[idxa] - arr[idxb])
if dist == min_dist... | Find the pair of indices corresponding to the closest elements in an array.
If multiple pairs are equally close, both pairs of indicies are returned.
Optionally returns the closest distance itself.
I am sure that this could be written as a cheaper operation. I
wrote this as a quick and dirty method be... |
def get_app_guid(self, app_name):
summary = self.space.get_space_summary()
for app in summary['apps']:
if app['name'] == app_name:
return app['guid'] | Returns the GUID for the app instance with
the given name. |
def bcc(
self,
bcc_emails,
global_substitutions=None,
is_multiple=False,
p=0):
if isinstance(bcc_emails, list):
for email in bcc_emails:
if isinstance(email, str):
email = Bcc(email, None)
... | Adds Bcc objects to the Personalization object
:param bcc_emails: An Bcc or list of Bcc objects
:type bcc_emails: Bcc, list(Bcc), tuple
:param global_substitutions: A dict of substitutions for all recipients
:type global_substitutions: dict
:param is_multiple: Create a new perso... |
def is_python_interpreter(filename):
real_filename = os.path.realpath(filename)
if (not osp.isfile(real_filename) or
not is_python_interpreter_valid_name(filename)):
return False
elif is_pythonw(filename):
if os.name == 'nt':
if not encoding.is_text_file(real_filen... | Evaluate wether a file is a python interpreter or not. |
def read_option_value_from_nibble(nibble, pos, values):
if nibble <= 12:
return nibble, pos
elif nibble == 13:
tmp = struct.unpack("!B", values[pos].to_bytes(1, "big"))[0] + 13
pos += 1
return tmp, pos
elif nibble == 14:
s = struct.Stru... | Calculates the value used in the extended option fields.
:param nibble: the 4-bit option header value.
:return: the value calculated from the nibble and the extended option value. |
def _ReadPropertySet(self, property_set):
for property_section in property_set.sections:
if property_section.class_identifier != self._CLASS_IDENTIFIER:
continue
for property_value in property_section.properties:
property_name = self._PROPERTY_NAMES.get(
property_value.identi... | Reads properties from a property set.
Args:
property_set (pyolecf.property_set): OLECF property set. |
def login(username, password, **kwargs):
user_id = util.hdb.login_user(username, password)
hydra_session = session.Session({},
validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'),
type='file',
cookie_expires=True,
data_dir=config.get('COOKIES', 'D... | Login a user, returning a dict containing their user_id and session_id
This does the DB login to check the credentials, and then creates a session
so that requests from apps do not need to perform a login
args:
username (string): The user's username
password(string): Th... |
def count(data, axis=None):
return np.sum(np.logical_not(isnull(data)), axis=axis) | Count the number of non-NA in this array along the given axis or axes |
def get_el(el):
tag_name = el.elt.tagName.lower()
if tag_name in {"input", "textarea", "select"}:
return el.value
else:
raise ValueError(
"Getter for %s (%s) not implemented!" % (tag_name, el.id)
) | Get value of given `el` tag element.
Automatically choose proper method to set the `value` based on the type
of the `el`.
Args:
el (obj): Element reference to the input you want to convert to
typeahead.
Returns:
str: Value of the object. |
def dK_dr_via_X(self, X, X2):
return self.dK_dr(self._scaled_dist(X, X2)) | compute the derivative of K wrt X going through X |
def plot(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT):
if title == "":
title = " "
if xlabel == "":
xlabel = " "
if ylabel == "":
ylabel = " "
if title is None:
title = ""
if xlabel is None:
xla... | Create a Plot object representing the SArray.
Notes
-----
- The plot will render either inline in a Jupyter Notebook, or in a
native GUI window, depending on the value provided in
`turicreate.visualization.set_target` (defaults to 'auto').
Parameters
-------... |
def delete_thumbnails(relative_source_path, root=None, basedir=None,
subdir=None, prefix=None):
thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir,
prefix)
return _delete_using_thumbs_list(thumbs) | Delete all thumbnails for a source image. |
def where(cmd, path=None):
raw_result = shutil.which(cmd, os.X_OK, path)
if raw_result:
return os.path.abspath(raw_result)
else:
raise ValueError("Could not find '{}' in the path".format(cmd)) | A function to wrap shutil.which for universal usage |
def mean_curve(values, weights=None):
if weights is None:
weights = [1. / len(values)] * len(values)
if not isinstance(values, numpy.ndarray):
values = numpy.array(values)
return numpy.average(values, axis=0, weights=weights) | Compute the mean by using numpy.average on the first axis. |
def urlsafe_b64decode(data):
pad = b'=' * (4 - (len(data) & 3))
return base64.urlsafe_b64decode(data + pad) | urlsafe_b64decode without padding |
def calculate_descriptors(self,mol):
self.ligand_atoms = {index:{"name":x.name} for index,x in enumerate(self.topology_data.universe.ligand_noH.atoms)}
contribs = self.calculate_logP(mol)
self.calculate_Gasteiger_charges(mol)
fcharges = self.calculate_formal_charge(mol)
for atom in self.ligand_atoms.keys():
... | Calculates descriptors such as logP, charges and MR and saves that in a dictionary. |
def _writeFeatures(self, i, image):
basename = 'features-%d.txt' % i
filename = '%s/%s' % (self._outputDir, basename)
featureList = image['graphInfo']['features']
with open(filename, 'w') as fp:
for feature in featureList:
fp.write('%s\n\n' % feature.feature)
... | Write a text file containing the features as a table.
@param i: The number of the image in self._images.
@param image: A member of self._images.
@return: The C{str} features file name - just the base name, not
including the path to the file. |
def parse_pseudo_open(self, sel, name, has_selector, iselector, index):
flags = FLG_PSEUDO | FLG_OPEN
if name == ':not':
flags |= FLG_NOT
if name == ':has':
flags |= FLG_RELATIVE
sel.selectors.append(self.parse_selectors(iselector, index, flags))
has_selec... | Parse pseudo with opening bracket. |
def list_processed_parameter_groups(self):
path = '/archive/{}/parameter-groups'.format(self._instance)
response = self._client.get_proto(path=path)
message = archive_pb2.ParameterGroupInfo()
message.ParseFromString(response.content)
groups = getattr(message, 'group')
ret... | Returns the existing parameter groups.
:rtype: ~collections.Iterable[str] |
def rename(store, src_path, dst_path):
src_path = normalize_storage_path(src_path)
dst_path = normalize_storage_path(dst_path)
if hasattr(store, 'rename'):
store.rename(src_path, dst_path)
else:
_rename_from_keys(store, src_path, dst_path) | Rename all items under the given path. If `store` provides a `rename` method,
this will be called, otherwise will fall back to implementation via the
`MutableMapping` interface. |
async def cycle(self, channel):
if not self.in_channel(channel):
raise NotInChannel(channel)
password = self.channels[channel]['password']
await self.part(channel)
await self.join(channel, password) | Rejoin channel. |
def _set_scores(self):
anom_scores = {}
self._generate_SAX()
self._construct_all_SAX_chunk_dict()
length = self.time_series_length
lws = self.lag_window_size
fws = self.future_window_size
for i, timestamp in enumerate(self.time_series.timestamps):
if i... | Compute anomaly scores for the time series by sliding both lagging window and future window. |
def Equals(self, other):
if other is None:
return False
if other.PrevHash.ToBytes() == self.PrevHash.ToBytes() and other.PrevIndex == self.PrevIndex:
return True
return False | Test for equality.
Args:
other (obj):
Returns:
bool: True `other` equals self. |
def delete_state_changes(self, state_changes_to_delete: List[int]) -> None:
with self.write_lock, self.conn:
self.conn.executemany(
'DELETE FROM state_events WHERE identifier = ?',
state_changes_to_delete,
) | Delete state changes.
Args:
state_changes_to_delete: List of ids to delete. |
def get_real_end_line(token):
end_line = token.end_mark.line + 1
if not isinstance(token, yaml.ScalarToken):
return end_line
pos = token.end_mark.pointer - 1
while (pos >= token.start_mark.pointer - 1 and
token.end_mark.buffer[pos] in string.whitespace):
if token.end_mark.buff... | Finds the line on which the token really ends.
With pyyaml, scalar tokens often end on a next line. |
def get_msg(self):
width = 72
_msg = self.msg % {'distro': self.distro, 'vendor': self.vendor,
'vendor_url': self.vendor_url,
'vendor_text': self.vendor_text,
'tmpdir': self.commons['tmpdir']}
_fmt = ""
for ... | This method is used to prepare the preamble text to display to
the user in non-batch mode. If your policy sets self.distro that
text will be substituted accordingly. You can also override this
method to do something more complicated. |
def handle_dataframe(
df: pd.DataFrame,
entrez_id_name,
log2_fold_change_name,
adjusted_p_value_name,
entrez_delimiter,
base_mean=None,
) -> List[Gene]:
logger.info("In _handle_df()")
if base_mean is not None and base_mean in df.columns:
df = df[pd.notnull... | Convert data frame on differential expression values as Gene objects.
:param df: Data frame with columns showing values on differential
expression.
:param cfp: An object that includes paths, cutoffs and other information.
:return list: A list of Gene objects. |
def build_routes(pfeed):
f = pfeed.frequencies[['route_short_name', 'route_long_name',
'route_type', 'shape_id']].drop_duplicates().copy()
f['route_id'] = 'r' + f['route_short_name'].map(str)
del f['shape_id']
return f | Given a ProtoFeed, return a DataFrame representing ``routes.txt``. |
def transitive_reduction(self):
combinations = []
for node, edges in self.graph.items():
combinations += [[node, edge] for edge in edges]
while True:
new_combinations = []
for comb1 in combinations:
for comb2 in combinations:
... | Performs a transitive reduction on the DAG. The transitive
reduction of a graph is a graph with as few edges as possible with the
same reachability as the original graph.
See https://en.wikipedia.org/wiki/Transitive_reduction |
def arity_evaluation_checker(function):
is_class = inspect.isclass(function)
if is_class:
function = function.__init__
function_info = inspect.getargspec(function)
function_args = function_info.args
if is_class:
function_args = function_args[1:]
de... | Build an evaluation checker that will return True when it is
guaranteed that all positional arguments have been accounted for. |
def update_config_value(self, config_m, config_key):
config_value = config_m.get_current_config_value(config_key)
if config_m is self.core_config_model:
list_store = self.core_list_store
elif config_m is self.gui_config_model:
list_store = self.gui_list_store
else... | Updates the corresponding list store of a changed config value
:param ConfigModel config_m: The config model that has been changed
:param str config_key: The config key who's value has been changed |
def verify_param(self, param, must=[], r=None):
if APIKEY not in param:
param[APIKEY] = self.apikey()
r = Result() if r is None else r
for p in must:
if p not in param:
r.code(Code.ARGUMENT_MISSING).detail('missing-' + p)
break
retu... | return Code.ARGUMENT_MISSING if every key in must not found in param |
def write_csvs(self,
asset_map,
show_progress=False,
invalid_data_behavior='warn'):
read = partial(
read_csv,
parse_dates=['day'],
index_col='day',
dtype=self._csv_dtypes,
)
return self.write... | Read CSVs as DataFrames from our asset map.
Parameters
----------
asset_map : dict[int -> str]
A mapping from asset id to file path with the CSV data for that
asset
show_progress : bool
Whether or not to show a progress bar while writing.
inva... |
def decrypt(self, data):
decrypted_data = b""
for i in range(0, len(data), 8):
block = data[i:i + 8]
block_length = len(block)
if block_length != 8:
raise ValueError("DES decryption must be a multiple of 8 "
"bytes")
... | DES decrypts the data based on the key it was initialised with.
:param data: The encrypted bytes string to decrypt
:return: The decrypted bytes string |
def db(cls, path=None):
if cls.PATH is None and path is None:
raise Exception("No database specified")
if path is None:
path = cls.PATH
if "." not in path:
raise Exception(('invalid path "%s"; database paths must be ' +
'of the for... | Returns a pymongo Collection object from the current database connection.
If the database connection is in test mode, collection will be in the
test database.
@param path: if is None, the PATH attribute of the current class is used;
if is not None, this is used instead
... |
def recalibrate_quality(bam_file, sam_ref, dbsnp_file, picard_dir):
cl = ["picard_gatk_recalibrate.py", picard_dir, sam_ref, bam_file]
if dbsnp_file:
cl.append(dbsnp_file)
subprocess.check_call(cl)
out_file = glob.glob("%s*gatkrecal.bam" % os.path.splitext(bam_file)[0])[0]
return out_file | Recalibrate alignments with GATK and provide pdf summary. |
def wait_for_task(upid, timeout=300):
start_time = time.time()
info = _lookup_proxmox_task(upid)
if not info:
log.error('wait_for_task: No task information '
'retrieved based on given criteria.')
raise SaltCloudExecutionFailure
while True:
if 'status' in info an... | Wait until a the task has been finished successfully |
def sys_register_SDL_renderer(callback: Callable[[Any], None]) -> None:
with _PropagateException() as propagate:
@ffi.def_extern(onerror=propagate)
def _pycall_sdl_hook(sdl_surface: Any) -> None:
callback(sdl_surface)
lib.TCOD_sys_register_SDL_renderer(lib._pycall_sdl_hook) | Register a custom randering function with libtcod.
Note:
This callback will only be called by the SDL renderer.
The callack will receive a :any:`CData <ffi-cdata>` void* to an
SDL_Surface* struct.
The callback is called on every call to :any:`tcod.console_flush`.
Args:
callback C... |
def bind_type(python_value):
binding_table = {'bool': Bool, 'int': Int, 'float': Float}
if python_value is None:
return NoneType()
python_type = type(python_value)
gibica_type = binding_table.get(python_type.__name__)
if gibica_type is None:
raise TypeError('Impossible to recognize u... | Return a Gibica type derived from a Python type. |
def get_func_args(func):
if isinstance(func, functools.partial):
return _signature(func.func)
if inspect.isfunction(func) or inspect.ismethod(func):
return _signature(func)
return _signature(func.__call__) | Given a callable, return a tuple of argument names. Handles
`functools.partial` objects and class-based callables.
.. versionchanged:: 3.0.0a1
Do not return bound arguments, eg. ``self``. |
def make_interval(long_name, short_name):
return Group(
Regex("(-+)?[0-9]+")
+ (
upkey(long_name + "s")
| Regex(long_name + "s").setParseAction(upcaseTokens)
| upkey(long_name)
| Regex(long_name).setParseAction(upcaseTokens)
| upkey(short_n... | Create an interval segment |
def samples(self):
if not hasattr(self,'sampler') and self._samples is None:
raise AttributeError('Must run MCMC (or load from file) '+
'before accessing samples')
if self._samples is not None:
df = self._samples
else:
self._ma... | Dataframe with samples drawn from isochrone according to posterior
Columns include both the sampling parameters from the MCMC
fit (mass, age, Fe/H, [distance, A_V]), and also evaluation
of the :class:`Isochrone` at each of these sample points---this
is how chains of physical/observable ... |
def _iter_keys(key):
for i in range(winreg.QueryInfoKey(key)[0]):
yield winreg.OpenKey(key, winreg.EnumKey(key, i)) | ! Iterate over subkeys of a key |
def primers(self, tm=60):
self.primers = coral.design.primers(self.template, tm=tm)
return self.primers | Design primers for amplifying the assembled sequence.
:param tm: melting temperature (lower than overlaps is best).
:type tm: float
:returns: Primer list (the output of coral.design.primers).
:rtype: list |
def gborders(img, alpha=1.0, sigma=1.0):
gradnorm = gaussian_gradient_magnitude(img, sigma, mode='constant')
return 1.0/np.sqrt(1.0 + alpha*gradnorm) | Stopping criterion for image borders. |
def get_wsgi_request_object(curr_request, method, url, headers, body):
x_headers = headers_to_include_from_request(curr_request)
method, t_headers = pre_process_method_headers(method, headers)
if "CONTENT_TYPE" not in t_headers:
t_headers.update({"CONTENT_TYPE": _settings.DEFAULT_CONTENT_TYPE})
... | Based on the given request parameters, constructs and returns the WSGI request object. |
def from_snl(cls, snl):
hist = []
for h in snl.history:
d = h.description
d['_snl'] = {'url': h.url, 'name': h.name}
hist.append(d)
return cls(snl.structure, history=hist) | Create TransformedStructure from SNL.
Args:
snl (StructureNL): Starting snl
Returns:
TransformedStructure |
def get_tissue_in_references(self, entry):
tissue_in_references = []
query = "./reference/source/tissue"
tissues = {x.text for x in entry.iterfind(query)}
for tissue in tissues:
if tissue not in self.tissues:
self.tissues[tissue] = models.TissueInReference(tis... | get list of models.TissueInReference from XML node entry
:param entry: XML node entry
:return: list of :class:`pyuniprot.manager.models.TissueInReference` objects |
def stream_members(self, stream_id):
response, status_code = self.__pod__.Streams.get_v1_admin_stream_id_membership_list(
sessionToken=self.__session__,
id=stream_id
).result()
self.logger.debug('%s: %s' % (status_code, response))
return status_code, response | get stream members |
def process_binding_statements(self):
G = self.G
statements = []
binding_nodes = self.find_event_with_outgoing_edges('Binding',
['Theme',
'Theme2'])
for node in bin... | Looks for Binding events in the graph and extracts them into INDRA
statements.
In particular, looks for a Binding event node with outgoing edges
with relations Theme and Theme2 - the entities these edges point to
are the two constituents of the Complex INDRA statement. |
def _get_parameter_conversion_entry(parameter_config):
entry = _PARAM_CONVERSION_MAP.get(parameter_config.get('type'))
if entry is None and 'enum' in parameter_config:
entry = _PARAM_CONVERSION_MAP['enum']
return entry | Get information needed to convert the given parameter to its API type.
Args:
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in the
method config.
Returns:
The entry from _PARAM_CONVERSION_MAP with functio... |
def _parse_deploy(self, deploy_values: dict, service_config: dict):
mode = {}
for d_value in deploy_values:
if 'restart_policy' in d_value:
restart_spec = docker.types.RestartPolicy(
**deploy_values[d_value])
service_config['restart_policy'... | Parse deploy key.
Args:
deploy_values (dict): deploy configuration values
service_config (dict): Service configuration |
def supportsType(self, type_uri):
return (
(type_uri in self.type_uris) or
(type_uri == OPENID_2_0_TYPE and self.isOPIdentifier())
) | Does this endpoint support this type?
I consider C{/server} endpoints to implicitly support C{/signon}. |
def _RunSingleHook(self, hook_cls, executed_set, required=None):
if hook_cls in executed_set:
return
for pre_hook in hook_cls.pre:
self._RunSingleHook(pre_hook, executed_set, required=hook_cls.__name__)
cls_instance = hook_cls()
if required:
logging.debug("Initializing %s, required by ... | Run the single hook specified by resolving all its prerequisites. |
def PyParseRangeCheck(lower_bound, upper_bound):
def CheckRange(string, location, tokens):
try:
check_number = tokens[0]
except IndexError:
check_number = -1
if check_number < lower_bound:
raise pyparsing.ParseException(
'Value: {0:d} precedes lower bound: {1:d}'.format(
... | Verify that a number is within a defined range.
This is a callback method for pyparsing setParseAction
that verifies that a read number is within a certain range.
To use this method it needs to be defined as a callback method
in setParseAction with the upper and lower bound set as parameters.
Args:
low... |
def read_hierarchy(self, fid):
lin = self.read_line(fid)
while lin != 'end':
parts = lin.split()
if lin != 'begin':
ind = self.get_index_by_name(parts[0])
for i in range(1, len(parts)):
self.vertices[ind].children.append(self.ge... | Read hierarchy information from acclaim skeleton file stream. |
def show_gateway_device(self, gateway_device_id, **_params):
return self.get(self.gateway_device_path % gateway_device_id,
params=_params) | Fetch a gateway device. |
def restore(self):
signal.signal(signal.SIGINT, self.original_sigint)
signal.signal(signal.SIGTERM, self.original_sigterm)
if os.name == 'nt':
signal.signal(signal.SIGBREAK, self.original_sigbreak) | Restore signal handlers to their original settings. |
def post(url, data=None, json=None, **kwargs):
_set_content_type(kwargs)
if _content_type_is_json(kwargs) and data is not None:
data = dumps(data)
_log_request('POST', url, kwargs, data)
response = requests.post(url, data, json, **kwargs)
_log_response(response)
return response | A wrapper for ``requests.post``. |
def all(self):
self._check_layout()
return LayoutSlice(self.layout, slice(0, len(self.layout.fields), 1)) | Returns all layout objects of first level of depth |
def get_one(self, fields=list()):
response = self.session.get(self._get_table_url(),
params=self._get_formatted_query(fields, limit=None, order_by=list(), offset=None))
content = self._get_content(response)
l = len(content)
if l > 1:
raise ... | Convenience function for queries returning only one result. Validates response before returning.
:param fields: List of fields to return in the result
:raise:
:MultipleResults: if more than one match is found
:return:
- Record content |
def init_logging():
fmt = '%(asctime)s.%(msecs)03d | %(name)-60s | %(levelname)-7s ' \
'| %(message)s'
logging.basicConfig(format=fmt, datefmt='%H:%M:%S', level=logging.DEBUG) | Initialise Python logging. |
def frequencies_plot(self, xmin=0, xmax=200):
helptext =
pconfig = {
'id': 'Jellyfish_kmer_plot',
'title': 'Jellyfish: K-mer plot',
'ylab': 'Counts',
'xlab': 'k-mer frequency',
'xDecimals': False,
'xmin': xmin,
'xmax': x... | Generate the qualities plot |
def get_shortcut(self, name):
name = self.__normalize_name(name)
action = self.get_action(name)
if not action:
return ""
return action.shortcut().toString() | Returns given action shortcut.
:param name: Action to retrieve the shortcut.
:type name: unicode
:return: Action shortcut.
:rtype: unicode |
def get_pins(self):
result = []
for a in range(0, 7):
result.append(GPIOPin(self, '_action', {'pin': 'A{}'.format(a)}, name='A{}'.format(a)))
for b in range(0, 7):
result.append(GPIOPin(self, '_action', {'pin': 'B{}'.format(b)}, name='B{}'.format(b)))
return resul... | Get a list containing references to all 16 pins of the chip.
:Example:
>>> expander = MCP23017I2C(gw)
>>> pins = expander.get_pins()
>>> pprint.pprint(pins)
[<GPIOPin A0 on MCP23017I2C>,
<GPIOPin A1 on MCP23017I2C>,
<GPIOPin A2 on MCP23017I2C>,
<GPIOP... |
def compose(f, *fs):
rfs = list(chain([f], fs))
rfs.reverse()
def composed(*args, **kwargs):
return reduce(
lambda result, fn: fn(result),
rfs[1:],
rfs[0](*args, **kwargs))
return composed | Compose functions right to left.
compose(f, g, h)(x) -> f(g(h(x)))
Args:
f, *fs: The head and rest of a sequence of callables. The
rightmost function passed can accept any arguments and
the returned function will have the same signature as
this last prov... |
def _inputcooker_store(self, char):
if self.sb:
self.sbdataq = self.sbdataq + char
else:
self.inputcooker_store_queue(char) | Put the cooked data in the correct queue |
def _changeGroupImage(self, image_id, thread_id=None):
thread_id, thread_type = self._getThread(thread_id, None)
data = {"thread_image_id": image_id, "thread_id": thread_id}
j = self._post(self.req_url.THREAD_IMAGE, data, fix_request=True, as_json=True)
return image_id | Changes a thread image from an image id
:param image_id: ID of uploaded image
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed |
def _update_field(self, action, field, value, max_tries, tries=0):
self.fetch()
action(self, field, value)
try:
self.save()
except requests.HTTPError as ex:
if tries < max_tries and ex.response.status_code == 409:
self._update_field(
... | Private update_field method. Wrapped by Document.update_field.
Tracks a "tries" var to help limit recursion. |
def document_quote (document):
doc, query = urllib.splitquery(document)
doc = url_quote_part(doc, '/=,')
if query:
return "%s?%s" % (doc, query)
return doc | Quote given document. |
def is_text_extractor_available(extension: str) -> bool:
if extension is not None:
extension = extension.lower()
info = ext_map.get(extension)
if info is None:
return False
availability = info[AVAILABILITY]
if type(availability) == bool:
return availability
elif callable(... | Is a text extractor available for the specified extension? |
def set_of_vars(arg_plot):
return set(var for var in arg_plot.split(',') if var in phyvars.PLATES) | Build set of needed variables.
Args:
arg_plot (str): string with variable names separated with ``,``.
Returns:
set of str: set of variables. |
def match_gpus(available_devices, requirements):
if not requirements:
return []
if not available_devices:
raise InsufficientGPUError("No GPU devices available, but {} devices required.".format(len(requirements)))
available_devices = available_devices.copy()
used_devices = []
for req ... | Determines sufficient GPUs for the given requirements and returns a list of GPUDevices.
If there aren't sufficient GPUs a InsufficientGPUException is thrown.
:param available_devices: A list of GPUDevices
:param requirements: A list of GPURequirements
:return: A list of sufficient devices |
def viewport_to_screen_space(framebuffer_size: vec2, point: vec4) -> vec2:
return (framebuffer_size * point.xy) / point.w | Transform point in viewport space to screen space. |
def ols_covariance(self):
Y = np.array([reg[self.lags:reg.shape[0]] for reg in self.data])
return (1.0/(Y[0].shape[0]))*np.dot(self.residuals(Y),np.transpose(self.residuals(Y))) | Creates OLS estimate of the covariance matrix
Returns
----------
The OLS estimate of the covariance matrix |
def load_device(self, serial=None):
serials = android_device.list_adb_devices()
if not serials:
raise Error('No adb device found!')
if not serial:
env_serial = os.environ.get('ANDROID_SERIAL', None)
if env_serial is not None:
serial = env_seria... | Creates an AndroidDevice for the given serial number.
If no serial is given, it will read from the ANDROID_SERIAL
environmental variable. If the environmental variable is not set, then
it will read from 'adb devices' if there is only one. |
def exists(self, obj_id, obj_type=None):
return self.object_key(obj_id, obj_type) in self._data | Return whether the given object exists in the search index.
:param obj_id: The object's unique identifier.
:param obj_type: The object's type. |
def return_real_id(self):
if self._prepopulated is False:
raise errors.EmptyDatabase(self.dbpath)
else:
return return_real_id_base(self.dbpath, self._set_object) | Returns a list of real_id's
Parameters
----------
Returns
-------
A list of real_id values for the dataset (a real_id is the filename minus the suffix and prefix) |
def set_unobserved_before(self,tlen,qlen,nt,p):
self._unobservable.set_before(tlen,qlen,nt,p) | Set the unobservable sequence data before this base
:param tlen: target homopolymer length
:param qlen: query homopolymer length
:param nt: nucleotide
:param p: p is the probability of attributing this base to the unobserved error
:type tlen: int
:type qlen: int
:type nt: char
:type p: ... |
def model_deleted(sender, instance,
using,
**kwargs):
opts = get_opts(instance)
model = '.'.join([opts.app_label, opts.object_name])
distill_model_event(instance, model, 'deleted') | Automatically triggers "deleted" actions. |
def Sign(verifiable, keypair):
prikey = bytes(keypair.PrivateKey)
hashdata = verifiable.GetHashData()
res = Crypto.Default().Sign(hashdata, prikey)
return res | Sign the `verifiable` object with the private key from `keypair`.
Args:
verifiable:
keypair (neocore.KeyPair):
Returns:
bool: True if successfully signed. False otherwise. |
def load_vint(buf, pos):
limit = min(pos + 11, len(buf))
res = ofs = 0
while pos < limit:
b = _byte_code(buf[pos])
res += ((b & 0x7F) << ofs)
pos += 1
ofs += 7
if b < 0x80:
return res, pos
raise BadRarFile('cannot load vint') | Load variable-size int. |
def run(
categories, param_file, project_dir, plugin, target,
status_update_interval
):
return _run(
categories, param_file, project_dir, plugin, target,
status_update_interval
) | Generate code for this project and run it |
def query(cls, *criteria, **filters):
query = cls.dbmodel.query.filter(
*criteria).filter_by(**filters)
return [cls(obj) for obj in query.all()] | Wrap sqlalchemy query methods.
A wrapper for the filter and filter_by functions of sqlalchemy.
Define a dict with which columns should be filtered by which values.
.. codeblock:: python
WorkflowObject.query(id=123)
WorkflowObject.query(status=ObjectStatus.COMPLETED)
... |
def allan_variance(data, dt, tmax=10):
allanvar = []
nmax = len(data) if len(data) < tmax / dt else int(tmax / dt)
for i in range(1, nmax+1):
databis = data[len(data) % i:]
y = databis.reshape(len(data)//i, i).mean(axis=1)
allanvar.append(((y[1:] - y[:-1])**2).mean() / 2)
return ... | Calculate Allan variance.
Args:
data (np.ndarray): Input data.
dt (float): Time between each data.
tmax (float): Maximum time.
Returns:
vk (np.ndarray): Frequency.
allanvar (np.ndarray): Allan variance. |
def to_type_with_default(value_type, value, default_value):
result = TypeConverter.to_nullable_type(value_type, value)
return result if result != None else default_value | Converts value into an object type specified by Type Code or returns default value when conversion is not possible.
:param value_type: the TypeCode for the data type into which 'value' is to be converted.
:param value: the value to convert.
:param default_value: the default value to return if... |
def zSaveFile(self, fileName):
cmd = "SaveFile,{}".format(fileName)
reply = self._sendDDEcommand(cmd)
return int(float(reply.rstrip())) | Saves the lens currently loaded in the server to a Zemax file |
def expect_dimensions(__funcname=_qualified_name, **dimensions):
if isinstance(__funcname, str):
def get_funcname(_):
return __funcname
else:
get_funcname = __funcname
def _expect_dimension(expected_ndim):
def _check(func, argname, argvalue):
actual_ndim = arg... | Preprocessing decorator that verifies inputs are numpy arrays with a
specific dimensionality.
Examples
--------
>>> from numpy import array
>>> @expect_dimensions(x=1, y=2)
... def foo(x, y):
... return x[0] + y[0, 0]
...
>>> foo(array([1, 1]), array([[1, 1], [2, 2]]))
2
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.