Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
362,500 | def _prepare_data_XY(self, X, Y, D, F):
XTY, XTDY, XTFY = self._make_templates(D, F, X, Y)
YTY_diag = np.sum(Y * Y, axis=0)
YTDY_diag = np.sum(Y * np.dot(D, Y), axis=0)
YTFY_diag = np.sum(Y * np.dot(F, Y), axis=0)
XTX, XTDX, XTFX = self._make_templates(D, F, X, X)
... | Prepares different forms of products of design matrix X
and data Y, or between themselves.
These products are re-used a lot during fitting.
So we pre-calculate them. Because these are reused,
it is in principle possible to update the fitting
as new data come i... |
362,501 | def inserir(self, name):
net_type_map = dict()
net_type_map[] = name
code, xml = self.submit(
{: net_type_map}, , )
return self.response(code, xml) | Insert new network type and return its identifier.
:param name: Network type name.
:return: Following dictionary: {'net_type': {'id': < id >}}
:raise InvalidParameterError: Network type is none or invalid.
:raise NomeTipoRedeDuplicadoError: A network type with this name already exists... |
362,502 | def get_wharton_gsrs_formatted(self, sessionid, date=None):
gsrs = self.get_wharton_gsrs(sessionid, date)
return self.switch_format(gsrs) | Return the wharton GSR listing formatted in studyspaces format. |
362,503 | def cmdSubstituteLines(self, cmd, count):
lineIndex = self._qpart.cursorPosition[0]
availableCount = len(self._qpart.lines) - lineIndex
effectiveCount = min(availableCount, count)
_globalClipboard.value = self._qpart.lines[lineIndex:lineIndex + effectiveCount]
with self... | S |
362,504 | def exclude_from_all(self, exclude_regex):
try:
re.compile(exclude_regex)
except re.error:
raise ZAPError(.format(exclude_regex))
self.logger.debug(.format(exclude_regex))
self.zap.core.exclude_from_proxy(exclude_regex)
self.zap.spider.exclude_f... | Exclude a pattern from proxy, spider and active scanner. |
362,505 | def parse_cgroups(filehandle):
for line in filehandle:
parts = line.strip().split(":")
if len(parts) != 3:
continue
cgroup_path = parts[2]
directory... | Reads lines from a file handle and tries to parse docker container IDs and kubernetes Pod IDs.
See tests.utils.docker_tests.test_cgroup_parsing for a set of test cases
:param filehandle:
:return: nested dictionary or None |
362,506 | def patched(f):
def wrapped(*args, **kwargs):
kwargs[] = False
kwargs[] = True
return f(*args, **kwargs)
return wrapped | Patches a given API function to not send. |
362,507 | def collect_argument(self, step, message):
runtime_arg_<name>
if step not in self.data:
self.data[step] = regexp_prompt(message) | given a key in the configuration, collect the runtime argument if
provided. Otherwise, prompt the user for the value.
Parameters
==========
step: the name of the step, should be 'runtime_arg_<name>'
message: the content of the step, the message to show the user if... |
362,508 | def from_array(array):
if array is None or not array:
return None
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data[] = int(array.get())
data[] = bool(array.get())
data[] = u(array.get())
data[] = u(array.get()... | Deserialize a new User from a given dictionary.
:return: new User instance.
:rtype: User |
362,509 | def new_result(self, loss, budget, parameters, update_model=True):
if loss is None:
loss = np.inf
if budget not in self.configs.keys():
self.configs[budget] = []
self.losses[budget] = []
if max(list(self.kde_models... | Function to register finished runs. Every time a run has finished, this function should be called
to register it with the loss.
Parameters:
-----------
loss: float
the loss of the parameters
budget: float
the budget of the parameters
parameters: d... |
362,510 | def update_classroom(self, course, classroomid, new_data):
student_list, tutor_list, other_students, _ = self.get_user_lists(course, classroomid)
new_data["tutors"] = [tutor for tutor in map(str.strip, new_data["tutors"]) if tutor in tutor_list]
students, groups, errored_stud... | Update classroom and returns a list of errored students |
362,511 | def only_root_can_write(self, root_group_can_write=True):
requirements = True
requirements &= self.owner ==
requirements &= not self.others_can_write()
if root_group_can_write:
if self.group != :
requirements &= not self.group_can... | Checks if only root is allowed to write the file (and anyone else is
barred from writing). Read and execute bits are not checked. The
write bits for root user/group are not checked because root can
read/write anything regardless of the read/write permissions.
When called with ``root_roo... |
362,512 | def leaveWhitespace( self ):
self.skipWhitespace = False
self.exprs = [ e.copy() for e in self.exprs ]
for e in self.exprs:
e.leaveWhitespace()
return self | Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on
all contained expressions. |
362,513 | def show_firmware_version_output_show_firmware_version_os_name(self, **kwargs):
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
output = ET.SubElement(show_firmware_version, "output")
show_firmware_... | Auto Generated Code |
362,514 | def remove_examples_all():
d = examples_all_dir()
if d.exists():
log.debug(, d)
d.rmtree()
else:
log.debug(, d) | remove arduino/examples/all directory.
:rtype: None |
362,515 | def sanitycheck(self):
tstart = datetime.now()
sc = sanity_check.Sanity_check(self.vcf_file)
std = sc.run()
tend = datetime.now()
execution_time = tend - tstart | Search and Remove variants with [0/0, ./.]
Search and Replace chr from the beggining of the chromossomes to get positionning.
Sort VCF by 1...22, X, Y, MT and nothing else
#Discard other variants |
362,516 | def _get_object_menu_models():
from pyoko.conf import settings
enabled_models = []
for entry in settings.OBJECT_MENU.values():
for mdl in entry:
if not in mdl:
enabled_models.append(mdl[])
return enabled_models | we need to create basic permissions
for only CRUD enabled models |
362,517 | def quickstart():
width = click.get_terminal_size()[0]
width = width if width <= 79 else 79
click.secho("twtxt - quickstart", fg="cyan")
click.secho("==================", fg="cyan")
click.echo()
help_text = "This wizard will generate a basic configuration file for twtxt with all mandatory... | Quickstart wizard for setting up twtxt. |
362,518 | def import_project_modules(module_name):
from django.conf import settings
submodules = []
for app in settings.INSTALLED_APPS:
module = import_app_module(app, module_name)
if module is not None:
submodules.append(module)
return submodules | Imports modules from registered apps using given module name
and returns them as a list.
:param str module_name:
:rtype: list |
362,519 | def location(self):
try:
lat, lng = self["metadata"]["latitude"], self["metadata"]["longitude"]
except KeyError:
return None
if not lat or not lng:
return None
return lat, lng | Returns the geolocation as a lat/lng pair |
362,520 | def pull(image,
insecure_registry=False,
api_response=False,
client_timeout=salt.utils.docker.CLIENT_TIMEOUT):
_prep_pull()
kwargs = {: True,
: client_timeout}
if insecure_registry:
kwargs[] = insecure_registry
time_started = time.time()
respon... | .. versionchanged:: 2018.3.0
If no tag is specified in the ``image`` argument, all tags for the
image will be pulled. For this reason is it recommended to pass
``image`` using the ``repo:tag`` notation.
Pulls an image from a Docker registry
image
Image to be pulled
insecur... |
362,521 | def get_db_instances(self):
if not self.connect_to_aws_rds():
return False
try:
instances = self.rdsc.describe_db_instances().get()
except:
return False
else:
return instances | DB instance |
362,522 | def set_runtime_value_int(self, ihcid: int, value: int) -> bool:
if self.client.set_runtime_value_int(ihcid, value):
return True
self.re_authenticate()
return self.client.set_runtime_value_int(ihcid, value) | Set integer runtime value with re-authenticate if needed |
362,523 | def payment_begin(self, wallet):
wallet = self._process_value(wallet, )
payload = {"wallet": wallet}
resp = self.call(, payload)
return resp[] | Begin a new payment session. Searches wallet for an account that's
marked as available and has a 0 balance. If one is found, the account
number is returned and is marked as unavailable. If no account is
found, a new account is created, placed in the wallet, and returned.
:param wallet: ... |
362,524 | def _structure_set(self, obj, cl):
if is_bare(cl) or cl.__args__[0] is Any:
return set(obj)
else:
elem_type = cl.__args__[0]
return {
self._structure_func.dispatch(elem_type)(e, elem_type)
for e in obj
} | Convert an iterable into a potentially generic set. |
362,525 | def reorder_keys(self, keys):
if len(keys) != len(self._set):
raise ValueError()
if set(keys) != self._set:
raise ValueError()
self._keys = list(keys) | Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys. |
362,526 | def preprocess(msg_body, delimiter, content_type=):
msg_body = _replace_link_brackets(msg_body)
msg_body = _wrap_splitter_with_newline(msg_body, delimiter, content_type)
return msg_body | Prepares msg_body for being stripped.
Replaces link brackets so that they couldn't be taken for quotation marker.
Splits line in two if splitter pattern preceded by some text on the same
line (done only for 'On <date> <person> wrote:' pattern).
Converts msg_body into a unicode. |
362,527 | def space_list(args):
r = fapi.list_workspaces()
fapi._check_response_code(r, 200)
spaces = []
project = args.project
if project:
project = re.compile( + project)
for space in r.json():
ns = space[][]
if project and not project.match(ns):
continue
... | List accessible workspaces, in TSV form: <namespace><TAB>workspace |
362,528 | def choose(self, versions, conflict=):
assert conflict in (, , )
if not versions:
raise VersionRangeMismatch()
version_map = {}
for version in versions:
version_map[version] = str2nr(version, mx=self.limit)
top_version, top_nr = None, 0
for version, nr in version_map.items():
if nr >= top_nr:... | Choose the highest version in the range.
:param versions: Iterable of available versions. |
362,529 | def _expand_probes(probes, defaults):
expected_probes = {}
for probe_name, probe_test in six.iteritems(probes):
if probe_name not in expected_probes.keys():
expected_probes[probe_name] = {}
probe_defaults = probe_test.pop(, {})
for test_name, test_details in six.iteri... | Updates the probes dictionary with different levels of default values. |
362,530 | def propose(self, current, r):
curLambda = current + self.offset
x, logProb = PoissonDistribution(curLambda).sample(r)
logBackward = PoissonDistribution(x+self.offset).logDensity(current)
return x, logProb, logBackward | Generates a random sample from the Poisson probability distribution with
with location and scale parameter equal to the current value (passed in).
Returns the value of the random sample, the log of the probability of
sampling that value, and the log of the probability of sampling the current
value if th... |
362,531 | def delete_launch_configuration(name, region=None, key=None, keyid=None,
profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
retries = 30
while True:
try:
conn.delete_launch_configuration(name)
log.info(, ... | Delete a launch configuration.
CLI example::
salt myminion boto_asg.delete_launch_configuration mylc |
362,532 | def available_delegations(self):
api_version = self._get_api_version()
if api_version == :
from .v2018_08_01.operations import AvailableDelegationsOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
... | Instance depends on the API version:
* 2018-08-01: :class:`AvailableDelegationsOperations<azure.mgmt.network.v2018_08_01.operations.AvailableDelegationsOperations>` |
362,533 | def get(self, url, status):
crl = self.cobj
try:
crl.setopt(pycurl.URL, url)
except UnicodeEncodeError:
crl.setopt(pycurl.URL, url.encode())
if not self.silent:
print(status, file=sys.stderr)
... | in favor of python-requests for speed |
362,534 | def simulate_roi(self, name=None, clear=True, randomize=True):
cm = self.counts_map()
data = cm.data
m = self.model_counts_map(name)
if clear:
data.fill(0.0)
if randomize:
if m.data.min()<0.:
self.logger.warning(
... | Simulate the whole ROI or inject a simulation of one or
more model components into the data.
Parameters
----------
name : str
Name of the model component to be simulated. If None then
the whole ROI will be simulated.
clear : bool
Zero the curre... |
362,535 | def parse(self, scope):
if not self.parsed:
self.parsed = .join(self.process(self.tokens, scope))
return self.parsed | Parse node
args:
scope (Scope): current scope
raises:
SyntaxError
returns:
parsed |
362,536 | def get(self,dimlist):
out=()
for i,d in enumerate(dimlist):
out+=(super(dimStr, self).get(d,None),)
return out | get dimensions
:parameter dimlist: list of dimensions |
362,537 | def dir_exists(self):
r = requests.request(self.method if self.method else , self.url, **self.storage_args)
try: r.raise_for_status()
except Exception: return False
return True | Makes a ``HEAD`` requests to the URI.
:returns: ``True`` if status code is 2xx. |
362,538 | async def mutual_friends(self):
state = self._state
mutuals = await state.http.get_mutual_friends(self.id)
return [User(state=state, data=friend) for friend in mutuals] | |coro|
Gets all mutual friends of this user.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to get mutual friends of this user.
HTTPException
Getting mutual friends failed.
Returns
... |
362,539 | def from_email_message(cls, message, local_id=None):
result = cls()
if local_id is not None:
result.local_id = id
message_id = message.get()
if message_id:
result.message_id_supplied = True
result.message_id = message_id
result.mime_... | Convert an :class:`email.message.Message` or compatible message
object into a CERP XML :class:`eulxml.xmlmap.cerp.Message`. If an
id is specified, it will be stored in the Message <LocalId>.
:param message: `email.message.Message` object
:param id: optional message id to be set as `loca... |
362,540 | def bar(hists,
stacked=True,
reverse=False,
xerr=False, yerr=True,
xpadding=0, ypadding=.1,
yerror_in_padding=True,
rwidth=0.8,
snap=True,
axes=None,
**kwargs):
if axes is None:
axes = plt.gca()
curr_xlim = axes.get_xlim()
... | Make a matplotlib bar plot from a ROOT histogram, stack or
list of histograms.
Parameters
----------
hists : Hist, list of Hist, HistStack
The histogram(s) to be plotted
stacked : bool or string, optional (default=True)
If True then stack the histograms with the first histogram on... |
362,541 | def _create_latent_variables(self):
no_of_features = self.ar
self.latent_variables.create(name=, dim=[self.layers, self.units], prior=fam.Cauchy(0, 1, transform=None), q=fam.Normal(0, 3))
self.latent_variables.create(name=, dim=[1], prior=fam.Cauchy(0, 1, transform=None), q=fam.Norma... | Creates the model's latent variables
Returns
----------
None (changes model attributes) |
362,542 | def get_trainer(self, model, method=, config=None, annealer=None, validator=None):
from deepy.trainers import GeneralNeuralTrainer
return GeneralNeuralTrainer(model, method=method, config=config, annealer=annealer, validator=validator) | Get a trainer to optimize given model.
:rtype: deepy.trainers.GeneralNeuralTrainer |
362,543 | def fromYaml(cls, ydata, filepath=):
builder = cls()
builder.loadYaml(ydata, filepath=filepath)
return builder | Generates a new builder from the given yaml data and then
loads its information.
:param ydata | <dict>
:return <Builder> || None |
362,544 | def extend(self, name, opts, info):
tifo = self.info.copy()
tifo.update(info)
topt = self.opts.copy()
topt.update(opts)
tobj = self.__class__(self.modl, name, tifo, topt)
tobj.subof = self.name
return tobj | Extend this type to construct a sub-type.
Args:
name (str): The name of the new sub-type.
opts (dict): The type options for the sub-type.
info (dict): The type info for the sub-type.
Returns:
(synapse.types.Type): A new sub-type instance. |
362,545 | def antiscia(self):
obj = self.copy()
obj.type = const.OBJ_GENERIC
obj.relocate(360 - obj.lon + 180)
return obj | Returns antiscia object. |
362,546 | def RRlist2bitmap(lst):
import math
bitmap = b""
lst = [abs(x) for x in sorted(set(lst)) if x <= 65535]
max_window_blocks = int(math.ceil(lst[-1] / 256.))
min_window_blocks = int(math.floor(lst[0] / 256.))
if min_window_blocks == max_window_blocks:
max_window_blocks += ... | Encode a list of integers representing Resource Records to a bitmap field
used in the NSEC Resource Record. |
362,547 | def newChild(self, parent, name, content):
if parent is None: parent__o = None
else: parent__o = parent._o
ret = libxml2mod.xmlNewChild(parent__o, self._o, name, content)
if ret is None:raise treeError()
__tmp = xmlNode(_obj=ret)
return __tmp | Creation of a new child element, added at the end of
@parent children list. @ns and @content parameters are
optional (None). If @ns is None, the newly created element
inherits the namespace of @parent. If @content is non None,
a child list containing the TEXTs and ENTITY_REFs nod... |
362,548 | def list_log_entries(
self,
resource_names,
project_ids=None,
filter_=None,
order_by=None,
page_size=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
... | Lists log entries. Use this method to retrieve log entries from Logging.
For ways to export log entries, see `Exporting
Logs <https://cloud.google.com/logging/docs/export>`__.
Example:
>>> from google.cloud import logging_v2
>>>
>>> client = logging_v2.Loggin... |
362,549 | def extract_missing_special_type_names(schema, type_dict):
for name in FieldParser.extract_types(schema):
if CardinalityField.matches_type(name) and (name not in type_dict):
yield name | Extract the type names for fields with CardinalityField part.
Selects only the missing type names that are not in the type dictionary.
:param schema: Parse schema to use (as string).
:param type_dict: Type dictionary with type converters.
:return: Generator with missing type names ... |
362,550 | def only_module(*modules):
modules = (modules and isinstance(modules[0], list)) and \
modules[0] or modules
for module in modules:
if not module in ONLY_MODULES:
ONLY_MODULES.append(module)
traceback.extract_tb = _new_extract_tb | This will exclude all modules from the traceback except these "modules"
:param modules: list of modules to report in traceback
:return: None |
362,551 | def _expand_vector(self,x):
x = np.atleast_2d(x)
x_expanded = np.zeros((x.shape[0],self.space.model_dimensionality))
x_expanded[:,np.array(self.noncontext_index).astype(int)] = x
x_expanded[:,np.array(self.context_index).astype(int)] = self.context_value
return x_expan... | Takes a value x in the subspace of not fixed dimensions and expands it with the values of the fixed ones.
:param x: input vector to be expanded by adding the context values |
362,552 | def _update_advertised(self, advertised):
if in advertised:
self._advertised = self._advertised + map(cbuuid_to_uuid, advertised[]) | Called when advertisement data is received. |
362,553 | def get_urls(self):
urls = super(DashboardSite, self).get_urls()
custom_urls = [
url(r,
self.admin_view(HomeView.as_view()),
name=),
url(r, include(logs_urlpatterns(self.admin_view))),
]
custom_urls += get_realtime_urls(se... | Get urls method.
Returns:
list: the list of url objects. |
362,554 | def is_merged(self):
url = self._build_url(, base_url=self._api)
return self._boolean(self._get(url), 204, 404) | Checks to see if the pull request was merged.
:returns: bool |
362,555 | def transform(self, data):
if self.transform_chain is None:
raise RuntimeError("`transform()` method called before `fit` or `fit_transform`.")
return self.transform_chain.transform(data) | Transform the SFrame `data` using a fitted model.
Parameters
----------
data : SFrame
The data to be transformed.
Returns
-------
A transformed SFrame.
Returns
-------
out: SFrame
A transformed SFrame.
See Also
... |
362,556 | def _docspec_comments(obj) -> Dict[str, str]:
class_docstring = getattr(obj, , None)
init_docstring = getattr(obj.__init__, , None) if hasattr(obj, ) else None
docstring = class_docstring or init_docstring or
doc = NumpyDocString(docstring)
params = doc["Parameters"]
comments: Dict[... | Inspect the docstring and get the comments for each parameter. |
362,557 | def progress_bar(self, c, broker):
v = broker.get(c)
if v and isinstance(v, dict) and len(v) > 0 and in v:
if v["type"] in self.responses:
print(self.responses[v["type"]].color + self.responses[v["type"]].intl + Style.RESET_ALL, end="", file=self.stream)
... | Print the formated progress information for the processed return types |
362,558 | def _check_for_indent(self, newline_token):
indent_delta = self._get_next_line_indent_delta(newline_token)
if indent_delta is None or indent_delta == 1:
newline_token.lexer.lineno)) | Checks that the line following a newline is indented, otherwise a
parsing error is generated. |
362,559 | def open_(filename, mode=, encoding=None):
if filename.endswith():
if six.PY2:
zf = io.BufferedReader(gzip.open(filename, mode))
if encoding:
return codecs.getreader(encoding)(zf)
else:
return zf
else:
return io.Buf... | Open a text file with encoding and optional gzip compression.
Note that on legacy Python any encoding other than ``None`` or opening
GZipped files will return an unpicklable file-like object.
Parameters
----------
filename : str
The filename to read.
mode : str, optional
The mo... |
362,560 | def set_display(self, index=None):
if index:
image = self.microbit.Image.STD_IMAGES[index]
else:
image = self.default_image
self.microbit.display.show(image) | Show an image on the display. |
362,561 | def from_csv(cls, path, folder, csv_fname, bs=64, tfms=(None,None),
val_idxs=None, suffix=, test_name=None, continuous=False, skip_header=True, num_workers=8, cat_separator=):
assert not (tfms[0] is None or tfms[1] is None), "please provide transformations for your train and validation s... | Read in images and their labels given as a CSV file.
This method should be used when training image labels are given in an CSV file as opposed to
sub-directories with label names.
Arguments:
path: a root path of the data (used for storing trained models, precomputed values, etc)
... |
362,562 | def get_hosts_from_hostgroups(hgname, hostgroups):
if not isinstance(hgname, list):
hgname = [e.strip() for e in hgname.split() if e.strip()]
host_names = []
for name in hgname:
hostgroup = hostgroups.find_by_name(name)
if hostgroup is None:
... | Get hosts of hostgroups
:param hgname: hostgroup name
:type hgname: str
:param hostgroups: hostgroups object (all hostgroups)
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: list of hosts
:rtype: list |
362,563 | def get_ssh_settings(application_name, user=None):
settings = {}
keys = {}
prefix =
if user:
prefix = .format(user)
for i, line in enumerate(ssh_known_hosts_lines(
application_name=application_name, user=user)):
settings[.format(prefix, i)] = line
if settings:
... | Retrieve the known host entries and public keys for application
Retrieve the known host entries and public keys for application for all
units of the given application related to this application for the
app + user combination.
:param application_name: Name of application eg nova-compute-something
... |
362,564 | def execute_network_pre_run(self, traj, network, network_dict, component_list, analyser_list):
self._execute_network_run(traj, network, network_dict, component_list, analyser_list,
pre_run=True) | Runs a network before the actual experiment.
Called by a :class:`~pypet.brian2.network.NetworkManager`.
Similar to :func:`~pypet.brian2.network.NetworkRunner.run_network`.
Subruns and their durations are extracted from the trajectory. All
:class:`~pypet.brian2.parameter.Brian2Parameter... |
362,565 | def newkeys(nbits=1024):
pubkey, privkey = rsa.newkeys(nbits, poolsize=1)
return pubkey, privkey | Create a new pair of public and private key pair to use. |
362,566 | def process_lines( self, input_lines, **kwargs ):
split_result_lines = False
remove_info = True
for argName, argVal in kwargs.items() :
if argName in [, ] and argVal in [True, False]:
split_result_lines = argVal
if argName in [, , ] and argVal in [... | Executes the pipeline of subsequent VISL_CG3 commands. The first process
in pipeline gets input_lines as an input, and each subsequent process gets
the output of the previous process as an input.
The idea of how to construct the pipeline borrows from:
https... |
362,567 | def static(**kwargs):
def wrap(fn):
fn.func_globals[] = fn
fn.__dict__.update(kwargs)
return fn
return wrap | USE carefully ^^ |
362,568 | def get_log_by_name(log_group_name, log_stream_name, out_file=None,
verbose=True):
logs = boto3.client()
kwargs = {: log_group_name,
: log_stream_name,
: True}
lines = []
while True:
response = logs.get_log_events(**kwargs)
... | Download a log given the log's group and stream name.
Parameters
----------
log_group_name : str
The name of the log group, e.g. /aws/batch/job.
log_stream_name : str
The name of the log stream, e.g. run_reach_jobdef/default/<UUID>
Returns
-------
lines : list[str]
... |
362,569 | def _get_members(self, class_obj, member_type, include_in_public=None):
try:
app = self.state.document.settings.env.app
except AttributeError:
app = None
if not include_in_public:
include_in_public = []
all_members = []
for member_name... | Return class members of the specified type.
class_obj: Class object.
member_type: Member type ('method' or 'attribute').
include_in_public: set/list/tuple with member names that should be
included in public members in addition to the public names (those
starting without un... |
362,570 | def constrain_cfgdict_list(cfgdict_list_, constraint_func):
cfgdict_list = []
for cfg_ in cfgdict_list_:
cfg = cfg_.copy()
if constraint_func(cfg) is not False and len(cfg) > 0:
if cfg not in cfgdict_list:
cfgdict_list.append(cfg)
return cfgdict_list | constrains configurations and removes duplicates |
362,571 | def path(project, credentials):
user, oauth_access_token = parsecredentials(credentials)
return settings.ROOT + "projects/" + user + + project + "/" | Get the path to the project (static method) |
362,572 | def SNRaverage(snr, method=, excludeBackground=True,
checkBackground=True,
backgroundLevel=None):
averageX75RMSmedian
if excludeBackground:
if backgroundLevel is None:
try:
f = FitHistogramPeaks(snr).fitParams
if ... | average a signal-to-noise map
:param method: ['average','X75', 'RMS', 'median'] - X75: this SNR will be exceeded by 75% of the signal
:type method: str
:param checkBackground: check whether there is actually a background level to exclude
:type checkBackground: bool
:returns: averaged SNR as ... |
362,573 | def disassemble(bytecode, pc=0, fork=DEFAULT_FORK):
return .join(map(str, disassemble_all(bytecode, pc=pc, fork=fork))) | Disassemble an EVM bytecode
:param bytecode: binary representation of an evm bytecode
:type bytecode: str | bytes | bytearray
:param pc: program counter of the first instruction(optional)
:type pc: int
:param fork: fork name (optional)
:type fork: str
:return: th... |
362,574 | def items2file(items, filename, encoding=, modifier=):
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True))) | json array to file, canonical json format |
362,575 | def b58decode(v):
v = v.rstrip()
v = scrub_input(v)
origlen = len(v)
v = v.lstrip(alphabet[0:1])
newlen = len(v)
acc = b58decode_int(v)
result = []
while acc > 0:
acc, mod = divmod(acc, 256)
result.append(mod)
return (b * (origlen - newlen) + bseq(reversed(re... | Decode a Base58 encoded string |
362,576 | def is_excluded(self, cid, pod_uid=None):
if not cid:
return True
if cid in self.cache:
return self.cache[cid]
if pod_uid and pod_uid in self.static_pod_uids:
self.cache[cid] = False
return False
if cid not in self.containers:
... | Queries the agent6 container filter interface. It retrieves container
name + image from the podlist, so static pod filtering is not supported.
Result is cached between calls to avoid the python-go switching cost for
prometheus metrics (will be called once per metric)
:param cid: contain... |
362,577 | def _merge_points(self, pc1, pc2):
res = pc1[:]
for p in pc2:
for sp in res:
if sp.time == p.time and (
sp.location is None or (sp.location.equals(p.location))
):
sp.members.extend(p.members)
... | Merges points based on time/location.
@TODO: move to paegan, SO SLOW |
362,578 | def observe(self, key: str, callback: Callable[[Any, Any], None]):
if key not in self._callbacks:
self._add_key(key)
self._callbacks[key].append(callback) | Subscribes to key changes |
362,579 | def unregister(self, name: str):
del self._callbacks[name]
if self._event_dispatcher is not None:
self._event_dispatcher.unregister(name) | Unregister hook. |
362,580 | def use_plenary_comment_view(self):
self._object_views[] = PLENARY
for session in self._get_provider_sessions():
try:
session.use_plenary_comment_view()
except AttributeError:
pass | Pass through to provider CommentLookupSession.use_plenary_comment_view |
362,581 | def check_submission_successful(self, submission_id=None):
status = self.submission_status(submission_id)
success = bool(status["concordance"]["value"])
return success | Check if the last submission passes submission criteria.
Args:
submission_id (str, optional): submission of interest, defaults to
the last submission done with the account
Return:
bool: True if the submission passed all checks, False otherwise.
Example:... |
362,582 | def _extract_ocsp_certs(self, ocsp_response):
status = ocsp_response[].native
if status == :
response_bytes = ocsp_response[]
if response_bytes[].native == :
response = response_bytes[].parsed
if response[]:
for other_... | Extracts any certificates included with an OCSP response and adds them
to the certificate registry
:param ocsp_response:
An asn1crypto.ocsp.OCSPResponse object to look for certs inside of |
362,583 | def visualize(
logdir, outdir, num_agents, num_episodes, checkpoint=None,
env_processes=True):
config = utility.load_config(logdir)
with tf.device():
batch_env = utility.define_batch_env(
lambda: _create_environment(config, outdir),
num_agents, env_processes)
graph = utility.defin... | Recover checkpoint and render videos from it.
Args:
logdir: Logging directory of the trained algorithm.
outdir: Directory to store rendered videos in.
num_agents: Number of environments to simulate in parallel.
num_episodes: Total number of episodes to simulate.
checkpoint: Checkpoint name to loa... |
362,584 | def _difference_map(image, color_axis):
if color_axis == 2:
image = _transpose_image(image)
dfdx = np.zeros_like(image)
dfdx[:, :, 0] = image[:, :, 1] - image[:, :, 0]
dfdx[:, :, -1] = image[:, :, -1] - image[:, :, -2]
dfdx[:, :, 1:-1] = 0.5 * (image[:, :, 2:] - ima... | Difference map of the image.
Approximate derivatives of the function image[c, :, :]
(e.g. PyTorch) or image[:, :, c] (e.g. Keras).
dfdx, dfdy = difference_map(image)
In:
image: numpy.ndarray
of shape C x h x w or h x w x C, with C = 1 or C = 3
(color channels), h, w >= 3, and [type] ... |
362,585 | def x_rotate(rotationAmt):
ma4 = Matrix4((1, 0, 0, 0),
(0, math.cos(rotationAmt), -math.sin(rotationAmt), 0),
(0, math.sin(rotationAmt), math.cos(rotationAmt), 0),
(0, 0, 0, 1))
return ma4 | Create a matrix that rotates around the x axis. |
362,586 | def fbeta_score(targets, predictions, beta=1.0, average=):
r
_supervised_evaluation_error_checking(targets, predictions)
_check_categorical_option_type(, average,
[, , None])
_check_same_type_not_float(targets, predictions)
opts = {"beta" : beta,
"average" : ... | r"""
Compute the F-beta score. The F-beta score is the weighted harmonic mean of
precision and recall. The score lies in the range [0,1] with 1 being ideal
and 0 being the worst.
The `beta` value is the weight given to `precision` vs `recall` in the
combined score. `beta=0` considers only precision... |
362,587 | def find_prop_overlap(rdf, prop1, prop2):
for s, o in sorted(rdf.subject_objects(prop1)):
if (s, prop2, o) in rdf:
yield (s, o) | Generate (subject,object) pairs connected by two properties. |
362,588 | def load_contexts_and_renderers(events, mediums):
sources = {event.source for event in events}
rendering_styles = {medium.rendering_style for medium in mediums if medium.rendering_style}
default_rendering_style = get_default_rendering_style()
if default_rendering_style:
rendering_styl... | Given a list of events and mediums, load the context model data into the contexts of the events. |
362,589 | def describe_listeners(load_balancer_arn=None, listener_arns=None, client=None):
kwargs = dict()
if load_balancer_arn:
kwargs.update(dict(LoadBalancerArn=load_balancer_arn))
if listener_arns:
kwargs.update(dict(ListenerArns=listener_arns))
return client.describe_listeners(**kwargs) | Permission: elasticloadbalancing:DescribeListeners |
362,590 | def get_image_uri(region_name, repo_name, repo_version=1):
repo = .format(repo_name, repo_version)
return .format(registry(region_name, repo_name), repo) | Return algorithm image URI for the given AWS region, repository name, and repository version |
362,591 | def check_table(table=None, family=):
*
ret = {: ,
: False}
if not table:
ret[] =
return ret
nft_family = _NFTABLES_FAMILIES[family]
cmd = . format(_nftables_cmd(), nft_family)
out = __salt__[](cmd, python_shell=False).find(.format(nft_family, table))
if out =... | Check for the existence of a table
CLI Example::
salt '*' nftables.check_table nat |
362,592 | def copy(src, dst):
src, src_is_storage = format_and_is_storage(src)
dst, dst_is_storage = format_and_is_storage(dst)
if not src_is_storage and not dst_is_storage:
return shutil_copy(src, dst)
with handle_os_exceptions():
if not hasattr(dst, ):
try:
... | Copies a source file to a destination file or directory.
Equivalent to "shutil.copy".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object):
Destination file... |
362,593 | def get_objective_banks_by_ids(self, objective_bank_ids=None):
if objective_bank_ids is None:
raise NullArgument()
banks = []
for i in objective_bank_ids:
bank = None
url_path = construct_url(,
bank_id=i)
... | Gets a ObjectiveBankList corresponding to the given IdList.
In plenary mode, the returned list contains all of the objective
banks specified in the Id list, in the order of the list,
including duplicates, or an error results if an Id in the
supplied list is not found or inaccessible. Oth... |
362,594 | def convpar(p):
if not in p:
return p
els = p[]
nel = len(els)
q = { }
for name, values in p.items():
if isinstance(values, dict):
m = 0
for itype, value in values:
if itype[0] == :
contin... | Convert a parameter set from convenient Python dictionary to the format
expected by the Fortran kernels. |
362,595 | def photometry(
self):
photResultsList = []
photResultsList[:] = [dict(l) for l in self.photResultsList]
return photResultsList | *The associated source photometry*
**Usage:**
.. code-block:: python
sourcePhotometry = tns.photometry |
362,596 | def remove_server(self, name):
for i in self._server_list:
if i[] == name:
try:
self._server_list.remove(i)
logger.debug("Remove server %s from the list" % name)
logger.debug("Updated servers list (%s servers): %s" ... | Remove a server from the dict. |
362,597 | def immerkaer(input, mode="reflect", cval=0.0):
r
kernel = [1, -2, 1]
for _ in range(input.ndim - 1):
kernel = numpy.tensordot(kernel, [1, -2, 1], 0)
divider = numpy.square(numpy.abs(kernel)).sum()
laplace = separable_convolution(input, [1, -2, 1], None, mode, cval)
facto... | r"""
Estimate the global noise.
The input image is assumed to have additive zero mean Gaussian noise. Using a
convolution with a Laplacian operator and a subsequent averaging the standard
deviation sigma of this noise is estimated. This estimation is global i.e. the
noise is assumed to be globa... |
362,598 | def _filter_unscheduled_routers(self, plugin, context, routers):
if NEUTRON_VERSION.version[0] <= NEUTRON_NEWTON_VERSION.version[0]:
context, plugin = plugin, context
unscheduled_routers = []
for router in routers:
if (router[routertype.TYPE_ATTR] !=
... | Filter from list of routers the ones that are not scheduled.
Only for release < pike. |
362,599 | def kdot(x, y, K=2):
xx = x.reshape(-1, x.shape[-1])
yy = y.reshape(y.shape[0], -1)
xx = numpy.ascontiguousarray(xx)
yy = numpy.ascontiguousarray(yy)
r = _accupy.kdot_helper(xx, yy).reshape((-1,) + x.shape[:-1] + y.shape[1:])
return ksum(r, K - 1) | Algorithm 5.10. Dot product algorithm in K-fold working precision,
K >= 3. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.