Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
7,300 | def run(self, data, rewrap=False, prefetch=0):
if rewrap:
data = [data]
for _filter in self._filters:
_filter.feed(data)
data = _filter
else:
iterable = self._prefetch_callable(data, prefetch) if prefetch else data
for out_dat... | Wires the pipeline and returns a lazy object of
the transformed data.
:param data: must be an iterable, where a full document
must be returned for each loop
:param rewrap: (optional) is a bool that indicates the need to rewrap
data in cases where iterating over it produces unde... |
7,301 | def get_edge(self, edge_id):
try:
edge_object = self.edges[edge_id]
except KeyError:
raise NonexistentEdgeError(edge_id)
return edge_object | Returns the edge object identified by "edge_id". |
7,302 | def copy(self):
vec1 = np.copy(self.scoef1._vec)
vec2 = np.copy(self.scoef2._vec)
return VectorCoefs(vec1, vec2, self.nmax, self.mmax) | Make a deep copy of this object.
Example::
>>> c2 = c.copy() |
7,303 | def DiamAns(cmd, **fields):
upfields, name = getCmdParams(cmd, False, **fields)
p = DiamG(**upfields)
p.name = name
return p | Craft Diameter answer commands |
7,304 | def downstream(self, step_name):
return list(self.steps[dep] for dep in self.dag.downstream(step_name)) | Returns the direct dependencies of the given step |
7,305 | def git_get_title_and_message(begin, end):
titles = git_get_log_titles(begin, end)
title = "Pull request for " + end
if len(titles) == 1:
title = titles[0]
pr_template = find_pull_request_template()
if pr_template:
message = get_pr_template_message(pr_template)
else:
... | Get title and message summary for patches between 2 commits.
:param begin: first commit to look at
:param end: last commit to look at
:return: number of commits, title, message |
7,306 | def _intersect(start1, end1, start2, end2):
start = max(start1, start2)
end = min(end1, end2)
if start > end:
return None, None
return start, end | Returns the intersection of two intervals. Returns (None,None) if the intersection is empty.
:param int start1: The start date of the first interval.
:param int end1: The end date of the first interval.
:param int start2: The start date of the second interval.
:param int end2: The end d... |
7,307 | def assemble_to_object(self, in_filename, verbose=False):
file_base_name = os.path.splitext(os.path.basename(in_filename))[0]
out_filename, already_exists = self._get_intermediate_file(file_base_name + ,
binary=True,
... | Assemble *in_filename* assembly into *out_filename* object.
If *iaca_marked* is set to true, markers are inserted around the block with most packed
instructions or (if no packed instr. were found) the largest block and modified file is
saved to *in_file*.
*asm_block* controls how the t... |
7,308 | def deconstruct(self):
name, path, args, kwargs = super(
HStoreField, self).deconstruct()
if self.uniqueness is not None:
kwargs[] = self.uniqueness
if self.required is not None:
kwargs[] = self.required
return name, path, args, kwargs | Gets the values to pass to :see:__init__ when
re-creating this object. |
7,309 | def save(self, *args, **kwargs):
self.slug = slugify(self.name)
self.uid = .format(self.slug)
super(ElectionCycle, self).save(*args, **kwargs) | **uid**: :code:`cycle:{year}` |
7,310 | def _state_delete(self):
try:
os.remove(self._state_file)
except OSError as err:
if err.errno not in (errno.EPERM, errno.ENOENT):
raise
try:
os.rmdir(self._state_dir)
except OSError as err:
if err.errno not in (err... | Try to delete the state.yml file and the folder .blockade |
7,311 | def _check_response_status(self, response):
if response.status_code != requests.codes.ok:
self._logger.error("%s %s", response.status_code, response.text)
raise exceptions.RequestNonSuccessException(
"Url {0} had status_code {1}".format(
respo... | Checks the speficied HTTP response from the requests package and
raises an exception if a non-200 HTTP code was returned by the
server. |
7,312 | def corr_flat_und(a1, a2):
n = len(a1)
if len(a2) != n:
raise BCTParamError("Cannot calculate flattened correlation on "
"matrices of different size")
triu_ix = np.where(np.triu(np.ones((n, n)), 1))
return np.corrcoef(a1[triu_ix].flat, a2[triu_ix].flat)[0][1] | Returns the correlation coefficient between two flattened adjacency
matrices. Only the upper triangular part is used to avoid double counting
undirected matrices. Similarity metric for weighted matrices.
Parameters
----------
A1 : NxN np.ndarray
undirected matrix 1
A2 : NxN np.ndarray... |
7,313 | def time_range(self, start, end):
self._set_query(self.time_query, time_start=self._format_time(start),
time_end=self._format_time(end))
return self | Add a request for a time range to the query.
This modifies the query in-place, but returns `self` so that multiple queries
can be chained together on one line.
This replaces any existing temporal queries that have been set.
Parameters
----------
start : datetime.dateti... |
7,314 | def _construct_derivatives(self, coefs, **kwargs):
return [self.basis_functions.derivatives_factory(coef, **kwargs) for coef in coefs] | Return a list of derivatives given a list of coefficients. |
7,315 | def single_html(epub_file_path, html_out=sys.stdout, mathjax_version=None,
numchapters=None, includes=None):
epub = cnxepub.EPUB.from_file(epub_file_path)
if len(epub) != 1:
raise Exception()
package = epub[0]
binder = cnxepub.adapt_package(package)
partcount.update({}.... | Generate complete book HTML. |
7,316 | def writeToCheckpoint(self, checkpointDir):
proto = self.getSchema().new_message()
self.write(proto)
checkpointPath = self._getModelCheckpointFilePath(checkpointDir)
if os.path.exists(checkpointDir):
if not os.path.isdir(checkpointDir):
raise Exception(("Existing filesystem en... | Serializes model using capnproto and writes data to ``checkpointDir`` |
7,317 | def notify(self):
if self.__method is not None:
self.__method(self.__peer)
return True
return False | Calls the notification method
:return: True if the notification method has been called |
7,318 | def node_vectors(node_id):
exp = Experiment(session)
direction = request_parameter(parameter="direction", default="all")
failed = request_parameter(parameter="failed", parameter_type="bool", default=False)
for x in [direction, failed]:
if type(x) == Response:
return x
... | Get the vectors of a node.
You must specify the node id in the url.
You can pass direction (incoming/outgoing/all) and failed
(True/False/all). |
7,319 | def resolve_type(arg):
arg_type = type(arg)
if arg_type == list:
assert isinstance(arg, list)
sample = arg[:min(4, len(arg))]
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return ListType(... | Resolve object to one of our internal collection types or generic built-in type.
Args:
arg: object to resolve |
7,320 | def put(self, name, value):
pm = ndarray_to_mxarray(self._libmx, value)
self._libeng.engPutVariable(self._ep, name, pm)
self._libmx.mxDestroyArray(pm) | Put a variable to MATLAB workspace. |
7,321 | def notify(self, resource):
observers = self._observeLayer.notify(resource)
logger.debug("Notify")
for transaction in observers:
with transaction:
transaction.response = None
transaction = self._requestLayer.receive_request(transaction)
... | Notifies the observers of a certain resource.
:param resource: the resource |
7,322 | def getFailureMessage(failure):
str(failure.type)
failure.getErrorMessage()
if len(failure.frames) == 0:
return "failure %(exc)s: %(msg)s" % locals()
(func, filename, line, some, other) = failure.frames[-1]
filename = scrubFilename(filename)
return "failure %(exc)s at %(filename)s:... | Return a short message based on L{twisted.python.failure.Failure}.
Tries to find where the exception was triggered. |
7,323 | def to_html(data):
base_html_template = Template()
code = to_json(data, indent=4)
if PYGMENTS_INSTALLED:
c = Context({
: highlight(code, JSONLexer(), HtmlFormatter()),
: HtmlFormatter().get_style_defs()
})
html = base_html_template.render(c)
else:
... | Serializes a python object as HTML
This method uses the to_json method to turn the given data object into
formatted JSON that is displayed in an HTML page. If pygments in installed,
syntax highlighting will also be applied to the JSON. |
7,324 | def get_config_value(self, name, defaultValue):
self.send_get_config_value(name, defaultValue)
return self.recv_get_config_value() | Parameters:
- name
- defaultValue |
7,325 | def random(self, cascadeFetch=False):
matchedKeys = list(self.getPrimaryKeys())
obj = None
while matchedKeys and not obj:
key = matchedKeys.pop(random.randint(0, len(matchedKeys)-1))
obj = self.get(key, cascadeFetch=cascadeFetch)
return obj | Random - Returns a random record in current filterset.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched immediately. If False, foreign objects will be fetched on-access.
@return - Instance of Model object, or None if no items math current f... |
7,326 | def get_mac_addr(mac_addr):
mac_addr = bytearray(mac_addr)
mac = b.join([( % o).encode() for o in mac_addr])
return mac | converts bytes to mac addr format
:mac_addr: ctypes.structure
:return: str
mac addr in format
11:22:33:aa:bb:cc |
7,327 | def partof(self, ns1, id1, ns2, id2):
rel_fun = lambda node, graph: self.partof_objects(node)
return self.directly_or_indirectly_related(ns1, id1, ns2, id2,
self.partof_closure,
rel_fun) | Return True if one entity is "partof" another.
Parameters
----------
ns1 : str
Namespace code for an entity.
id1 : str
URI for an entity.
ns2 : str
Namespace code for an entity.
id2 : str
URI for an entity.
Returns... |
7,328 | def bck_from_spt (spt):
spt = np.asfarray (spt)
return np.piecewise (spt,
[spt < 30,
spt < 19,
spt <= 14,
spt < 10,
(spt < 2) | (spt >= 30)],
... | Calculate a bolometric correction constant for a J band magnitude based on
a spectral type, using the fits of Wilking+ (1999AJ....117..469W), Dahn+
(2002AJ....124.1170D), and Nakajima+ (2004ApJ...607..499N).
spt - Numerical spectral type. M0=0, M9=9, L0=10, ...
Returns: the correction `bck` such that ... |
7,329 | def liftover_to_genome(pass_pos, gtf):
fixed_pos = []
for pos in pass_pos:
if pos["chrom"] not in gtf:
continue
db_pos = gtf[pos["chrom"]][0]
mut = _parse_mut(pos["sv"])
print([db_pos, pos])
if db_pos[3] == "+":
pos[] = db_pos[1] + pos["pre_p... | Liftover from precursor to genome |
7,330 | def get_config(self):
config = {
: _serialize_function(self._make_distribution_fn),
: _serialize(self._convert_to_tensor_fn),
}
base_config = super(DistributionLambda, self).get_config()
return dict(list(base_config.items()) + list(config.items())) | Returns the config of this layer.
This Layer's `make_distribution_fn` is serialized via a library built on
Python pickle. This serialization of Python functions is provided for
convenience, but:
1. The use of this format for long-term storage of models is discouraged.
In particular, it may... |
7,331 | def maybeparens(lparen, item, rparen):
return item | lparen.suppress() + item + rparen.suppress() | Wrap an item in optional parentheses, only applying them if necessary. |
7,332 | async def _get_security_token(self) -> None:
_LOGGER.debug()
if self._credentials is None:
return
async with self._security_token_lock:
if self._security_token is None:
login_resp = await self._request(
,... | Request a security token. |
7,333 | def process_node(self, node, parent, end, open_list, open_value=True):
ng = self.calc_cost(parent, node)
if not node.opened or ng < node.g:
node.g = ng
node.h = node.h or \
self.apply_heuristic(node, end) * self.weight
n... | we check if the given node is path of the path by calculating its
cost and add or remove it from our path
:param node: the node we like to test
(the neighbor in A* or jump-node in JumpPointSearch)
:param parent: the parent node (the current node we like to test)
:param end: t... |
7,334 | def update_bounds(self, bounds):
self.bounds = np.array(bounds, dtype=)
vertices, directions = self._gen_bounds(self.bounds)
self._verts_vbo.set_data(vertices)
self._directions_vbo.set_data(directions)
self.widget.update() | Update the bounds inplace |
7,335 | def goto_step(self, inst: InstanceNode) -> InstanceNode:
return inst.look_up(**self.parse_keys(inst.schema_node)) | Return member instance of `inst` addressed by the receiver.
Args:
inst: Current instance. |
7,336 | def is_valid(self, qstr=None):
if qstr is None:
qstr = self.currentText()
return is_module_or_package(to_text_string(qstr)) | Return True if string is valid |
7,337 | def compose(request, recipient=None, form_class=ComposeForm,
template_name=, success_url=None, recipient_filter=None):
if request.method == "POST":
sender = request.user
form = form_class(request.POST, recipient_filter=recipient_filter)
if form.is_valid():
form.save(... | Displays and handles the ``form_class`` form to compose new messages.
Required Arguments: None
Optional Arguments:
``recipient``: username of a `django.contrib.auth` User, who should
receive the message, optionally multiple usernames
could be separated by a ... |
7,338 | def inference(self, kern_r, kern_c, Xr, Xc, Zr, Zc, likelihood, Y, qU_mean ,qU_var_r, qU_var_c, indexD, output_dim):
N, D, Mr, Mc, Qr, Qc = Y.shape[0], output_dim,Zr.shape[0], Zc.shape[0], Zr.shape[1], Zc.shape[1]
uncertain_inputs_r = isinstance(Xr, VariationalPosterior)
uncertain_inp... | The SVI-VarDTC inference |
7,339 | def json_template(data, template_name, template_context):
html = render_to_string(template_name, template_context)
data = data or {}
data[] = html
return HttpResponse(json_encode(data), content_type=) | Old style, use JSONTemplateResponse instead of this. |
7,340 | def _blast(bvname2vals, name_map):
if len(name_map) == 0:
return dict()
return fn.merge(*(dict(zip(names, bvname2vals[bvname]))
for bvname, names in name_map)) | Helper function to expand (blast) str -> int map into str ->
bool map. This is used to send word level inputs to aiger. |
7,341 | def search_accounts(self, **kwargs):
response = self.__requester.request(
,
,
_kwargs=combine_kwargs(**kwargs)
)
return response.json() | Return a list of up to 5 matching account domains. Partial matches on
name and domain are supported.
:calls: `GET /api/v1/accounts/search \
<https://canvas.instructure.com/doc/api/account_domain_lookups.html#method.account_domain_lookups.search>`_
:rtype: dict |
7,342 | def from_definition(self, table: Table, version: int):
self.table(table)
self.add_columns(*table.columns.get_with_version(version))
return self | Add all columns from the table added in the specified version |
7,343 | def _estimate_gas(self, initializer: bytes, salt_nonce: int,
payment_token: str, payment_receiver: str) -> int:
gas: int = self.proxy_factory_contract.functions.createProxyWithNonce(self.master_copy_address,
... | Gas estimation done using web3 and calling the node
Payment cannot be estimated, as no ether is in the address. So we add some gas later.
:param initializer: Data initializer to send to GnosisSafe setup method
:param salt_nonce: Nonce that will be used to generate the salt to calculate
t... |
7,344 | def items_iter(self, limit):
itemsitems
pages = (page.get() for page in self._pages())
items = itertools.chain.from_iterable(
(p[self.ITEM_KEY] for p in pages)
)
if limit is not None:
items = itertools.islice(items, limit)
return items | Get an iterator of the 'items' in each page. Instead of a feature
collection from each page, the iterator yields the features.
:param int limit: The number of 'items' to limit to.
:return: iter of items in page |
7,345 | def preprocess_data(self, div=1, downsample=0, sum_norm=None,
include_genes=None, exclude_genes=None,
include_cells=None, exclude_cells=None,
norm=, min_expression=1, thresh=0.01,
filter_genes=True):
... | Log-normalizes and filters the expression data.
Parameters
----------
div : float, optional, default 1
The factor by which the gene expression will be divided prior to
log normalization.
downsample : float, optional, default 0
The factor by which to... |
7,346 | def imresize(img, size, interpolate="bilinear", channel_first=False):
img = _imresize_before(img, size, channel_first,
interpolate, list(interpolations_map.keys()))
expand_flag = False
if len(img.shape) == 3 and img.shape[-1] == 1:
img = img.reshape(img.sha... | Resize image by pil module.
Args:
img (numpy.ndarray): Image array to save.
Image shape is considered as (height, width, channel) for RGB or (height, width) for gray-scale by default.
size (tupple of int): (width, height).
channel_first (bool):
This argument specifies... |
7,347 | def build_tf_to_pytorch_map(model, config):
tf_to_pt_map = {}
if hasattr(model, ):
tf_to_pt_map.update({
"transformer/adaptive_softmax/cutoff_0/cluster_W": model.crit.cluster_weight,
"transformer/adaptive_softmax/cutoff_0/cluster_b": model.crit.cluster_bias})
... | A map of modules from TF to PyTorch.
This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible. |
7,348 | def createphysicalnetwork(type, create_processor = partial(default_processor, excluding=(, )),
reorder_dict = default_iterate_dict):
def walker(walk, write, timestamp, parameters_dict):
for key, parameters in reorder_dict(parameters_dict):
try:
... | :param type: physical network type
:param create_processor: create_processor(physicalnetwork, walk, write, \*, parameters) |
7,349 | def energy_density(self, strain, convert_GPa_to_eV=True):
e_density = np.sum(self.calculate_stress(strain)*strain) / self.order
if convert_GPa_to_eV:
e_density *= self.GPa_to_eV_A3
return e_density | Calculates the elastic energy density due to a strain |
7,350 | def _folder_item_instrument(self, analysis_brain, item):
item[] =
if not analysis_brain.getInstrumentEntryOfResults:
item[] = _()
item[][] = \
.format(t(_()))
return
is_editable = self.is_analysis_edition_allowe... | Fills the analysis' instrument to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row |
7,351 | def formfield(self, form_class=None, choices_form_class=None, **kwargs):
defaults = {
: not self.blank,
: capfirst(self.verbose_name),
: self.help_text,
}
if self.has_default():
if callable(self.default):
defaults[] = self.... | Returns a django.forms.Field instance for this database Field. |
7,352 | def extendedboldqc(auth, label, scan_ids=None, project=None, aid=None):
.........AB1234C
if not aid:
aid = accession(auth, label, project)
path =
params = {
: ,
: .join(extendedboldqc.columns.keys())
}
if project:
params[] = project
params[] = aid
_,resul... | Get ExtendedBOLDQC data as a sequence of dictionaries.
Example:
>>> import yaxil
>>> import json
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> for eqc in yaxil.extendedboldqc2(auth, 'AB1234C')
... print(json.dumps(eqc, indent=2))
:param au... |
7,353 | def autosave_all(self):
for index in range(self.stack.get_stack_count()):
self.autosave(index) | Autosave all opened files. |
7,354 | def comment_form(context, object):
user = context.get("user")
form_class = context.get("form", CommentForm)
form = form_class(obj=object, user=user)
return form | Usage:
{% comment_form obj as comment_form %}
Will read the `user` var out of the contex to know if the form should be
form an auth'd user or not. |
7,355 | def render_image(**kwargs):
html =
url = kwargs.get(, None)
if url:
html =
alt_text = kwargs.get(, None)
if alt_text:
html += .format(alt_text)
title = kwargs.get(, None)
if title:
html += .format(title)
html += .format(url)
... | Unstrict template block for rendering an image:
<img alt="{alt_text}" title="{title}" src="{url}"> |
7,356 | def path_order (x, y):
if x == y:
return 0
xg = get_grist (x)
yg = get_grist (y)
if yg and not xg:
return -1
elif xg and not yg:
return 1
else:
if not xg:
x = feature.expand_subfeatures([x])
y = feature.expand_subfeatures([y])
... | Helper for as_path, below. Orders properties with the implicit ones
first, and within the two sections in alphabetical order of feature
name. |
7,357 | def _make_cloud_datastore_context(app_id, external_app_ids=()):
from . import model
if not datastore_pbs._CLOUD_DATASTORE_ENABLED:
raise datastore_errors.BadArgumentError(
datastore_pbs.MISSING_CLOUD_DATASTORE_MESSAGE)
import googledatastore
try:
from google.appengine.datastore import cl... | Creates a new context to connect to a remote Cloud Datastore instance.
This should only be used outside of Google App Engine.
Args:
app_id: The application id to connect to. This differs from the project
id as it may have an additional prefix, e.g. "s~" or "e~".
external_app_ids: A list of apps that... |
7,358 | def cyber_observable_check(original_function):
def new_function(*args, **kwargs):
if not has_cyber_observable_data(args[0]):
return
func = original_function(*args, **kwargs)
if isinstance(func, Iterable):
for x in original_function(*args, **kwargs):
... | Decorator for functions that require cyber observable data. |
7,359 | def get_warmer(self, doc_types=None, indices=None, name=None, querystring_args=None):
name = name or
if not querystring_args:
querystring_args = {}
doc_types_str =
if doc_types:
doc_types_str = + .join(doc_types)
path = .format(.join(indices), ... | Retrieve warmer
:param doc_types: list of document types
:param warmer: anything with ``serialize`` method or a dictionary
:param name: warmer name. If not provided, all warmers will be returned
:param querystring_args: additional arguments passed as GET params to ES |
7,360 | def _next_pattern(self):
current_state = self.state_stack[-1]
position = self._position
for pattern in self.patterns:
if current_state not in pattern.states:
continue
m = pattern.regex.match(self.source, position)
if not m:
... | Parses the next pattern by matching each in turn. |
7,361 | def _start_loop(self, websocket, event_handler):
log.debug()
while True:
try:
yield from asyncio.wait_for(
self._wait_for_message(websocket, event_handler),
timeout=self.options[]
)
except asyncio.TimeoutError:
yield from websocket.pong()
log.debug("Sending heartbeat...")
cont... | We will listen for websockets events, sending a heartbeat/pong everytime
we react a TimeoutError. If we don't the webserver would close the idle connection,
forcing us to reconnect. |
7,362 | def to_file(self, filename, format=, header=None, errors=False,
**kwargs):
if format is :
if errors is True and self.errors is None:
raise ValueError(
)
if self.omega is None:
omega = 0.
... | Save spherical harmonic coefficients to a file.
Usage
-----
x.to_file(filename, [format='shtools', header, errors])
x.to_file(filename, [format='npy', **kwargs])
Parameters
----------
filename : str
Name of the output file.
format : str, opti... |
7,363 | def clear(self):
self.root = None
for leaf in self.leaves:
leaf.p, leaf.sib, leaf.side = (None, ) * 3 | Clears the Merkle Tree by releasing the Merkle root and each leaf's references, the rest
should be garbage collected. This may be useful for situations where you want to take an existing
tree, make changes to the leaves, but leave it uncalculated for some time, without node
references that are ... |
7,364 | def uniqueify_all(init_reqs, *other_reqs):
union = set(init_reqs)
for reqs in other_reqs:
union.update(reqs)
return list(union) | Find the union of all the given requirements. |
7,365 | def msgDict(d,matching=None,sep1="=",sep2="\n",sort=True,cantEndWith=None):
msg=""
if "record" in str(type(d)):
keys=d.dtype.names
else:
keys=d.keys()
if sort:
keys=sorted(keys)
for key in keys:
if key[0]=="_":
continue
if matching:
... | convert a dictionary to a pretty formatted string. |
7,366 | def create_scoped_session(self, options=None):
if options is None:
options = {}
scopefunc = options.pop(, _app_ctx_stack.__ident_func__)
options.setdefault(, self.Query)
return orm.scoped_session(
self.create_session(options), scopefunc=scopefunc
... | Create a :class:`~sqlalchemy.orm.scoping.scoped_session`
on the factory from :meth:`create_session`.
An extra key ``'scopefunc'`` can be set on the ``options`` dict to
specify a custom scope function. If it's not provided, Flask's app
context stack identity is used. This will ensure th... |
7,367 | def select(self, key, where=None, start=None, stop=None, columns=None,
iterator=False, chunksize=None, auto_close=False, **kwargs):
group = self.get_node(key)
if group is None:
raise KeyError(.format(key=key))
where = _ensure_term(where, scope_level=... | Retrieve pandas object stored in file, optionally based on where
criteria
Parameters
----------
key : object
where : list of Term (or convertible) objects, optional
start : integer (defaults to None), row number to start selection
stop : integer (defaults to Non... |
7,368 | def save_to_local(self, callback_etat=print):
callback_etat("Aquisition...", 0, 3)
d = self.dumps()
s = json.dumps(d, indent=4, cls=formats.JsonEncoder)
callback_etat("Chiffrement...", 1, 3)
s = security.protege_data(s, True)
callback_etat("Enregistrement...", 2,... | Saved current in memory base to local file.
It's a backup, not a convenient way to update datas
:param callback_etat: state callback, taking str,int,int as args |
7,369 | def addchild(self, startip, endip, name, description):
add_child_ip_scope(self.auth, self.url, startip, endip, name, description, self.id) | Method takes inpur of str startip, str endip, name, and description and adds a child scope.
The startip and endip MUST be in the IP address range of the parent scope.
:param startip: str of ipv4 address of the first address in the child scope
:param endip: str of ipv4 address of the last address... |
7,370 | def generic_find_fk_constraint_names(table, columns, referenced, insp):
names = set()
for fk in insp.get_foreign_keys(table):
if fk[] == referenced and set(fk[]) == columns:
names.add(fk[])
return names | Utility to find foreign-key constraint names in alembic migrations |
7,371 | def parse(url):
result = urlparse.urlparse(nstr(url))
path = result.scheme + + result.netloc
if result.path:
path += result.path
query = {}
if result.query:
url_query = urlparse.parse_qs(result.query)
for key, value in url_query.items():
if type(valu... | Parses out the information for this url, returning its components
expanded out to Python objects.
:param url | <str>
:return (<str> path, <dict> query, <str> fragment) |
7,372 | def augment_audio_with_sox(path, sample_rate, tempo, gain):
with NamedTemporaryFile(suffix=".wav") as augmented_file:
augmented_filename = augmented_file.name
sox_augment_params = ["tempo", "{:.3f}".format(tempo), "gain", "{:.3f}".format(gain)]
sox_params = "sox \"{}\" -r {} -c 1 -b 16 ... | Changes tempo and gain of the recording with sox and loads it. |
7,373 | def get_title():
MAX_LEN = 256
buffer_ = create_unicode_buffer(MAX_LEN)
kernel32.GetConsoleTitleW(buffer_, MAX_LEN)
log.debug(, buffer_.value)
return buffer_.value | Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle |
7,374 | def check(self, order, sids):
payload = "{}"
raw_msg = self.client.blpop(self.channel, timeout=self.timeout)
if raw_msg:
_, payload = raw_msg
msg = json.loads(payload.replace(""utf-8ordering {} of {}skipping unknown symbol {}'.format(sid)) | Check if a message is available |
7,375 | def value(val, transform=None):
if transform:
return dict(value=val, transform=transform)
return dict(value=val) | Convenience function to explicitly return a "value" specification for
a Bokeh :class:`~bokeh.core.properties.DataSpec` property.
Args:
val (any) : a fixed value to specify for a ``DataSpec`` property.
transform (Transform, optional) : a transform to apply (default: None)
Returns:
... |
7,376 | def create_geom_filter(request, mapped_class, geom_attr):
tolerance = float(request.params.get(, 0.0))
epsg = None
if in request.params:
epsg = int(request.params[])
box = request.params.get()
shape = None
if box is not None:
box = [float(x) for x in box.split()]
sh... | Create MapFish geometry filter based on the request params. Either
a box or within or geometry filter, depending on the request params.
Additional named arguments are passed to the spatial filter.
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
geom_... |
7,377 | def getref():
ans=dict(graphtable=GRAPHTABLE,
comptable=COMPTABLE,
thermtable=THERMTABLE,
area=PRIMARY_AREA,
waveset=_default_waveset_str)
return ans | Current default values for graph and component tables, primary area,
and wavelength set.
.. note::
Also see :func:`setref`.
Returns
-------
ans : dict
Mapping of parameter names to their current values. |
7,378 | def build_board_checkers():
grd = Grid(8,8, ["B","W"])
for c in range(4):
grd.set_tile(0,(c*2) - 1, "B")
grd.set_tile(1,(c*2) - 0, "B")
grd.set_tile(6,(c*2) + 1, "W")
grd.set_tile(7,(c*2) - 0, "W")
print(grd)
return grd | builds a checkers starting board
Printing Grid
0 B 0 B 0 B 0 B
B 0 B 0 B 0 B 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 ... |
7,379 | def write_config(config_data: Dict[str, Path],
path: Path = None):
path = Path(path) if path else infer_config_base_dir()
valid_names = [ce.name for ce in CONFIG_ELEMENTS]
try:
os.makedirs(path, exist_ok=True)
with (path/_CONFIG_FILENAME).open() as base_f:
j... | Save the config file.
:param config_data: The index to save
:param base_dir: The place to save the file. If ``None``,
:py:meth:`infer_config_base_dir()` will be used
Only keys that are in the config elements will be saved. |
7,380 | def copy_fields(layer, fields_to_copy):
for field in fields_to_copy:
index = layer.fields().lookupField(field)
if index != -1:
layer.startEditing()
source_field = layer.fields().at(index)
new_field = QgsField(source_field)
new_field.setName(fie... | Copy fields inside an attribute table.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict |
7,381 | def main(sample_id, fastq_pair, gsize, minimum_coverage, opts):
logger.info("Starting integrity coverage main")
if "-e" in opts:
skip_encoding = True
else:
skip_encoding = False
gmin, gmax = 99, 0
encoding = []
phred = None
chars = 0
nreads = 0
... | Main executor of the integrity_coverage template.
Parameters
----------
sample_id : str
Sample Identification string.
fastq_pair : list
Two element list containing the paired FastQ files.
gsize : float or int
Estimate of genome size in Mb.
minimum_coverage : float or int... |
7,382 | def countries(self):
if self._countries is None:
self._countries = CountryList(self._version, )
return self._countries | Access the countries
:returns: twilio.rest.voice.v1.dialing_permissions.country.CountryList
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryList |
7,383 | def download(
self,
file: Union[IO[bytes], asyncio.StreamWriter, None]=None,
raw: bool=False, rewind: bool=True,
duration_timeout: Optional[float]=None):
if self._session_state != SessionState.request_sent:
raise RuntimeError()
if rew... | Read the response content into file.
Args:
file: A file object or asyncio stream.
raw: Whether chunked transfer encoding should be included.
rewind: Seek the given file back to its original offset after
reading is finished.
duration_timeout: Maxim... |
7,384 | def check(text):
err = "MSC104"
msg = u"Don't fail to capitalize roman numeral abbreviations."
pwd_regex = " (I(i*)|i*)"
password = [
"World War{}".format(pwd_regex),
]
return blacklist(text, password, err, msg) | Check the text. |
7,385 | def apply_noise(self, noise_weights=None, uniform_amount=0.1):
for node in self.node_list:
for link in node.link_list:
if noise_weights is not None:
noise_amount = round(weighted_rand(noise_weights), 3)
else:
n... | Add noise to every link in the network.
Can use either a ``uniform_amount`` or a ``noise_weight`` weight
profile. If ``noise_weight`` is set, ``uniform_amount`` will be
ignored.
Args:
noise_weights (list): a list of weight tuples
of form ``(float, float)`` c... |
7,386 | def raise_for_status(self):
if 400 <= self.status_code < 600:
message = % (self.status_code, self.url)
raise HTTPError(message) | Raises HTTPError if the request got an error. |
7,387 | def ensure_crops(self, *required_crops):
if self._can_crop():
if settings.CELERY or settings.USE_CELERY_DECORATOR:
args = [self.pk]+list(required_crops)
tasks.ensure_crops.apply_async(args=args, countdown=5)
else:
... | Make sure a crop exists for each crop in required_crops.
Existing crops will not be changed.
If settings.ASSET_CELERY is specified then
the task will be run async |
7,388 | def set_umr_namelist(self):
arguments, valid = QInputDialog.getText(self, _(),
_("Set the list of excluded modules as "
"this: <i>numpy, scipy</i>"),
QLineEdit.Normal,
... | Set UMR excluded modules name list |
7,389 | def connect(self):
if self.r_session:
self.session_logout()
if self.admin_party:
self._use_iam = False
self.r_session = ClientSession(
timeout=self._timeout
)
elif self._use_basic_auth:
self._use_iam = False
... | Starts up an authentication session for the client using cookie
authentication if necessary. |
7,390 | def GenerateLabels(self, hash_information):
if not hash_information:
return []
projects = []
tags = []
for project, entries in iter(hash_information.items()):
if not entries:
continue
projects.append(project)
for entry in entries:
if entry[]:
tag... | Generates a list of strings that will be used in the event tag.
Args:
hash_information (dict[str, object]): JSON decoded contents of the result
of a Viper lookup, as produced by the ViperAnalyzer.
Returns:
list[str]: list of labels to apply to events. |
7,391 | def convert_to_int(x: Any, default: int = None) -> int:
try:
return int(x)
except (TypeError, ValueError):
return default | Transforms its input into an integer, or returns ``default``. |
7,392 | def getBucketInfo(self, buckets):
if self.ncategories==0:
return 0
topDownMappingM = self._getTopDownMapping()
categoryIndex = buckets[0]
category = self.categories[categoryIndex]
encoding = topDownMappingM.getRow(categoryIndex)
return [EncoderResult(value=category, scalar=categor... | See the function description in base.py |
7,393 | def search_device_by_id(self, deviceID) -> Device:
for d in self.devices:
if d.id == deviceID:
return d
return None | searches a device by given id
Args:
deviceID(str): the device to search for
Returns
the Device object or None if it couldn't find a device |
7,394 | def mkdir(self, paths, create_parent=False, mode=0o755):
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("mkdirs: no path given")
for path in paths:
if not path.startswit... | Create a directoryCount
:param paths: Paths to create
:type paths: list of strings
:param create_parent: Also create the parent directories
:type create_parent: boolean
:param mode: Mode the directory should be created with
:type mode: int
:returns: a generator t... |
7,395 | def remote_pdb_handler(signum, frame):
try:
from remote_pdb import RemotePdb
rdb = RemotePdb(host="127.0.0.1", port=0)
rdb.set_trace(frame=frame)
except ImportError:
log.warning(
"remote_pdb unavailable. Please install remote_pdb to "
"allow remote ... | Handler to drop us into a remote debugger upon receiving SIGUSR1 |
7,396 | def _open_file(self, filename):
if not self._os_is_windows:
self._fh = open(filename, "rb")
self.filename = filename
self._fh.seek(0, os.SEEK_SET)
self.oldsize = 0
return
import win32file
import msvcrt
... | Open a file to be tailed |
7,397 | def read_until(self, marker):
if not isinstance(marker, byte_cls) and not isinstance(marker, Pattern):
raise TypeError(pretty_message(
,
type_name(marker)
))
output = b
is_regex = isinstance(marker, Pattern)
while True:... | Reads data from the socket until a marker is found. Data read includes
the marker.
:param marker:
A byte string or regex object from re.compile(). Used to determine
when to stop reading. Regex objects are more inefficient since
they must scan the entire byte string o... |
7,398 | async def ensure_usable_media(self, media: BaseMedia) -> UrlMedia:
if not isinstance(media, UrlMedia):
raise ValueError()
return media | So far, let's just accept URL media. We'll see in the future how it
goes. |
7,399 | def prop_budget(self, budget):
if self.minisat:
pysolvers.minisatgh_pbudget(self.minisat, budget) | Set limit on the number of propagations. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.