Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
11,100 | def block_html(self, html):
if self.options.get() and \
html.lower().startswith():
return
if self.options.get():
return escape(html)
return html | Rendering block level pure html content.
:param html: text content of the html snippet. |
11,101 | def run_single_with_display(wf, display):
S = Scheduler(error_handler=display.error_handler)
W = Queue() \
>> branch(log_job_start.to(sink_map(display))) \
>> worker \
>> branch(sink_map(display))
return S.run(W, get_workflow(wf)) | Adds a display to the single runner. Everything still runs in a single
thread. Every time a job is pulled by the worker, a message goes to the
display routine; when the job is finished the result is sent to the display
routine. |
11,102 | def uncrop(data, crinfo, orig_shape, resize=False, outside_mode="constant", cval=0):
if crinfo is None:
crinfo = list(zip([0] * data.ndim, orig_shape))
elif np.asarray(crinfo).size == data.ndim:
crinfo = list(zip(crinfo, np.asarray(crinfo) + data.shape))
crinfo = fix_crinfo(crinfo)
... | Put some boundary to input image.
:param data: input data
:param crinfo: array with minimum and maximum index along each axis
[[minX, maxX],[minY, maxY],[minZ, maxZ]]. If crinfo is None, the whole input image is placed into [0, 0, 0].
If crinfo is just series of three numbers, it is used as an... |
11,103 | def create_regular_expression(self, regexp):
for parameter in self.situation_context.situation_parameters:
if parameter.type == :
return self.add_parameter_value(
,
**{: parameter.href,
: regexp})
raise... | Create a regular expression for this inspection situation
context. The inspection situation must be using an inspection
context that supports regex.
:param str regexp: regular expression string
:raises CreateElementFailed: failed to modify the situation |
11,104 | def getfqdn(name=):
name = name.strip()
if not name or name == :
name = gethostname()
try:
hostname, aliases, ipaddrs = gethostbyaddr(name)
except error:
pass
else:
aliases.insert(0, hostname)
for name in aliases:
if in name:
... | Get fully qualified domain name from name.
An empty argument is interpreted as meaning the local host.
First the hostname returned by gethostbyaddr() is checked, then
possibly existing aliases. In case no FQDN is available, hostname
from gethostname() is returned. |
11,105 | def object(self, o_type, o_name=None):
o_found = self._get_object(o_type=o_type, o_name=o_name)
if not o_found:
return {: u, : u % o_type}
return o_found | Get an object from the scheduler.
The result is a serialized object which is a Json structure containing:
- content: the serialized object content
- __sys_python_module__: the python class of the returned object
The Alignak unserialize function of the alignak.misc.serialization package... |
11,106 | def add_mod(self, seq, mod):
modstr = self.value(mod)
if modstr == :
seq.parser_tree = parsing.Complement(seq.parser_tree)
elif modstr == :
seq.parser_tree = parsing.LookAhead(seq.parser_tree)
elif modstr == :
seq.parser_tree = parsing.Neg(seq.parser_tree)
elif modstr ==... | Create a tree.{Complement, LookAhead, Neg, Until} |
11,107 | def _setup_metric_group_values(self):
mg_defs = self._metrics_context.metric_group_definitions
metric_group_name = None
resource_uri = None
dt_timestamp = None
object_values = None
metric_group_values = list()
state = 0
for mr_line in self._met... | Return the list of MetricGroupValues objects for this metrics response,
by processing its metrics response string.
The lines in the metrics response string are::
MetricsResponse: MetricsGroup{0,*}
<emptyline> a third empty line at the end
Metr... |
11,108 | def project_from_files(
files, func_wrapper=_astroid_wrapper, project_name="no name", black_list=("CVS",)
):
astroid_manager = manager.AstroidManager()
project = Project(project_name)
for something in files:
if not os.path.exists(something):
fpath = modutils.file_from_modpa... | return a Project from a list of files or modules |
11,109 | def upload_file_handle(
self,
bucket: str,
key: str,
src_file_handle: typing.BinaryIO,
content_type: str=None,
metadata: dict=None):
raise NotImplementedError() | Saves the contents of a file handle as the contents of an object in a bucket. |
11,110 | def uninstall(self, package):
if isinstance(package, tuple):
package = .join(package)
if not self.is_installed(package):
self._write_to_log( % package)
return
try:
self._execute_pip([, , package])
except subprocess.CalledProcessErr... | Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment. |
11,111 | def delete(args):
m = TemplateManager(args.hosts)
m.delete(args.name) | Delete a template by name |
11,112 | def _scatter_obs(
adata,
x=None,
y=None,
color=None,
use_raw=None,
layers=,
sort_order=True,
alpha=None,
basis=None,
groups=None,
components=None,
projection=,
legend_loc=,
legend_fontsize=None,
legen... | See docstring of scatter. |
11,113 | def pkg_config_libdirs(packages):
if token.startswith("-L"):
libdirs.append(token[2:])
return libdirs | Returns a list of all library paths that pkg-config says should be included when
linking against the list of packages given as 'packages'. An empty return list means
that the package may be found in the standard system locations, irrespective of
pkg-config. |
11,114 | def children(self):
for c in self.table.columns:
if c.parent == self.name and not c.valuetype_class.is_label():
yield c | Return the table's other column that have this column as a parent, excluding labels |
11,115 | def format_lines(statements, lines):
pairs = []
i = 0
j = 0
start = None
statements = sorted(statements)
lines = sorted(lines)
while i < len(statements) and j < len(lines):
if statements[i] == lines[j]:
if start == None:
start = lines[j]
e... | Nicely format a list of line numbers.
Format a list of line numbers for printing by coalescing groups of lines as
long as the lines represent consecutive statements. This will coalesce
even if there are gaps between statements.
For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and
`lines... |
11,116 | def stage_config(self):
def get_stage_setting(stage, extended_stages=None):
if extended_stages is None:
extended_stages = []
if stage in extended_stages:
raise RuntimeError(stage + " has already been extended to these settings. "
... | A shortcut property for settings of a stage. |
11,117 | def _len_objid(self):
try:
return self._size
except AttributeError:
temp = (self.object_id, self.birth_vol_id, self.birth_object_id, self.birth_domain_id)
self._size = sum([ObjectID._UUID_SIZE for data in temp if data is not None])
return self._size | Get the actual size of the content, as some attributes have variable sizes |
11,118 | def _update_progress(self, percentage, **kwargs):
if self._show_progressbar:
if self._progressbar is None:
self._initialize_progressbar()
self._progressbar.update(percentage * 10000)
if self._progress_callback is not None:
self._progress_ca... | Update the progress with a percentage, including updating the progressbar as well as calling the progress
callback.
:param float percentage: Percentage of the progressbar. from 0.0 to 100.0.
:param kwargs: Other parameters that will be passed to the progress_callback handler.
... |
11,119 | def create_channel(
self, name, values=None, *, shape=None, units=None, dtype=None, **kwargs
) -> Channel:
if name in self.channel_names:
warnings.warn(name, wt_exceptions.ObjectExistsWarning)
return self[name]
elif name in self.variable_names:
ra... | Append a new channel.
Parameters
----------
name : string
Unique name for this channel.
values : array (optional)
Array. If None, an empty array equaling the data shape is
created. Default is None.
shape : tuple of int
Shape to use... |
11,120 | def choose(n, k):
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in xrange(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0 | A fast way to calculate binomial coefficients by Andrew Dalke (contrib). |
11,121 | def added_env_paths(env_vars, env=None):
if not env_vars:
return None
if not env:
env = dict(os.environ)
result = dict(env)
for env_var, paths in env_vars.items():
separator = paths[0]
paths = paths[1:]
current = env.get(env_var, "")
current = [x fo... | :param dict|None env_vars: Env vars to customize
:param dict env: Original env vars |
11,122 | def connect_put_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs):
kwargs[] = True
if kwargs.get():
return self.connect_put_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, **kwargs)
else:
(data) = self.connect_... | connect_put_namespaced_service_proxy_with_path # noqa: E501
connect PUT requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_namespaced_service_p... |
11,123 | def role_exists(role, **kwargs):
return len(tsql_query(query=.format(role), as_dict=True, **kwargs)) == 1 | Checks if a role exists.
CLI Example:
.. code-block:: bash
salt minion mssql.role_exists db_owner |
11,124 | def list_authors():
authors = Author.query.all()
content =
for author in authors:
content += % author.name
return content | List all authors.
e.g.: GET /authors |
11,125 | def poisson_equation(image, gradient=1, max_iter=100, convergence=.01, percentile = 90.0):
pe = np.zeros((image.shape[0]+2, image.shape[1]+2))
if image.shape[0] > 64 and image.shape[1] > 64:
sub_image = image[::2, ::2]
sub_pe = poisson_equation(sub_image,
... | Estimate the solution to the Poisson Equation
The Poisson Equation is the solution to gradient(x) = h^2/4 and, in this
context, we use a boundary condition where x is zero for background
pixels. Also, we set h^2/4 = 1 to indicate that each pixel is a distance
of 1 from its neighbors.
The estimatio... |
11,126 | def apply_parameters(self, parameters):
class SafeString(object):
def __init__(self, s):
self.string = s
def __repr__(self):
return "{" + self.string + "}"
def __str__(self):
return "{" + self.string + "}"
... | Recursively apply dictionary entries in 'parameters' to {item}s in recipe
structure, leaving undefined {item}s as they are. A special case is a
{$REPLACE:item}, which replaces the string with a copy of the referenced
parameter item.
Examples:
parameters = { 'x':'5' }
ap... |
11,127 | def _compute_sources_for_target(self, target):
def resolve_target_sources(target_sources):
resolved_sources = []
for tgt in target_sources:
if tgt.has_sources():
resolved_sources.extend(tgt.sources_relative_to_buildroot())
return resolved_sources
sources = [s for s in t... | Computes and returns the sources (relative to buildroot) for the given target. |
11,128 | def from_string(string):
lines = list(clean_lines(string.splitlines()))
def input_mode(line):
if line[0] == "&":
return ("sections", line[1:].lower())
elif "ATOMIC_SPECIES" in line:
return ("pseudo", )
elif "K_POINTS" in line:... | Reads an PWInput object from a string.
Args:
string (str): PWInput string
Returns:
PWInput object |
11,129 | def _from_dict(cls, _dict):
args = {}
if in _dict:
args[] = WorkspaceSystemSettingsTooling._from_dict(
_dict.get())
if in _dict:
args[
] = WorkspaceSystemSettingsDisambiguation._from_dict(
_dict.get())
... | Initialize a WorkspaceSystemSettings object from a json dictionary. |
11,130 | def update_settings(self, settings, force=False, timeout=-1):
data = settings.copy()
if in data:
ethernet_default_values = self._get_default_values(self.SETTINGS_ETHERNET_DEFAULT_VALUES)
data[] = merge_resources(data[],
... | Updates interconnect settings on the logical interconnect. Changes to interconnect settings are asynchronously
applied to all managed interconnects.
(This method is not available from API version 600 onwards)
Args:
settings: Interconnect settings
force: If set to true, th... |
11,131 | def get_html_string(self, **kwargs):
options = self._get_options(kwargs)
if options["format"]:
string = self._get_formatted_html_string(options)
else:
string = self._get_simple_html_string(options)
return string | Return string representation of HTML formatted version of table in current state.
Arguments:
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields - names of fields (columns) to include
header -... |
11,132 | def partial(self, *args):
def part(*args2):
args3 = args + args2
return self.obj(*args3)
return self._wrap(part) | Partially apply a function by creating a version that has had some of
its arguments pre-filled, without changing its dynamic `this` context. |
11,133 | def _CreateDatabase(self):
goodlogging.Log.Info("DB", "Initialising new database", verbosity=self.logVerbosity)
with sqlite3.connect(self._dbPath) as db:
db.execute("CREATE TABLE Config ("
"Name TEXT UNIQUE NOT NULL, "
"Value TEXT)")
db.execute("CREA... | Create all database tables. |
11,134 | def __getCashToBuyStock(self):
account=self.__strategy.getAccountCopy()
if (account.getCash() >= account.getTotalValue() / self.buying_ratio):
return account.getTotalValue() / self.buying_ratio
else:
return 0 | calculate the amount of money to buy stock |
11,135 | def write_main(self):
main_section =
main_header = self.write_main_header()
main_section = main_section + main_header
main_section = main_section +
wf_declarations_to_write = self.write_main_wfdeclarations()
main_section = main_section + wf... | Writes out a huge string representing the main section of the python
compiled toil script.
Currently looks at and writes 5 sections:
1. JSON Variables (includes importing and preparing files as tuples)
2. TSV Variables (includes importing and preparing files as tuples)
3. CSV Va... |
11,136 | def inferRowCompat(self, distribution):
if self.hack_ is None:
self.clean_outcpd()
return self.hack_.vecMaxProd(distribution) | Equivalent to the category inference of zeta1.TopLevel.
Computes the max_prod (maximum component of a component-wise multiply)
between the rows of the histogram and the incoming distribution.
May be slow if the result of clean_outcpd() is not valid.
:param distribution: Array of length equal to the num... |
11,137 | def compile_vocab(docs, limit=1e6, verbose=0, tokenizer=Tokenizer(stem=None, lower=None, strip=None)):
tokenizer = make_tokenizer(tokenizer)
d = Dictionary()
try:
limit = min(limit, docs.count())
docs = docs.iterator()
except (AttributeError, TypeError):
pass
for i, doc... | Get the set of words used anywhere in a sequence of documents and assign an integer id
This vectorizer is much faster than the scikit-learn version (and only requires low/constant RAM ?).
>>> gen = ('label: ' + chr(ord('A') + i % 3)*3 for i in range(11))
>>> d = compile_vocab(gen, verbose=0)
>>> d
... |
11,138 | def search_messages(session, thread_id, query, limit=20,
offset=0, message_context_details=None,
window_above=None, window_below=None):
query = {
: thread_id,
: query,
: limit,
: offset
}
if message_context_details:
query[]... | Search for messages |
11,139 | def prepare_dispatches():
dispatches = []
target_messages = Message.get_without_dispatches()
cache = {}
for message_model in target_messages:
if message_model.cls not in cache:
message_cls = get_registered_message_type(message_model.cls)
subscribers = message_cls.... | Automatically creates dispatches for messages without them.
:return: list of Dispatch
:rtype: list |
11,140 | def greaterThan(self, value):
newq = self.copy()
newq.setOp(Query.Op.GreaterThan)
newq.setValue(value)
return newq | Sets the operator type to Query.Op.GreaterThan and sets the
value to the inputted value.
:param value <variant>
:return <Query>
:sa __gt__
:usage |>>> from orb import Query as Q
|>>> query = Q('te... |
11,141 | def write_error(self, status_code, **kwargs):
if "exc_info" in kwargs:
exc_info = kwargs["exc_info"]
error = exc_info[1]
errormessage = "%s: %s" % (status_code, error)
self.render("error.html", errormessage=errormessage)
else:
errormessage = "%s" % (status_code)
self.re... | :param status_code:
:param kwargs:
:return: |
11,142 | def macontrol(self, data: [, str] = None,
ewmachart: str = None,
machart: str = None,
procopts: str = None,
stmtpassthrough: str = None,
**kwargs: dict) -> :
| Python method to call the MACONTROL procedure
Documentation link:
https://go.documentation.sas.com/?cdcId=pgmsascdc&cdcVersion=9.4_3.4&docsetId=qcug&docsetTarget=qcug_macontrol_toc.htm&locale=en
:param data: SASdata object or string. This parameter is required.
:parm ewmachart: The ewm... |
11,143 | def get_edit_token(self):
if not self.edit_token or (time.time() - self.instantiation_time) > self.token_renew_period:
self.generate_edit_credentials()
self.instantiation_time = time.time()
return self.edit_token | Can be called in order to retrieve the edit token from an instance of WDLogin
:return: returns the edit token |
11,144 | async def disconnect(self):
self._is_shutdown = True
self.ready.clear()
self.update_state(NodeState.DISCONNECTING)
await self.player_manager.disconnect()
if self._ws is not None and self._ws.open:
await self._ws.close()
if self._listener_task is n... | Shuts down and disconnects the websocket. |
11,145 | def lvscan(self):
self.open()
lv_list = []
lv_handles = lvm_vg_list_lvs(self.handle)
if not bool(lv_handles):
return lv_list
lvh = dm_list_first(lv_handles)
while lvh:
c = cast(lvh, POINTER(lvm_lv_list))
lv = LogicalVolume(self... | Probes the volume group for logical volumes and returns a list of
LogicalVolume instances::
from lvm2py import *
lvm = LVM()
vg = lvm.get_vg("myvg")
lvs = vg.lvscan()
*Raises:*
* HandleError |
11,146 | def save(self, filename=None, *, gzipped=None, byteorder=None):
if gzipped is None:
gzipped = self.gzipped
if filename is None:
filename = self.filename
if filename is None:
raise ValueError()
open_file = gzip.open if gzipped else ... | Write the file at the specified location.
The `gzipped` keyword only argument indicates if the file should
be gzipped. The `byteorder` keyword only argument lets you
specify whether the file should be big-endian or little-endian.
If the method is called without any argument, it w... |
11,147 | def server_exists(s_name, ip=None, s_state=None, **connection_args):
*serverName
server = _server_get(s_name, **connection_args)
if server is None:
return False
if ip is not None and ip != server.get_ipaddress():
return False
if s_state is not None and s_state.upper() != server.get_s... | Checks if a server exists
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_exists 'serverName' |
11,148 | def _map_block_index_to_location(ir_blocks):
block_index_to_location = {}
current_block_ixs = []
for num, ir_block in enumerate(ir_blocks):
if isinstance(ir_block, blocks.GlobalOperationsStart):
if len(current_block_ixs) > 0:
unassociated_blocks = [ir_... | Associate each IR block with its corresponding location, by index. |
11,149 | def save_anim(self, fig, animate, init, bitrate=10000, fps=30):
from matplotlib import animation
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20)
FFMpegWriter = animation.writers[]
writer = FFMpegWriter(bitrate= bitrate, fps=fps)
... | Not functional -- TODO |
11,150 | def count(self):
if self._total_count is None:
self._total_count = self._get_total_count()
return self._total_count | Approximate number of results, according to the API |
11,151 | def fetch(self, start=False, full_data=True):
if self.id is None:
return self
if full_data is True:
fields = None
elif isinstance(full_data, dict):
fields = full_data
else:
fields = {
"_id": 0,
"pa... | Get the current job data and possibly flag it as started. |
11,152 | def personal_sign(self, message, account, password=None):
return (yield from self.rpc_call(,
[message, account, password])) | https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
:param message: Message for sign
:type message: str
:param account: Account address
:type account: str
:param password: Password of account (optional)
:type password: str
:return: signa... |
11,153 | def _cut_to_pieces(self, bunch_stack):
stack_len = len(bunch_stack[0])
for i in xrange(0, stack_len, self.fragment_length):
yield np.array(map(lambda stack: stack[i: i + self.fragment_length], bunch_stack)) | :type bunch_stack: list of list of int |
11,154 | async def setup_hostname() -> str:
machine_id = open().read().strip()
hostname = machine_id[:6]
with open(, ) as ehn:
ehn.write(f)
LOG.debug("Setting hostname")
proc = await asyncio.create_subprocess_exec(
, , ,
stdout=asyncio.subprocess.PIPE, stderr=asyn... | Intended to be run when the server starts. Sets the machine hostname.
The machine hostname is set from the systemd-generated machine-id, which
changes at every boot.
Once the hostname is set, we restart avahi.
This is a separate task from establishing and changing the opentrons
machine name, whic... |
11,155 | def sign(self, value):
value = want_bytes(value)
timestamp = base64_encode(int_to_bytes(self.get_timestamp()))
sep = want_bytes(self.sep)
value = value + sep + timestamp
return value + sep + self.get_signature(value) | Signs the given string and also attaches a time information. |
11,156 | def modification_time(self):
timestamp = getattr(
self._cpio_archive_file_entry, , None)
if timestamp is None:
return None
return dfdatetime_posix_time.PosixTime(timestamp=timestamp) | dfdatetime.DateTimeValues: modification time or None if not available. |
11,157 | def register_type(self, typename):
typekey = typehash(typename)
if typekey in self._type_register:
raise ValueError("Type name collision. Type %s has the same hash." % repr(self._type_register[typekey]))
self._type_register[typekey] = typename | Registers a type name so that it may be used to send and receive packages.
:param typename: Name of the packet type. A method with the same name and a
"on_" prefix should be added to handle incomming packets.
:raises ValueError: If there is a hash code collision. |
11,158 | def issue_instant_ok(self):
upper = time_util.shift_time(time_util.time_in_a_while(days=1),
self.timeslack).timetuple()
lower = time_util.shift_time(time_util.time_a_while_ago(days=1),
-self.timeslack).timetuple()
... | Check that the response was issued at a reasonable time |
11,159 | def is_script(self, container):
try:
style = self._style(container)
return style.get_value(,
container) != TextPosition.NORMAL
except StyleException:
return False | Returns `True` if this styled text is super/subscript. |
11,160 | def _parse_proxy(proxy):
scheme, r_scheme = splittype(proxy)
if not r_scheme.startswith("/"):
scheme = None
authority = proxy
else:
if not r_scheme.startswith("//"):
raise ValueError("proxy URL with no authority: %r" % proxy)
... | Return (scheme, user, password, host/port) given a URL or an authority.
If a URL is supplied, it must have an authority (host:port) component.
According to RFC 3986, having an authority component means the URL must
have two slashes after the scheme:
>>> _parse_proxy('file:/ftp.example.com/')
Trace... |
11,161 | def wait_for_current_tasks(self):
logger.info("Waiting for all remaining tasks to complete")
for task_id in self.tasks:
fut = self.tasks[task_id][]
if not fut.done():
logger.debug("Waiting for task {} to complete".format(task_id... | Waits for all tasks in the task list to be completed, by waiting for their
AppFuture to be completed. This method will not necessarily wait for any tasks
added after cleanup has started (such as data stageout?) |
11,162 | def symmetry_reduce(tensors, structure, tol=1e-8, **kwargs):
sga = SpacegroupAnalyzer(structure, **kwargs)
symmops = sga.get_symmetry_operations(cartesian=True)
unique_mapping = TensorMapping([tensors[0]], [[]], tol=tol)
for tensor in tensors[1:]:
is_unique = True
for unique_tensor,... | Function that converts a list of tensors corresponding to a structure
and returns a dictionary consisting of unique tensor keys with symmop
values corresponding to transformations that will result in derivative
tensors from the original list
Args:
tensors (list of tensors): list of Tensor objec... |
11,163 | def point_in_segment(ac, b):
onin
(a,c) = ac
abc = [np.asarray(u) for u in (a,b,c)]
if any(len(u.shape) > 1 for u in abc): (a,b,c) = [np.reshape(u,(len(u),-1)) for u in abc]
else: (a,b,c) = abc
vab = b - a
vbc = c - b
vac = c - a
dab = np.sqrt(np.sum(... | point_in_segment((a,b), c) yields True if point x is in segment (a,b) and False otherwise. Note
that this differs from point_on_segment in that a point that if c is equal to a or b it is
considered 'on' but not 'in' the segment. |
11,164 | def count_collisions(Collisions):
CollisionCount = 0
CollisionIndicies = []
lastval = True
for i, val in enumerate(Collisions):
if val == True and lastval == False:
CollisionIndicies.append(i)
CollisionCount += 1
lastval = val
return CollisionCount, Colli... | Counts the number of unique collisions and gets the collision index.
Parameters
----------
Collisions : array_like
Array of booleans, containing true if during a collision event, false otherwise.
Returns
-------
CollisionCount : int
Number of unique collisions
CollisionIndi... |
11,165 | def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_i... | Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup |
11,166 | def print_results(self):
if self.package_data.get():
print(.format(c.Style.BRIGHT, c.Fore.BLUE))
for p in self.package_data[]:
print(
.format(
p.get(), c.Style.BRIGHT, c.Fore.CYAN, p.get()
)... | Print results of the package command. |
11,167 | def NDP_Attack_DAD_DoS_via_NA(iface=None, mac_src_filter=None, tgt_filter=None,
reply_mac=None):
def na_reply_callback(req, reply_mac, iface):
mac = req[Ether].src
dst = req[IPv6].dst
tgt = req[ICMPv6ND_NS].tgt
rep = Ether(src=re... | Perform the DAD DoS attack using NS described in section 4.1.3 of RFC
3756. This is done by listening incoming NS messages *sent from the
unspecified address* and sending a NA reply for the target address,
leading the peer to believe that another node is also performing DAD
for that address.
By def... |
11,168 | def cover(self, match_set):
assert isinstance(match_set, MatchSet)
assert match_set.model.algorithm is self
condition = bitstrings.BitCondition.cover(
match_set.situation,
self.wildcard_probability
)
action_candidates... | Return a new classifier rule that can be added to the match set,
with a condition that matches the situation of the match set and an
action selected to avoid duplication of the actions already
contained therein. The match_set argument is a MatchSet instance
representing the match set to ... |
11,169 | def matching_tokens(self, text, start=0):
for token_class, regexp in self._tokens:
match = regexp.match(text, pos=start)
if match:
yield token_class, match | Retrieve all token definitions matching the beginning of a text.
Args:
text (str): the text to test
start (int): the position where matches should be searched in the
string (see re.match(rx, txt, pos))
Yields:
(token_class, re.Match): all token class... |
11,170 | def install(args: List[str]) -> None:
with clean_pip_env():
subprocess_env = os.environ.copy()
sitedir_index = _first_sitedir_index()
_extend_python_path(subprocess_env, sys.path[sitedir_index:])
process = subprocess.Popen(
[sys.executabl... | `pip install` as a function.
Accepts a list of pip arguments.
.. code-block:: py
>>> install(['numpy', '--target', 'site-packages'])
Collecting numpy
Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB)
100% || 16.9MB 53kB/s
Installing collected packa... |
11,171 | def build_index_from_design(df, design, remove_prefix=None, types=None, axis=1, auto_convert_numeric=True, unmatched_columns=):
df = df.copy()
if not in design.index.names:
design = design.set_index()
if remove_prefix is None:
remove_prefix = []
if type(remove_prefix) is str:
... | Build a MultiIndex from a design table.
Supply with a table with column headings for the new multiindex
and a index containing the labels to search for in the data.
:param df:
:param design:
:param remove:
:param types:
:param axis:
:param auto_convert_numeric:
:return: |
11,172 | def ics2task():
from argparse import ArgumentParser, FileType
from sys import stdin
parser = ArgumentParser(description=)
parser.add_argument(, nargs=, type=FileType(), default=stdin,
help=)
parser.add_argument(, nargs=, help=, default=expanduser())
args = parser.pa... | Command line tool to convert from iCalendar to Taskwarrior |
11,173 | def _addToSegmentUpdates(self, c, i, segUpdate):
if segUpdate is None or len(segUpdate.activeSynapses) == 0:
return
key = (c, i)
if self.segmentUpdates.has_key(key):
self.segmentUpdates[key] += [(self.lrnIterationIdx, segUpdate)]
else:
self.segmentUpdates[key] = ... | Store a dated potential segment update. The "date" (iteration index) is used
later to determine whether the update is too old and should be forgotten.
This is controlled by parameter ``segUpdateValidDuration``.
:param c: TODO: document
:param i: TODO: document
:param segUpdate: TODO: document |
11,174 | def obj_box_zoom(
im, classes=None, coords=None, zoom_range=(0.9,
1.1), row_index=0, col_index=1, channel_index=2, fill_mode=,
cval=0., order=1, is_rescale=False, is_center=False, is_random=False, thresh_wh=0.02, thresh_wh2=12.
):
if classes is... | Zoom in and out of a single image, randomly or non-randomly, and compute the new bounding box coordinates.
Objects outside the cropped image will be removed.
Parameters
-----------
im : numpy.array
An image with dimension of [row, col, channel] (default).
classes : list of int or None
... |
11,175 | def concentric_circles_path(size):
width, height = size
x0, y0 = width // 2, height // 2
max_radius = int(sqrt(2) * max(height, width))
yield from fill_concentric_circles(radius=max_radius, center=(x0, y0), size=size) | Yields a set of paths that are concentric circles, moving outwards, about the center of the image.
:param size: The (width, height) of the image
:return: Yields individual circles, where each circle is a generator that yields pixel coordinates. |
11,176 | def getOverlayInputMethod(self, ulOverlayHandle):
fn = self.function_table.getOverlayInputMethod
peInputMethod = VROverlayInputMethod()
result = fn(ulOverlayHandle, byref(peInputMethod))
return result, peInputMethod | Returns the current input settings for the specified overlay. |
11,177 | def str(self, var, default=NOTSET, multiline=False):
value = self.get_value(var, default=default)
if multiline:
return value.replace(, )
return value | :rtype: str |
11,178 | def decompose_by_component(model, observed_time_series, parameter_samples):
with tf.compat.v1.name_scope(,
values=[observed_time_series]):
[
observed_time_series,
is_missing
] = sts_util.canonicalize_observed_time_series_with_mask(
observed_time_serie... | Decompose an observed time series into contributions from each component.
This method decomposes a time series according to the posterior represention
of a structural time series model. In particular, it:
- Computes the posterior marginal mean and covariances over the additive
model's latent space.
-... |
11,179 | def img2img_transformer2d_n31():
hparams = img2img_transformer2d_base()
hparams.batch_size = 1
hparams.num_encoder_layers = 6
hparams.num_decoder_layers = 12
hparams.num_heads = 8
hparams.query_shape = (16, 32)
hparams.memory_flange = (16, 32)
return hparams | Set of hyperparameters. |
11,180 | def parse_media_range(range):
(type, subtype, params) = parse_mime_type(range)
if not in params or not params[] or \
float(params[]) > 1 or float(params[]) < 0:
params[] =
return (type, subtype, params) | Carves up a media range and returns a tuple of the
(type, subtype, params) where 'params' is a dictionary
of all the parameters for the media range.
For example, the media range 'application/*;q=0.5' would
get parsed into:
('application', '*', {'q', '0.5'})
In addition this f... |
11,181 | def add_node(self, info):
if not info.initialized:
return
graph = self._request_graph(info.ui.control)
if graph is None:
return
IDs = [v.ID for v in graph.nodes]
node = Node(ID=make_unique_name("node", IDs))
graph.nodes.append(node)
... | Handles adding a Node to the graph. |
11,182 | def check(self, completed, failed=None):
if len(self) == 0:
return True
against = set()
if self.success:
against = completed
if failed is not None and self.failure:
against = against.union(failed)
if self.all:
return self.i... | check whether our dependencies have been met. |
11,183 | def init():
cwd = _getcwd()
res = _glfw.glfwInit()
os.chdir(cwd)
return res | Initializes the GLFW library.
Wrapper for:
int glfwInit(void); |
11,184 | def _get_struct_dropshadowfilter(self):
obj = _make_object("DropShadowFilter")
obj.DropShadowColor = self._get_struct_rgba()
obj.BlurX = unpack_fixed16(self._src)
obj.BlurY = unpack_fixed16(self._src)
obj.Angle = unpack_fixed16(self._src)
obj.Distance = unpack_fi... | Get the values for the DROPSHADOWFILTER record. |
11,185 | def setattr(self, name, val):
nodes = self._do_query(multiple=False)
try:
return self.poco.agent.hierarchy.setAttr(nodes, name, val)
except UnableToSetAttributeException as e:
raise InvalidOperationException(.format(str(e), self)) | Change the attribute value of the UI element. Not all attributes can be casted to text. If changing the
immutable attributes or attributes which do not exist, the InvalidOperationException exception is raised.
Args:
name: attribute name
val: new attribute value to cast
... |
11,186 | def _set_lldp(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=lldp.lldp, is_container=, presence=True, yang_name="lldp", rest_name="lldp", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u:... | Setter method for lldp, mapped from YANG variable /protocol/lldp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_lldp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_lldp() directly. |
11,187 | def list_overlay_names(self):
overlay_names = []
for fname in _ls(self._overlays_abspath):
name, ext = os.path.splitext(fname)
overlay_names.append(name)
return overlay_names | Return list of overlay names. |
11,188 | def read_client_secrets():
client_secrets = _default_client_secrets()
secrets = get_secrets_file()
if secrets is not None:
client_secrets = read_json(secrets)
else:
from sregistry.defaults import SREGISTRY_CLIENT_SECRETS
write_json(client_secrets, SREGISTRY... | for private or protected registries, a client secrets file is required
to be located at .sregistry. If no secrets are found, we use default
of Singularity Hub, and return a dummy secrets. |
11,189 | def infos(self, type=None, failed=False):
nodes = self.nodes(failed="all")
infos = []
for n in nodes:
infos.extend(n.infos(type=type, failed=failed))
return infos | Get all infos created by the participants nodes.
Return a list of infos produced by nodes associated with the
participant. If specified, ``type`` filters by class. By default, failed
infos are excluded, to include only failed nodes use ``failed=True``,
for all nodes use ``failed=all``. ... |
11,190 | def build_message(self, checker):
solution = % checker.solution if self.with_solutions else
return .format(checker.code,
checker.msg,
solution) | Builds the checker's error message to report |
11,191 | def filter_composite_from_subgroups(s):
dims = []
for letter, sg in zip(, s[2:]):
dims.append(.format(letter))
if dims:
return .join(dims) | Given a sorted list of subgroups, return a string appropriate to provide as
the a composite track's `filterComposite` argument
>>> import trackhub
>>> trackhub.helpers.filter_composite_from_subgroups(['cell', 'ab', 'lab', 'knockdown'])
'dimA dimB'
Parameters
----------
s : list
A l... |
11,192 | def status_counter(self):
counter = collections.Counter()
for task in self:
counter[str(task.status)] += 1
return counter | Returns a `Counter` object that counts the number of task with
given status (use the string representation of the status as key). |
11,193 | def get_reference_line_numeration_marker_patterns(prefix=u):
title = u""
if type(prefix) in (str, unicode):
title = prefix
g_name = u
g_close = u
space = r
patterns = [
space + title + g_name + r + g_close,
space + title + g_name + r + g_close,
... | Return a list of compiled regex patterns used to search for the marker.
Marker of a reference line in a full-text document.
:param prefix: (string) the possible prefix to a reference line
:return: (list) of compiled regex patterns. |
11,194 | def gather_dilated_memory_blocks(x,
num_memory_blocks,
gap_size,
query_block_size,
memory_block_size,
gather_indices,
dire... | Gathers blocks with gaps in between.
Args:
x: Tensor of shape [length, batch, heads, depth]
num_memory_blocks: how many memory blocks to look in "direction". Each will
be separated by gap_size.
gap_size: an integer indicating the gap size
query_block_size: an integer indicating size of query bl... |
11,195 | def Nu_cylinder_Zukauskas(Re, Pr, Prw=None):
r
if Re <= 40:
c, m = 0.75, 0.4
elif Re < 1E3:
c, m = 0.51, 0.5
elif Re < 2E5:
c, m = 0.26, 0.6
else:
c, m = 0.076, 0.7
if Pr <= 10:
n = 0.37
else:
n = 0.36
Nu = c*Re**m*Pr**n
if Prw:
... | r'''Calculates Nusselt number for crossflow across a single tube at a
specified Re. Method from [1]_, also shown without modification in [2]_.
.. math::
Nu_{D}=CRe^{m}Pr^{n}\left(\frac{Pr}{Pr_s}\right)^{1/4}
Parameters
----------
Re : float
Reynolds number with respect to cylinder ... |
11,196 | def sources(self):
try:
return self._sources
except AttributeError:
self._sources = find_sources(self)
return self._sources | Returns a dictionary of source methods found on this object,
keyed on method name. Source methods are identified by
(self, context) arguments on this object. For example:
.. code-block:: python
def f(self, context):
...
is a source method, but
... |
11,197 | def variations(iterable, optional=lambda x: False):
iterable = tuple(iterable)
o = [optional(x) for x in iterable]
a = set()
for p in product([False, True], repeat=sum(o)):
p = list(p)
v = [b and (b and p.pop(0)) for b in o]
v = tuple(... | Returns all possible variations of a sequence with optional items. |
11,198 | def update_Broyden_J(self):
CLOG.debug()
delta_vals = self.param_vals - self._last_vals
delta_residuals = self.calc_residuals() - self._last_residuals
nrm = np.sqrt(np.dot(delta_vals, delta_vals))
direction = delta_vals / nrm
vals = delta_residuals / nrm
... | Execute a Broyden update of J |
11,199 | def start(self):
version = self.request("get", "/version")
if version != 2:
raise GanetiApiError("Cans calm down, this is totally reasonable. Certain
features = []
else:
raise
logging.info("RAPI... | Confirm that we may access the target cluster. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.