code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _prepare_data_XY(self, X, Y, D, F):
"""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 t... | 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... |
def inserir(self, name):
"""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 networ... | 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... |
def get_wharton_gsrs_formatted(self, sessionid, date=None):
""" Return the wharton GSR listing formatted in studyspaces format. """
gsrs = self.get_wharton_gsrs(sessionid, date)
return self.switch_format(gsrs) | Return the wharton GSR listing formatted in studyspaces format. |
def cmdSubstituteLines(self, cmd, count):
""" S
"""
lineIndex = self._qpart.cursorPosition[0]
availableCount = len(self._qpart.lines) - lineIndex
effectiveCount = min(availableCount, count)
_globalClipboard.value = self._qpart.lines[lineIndex:lineIndex + effectiveCount]
... | S |
def exclude_from_all(self, exclude_regex):
"""Exclude a pattern from proxy, spider and active scanner."""
try:
re.compile(exclude_regex)
except re.error:
raise ZAPError('Invalid regex "{0}" provided'.format(exclude_regex))
self.logger.debug('Excluding {0} from pr... | Exclude a pattern from proxy, spider and active scanner. |
def parse_cgroups(filehandle):
"""
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
"""
for line in filehandle:
... | 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 |
def patched(f):
"""Patches a given API function to not send."""
def wrapped(*args, **kwargs):
kwargs['return_response'] = False
kwargs['prefetch'] = True
return f(*args, **kwargs)
return wrapped | Patches a given API function to not send. |
def collect_argument(self, step, 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: th... | 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... |
def from_array(array):
"""
Deserialize a new User from a given dictionary.
:return: new User instance.
:rtype: User
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data... | Deserialize a new User from a given dictionary.
:return: new User instance.
:rtype: User |
def new_result(self, loss, budget, parameters, update_model=True):
"""
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 paramete... | 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... |
def update_classroom(self, course, classroomid, new_data):
""" Update classroom and returns a list of errored students"""
student_list, tutor_list, other_students, _ = self.get_user_lists(course, classroomid)
# Check tutors
new_data["tutors"] = [tutor for tutor in map(str.strip, new_dat... | Update classroom and returns a list of errored students |
def only_root_can_write(self, root_group_can_write=True):
"""
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 ... | 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... |
def leaveWhitespace( self ):
"""Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on
all contained expressions."""
self.skipWhitespace = False
self.exprs = [ e.copy() for e in self.exprs ]
for e in self.exprs:
e.leaveWhitespace... | Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on
all contained expressions. |
def show_firmware_version_output_show_firmware_version_os_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
output = ET.SubElement(show_firmware_version... | Auto Generated Code |
def remove_examples_all():
"""remove arduino/examples/all directory.
:rtype: None
"""
d = examples_all_dir()
if d.exists():
log.debug('remove %s', d)
d.rmtree()
else:
log.debug('nothing to remove: %s', d) | remove arduino/examples/all directory.
:rtype: None |
def sanitycheck(self):
"""
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
"""
# logging.info('Starting Sanity C... | 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 |
def _get_object_menu_models():
"""
we need to create basic permissions
for only CRUD enabled models
"""
from pyoko.conf import settings
enabled_models = []
for entry in settings.OBJECT_MENU.values():
for mdl in entry:
if 'wf' not in mdl:
enabled_models.app... | we need to create basic permissions
for only CRUD enabled models |
def quickstart():
"""Quickstart wizard for setting up twtxt."""
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 co... | Quickstart wizard for setting up twtxt. |
def import_project_modules(module_name):
"""Imports modules from registered apps using given module name
and returns them as a list.
:param str module_name:
:rtype: list
"""
from django.conf import settings
submodules = []
for app in settings.INSTALLED_APPS:
module = import_ap... | Imports modules from registered apps using given module name
and returns them as a list.
:param str module_name:
:rtype: list |
def location(self):
"""
Returns the geolocation as a lat/lng pair
"""
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 |
def pull(image,
insecure_registry=False,
api_response=False,
client_timeout=salt.utils.docker.CLIENT_TIMEOUT):
'''
.. 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... | .. 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... |
def get_db_instances(self):
''' DB instance '''
if not self.connect_to_aws_rds():
return False
try:
instances = self.rdsc.describe_db_instances().get('DBInstances')
except:
return False
else:
return instances | DB instance |
def set_runtime_value_int(self, ihcid: int, value: int) -> bool:
""" Set integer runtime value with re-authenticate if needed"""
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 |
def payment_begin(self, wallet):
"""
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 ... | 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: ... |
def _structure_set(self, obj, cl):
"""Convert an iterable into a potentially generic set."""
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_typ... | Convert an iterable into a potentially generic set. |
def reorder_keys(self, keys):
'''Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys.'''
if len(keys) != len(self._set):
raise ValueError('The supplied number of keys does not match.')
if set(ke... | Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys. |
def preprocess(msg_body, delimiter, content_type='text/plain'):
"""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:' p... | 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. |
def space_list(args):
''' List accessible workspaces, in TSV form: <namespace><TAB>workspace'''
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... | List accessible workspaces, in TSV form: <namespace><TAB>workspace |
def choose(self, versions, conflict='silent'):
"""
Choose the highest version in the range.
:param versions: Iterable of available versions.
"""
assert conflict in ('silent', 'warning', 'error')
if not versions:
raise VersionRangeMismatch('No versions to choose from')
version_map = {}
for version in... | Choose the highest version in the range.
:param versions: Iterable of available versions. |
def _expand_probes(probes, defaults):
'''
Updates the probes dictionary with different levels of default values.
'''
expected_probes = {}
for probe_name, probe_test in six.iteritems(probes):
if probe_name not in expected_probes.keys():
expected_probes[probe_name] = {}
... | Updates the probes dictionary with different levels of default values. |
def propose(self, current, r):
"""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 o... | 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... |
def delete_launch_configuration(name, region=None, key=None, keyid=None,
profile=None):
'''
Delete a launch configuration.
CLI example::
salt myminion boto_asg.delete_launch_configuration mylc
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile... | Delete a launch configuration.
CLI example::
salt myminion boto_asg.delete_launch_configuration mylc |
def available_delegations(self):
"""Instance depends on the API version:
* 2018-08-01: :class:`AvailableDelegationsOperations<azure.mgmt.network.v2018_08_01.operations.AvailableDelegationsOperations>`
"""
api_version = self._get_api_version('available_delegations')
if api_ver... | Instance depends on the API version:
* 2018-08-01: :class:`AvailableDelegationsOperations<azure.mgmt.network.v2018_08_01.operations.AvailableDelegationsOperations>` |
def get(self, url, status):
"""
in favor of python-requests for speed
"""
# consistently faster than requests by 3x
#
# r = requests.get(url,
# headers={'User-Agent': self.user_agent})
# return r.text
crl = self.cobj
try... | in favor of python-requests for speed |
def simulate_roi(self, name=None, clear=True, randomize=True):
"""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 wh... | 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... |
def parse(self, scope):
"""Parse node
args:
scope (Scope): current scope
raises:
SyntaxError
returns:
parsed
"""
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 |
def get(self,dimlist):
'''
get dimensions
:parameter dimlist: list of dimensions
'''
out=()
for i,d in enumerate(dimlist):
out+=(super(dimStr, self).get(d,None),)
return out | get dimensions
:parameter dimlist: list of dimensions |
def dir_exists(self):
"""
Makes a ``HEAD`` requests to the URI.
:returns: ``True`` if status code is 2xx.
"""
r = requests.request(self.method if self.method else 'HEAD', self.url, **self.storage_args)
try: r.raise_for_status()
except Exception: return False
... | Makes a ``HEAD`` requests to the URI.
:returns: ``True`` if status code is 2xx. |
async def mutual_friends(self):
"""|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 ... | |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
... |
def from_email_message(cls, message, local_id=None):
'''
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.... | 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... |
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):
"""
Make a matplotlib bar plot from a ROOT histogram, stack or
list of hist... | 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... |
def _create_latent_variables(self):
""" Creates the model's latent variables
Returns
----------
None (changes model attributes)
"""
no_of_features = self.ar
self.latent_variables.create(name='Bias', dim=[self.layers, self.units], prior=fam.Cauchy(0, 1, transfor... | Creates the model's latent variables
Returns
----------
None (changes model attributes) |
def get_trainer(self, model, method='sgd', config=None, annealer=None, validator=None):
"""
Get a trainer to optimize given model.
:rtype: deepy.trainers.GeneralNeuralTrainer
"""
from deepy.trainers import GeneralNeuralTrainer
return GeneralNeuralTrainer(model, method=me... | Get a trainer to optimize given model.
:rtype: deepy.trainers.GeneralNeuralTrainer |
def fromYaml(cls, ydata, filepath=''):
"""
Generates a new builder from the given yaml data and then
loads its information.
:param ydata | <dict>
:return <Builder> || None
"""
builder = cls()
builder.loadYaml(ydata, filepath=file... | Generates a new builder from the given yaml data and then
loads its information.
:param ydata | <dict>
:return <Builder> || None |
def extend(self, name, opts, info):
'''
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:
(synap... | 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. |
def antiscia(self):
""" Returns antiscia object. """
obj = self.copy()
obj.type = const.OBJ_GENERIC
obj.relocate(360 - obj.lon + 180)
return obj | Returns antiscia object. |
def RRlist2bitmap(lst):
"""
Encode a list of integers representing Resource Records to a bitmap field
used in the NSEC Resource Record.
"""
# RFC 4034, 4.1.2. The Type Bit Maps Field
import math
bitmap = b""
lst = [abs(x) for x in sorted(set(lst)) if x <= 65535]
# number of window... | Encode a list of integers representing Resource Records to a bitmap field
used in the NSEC Resource Record. |
def newChild(self, parent, name, content):
"""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,
... | 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... |
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,
):
"""
Lis... | 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... |
def extract_missing_special_type_names(schema, type_dict):
"""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 wit... | 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 ... |
def only_module(*modules):
"""
This will exclude all modules from the traceback except these "modules"
:param modules: list of modules to report in traceback
:return: None
"""
modules = (modules and isinstance(modules[0], list)) and \
modules[0] or modules
for module... | This will exclude all modules from the traceback except these "modules"
:param modules: list of modules to report in traceback
:return: None |
def _expand_vector(self,x):
'''
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
'''
x = np.atleast_2d(x)
x_expanded = np.zeros((x.shape[0],self.spa... | 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 |
def _update_advertised(self, advertised):
"""Called when advertisement data is received."""
# Advertisement data was received, pull out advertised service UUIDs and
# name from advertisement data.
if 'kCBAdvDataServiceUUIDs' in advertised:
self._advertised = self._advertised ... | Called when advertisement data is received. |
def get_urls(self):
"""
Get urls method.
Returns:
list: the list of url objects.
"""
urls = super(DashboardSite, self).get_urls()
custom_urls = [
url(r'^$',
self.admin_view(HomeView.as_view()),
name='index'),
... | Get urls method.
Returns:
list: the list of url objects. |
def is_merged(self):
"""Checks to see if the pull request was merged.
:returns: bool
"""
url = self._build_url('merge', base_url=self._api)
return self._boolean(self._get(url), 204, 404) | Checks to see if the pull request was merged.
:returns: bool |
def transform(self, data):
"""
Transform the SFrame `data` using a fitted model.
Parameters
----------
data : SFrame
The data to be transformed.
Returns
-------
A transformed SFrame.
Returns
-------
out: SFrame
... | 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
... |
def _docspec_comments(obj) -> Dict[str, str]:
"""
Inspect the docstring and get the comments for each parameter.
"""
# Sometimes our docstring is on the class, and sometimes it's on the initializer,
# so we've got to check both.
class_docstring = getattr(obj, '__doc__', None)
init_docstring ... | Inspect the docstring and get the comments for each parameter. |
def progress_bar(self, c, broker):
"""
Print the formated progress information for the processed return types
"""
v = broker.get(c)
if v and isinstance(v, dict) and len(v) > 0 and 'type' in v:
if v["type"] in self.responses:
print(self.responses[v["ty... | Print the formated progress information for the processed return types |
def _check_for_indent(self, newline_token):
"""
Checks that the line following a newline is indented, otherwise a
parsing error is generated.
"""
indent_delta = self._get_next_line_indent_delta(newline_token)
if indent_delta is None or indent_delta == 1:
# Nex... | Checks that the line following a newline is indented, otherwise a
parsing error is generated. |
def open_(filename, mode='r', encoding=None):
"""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 file... | 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... |
def set_display(self, index=None):
"""Show an image on the display."""
# pylint: disable=no-member
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. |
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=' '):
""" Read in images and their labels given as a CSV file.
This method should be used when training image lab... | 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)
... |
def get_hosts_from_hostgroups(hgname, hostgroups):
"""
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
... | 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 |
def get_ssh_settings(application_name, user=None):
"""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 applicatio... | 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
... |
def execute_network_pre_run(self, traj, network, network_dict, component_list, analyser_list):
"""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 thei... | 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... |
def newkeys(nbits=1024):
"""
Create a new pair of public and private key pair to use.
"""
pubkey, privkey = rsa.newkeys(nbits, poolsize=1)
return pubkey, privkey | Create a new pair of public and private key pair to use. |
def process_lines( self, input_lines, **kwargs ):
''' 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 h... | 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... |
def static(**kwargs):
""" USE carefully ^^ """
def wrap(fn):
fn.func_globals['static'] = fn
fn.__dict__.update(kwargs)
return fn
return wrap | USE carefully ^^ |
def get_log_by_name(log_group_name, log_stream_name, out_file=None,
verbose=True):
"""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 ... | 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]
... |
def _get_members(self, class_obj, member_type, include_in_public=None):
"""
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
inc... | 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... |
def constrain_cfgdict_list(cfgdict_list_, constraint_func):
""" constrains configurations and removes duplicates """
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:
c... | constrains configurations and removes duplicates |
def path(project, credentials):
"""Get the path to the project (static method)"""
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
return settings.ROOT + "projects/" + user + '/' + project + "/" | Get the path to the project (static method) |
def SNRaverage(snr, method='average', excludeBackground=True,
checkBackground=True,
backgroundLevel=None):
'''
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
... | 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 ... |
def disassemble(bytecode, pc=0, fork=DEFAULT_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... | 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... |
def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
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_ke... | json array to file, canonical json format |
def b58decode(v):
'''Decode a Base58 encoded string'''
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'\0'... | Decode a Base58 encoded string |
def is_excluded(self, cid, pod_uid=None):
"""
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 metric... | 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... |
def _merge_points(self, pc1, pc2):
"""
Merges points based on time/location.
@TODO: move to paegan, SO SLOW
"""
res = pc1[:]
for p in pc2:
for sp in res:
if sp.time == p.time and (
sp.location is None or (sp.location.equal... | Merges points based on time/location.
@TODO: move to paegan, SO SLOW |
def observe(self, key: str, callback: Callable[[Any, Any], None]):
"""Subscribes to key changes"""
if key not in self._callbacks:
self._add_key(key)
self._callbacks[key].append(callback) | Subscribes to key changes |
def unregister(self, name: str):
'''Unregister hook.'''
del self._callbacks[name]
if self._event_dispatcher is not None:
self._event_dispatcher.unregister(name) | Unregister hook. |
def use_plenary_comment_view(self):
"""Pass through to provider CommentLookupSession.use_plenary_comment_view"""
self._object_views['comment'] = PLENARY
# self._get_provider_session('comment_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions... | Pass through to provider CommentLookupSession.use_plenary_comment_view |
def check_submission_successful(self, submission_id=None):
"""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 i... | 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:... |
def _extract_ocsp_certs(self, ocsp_response):
"""
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
"""
status = ocsp_re... | 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 |
def visualize(
logdir, outdir, num_agents, num_episodes, checkpoint=None,
env_processes=True):
"""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... | 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... |
def _difference_map(image, color_axis):
"""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
... | 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] ... |
def x_rotate(rotationAmt):
"""Create a matrix that rotates around the x axis."""
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))
... | Create a matrix that rotates around the x axis. |
def fbeta_score(targets, predictions, beta=1.0, average='macro'):
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... | 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... |
def find_prop_overlap(rdf, prop1, prop2):
"""Generate (subject,object) pairs connected by two properties."""
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. |
def load_contexts_and_renderers(events, mediums):
"""
Given a list of events and mediums, load the context model data into the contexts of the events.
"""
sources = {event.source for event in events}
rendering_styles = {medium.rendering_style for medium in mediums if medium.rendering_style}
# F... | Given a list of events and mediums, load the context model data into the contexts of the events. |
def describe_listeners(load_balancer_arn=None, listener_arns=None, client=None):
"""
Permission: elasticloadbalancing:DescribeListeners
"""
kwargs = dict()
if load_balancer_arn:
kwargs.update(dict(LoadBalancerArn=load_balancer_arn))
if listener_arns:
kwargs.update(dict(ListenerAr... | Permission: elasticloadbalancing:DescribeListeners |
def get_image_uri(region_name, repo_name, repo_version=1):
"""Return algorithm image URI for the given AWS region, repository name, and repository version"""
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 |
def check_table(table=None, family='ipv4'):
'''
Check for the existence of a table
CLI Example::
salt '*' nftables.check_table nat
'''
ret = {'comment': '',
'result': False}
if not table:
ret['comment'] = 'Table needs to be specified'
return ret
nft_fam... | Check for the existence of a table
CLI Example::
salt '*' nftables.check_table nat |
def copy(src, dst):
"""
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 objec... | 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... |
def get_objective_banks_by_ids(self, objective_bank_ids=None):
"""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 resul... | 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... |
def convpar(p):
"""
Convert a parameter set from convenient Python dictionary to the format
expected by the Fortran kernels.
"""
if 'el' not in p:
return p
els = p['el']
nel = len(els)
q = { }
for name, values in p.items():
if isinstance(values, dict):
... | Convert a parameter set from convenient Python dictionary to the format
expected by the Fortran kernels. |
def photometry(
self):
"""*The associated source photometry*
**Usage:**
.. code-block:: python
sourcePhotometry = tns.photometry
"""
photResultsList = []
photResultsList[:] = [dict(l) for l in self.photResultsList]
return photRe... | *The associated source photometry*
**Usage:**
.. code-block:: python
sourcePhotometry = tns.photometry |
def remove_server(self, name):
"""Remove a server from the dict."""
for i in self._server_list:
if i['key'] == name:
try:
self._server_list.remove(i)
logger.debug("Remove server %s from the list" % name)
logger.debug... | Remove a server from the dict. |
def immerkaer(input, mode="reflect", cval=0.0):
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... | 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... |
def _filter_unscheduled_routers(self, plugin, context, routers):
"""Filter from list of routers the ones that are not scheduled.
Only for release < pike.
"""
if NEUTRON_VERSION.version[0] <= NEUTRON_NEWTON_VERSION.version[0]:
context, plugin = plugin, context
unsc... | Filter from list of routers the ones that are not scheduled.
Only for release < pike. |
def kdot(x, y, K=2):
"""Algorithm 5.10. Dot product algorithm in K-fold working precision,
K >= 3.
"""
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.shap... | 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.