Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
340,100 | def gpu_c2r_ifft(in1, is_gpuarray=False, store_on_gpu=False):
if is_gpuarray:
gpu_in1 = in1
else:
gpu_in1 = gpuarray.to_gpu_async(in1.astype(np.complex64))
output_size = np.array(in1.shape)
output_size[1] = 2*(output_size[1]-1)
gpu_out1 = gpuarray.empty([output_size[0],output... | This function makes use of the scikits implementation of the FFT for GPUs to take the complex to real IFFT.
INPUTS:
in1 (no default): The array on which the IFFT is to be performed.
is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu.
store_on_... |
340,101 | def user_agent(self):
if not self._user_agent:
session = requests.Session()
user_agent = session.headers[]
self._user_agent = % (self.base_user_agent, user_agent)
return self._user_agent | User-Agent para as requisições feitas para o Postmon.
Retorna o ``base_user_agent`` concatenado com o ``User-Agent`` padrão
do requests. |
340,102 | def rand_bytes(length):
if not isinstance(length, int_types):
raise TypeError(pretty_message(
,
type_name(length)
))
if length < 1:
raise ValueError()
if length > 1024:
raise ValueError()
return os.urandom(length) | Returns a number of random bytes suitable for cryptographic purposes
:param length:
The desired number of bytes
:raises:
ValueError - when any of the parameters contain an invalid value
TypeError - when any of the parameters are of the wrong type
OSError - when an error is retu... |
340,103 | def refresh(self, app, client_id, ttl):
return super(Album, self).refresh(app, client_id, ttl) or list() | Query the API to update this instance.
:raise APIError: When Imgur responds with errors or unexpected data.
:param sphinx.application.Sphinx app: Sphinx application object.
:param str client_id: Imgur API client ID to use. https://api.imgur.com/oauth2
:param int ttl: Number of seconds ... |
340,104 | def delete_items_by_index(list_, index_list, copy=False):
if copy:
list_ = list_[:]
index_list_ = [(len(list_) + x if x < 0 else x) for x in index_list]
index_list_ = sorted(index_list_, reverse=True)
for index in index_list_:
del list_[index]
return list_ | Remove items from ``list_`` at positions specified in ``index_list``
The original ``list_`` is preserved if ``copy`` is True
Args:
list_ (list):
index_list (list):
copy (bool): preserves original list if True
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list im... |
340,105 | def absolute_name(self, depth=0):
node, node_depth = self, self.depth
if depth < 1:
depth = node_depth
while node_depth > depth and node.package is not None:
node = node.package
node_depth -= 1
names = []
while node is not None:
... | Return the absolute name of the node.
Concatenate names from root to self within depth.
Args:
depth (int): maximum depth to go to.
Returns:
str: absolute name of the node (until given depth is reached). |
340,106 | def add(self, name, priority=3, comment="", parent=""):
item = [name, priority, comment, False, []]
data = self.data
for c in self._split(parent):
data = data[int(c) - 1][4]
data.append(item) | Adds new item to the model.
Name argument may contain (ref:) syntax, which will be
stripped down as needed.
:parent: should have a form "<itemref>.<subitemref...>" (e.g. "1.1").
:name: Name (with refs).
:priority: Item's priority.
:comment: Comment.
:parent: It... |
340,107 | def GetHistRaw(tag_name, start_time, end_time, high_speed=False,
desc_as_label=False, label=None):
return GetHist(tag_name, start_time, end_time, mode="raw",
desc_as_label=desc_as_label, label=label) | Retrieves raw data from eDNA history for a given tag.
:param tag_name: fully-qualified (site.service.tag) eDNA tag
:param start_time: must be in format mm/dd/yy hh:mm:ss
:param end_time: must be in format mm/dd/yy hh:mm:ss
:param high_speed: true = pull milliseconds
:param desc_as_label: use ... |
340,108 | def _horiz_cross(t, alt, rise_set, horizon=0*u.degree):
if rise_set == :
condition = (alt[:-1] < horizon) * (alt[1:] > horizon)
elif rise_set == :
condition = (alt[:-1] > horizon) * (alt[1:] < horizon)
if np.count_nonzero(condition) == 0:
warnmsg = (
... | Find time ``t`` when values in array ``a`` go from
negative to positive or positive to negative (exclude endpoints)
``return_limits`` will return nearest times to zero-crossing.
Parameters
----------
t : `~astropy.time.Time`
Grid of times
alt : `~astropy.units.Quantity`
Grid of... |
340,109 | def _reduce_method(cls, func):
def wrapped_func(self, **kwargs):
from .dataarray import DataArray
reduced = self.obj.variable.coarsen(
self.windows, func, self.boundary, self.side)
coords = {}
for c, v in self.obj.coords.items():
... | Return a wrapped function for injecting numpy methods.
see ops.inject_coarsen_methods |
340,110 | def show(self, obj):
if self.interactive:
if isinstance(obj, list):
return [self.get_plot(o) for o in obj]
return self.get_plot(obj)
from .plot import MPLPlot
MPLPlot._close_figures = False
try:
plots = []
objects ... | Renders the supplied object and displays it using the active
GUI backend. |
340,111 | def fit(self, X, u=None, sv=None, v=None):
if self.mode is :
Xall = X.copy()
X = np.reshape(Xall.copy(), (-1, Xall.shape[-1]))
if (u is None) or (sv is None) or (v is None):
init_sort = np.random.permutation(NN)[:,np.newaxis]
... | Fit X into an embedded space.
Parameters
----------
X : array, shape (n_samples, n_features)
y : Ignored |
340,112 | def clean_meta(meta, including_info=False, logger=None):
modified = set()
for key in meta.keys():
if [key] not in METAFILE_STD_KEYS:
if logger:
logger("Removing key %r..." % (key,))
del meta[key]
modified.add(key)
if including_info:
... | Clean meta dict. Optionally log changes using the given logger.
@param logger: If given, a callable accepting a string message.
@return: Set of keys removed from C{meta}. |
340,113 | def get_manifest(self, accept=MEDIA_TYPE_TAXII_V20, **filter_kwargs):
self._verify_can_read()
query_params = _filter_kwargs_to_query_params(filter_kwargs)
return self._conn.get(self.url + "manifest/",
headers={"Accept": accept},
... | Implement the ``Get Object Manifests`` endpoint (section 5.6). |
340,114 | def get_account_state(self, address, **kwargs):
return self._call(JSONRPCMethods.GET_ACCOUNT_STATE.value, params=[address, ], **kwargs) | Returns the account state information associated with a specific address.
:param address: a 34-bit length address (eg. AJBENSwajTzQtwyJFkiJSv7MAaaMc7DsRz)
:type address: str
:return: dictionary containing the account state information
:rtype: dict |
340,115 | def remove_cgc_attachments(self):
cgc_package_list = None
cgc_extended_application = None
for data in self.data:
if data.sort == :
cgc_package_list = data
elif data.sort == :
cgc_extended_application = data
if not cgc_pa... | Remove CGC attachments.
:return: True if CGC attachments are found and removed, False otherwise
:rtype: bool |
340,116 | def ximplot(ycut, title=None, show=True, plot_bbox=(0, 0),
geometry=(0, 0, 640, 480), tight_layout=True,
debugplot=None):
if type(ycut) is not np.ndarray:
raise ValueError("ycut=" + str(ycut) +
" must be a numpy.ndarray")
elif ycut.ndim is not ... | Auxiliary function to display 1d plot.
Parameters
----------
ycut : 1d numpy array, float
Array to be displayed.
title : string
Plot title.
show : bool
If True, the function shows the displayed image. Otherwise
plt.show() is expected to be executed outside.
plot_... |
340,117 | def _resnet_block(x, filters, kernel, stride, kernel_posterior_fn):
x = tf.keras.layers.BatchNormalization()(x)
x = tf.keras.layers.Activation()(x)
if stride != 1 or filters != x.shape[1]:
shortcut = _projection_shortcut(x, filters, stride, kernel_posterior_fn)
else:
shortcut = x
x = tfp.layers.C... | Network block for ResNet. |
340,118 | def enable_debug(self):
if not self.connected:
raise HardwareError("Cannot enable debug if we are not in a connected state")
self._loop.run_coroutine(self.adapter.open_interface(0, )) | Open the debug interface on the connected device. |
340,119 | def _apply_new_data_port_name(self, path, new_name):
try:
data_port_id = self.list_store[path][self.ID_STORAGE_ID]
if self.state_data_port_dict[data_port_id].name != new_name:
self.state_data_port_dict[data_port_id].name = new_name
except (TypeError, Valu... | Applies the new name of the data port defined by path
:param str path: The path identifying the edited data port
:param str new_name: New name |
340,120 | def clone_pod(self, source, dest, **kwargs):
data = {"source": source}
data.update(kwargs)
return self._request("POST", "pod/{0}".format(dest), data) | Clone an existing pod to a new one.
:param source: Name of the pod the be cloned.
:type source: str
:param dest: Name of the target pod to clone into
:type dest: str
:param \*\*kwargs: See the REST API Guide on your array for the
documentation on the r... |
340,121 | def map_2d_array_to_masked_1d_array(self, array_2d):
if array_2d is None or isinstance(array_2d, float):
return array_2d
return mapping_util.map_2d_array_to_masked_1d_array_from_array_2d_and_mask(self, array_2d) | For a 2D array (e.g. an image, noise_map, etc.) map it to a masked 1D array of valuees using this mask.
Parameters
----------
array_2d : ndarray | None | float
The 2D array to be mapped to a masked 1D array. |
340,122 | def urlize_tweet(tweet):
text = tweet.get(, tweet[])
for hash in tweet[][]:
text = text.replace( % hash[], TWITTER_HASHTAG_URL % (quote(hash[].encode("utf-8")), hash[]))
for mention in tweet[][]:
text = text.replace( % mention[], TWITTER_USERNAME_URL % (quote(mention[]), mention[]))
... | Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django. |
340,123 | def trim(self, start, end):
startend
self.seq = self.seq[start:len(self.seq) - end] | Removes first 'start'/'end' bases off the start/end of the sequence |
340,124 | def monthly_wind_dirs(self):
mwd = zip(*self._monthly_wind_dirs)
return [self._wind_dirs[mon.index(max(mon))] for mon in mwd] | A list of prevailing wind directions for each month. |
340,125 | def get(url, max_backoff=32, verbose=False, **kwargs):
sleep_seconds = 1
while sleep_seconds <= max_backoff:
try:
response = requests.get(url, **{**{: 30}, **kwargs})
if 400 <= response.status_code < 500:
return None
... | Adding retries to requests.get with exponential backoff.
Args:
url (str): The URL to fetch
max_backoff (int): The number of seconds to sleep at maximums
verbose (bool): Whether to print exceptions.
Returns:
Response: For successful requests return requests' response. `None` oth... |
340,126 | def _Liquid(T, P=0.1):
if T <= 253.15 or T >= 383.15 or P < 0.1 or P > 0.3:
raise NotImplementedError("Incoming out of bound")
elif P != 0.1:
warnings.warn("Using extrapolated values")
R = 0.46151805
Po = 0.1
Tr = 10
tau = T/Tr
alfa = Tr/(593-T)
bet... | 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
-------
prop : dict
Dict w... |
340,127 | def list(self, resource=None, sort=None):
schema = TagSchema()
resp = self.service.get(self.base, params={: resource, : sort})
return self.service.decode(schema, resp, many=True) | Get a list of tags.
:param resource: (optional) Restrict to given resource type as string.
:param sort: (optional) Sort fields to apply as string list.
:return: :class:`tags.Tag <tags.Tag>` list |
340,128 | def _load_calib(self):
| Load and compute intrinsic and extrinsic calibration parameters. |
340,129 | def token(self, adata, load):
try:
token = self.loadauth.get_tok(load[])
except Exception as exc:
log.error(, exc)
yield {}
if not token:
log.warning()
yield {}
for sub_auth in adata:
for sub_adata in adata:... | Determine if token auth is valid and yield the adata |
340,130 | def extend(self, namespace = None, name = None, **kwargs):
if name is None:
name = self._readablename
d = dict(self._values)
d.update(kwargs)
return enum(name, namespace, self, self._bitwise, **d) | Create a new enumerate with current values merged with new enumerate values
:param namespace: same as __init__
:param name: same as __init__
:param kwargs: same as __init__
:returns: a new enumerate type |
340,131 | def _translate_hits(es_response):
def translate_result(result):
translated_result = copy.copy(result)
data = translated_result.pop("_source")
translated_result.update({
"data": data,
"score": translated_result["_score"]
})
return trans... | Provide resultset in our desired format from elasticsearch results |
340,132 | def open_file_with_default_program(file_path,
background=False, return_cmd=False):
s preferred application.
Args:
file_path (str) : Path to the file to be opened.
background (bool): Run the program in the background, instead of waiting for completion. Defaults to ``False``.
return_cmd (bool): Re... | Opens a file with the default program for that type.
Open the file with the user's preferred application.
Args:
file_path (str) : Path to the file to be opened.
background (bool): Run the program in the background, instead of waiting for completion. Defaults to ``False``.
return_cmd (bool): Returns the co... |
340,133 | def to_numpy_matrix(self, variable_order=None):
import numpy as np
if variable_order is None:
num_variables = len(self)
mat = np.zeros((num_variables, num_variables), dtype=float)
try:
for v, bias in iteritems(self.binary.linear... | Convert a binary quadratic model to NumPy 2D array.
Args:
variable_order (list, optional):
If provided, indexes the rows/columns of the NumPy array. If `variable_order` includes
any variables not in the binary quadratic model, these are added to the NumPy array.
... |
340,134 | def mean(self, axis=0, *args, **kwargs):
nv.validate_mean(args, kwargs)
valid_vals = self._valid_sp_values
sp_sum = valid_vals.sum()
ct = len(valid_vals)
if self._null_fill_value:
return sp_sum / ct
else:
nsparse = self.sp_index.ngaps
... | Mean of non-NA/null values
Returns
-------
mean : float |
340,135 | def create_scree_plot(in_filename, out_filename, plot_title):
scree_plot_args = ("--evec", in_filename, "--out", out_filename,
"--scree-plot-title", plot_title)
try:
PlotEigenvalues.main(argString=scree_plot_args)
except PlotEigenvalues.ProgramError as e:
... | Creates a scree plot using smartpca results.
:param in_filename: the name of the input file.
:param out_filename: the name of the output file.
:param plot_title: the title of the scree plot.
:type in_filename: str
:type out_filename: str
:type plot_title: str |
340,136 | def _generate_message_error(cls, response_code, messages, response_id):
line_response_code = cls._FORMAT_RESPONSE_CODE_LINE \
.format(response_code)
line_response_id = cls._FORMAT_RESPONSE_ID_LINE.format(response_id)
line_error_message = cls._FORMAT_ERROR_MESSAGE_LINE.forma... | :type response_code: int
:type messages: list[str]
:type response_id: str
:rtype: str |
340,137 | def configure(logger=None, **kwargs):
configuration = Configuration.auto(**kwargs)
if logger is None:
logger = logging.getLogger()
configuration(logger) | Configures a logger, according to the following rules:
* With no options set, enables ``INFO`` level on stderr if stderr is a TTY;
otherwise enables ``INFO`` level to Syslog.
* With ``syslog=`` and/or ``stderr=``, configures as specified.
* With ``level=``, enables either Syslog or stderr logging a... |
340,138 | def compute_bundle(self, name, tdb, tdb2=0.0):
input_was_scalar = getattr(tdb, , ()) == ()
if input_was_scalar:
tdb = np.array((tdb,))
coefficient_sets = self.load(name)
number_of_sets, axis_count, coefficient_count = coefficient_sets.shape
jalpha,... | [DEPRECATED] Return a tuple of coefficients and parameters for `tdb`.
The return value is a tuple that bundles together the
coefficients and other Chebyshev intermediate values that are
needed for the computation of either the position or velocity.
The bundle can then be passed to eithe... |
340,139 | def validate(self):
depr = self._all_deprecated
return dict((key, val[1]) for key, val in
six.iteritems(self.defaultParams)
if key not in depr) | Dictionary with validation methods as values |
340,140 | def quote_selection(self):
selection = self.get_selection()
current_table = self.grid.current_table
for row, col, tab in self.grid.code_array.dict_grid.keys():
if tab == current_table and (row, col) in selection:
self.grid.actions.quote_code((row, col, tab))... | Quotes selected cells, marks content as changed |
340,141 | def iter_parts(self):
def walk_parts(source, visited=list()):
for rel in source.rels.values():
if rel.is_external:
continue
part = rel.target_part
if part in visited:
continue
visited.app... | Generate exactly one reference to each of the parts in the package by
performing a depth-first traversal of the rels graph. |
340,142 | def do_drink(self, arg):
try:
self.gold -= int(arg)
except ValueError:
if arg:
self.poutput(s "{0}"? I.format(arg))
self.gold -= 1 | Drown your sorrrows in rrrum.
drink [n] - drink [n] barrel[s] o' rum. |
340,143 | def _build_rdf(self, data=None):
self.rdf = SimpleNamespace()
self.rdf.data = data
self.rdf.prefixes = SimpleNamespace()
self.rdf.uris = SimpleNamespace()
for prefix,uri in self.repo.context.items():
setattr(self.rdf.prefixes, prefix, rdflib.Namespace(uri))
self._parse_graph() | Parse incoming rdf as self.rdf.orig_graph, create copy at self.rdf.graph
Args:
data (): payload from GET request, expected RDF content in various serialization formats
Returns:
None |
340,144 | def acquire(self, **kwargs):
return config.download_data(self.temp_filename, self.url,
self.sha256) | Download the file and return its path
Returns
-------
str or None
The path of the file in BatchUp's temporary directory or None if
the download failed. |
340,145 | def _generic_mixer(slice1, slice2, mixer_name, **kwargs):
mixer_name = mixer_name.lower()
if mixer_name in [, ]:
mixed = _mix_color(slice1, slice2, **kwargs)
cmap = None
elif mixer_name in [, , , ]:
checkers = _get_checkers(slice1.shape, **kwargs)
mixed = _checker_mix... | Generic mixer to process two slices with appropriate mixer
and return the composite to be displayed. |
340,146 | def rotate_du_by_yaw(self, du, heading):
mask = (self.pmts.du == du)
dom_ids = np.unique(self.pmts.dom_id[mask])
for dom_id in dom_ids:
self.rotate_dom_by_yaw(dom_id, heading)
self.reset_caches() | Rotate all DOMs on DU by a given (yaw) heading. |
340,147 | def load_ratings(data_home, size):
if size == :
with open(os.path.join(data_home, ), encoding=) as f:
lines = list(map(lambda l: list(map(int, l.rstrip().split())), f.readlines()))
elif size == :
with open(os.path.join(data_home, ), encoding=) as f:
lines = list(map... | Load all samples in the dataset. |
340,148 | def seek(self, position, whence=os.SEEK_SET):
_complain_ifclosed(self.closed)
return self.f.seek(position, whence) | Seek to ``position`` in file.
:type position: int
:param position: offset in bytes to seek to
:type whence: int
:param whence: defaults to ``os.SEEK_SET`` (absolute); other
values are ``os.SEEK_CUR`` (relative to the current position)
and ``os.SEEK_END`` (relative to... |
340,149 | def get_element_by_attr_key(self, attr_key, el_idx=0):
el_list = self.get_element_list_by_attr_key(attr_key)
try:
return el_list[el_idx]
except IndexError:
raise SimpleXMLWrapperException(
.format(attr_key, el_idx, len(el_list))
... | Args:
attr_key : str
Name of attribute for which to search
el_idx : int
Index of element to use as base in the event that there are multiple sibling
elements with the same name.
Returns:
Element containing an attribute key named ``attr_key``. |
340,150 | def which(cmd, safe=False):
from autopaths.file_path import FilePath
def is_executable(path):
return os.path.exists(path) and os.access(path, os.X_OK) and not os.path.isdir(path)
path, name = os.path.split(cmd)
if path:
if is_executable(cmd): return FilePath(cmd)
else:
f... | https://github.com/jc0n/python-which |
340,151 | def install():
file_created(fname) | Function executed when running the script with the -install switch |
340,152 | def stream_restore_delete(obj_name_or_list):
if is_str(obj_name_or_list, PulseExtStreamRestoreInfo):
obj_name_or_list = [obj_name_or_list]
name_list = list((obj.name if isinstance( obj,
PulseExtStreamRestoreInfo ) else obj) for obj in obj_name_or_list)
name_struct = (c.c_char_p * len(name_list))()
name... | Can be passed string name,
PulseExtStreamRestoreInfo object or a list of any of these. |
340,153 | def _UpdateYear(self, mediator, month):
if not self._year_use:
self._year_use = mediator.GetEstimatedYear()
if not self._maximum_year:
self._maximum_year = mediator.GetLatestYear()
if not self._last_month:
self._last_month = month
return
if self._last_month ... | Updates the year to use for events, based on last observed month.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
month (int): month observed by the parser, where January is 1. |
340,154 | def parse_job_files(self):
repo_jobs = []
for rel_job_file_path, job_info in self.job_files.items():
LOGGER.debug("Checking for job definitions in %s", rel_job_file_path)
jobs = self.parse_job_definitions(rel_job_file_path, job_info)
LOGGER.debug("Found %d jo... | Check for job definitions in known zuul files. |
340,155 | def transform(self, X=None, y=None):
shear = [math.pi / 180 * s for s in self.shear]
shear_x, shear_y = shear
shear_matrix = np.array([[1, shear_x, 0],
[shear_y, 1, 0]])
self.tx.set_parameters(shear_matrix)
if self.lazy or X is ... | Transform an image using an Affine transform with the given
shear parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
... |
340,156 | def prettify_object(obj):
try:
return pprint.pformat(str(obj))
except UnicodeDecodeError as e:
raise
except Exception as e:
return "[could not display: <%s: %s>]" % (e.__class__.__name__, str(e)) | Makes a pretty string for an object for nice output |
340,157 | def add_catalogue(self, catalogue, overlay=False):
min_latmax_latmin_lonmax_lon
con_min = np.where(np.array([symb[0] for symb in DEFAULT_SYMBOLOGY]) <
np.min(catalogue.data[]))[0]
con_max = np.where(np.array([symb[1] for symb in DEFAULT_SYMBO... | :param catalogue:
Earthquake catalogue as instance of
:class:`openquake.hmtk.seismicity.catalogue.Catalogue`
:param dict config:
Configuration parameters of the algorithm, containing the
following information:
'min_lat' Minimum value of latitude (in d... |
340,158 | def is_datafile_valid(datafile):
try:
datafile_json = json.loads(datafile)
except:
return False
try:
jsonschema.Draft4Validator(constants.JSON_SCHEMA).validate(datafile_json)
except:
return False
return True | Given a datafile determine if it is valid or not.
Args:
datafile: JSON string representing the project.
Returns:
Boolean depending upon whether datafile is valid or not. |
340,159 | def is_diagonal_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat)
if mat.ndim != 2:
return False
return np.allclose(mat, np.diag(np.diagonal(mat)), rtol=rtol, atol=atol) | Test if an array is a diagonal matrix |
340,160 | def server_close(self):
if self.remove_file:
try:
os.remove(self.remove_file)
except:
pass
self.socket.close() | Called to clean-up the server.
May be overridden. |
340,161 | def Entry(self, name, directory=None, create=1):
return self._create_node(name, self.env.fs.Entry, directory, create) | Create `SCons.Node.FS.Entry` |
340,162 | def saveCertPem(self, cert, path):
with s_common.genfile(path) as fd:
fd.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) | Save a certificate in PEM format to a file outside the certdir. |
340,163 | def mail_sent_contains_html(self):
for email in mail.outbox:
try:
html = next(content for content, mime in email.alternatives
if mime == )
dom1 = parse_html(html)
dom2 = parse_html(self.multiline)
assert_in(dom1, dom2)
e... | Test that an email contains the HTML (assert HTML in) in the multiline as
one of its MIME alternatives.
The HTML is normalised by passing through Django's
:func:`django.test.html.parse_html`.
Example:
.. code-block:: gherkin
And I have sent an email with the following HTML alternative:
... |
340,164 | def _on_entry(self, event):
contents = self._entry.get()
if contents == "":
return
try:
value = self._variable.set(int(contents))
except ValueError:
value = None
if not value:
self._on_scale(None) | Callback for the Entry widget, sets the Scale variable to the appropriate value.
:param event: Tkinter event |
340,165 | def welcome_page(self):
message = "HTTP/1.1 200 OK RINZLER FRAMEWORK"
return HttpResponse(
"<center><h1>{0}({1})</h1></center>".format(message, self.app.app_name),
content_type="text/html", charset="utf-8"
) | Defaulf welcome page when the route / is note mapped yet
:rtype: HttpResponse |
340,166 | def posterior_covariance_between_points(self, X1, X2):
return self.posterior.covariance_between_points(self.kern, self.X, X1, X2) | Computes the posterior covariance between points.
:param X1: some input observations
:param X2: other input observations |
340,167 | def load_tool(result):
def load_tool_module(tool_module):
if not tool_module:
logging.warning(
,
Util.prettylist(result.attributes[]))
return None
try:
logging.debug(, tool_module)
return __i... | Load the module with the tool-specific code. |
340,168 | def delete(filename, delete_v1=True, delete_v2=True):
f = open(filename, )
if delete_v1:
try:
f.seek(-128, 2)
except IOError:
pass
else:
if f.read(3) == b:
f.seek(-128, 2)
f.truncate()
if delete_v2:... | Remove tags from a file.
Keyword arguments:
* delete_v1 -- delete any ID3v1 tag
* delete_v2 -- delete any ID3v2 tag |
340,169 | def find_files_for_tar(self, context, silent_build):
if not context.enabled:
return
files = self.find_files(context, silent_build)
for path in files:
relname = os.path.relpath(path, context.parent_dir)
arcname = "./{0}".format(relname.encode().decod... | Return [(filename, arcname), ...] for all the files. |
340,170 | def request(self, *args, **kwargs):
try:
import settings
with open(os.path.join(settings.BASE_DIR, "keys.json")) as f:
keys = json.load(f)
privkey = keys["privkey"]
message = json.dumps(kwargs)
signature = Bip32Keys.sign_message(message, privkey)
result = super().request(method_name=kwargs... | Overrided method. Returns jsonrpc response
or fetches exception? returns appropriate data to client
and response mail to administrator. |
340,171 | def threshold(self, data, recall_weight=1.5):
blocked_pairs = self._blockData(data)
return self.thresholdBlocks(blocked_pairs, recall_weight) | Returns the threshold that maximizes the expected F score,
a weighted average of precision and recall for a sample of
data.
Arguments:
data -- Dictionary of records, where the keys are record_ids
and the values are dictionaries with the keys being
... |
340,172 | def isItemAllowed(self, obj):
if not obj:
return False
if obj.review_state == and \
not self.has_permission(ViewRetractedAnalyses):
return False
return True | Checks if the passed in Analysis must be displayed in the list.
:param obj: A single Analysis brain or content object
:type obj: ATContentType/CatalogBrain
:returns: True if the item can be added to the list.
:rtype: bool |
340,173 | def init_widget(self):
if not self.toast:
return
super(AndroidToast, self).init_widget()
d = self.declaration
if not self.made_toast:
self.toast.setDuration(1)
if d.gravity:
self.set_gravity(d.gravity)
if d.show:
... | Our widget may not exist yet so we have to diverge from the normal
way of doing initialization. See `update_widget` |
340,174 | def Verify(self):
if not self.Hash.ToBytes() == GetGenesis().Hash.ToBytes():
return False
bc = GetBlockchain()
if not bc.ContainsBlock(self.Index):
return False
if self.Index > 0:
prev_header = GetBlockchain().GetHeader(self.PrevHash.ToByte... | Verify block using the verification script.
Returns:
bool: True if valid. False otherwise. |
340,175 | def handleMessage(self, lmsg):
logger.debug(, self.state, lmsg)
msgName = lmsg.getName()
lmsg.proto = self
lmsg.peername = self.peername
logger.debug(, msgName)
for fn in self._message_callbacks[msgName]:
fn(lmsg)
logger.debug(, msgN... | Implements the LLRP client state machine. |
340,176 | def get_uncommon_items(pronac):
segment_id = get_segment_id(str(pronac))
seg_common_items = (
segment_common_items(segment_id)
.set_index()
.index
)
project_items = (
get_project_items(pronac)
.set_index()
.index
)
diff = list(project_items.d... | Return all uncommon items of a project
(related to segment common items). |
340,177 | def enable_model_triggers(self, state):
for node in foundations.walkers.nodes_walker(self.root_node):
node.trigger_model = state
for attribute in node.get_attributes():
attribute.trigger_model = state | Enables Model Nodes and attributes triggers.
:param state: Inform model state.
:type state: bool
:return: Method success.
:rtype: bool |
340,178 | def delete_certificate(self, certificate_id):
api = self._get_api(iam.DeveloperApi)
api.delete_certificate(certificate_id)
return | Delete a certificate.
:param str certificate_id: The certificate id (Required)
:returns: void |
340,179 | def validate_parameters(self):
for p in self.params:
if p not in self.known_params:
raise errors.UnknownParameter(p, self.known_params) | Validate that the parameters are correctly specified. |
340,180 | def decode_preflist(self, item):
result = {: item.partition,
: bytes_to_str(item.node),
: item. primary}
return result | Decodes a preflist response
:param preflist: a bucket/key preflist
:type preflist: list of
riak.pb.riak_kv_pb2.RpbBucketKeyPreflistItem
:rtype dict |
340,181 | def wait_functional(self):
while not self._is_functional():
self._rtt = None
self._ping_index += 1
self._ping_time = self._loop.time()
self._conn.ping(struct.pack(, self._ping_index))
self._flush()
try:
yield from a... | Wait until the connection becomes functional.
The connection is count functional if it was active within last few
seconds (defined by `functional_timeout`), where a newly-made
connection and received data indicate activeness.
:return: Most recently calculated round-trip time if any. |
340,182 | def handleTickOptionComputation(self, msg):
def calc_generic_val(data, field):
last_val = data[ + field].values[-1]
bid_val = data[ + field].values[-1]
ask_val = data[ + field].values[-1]
bid_ask_val = last_val
if bid_val != 0 and ask_val !=... | holds latest option data timestamp
only option price is kept at the moment
https://www.interactivebrokers.com/en/software/api/apiguide/java/tickoptioncomputation.htm |
340,183 | def list(self, cat, ctr=None, nb_results=None, offset=None):
path = LIST_URL + "?c=3&cat={}".format(requests.utils.quote(cat))
if ctr is not None:
path += "&ctr={}".format(requests.utils.quote(ctr))
if nb_results is not None:
path += "&n={}".format(requests.utils... | List all possible subcategories for a specific category. If
also a subcategory is provided, list apps from this category.
Args:
cat (str): category id
ctr (str): subcategory id
nb_results (int): if a subcategory is specified, limit number
of results t... |
340,184 | def sniff_field_spelling(mlog, source):
position_field_type_default = position_field_types[0]
msg = mlog.recv_match(source)
mlog._rewind()
position_field_selection = [spelling for spelling in position_field_types if hasattr(msg, spelling[0])]
return position_field_selection[0] if p... | attempt to detect whether APM or PX4 attributes names are in use |
340,185 | def cli_parse(parser):
parser.add_argument(, , type=int, required=True,
help=)
return parser | Add method specific options to CLI parser.
Parameters
----------
parser : argparse object
Returns
----------
Updated argparse object |
340,186 | async def connect(self, conn_id, connection_string):
id_number = int(connection_string)
if id_number not in self.devices:
raise DeviceAdapterError(conn_id, , )
if self._get_conn_id(connection_string) is not None:
raise DeviceAdapterError(conn_id, , )
d... | Asynchronously connect to a device
Args:
conn_id (int): A unique identifer that will refer to this connection
connection_string (string): A DeviceAdapter specific string that can be used to connect to
a device using this DeviceAdapter.
callback (callable): A ... |
340,187 | def docx_to_md(input_name, output_name):
if output_name[-5:] == :
os.system("pandoc " + input_name + " -o " + output_name)
else:
os.system("pandoc " + input_name + " -o " + output_name + ".docx" ) | Converts an input docx file to MarkDown file of the given output name.
Parameters
==========
input_name : String
Relative file location of the input file to where this function is being called.
output_name : String
Relative file location of the output file to where this function is being calle... |
340,188 | def _get_block_transactions(
self,
transaction_root: Hash32,
transaction_class: Type[]) -> Iterable[]:
for encoded_transaction in self._get_block_transaction_data(self.db, transaction_root):
yield rlp.decode(encoded_transaction, sedes=transaction_class) | Memoizable version of `get_block_transactions` |
340,189 | def args_from_interpreter_flags():
flag_opt_map = {
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
}
args = []
for flag, opt in flag_opt_map.items():
v = getattr(sys.flags, flag, 0)
if v > 0:
args.append( + opt... | Return a list of command-line arguments reproducing the current
settings in sys.flags and sys.warnoptions. |
340,190 | def sanitize_excel_sheet_name(sheet_name, replacement_text=""):
try:
unicode_sheet_name = _preprocess(sheet_name)
except AttributeError as e:
raise ValueError(e)
modify_sheet_name = __RE_INVALID_EXCEL_SHEET_NAME.sub(replacement_text, unicode_sheet_name)
return modify_sheet_name[:... | Replace invalid characters for an Excel sheet name within
the ``sheet_name`` with the ``replacement_text``.
Invalid characters are as follows:
|invalid_excel_sheet_chars|.
The ``sheet_name`` truncate to 31 characters
(max sheet name length of Excel) from the head, if the length
of the name is ex... |
340,191 | def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)... | Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f |
340,192 | def add_vts(self, task_name, targets, cache_key, valid, phase):
if task_name not in self._task_reports:
self.add_task(task_name)
self._task_reports[task_name].add(targets, cache_key, valid, phase) | Add a single VersionedTargetSet entry to the report.
:param InvalidationCacheManager cache_manager:
:param CacheKey cache_key:
:param bool valid:
:param string phase: |
340,193 | def sub(value, arg):
try:
return valid_numeric(value) - valid_numeric(arg)
except (ValueError, TypeError):
try:
return value - arg
except Exception:
return | Subtract the arg from the value. |
340,194 | def cleanup(self):
for path in self.paths:
if isinstance(path, tuple):
os.close(path[0])
os.unlink(path[1])
else:
shutil.rmtree(path)
self.paths = [] | Remove any created temp paths |
340,195 | def complete_all(self, pick_up=True, halt_on_manual=True):
while self.complete_next(pick_up, halt_on_manual):
pass | Runs all branches until completion. This is a convenience wrapper
around :meth:`complete_next`, and the pick_up argument is passed
along.
:type pick_up: bool
:param pick_up: Passed on to each call of complete_next().
:type halt_on_manual: bool
:param halt_on_manual: Wh... |
340,196 | def to_utf8(buf, errors=):
if isinstance(buf, unicode):
return buf.encode(, errors)
else:
return buf | Encodes a string into a UTF-8 compatible, ASCII string.
`buf`
string or unicode to convert.
Returns string.
* Raises a ``UnicodeEncodeError`` exception if encoding failed and
`errors` isn't set to 'replace'. |
340,197 | def p_object_field_list(self, p):
obj = p[1].copy()
obj.update(p[2])
p[0] = obj | object_field_list : object_field_list object_field |
340,198 | def _is_targeted_region(cur_bed, data):
cores = dd.get_num_cores(data)
if cores > 0:
return dd.get_coverage_interval(data) not in ["genome"]
else:
return coverage_interval_from_bed(cur_bed, per_chrom=False) == "targeted" | Calculate if we should process region as a targeted or WGS.
Currently always based on total coverage interval, as that validates best and
is consistent between CWL (larger blocks) and non-CWL runs (smaller blocks).
We can check core usage and provide a consistent report when moving to CWL
exclusively. |
340,199 | def read(self):
val = self._fd.read()
self._fd.seek(0)
return int(val) | Read pin value
@rtype: int
@return: I{0} when LOW, I{1} when HIGH |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.