code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def update_channels(self):
"""Update the GUI to reflect channels and image listing.
"""
if not self.gui_up:
return
self.logger.debug("channel configuration has changed--updating gui")
try:
channel = self.fv.get_channel(self.chname)
except KeyErro... | Update the GUI to reflect channels and image listing. |
def increment_step_and_update_last_reward(self):
"""
Increment the step count of the trainer and Updates the last reward
"""
if len(self.stats['Environment/Cumulative Reward']) > 0:
mean_reward = np.mean(self.stats['Environment/Cumulative Reward'])
self.policy.upd... | Increment the step count of the trainer and Updates the last reward |
def parse_lheading(self, m):
"""Parse setext heading."""
self.tokens.append({
'type': 'heading',
'level': 1 if m.group(2) == '=' else 2,
'text': m.group(1),
}) | Parse setext heading. |
def print_request(request):
""" Prints a prepared request to give the user info as to what they're sending
:param request.PreparedRequest request: PreparedRequest object to be printed
:return: Nothing
"""
print('{}\n{}\n{}\n\n{}'.format(
'-----------START-----------',
request.method... | Prints a prepared request to give the user info as to what they're sending
:param request.PreparedRequest request: PreparedRequest object to be printed
:return: Nothing |
def get_frames_mouth(self, detector, predictor, frames):
"""
Get frames using mouth crop
"""
mouth_width = 100
mouth_height = 50
horizontal_pad = 0.19
normalize_ratio = None
mouth_frames = []
for frame in frames:
dets = detector(frame, ... | Get frames using mouth crop |
def path_get(p: tcod.path.AStar, idx: int) -> Tuple[int, int]:
"""Get a point on a path.
Args:
p (AStar): An AStar instance.
idx (int): Should be in range: 0 <= inx < :any:`path_size`
"""
x = ffi.new("int *")
y = ffi.new("int *")
lib.TCOD_path_get(p._path_c, idx, x, y)
retur... | Get a point on a path.
Args:
p (AStar): An AStar instance.
idx (int): Should be in range: 0 <= inx < :any:`path_size` |
def getattr_sdk(attr, name):
"""
Filter SDK attributes
Args:
attr(attribute): Attribute as returned by :func:`getattr`.
name(str): Attribute name.
Returns:
`attr` if passed.
"""
if inspect.isroutine(attr):
if hasattr(attr, '_sdkmeta'):
return attr
... | Filter SDK attributes
Args:
attr(attribute): Attribute as returned by :func:`getattr`.
name(str): Attribute name.
Returns:
`attr` if passed. |
def gaussApprox(self,xy,**kwargs):
"""
NAME:
gaussApprox
PURPOSE:
return the mean and variance of a Gaussian approximation to the stream DF at a given phase-space point in Galactocentric rectangular coordinates (distribution is over missing directions)
INPUT:
... | NAME:
gaussApprox
PURPOSE:
return the mean and variance of a Gaussian approximation to the stream DF at a given phase-space point in Galactocentric rectangular coordinates (distribution is over missing directions)
INPUT:
xy - phase-space point [X,Y,Z,vX,vY,vZ]; the ... |
def phi(v):
"""Neutrino direction in polar coordinates.
``phi``, ``theta`` is the opposite of ``zenith``, ``azimuth``.
Angles in radians.
"""
v = np.atleast_2d(v)
dir_x = v[:, 0]
dir_y = v[:, 1]
return phi_separg(dir_x, dir_y) | Neutrino direction in polar coordinates.
``phi``, ``theta`` is the opposite of ``zenith``, ``azimuth``.
Angles in radians. |
def get_spectrum(self, nr_id=None, abmn=None, plot_filename=None):
"""Return a spectrum and its reciprocal counter part, if present in the
dataset. Optimally, refer to the spectrum by its normal-reciprocal id.
Returns
-------
spectrum_nor : :py:class:`reda.eis.plots.sip_response... | Return a spectrum and its reciprocal counter part, if present in the
dataset. Optimally, refer to the spectrum by its normal-reciprocal id.
Returns
-------
spectrum_nor : :py:class:`reda.eis.plots.sip_response`
Normal spectrum. None if no normal spectrum is available
... |
def servers_update_addresses(request, servers, all_tenants=False):
"""Retrieve servers networking information from Neutron if enabled.
Should be used when up to date networking information is required,
and Nova's networking info caching mechanism is not fast enough.
"""
# NOTE(amotoki): This... | Retrieve servers networking information from Neutron if enabled.
Should be used when up to date networking information is required,
and Nova's networking info caching mechanism is not fast enough. |
def resampled(
chunksize_bytes=DEFAULT_CHUNK_SIZE,
resample_to=SR44100(),
store_resampled=False):
"""
Create a basic processing pipeline that can resample all incoming audio
to a normalized sampling rate for downstream processing, and store a
convenient, compressed version for pl... | Create a basic processing pipeline that can resample all incoming audio
to a normalized sampling rate for downstream processing, and store a
convenient, compressed version for playback
:param chunksize_bytes: The number of bytes from the raw stream to process
at once
:param resample_to: The new, no... |
def clear(self) -> None:
"""Clears the text if it's a text entry element."""
self.click()
for i in self.text:
self._parent.send_keyevents(Keys.DEL) | Clears the text if it's a text entry element. |
def drop(self, fname):
"""
drop the table, view or delete the file
"""
if self.dataset_type == 'file':
import os
try:
os.remove(fname)
except Exception as ex:
print('cant drop file "' + fname + '" : ' + str(ex)) | drop the table, view or delete the file |
def variability_fp(ts, freqs=None, ncycles=6, plot=True):
"""Example variability function.
Gives two continuous, time-resolved measures of the variability of a
time series, ranging between -1 and 1.
The two measures are based on variance of the centroid frequency and
variance of the height of the ... | Example variability function.
Gives two continuous, time-resolved measures of the variability of a
time series, ranging between -1 and 1.
The two measures are based on variance of the centroid frequency and
variance of the height of the spectral peak, respectively.
(Centroid frequency meaning the ... |
def update_firmware_nfs_or_cifs(filename, share,
host=None,
admin_username=None,
admin_password=None):
'''
Executes the following for CIFS
(using username and password stored in the pillar data)
.. code-bloc... | Executes the following for CIFS
(using username and password stored in the pillar data)
.. code-block:: bash
racadm update -f <updatefile> -u user –p pass -l //IP-Address/share
Or for NFS
(using username and password stored in the pillar data)
.. code-block:: bash
racadm upda... |
def capture_payment(request):
"""
Capture the payment for a basket and create an order
request.data should contain:
'address': Dict with the following fields:
shipping_name
shipping_address_line1
shipping_address_city
shipping_address_zip
shipping_address_countr... | Capture the payment for a basket and create an order
request.data should contain:
'address': Dict with the following fields:
shipping_name
shipping_address_line1
shipping_address_city
shipping_address_zip
shipping_address_country
billing_name
billing_add... |
def Theta(i,j,theta,omega_rescaled,omega_min,
detunings,detuningsij,combinations,detuning_indices,
Lij,i_d,I_nd,Nnd,
states=None,verbose=1,other_the=None):
"""This function returns code for Theta_i j as defined in the equation labeled Theta. in terms
of detunings. It recieves indexes i,j starting from 1."""
... | This function returns code for Theta_i j as defined in the equation labeled Theta. in terms
of detunings. It recieves indexes i,j starting from 1. |
def strip_prompt_login(path):
"""
Strips 'login' from the 'prompt' query parameter.
"""
uri = urlsplit(path)
query_params = parse_qs(uri.query)
prompt_list = query_params.get('prompt', '')[0].split()
if 'login' in prompt_list:
prompt_list.remove('login')
query_params['prompt'... | Strips 'login' from the 'prompt' query parameter. |
def sort(self, ascending=True):
"""
Sort all values in this SArray.
Sort only works for sarray of type str, int and float, otherwise TypeError
will be raised. Creates a new, sorted SArray.
Parameters
----------
ascending: boolean, optional
If true, th... | Sort all values in this SArray.
Sort only works for sarray of type str, int and float, otherwise TypeError
will be raised. Creates a new, sorted SArray.
Parameters
----------
ascending: boolean, optional
If true, the sarray values are sorted in ascending order, other... |
def cli(conf):
""" OpenVPN user_pass_verify method
"""
config = init_config(conf)
nas_id = config.get('DEFAULT', 'nas_id')
nas_addr = config.get('DEFAULT', 'nas_addr')
secret = config.get('DEFAULT', 'radius_secret')
radius_addr = config.get('DEFAULT', 'radius_addr')
radius_auth_port = co... | OpenVPN user_pass_verify method |
def count(self, Class, set=None, recursive=True, ignore=True, node=None):
"""Like :meth:`AbstractElement.select`, but instead of returning the elements, it merely counts them.
Returns:
int
"""
return sum(1 for i in self.select(Class,set,recursive,ignore,node) ) | Like :meth:`AbstractElement.select`, but instead of returning the elements, it merely counts them.
Returns:
int |
def constraint_piechart(self,primarylist=None,
fig=None,title='',colordict=None,
legend=True,nolabels=False):
"""Makes piechart illustrating constraints on population
:param primarylist: (optional)
List of most import constraints to sh... | Makes piechart illustrating constraints on population
:param primarylist: (optional)
List of most import constraints to show (see
:func:`StarPopulation.constraint_stats`)
:param fig: (optional)
Passed to :func:`plotutils.setfig`.
:param title: (optional)
... |
def get_user(self):
"""
returns the username on this computer
"""
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
user = os.environ.get(name)
if user:
break
for u in users:
if u['name'] == user:
retu... | returns the username on this computer |
def check_runtime_remaining(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.4.1.318.1.1.1.2.2.3.0
MIB excerpt
The UPS battery run time remaining before battery
exhaustion.
SNMP value is in TimeTicks aka hundredths of a second
"""
a_minute_value = calc_minutes_from_ticks(the_s... | OID .1.3.6.1.4.1.318.1.1.1.2.2.3.0
MIB excerpt
The UPS battery run time remaining before battery
exhaustion.
SNMP value is in TimeTicks aka hundredths of a second |
def simplify(self, options=None):
"""
generate a simple dict representing this change data, and
collecting all of the sub-change instances (which are NOT
immediately simplified themselves)
"""
data = super(SuperChange, self).simplify(options)
show_ignored = Fals... | generate a simple dict representing this change data, and
collecting all of the sub-change instances (which are NOT
immediately simplified themselves) |
def verify_x509_cert_chain(cert_chain, ca_pem_file=None, ca_path=None):
"""
Look at certs in the cert chain and add them to the store one by one.
Return the cert at the end of the chain. That is the cert to be used by the caller for verifying.
From https://www.w3.org/TR/xmldsig-core2/#sec-X509Data:
... | Look at certs in the cert chain and add them to the store one by one.
Return the cert at the end of the chain. That is the cert to be used by the caller for verifying.
From https://www.w3.org/TR/xmldsig-core2/#sec-X509Data:
"All certificates appearing in an X509Data element must relate to the validation key... |
def set_identity_pool_roles(IdentityPoolId, AuthenticatedRole=None, UnauthenticatedRole=None,
region=None, key=None, keyid=None, profile=None):
'''
Given an identity pool id, set the given AuthenticatedRole and UnauthenticatedRole (the Role
can be an iam arn, or a role name) If AuthenticatedRole or... | Given an identity pool id, set the given AuthenticatedRole and UnauthenticatedRole (the Role
can be an iam arn, or a role name) If AuthenticatedRole or UnauthenticatedRole is not given,
the authenticated and/or the unauthenticated role associated previously with the pool will be
cleared.
Returns set T... |
def _selectItem(self, index):
"""Select item in the list
"""
self._selectedIndex = index
self.setCurrentIndex(self.model().createIndex(index, 0)) | Select item in the list |
def natural_keys(text):
"""Sort list of string with number in human order.
Examples
----------
>>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg']
>>> l.sort(key=tl.files.natural_keys)
['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg']
>>> l.sort... | Sort list of string with number in human order.
Examples
----------
>>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg']
>>> l.sort(key=tl.files.natural_keys)
['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg']
>>> l.sort() # that is what we dont want
... |
def do_bb_intersect(a, b):
"""Check if BoundingBox a intersects with BoundingBox b."""
return a.p1.x <= b.p2.x \
and a.p2.x >= b.p1.x \
and a.p1.y <= b.p2.y \
and a.p2.y >= b.p1.y | Check if BoundingBox a intersects with BoundingBox b. |
def out_of_china(lng, lat):
"""
判断是否在国内,不在国内不做偏移
:param lng:
:param lat:
:return:
"""
if lng < 72.004 or lng > 137.8347:
return True
if lat < 0.8293 or lat > 55.8271:
return True
return False | 判断是否在国内,不在国内不做偏移
:param lng:
:param lat:
:return: |
def _getPrefixURL(self, url):
"""
Given a url return namespace prefix.
Leverages prefixes already in graph namespace
Ex. "http://www.drugbank.ca/drugs/DDD"
-> "http://www.drugbank.ca/drugs/"
"""
for prefix, namespace in self._rdfGraph.namespaces():
... | Given a url return namespace prefix.
Leverages prefixes already in graph namespace
Ex. "http://www.drugbank.ca/drugs/DDD"
-> "http://www.drugbank.ca/drugs/" |
def encode_request(from_pid, to_pid, method, body=None, content_type=None, legacy=False):
"""
Encode a request into a raw HTTP request. This function returns a string
of bytes that represent a valid HTTP/1.0 request, including any libprocess
headers required for communication.
Use the `legacy` option (set to... | Encode a request into a raw HTTP request. This function returns a string
of bytes that represent a valid HTTP/1.0 request, including any libprocess
headers required for communication.
Use the `legacy` option (set to True) to use the legacy User-Agent based
libprocess identification. |
def _miraligner(fastq_file, out_file, species, db_folder, config):
"""
Run miraligner tool (from seqcluster suit) with default
parameters.
"""
resources = config_utils.get_resources("miraligner", config)
miraligner = config_utils.get_program("miraligner", config)
jvm_opts = "-Xms750m -Xmx4g... | Run miraligner tool (from seqcluster suit) with default
parameters. |
def get_base_type_of_signal(signal):
# type: (canmatrix.Signal) -> typing.Tuple[str, int]
"""Get signal arxml-type and size based on the Signal properties."""
if signal.is_float:
if signal.size > 32:
create_type = "double"
size = 64
else:
create_type = "si... | Get signal arxml-type and size based on the Signal properties. |
def reply_video_note(
self,
video_note: str,
quote: bool = None,
duration: int = 0,
length: int = 1,
thumb: str = None,
disable_notification: bool = None,
reply_to_message_id: int = None,
reply_markup: Union[
"pyrogram.InlineKeyboardMar... | Bound method *reply_video_note* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_video_note(
chat_id=message.chat.id,
video_note=video_note
)
Example:
.. code-block:: python
... |
def sortBy(self, sortOptions, reverse=False):
"""
Sort ``fonts`` with the ordering preferences defined
by ``sortBy``. ``sortBy`` must be one of the following:
* sort description string
* :class:`BaseInfo` attribute name
* sort value function
* list/tuple containi... | Sort ``fonts`` with the ordering preferences defined
by ``sortBy``. ``sortBy`` must be one of the following:
* sort description string
* :class:`BaseInfo` attribute name
* sort value function
* list/tuple containing sort description strings, :class:`BaseInfo`
attribute... |
def json_dumps(self, data, **options):
"""
Wrapper around `json.dumps` that uses a special JSON encoder.
"""
params = {'sort_keys': True, 'indent': 2}
params.update(options)
# This code is based off django's built in JSON serializer
if json.__version__.split('.') ... | Wrapper around `json.dumps` that uses a special JSON encoder. |
def flush(self):
"""Flushes this instance's cache.
The driver of this instance should call this method every
`flush_interval`.
Returns:
list['CheckRequest']: corresponding to CheckRequests that were
pending
"""
if self._cache is None:
re... | Flushes this instance's cache.
The driver of this instance should call this method every
`flush_interval`.
Returns:
list['CheckRequest']: corresponding to CheckRequests that were
pending |
def list_user_permissions(self, name):
"""
A list of all permissions for a given user.
:param name: The user's name
:type name: str
"""
return self._api_get('/api/users/{0}/permissions'.format(
urllib.parse.quote_plus(name)
)) | A list of all permissions for a given user.
:param name: The user's name
:type name: str |
def is_running(self):
"""Check if ZAP is running."""
try:
result = requests.get(self.proxy_url)
except RequestException:
return False
if 'ZAP-Header' in result.headers.get('Access-Control-Allow-Headers', []):
return True
raise ZAPError('Anoth... | Check if ZAP is running. |
def _cnf_formula(lexer, varname, nvars, nclauses):
"""Return a DIMACS CNF formula."""
clauses = _clauses(lexer, varname, nvars)
if len(clauses) < nclauses:
fstr = "formula has fewer than {} clauses"
raise Error(fstr.format(nclauses))
if len(clauses) > nclauses:
fstr = "formula h... | Return a DIMACS CNF formula. |
def uninstall(python=PYTHON):
"""Uninstall from site-packages"""
site_packages = local(
"{python} -c 'from distutils.sysconfig import "
"get_python_lib; print(get_python_lib())'".format(python=python),
capture=True,
)
with lcd(site_packages):
local("sudo rm mpfr.so")
... | Uninstall from site-packages |
def _rewrite_source(self, s):
"""
Mutate the source according to the per-task parameters.
"""
# While Ansible rewrites the #! using ansible_*_interpreter, it is
# never actually used to execute the script, instead it is a shell
# fragment consumed by shell/__init__.py::bu... | Mutate the source according to the per-task parameters. |
def explain_rf_feature_importance(estimator,
vec=None,
top=_TOP,
target_names=None, # ignored
targets=None, # ignored
feature_names=None,
... | Return an explanation of a tree-based ensemble estimator.
See :func:`eli5.explain_weights` for description of
``top``, ``feature_names``, ``feature_re`` and ``feature_filter``
parameters.
``target_names`` and ``targets`` parameters are ignored.
``vec`` is a vectorizer instance used to transform
... |
def permute(self, permutations: List[mx.nd.NDArray]) -> 'ParallelDataSet':
"""
Permutes the data within each bucket. The permutation is received as an argument,
allowing the data to be unpermuted (i.e., restored) later on.
:param permutations: For each bucket, a permutation of the data ... | Permutes the data within each bucket. The permutation is received as an argument,
allowing the data to be unpermuted (i.e., restored) later on.
:param permutations: For each bucket, a permutation of the data within that bucket.
:return: A new, permuted ParallelDataSet. |
def get_output_lines_from_command(host, command):
"""Execute a command on the specified host, returning a list of
output lines.
:param host: the host name
:type host: str
:param command: the command
:type commmand: str
"""
with closing(ssh_client(host)) as ssh:
_, stdout, stderr... | Execute a command on the specified host, returning a list of
output lines.
:param host: the host name
:type host: str
:param command: the command
:type commmand: str |
def visit_FunctionDef(self, node):
""" Determine this function definition can be inlined. """
if (len(node.body) == 1 and
isinstance(node.body[0], (ast.Call, ast.Return))):
ids = self.gather(Identifiers, node.body[0])
# FIXME : It mark "not inlinable" def foo(foo)... | Determine this function definition can be inlined. |
def create(cls, name, situation_context, attacker=None, target=None,
severity='information', situation_type=None, description=None,
comment=None):
"""
Create an inspection situation.
:param str name: name of the situation
:param InspectionSituationC... | Create an inspection situation.
:param str name: name of the situation
:param InspectionSituationContext situation_context: The situation
context type used to define this situation. Identifies the proper
parameter that identifies how the situation is defined (i.e. regex,... |
def CompileFilesRelative(self):
"""
Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory.
"""
return (os.path.relpath(path, self.ProjectHome) for path in sorted(self.CompileFiles, key=self.lower)) | Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory. |
def begin_write(self, content_type=None):
"""Open content as a stream for writing.
See DAVResource.begin_write()
"""
assert not self.is_collection
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
# _logger.debug("begin_write: {}, {}".format(self._fil... | Open content as a stream for writing.
See DAVResource.begin_write() |
def _applyTriggerValue(self, triggerName, outval):
""" Here we look through the entire .cfgspc to see if any parameters
are affected by this trigger. For those that are, we apply the action
to the GUI widget. The action is specified by depType. """
# First find which items are dependen... | Here we look through the entire .cfgspc to see if any parameters
are affected by this trigger. For those that are, we apply the action
to the GUI widget. The action is specified by depType. |
def DbImportDevice(self, argin):
""" Import a device from the database
:param argin: Device name (or alias)
:type: tango.DevString
:return: Str[0] = device name
Str[1] = CORBA IOR
Str[2] = device version
Str[3] = device server process name
Str[4] = host n... | Import a device from the database
:param argin: Device name (or alias)
:type: tango.DevString
:return: Str[0] = device name
Str[1] = CORBA IOR
Str[2] = device version
Str[3] = device server process name
Str[4] = host name
Str[5] = Tango class name
... |
def filter_gradient_threshold(self, analyte, win, threshold, recalc=True):
"""
Apply gradient threshold filter.
Generates threshold filters for the given analytes above and below
the specified threshold.
Two filters are created with prefixes '_above' and '_below'.
'... | Apply gradient threshold filter.
Generates threshold filters for the given analytes above and below
the specified threshold.
Two filters are created with prefixes '_above' and '_below'.
'_above' keeps all the data above the threshold.
'_below' keeps all the data below t... |
def _auth(self, username, password) :
""" Authentificate user and store token """
self.user_credentials = self.call('auth', {'username': username, 'password': password})
if 'error' in self.user_credentials:
raise T411Exception('Error while fetching authentication token: %s'\... | Authentificate user and store token |
async def handle_websocket_exception(self, error: Exception) -> Optional[Response]:
"""Handle an uncaught exception.
By default this logs the exception and then re-raises it.
"""
await got_websocket_exception.send(self, exception=error)
self.log_exception(sys.exc_info())
... | Handle an uncaught exception.
By default this logs the exception and then re-raises it. |
def update_serial(self, new_serial):
"""Updates the serial number of a device.
The "serial number" used with adb's `-s` arg is not necessarily the
actual serial number. For remote devices, it could be a combination of
host names and port numbers.
This is used for when such iden... | Updates the serial number of a device.
The "serial number" used with adb's `-s` arg is not necessarily the
actual serial number. For remote devices, it could be a combination of
host names and port numbers.
This is used for when such identifier of remote devices changes during
... |
def preprocess(self, raw_inputs):
"""Convert images into the format required by our model.
Our model requires that inputs be grayscale (mode 'L'), be resized to
`MNIST_DIM`, and be represented as float32 numpy arrays in range
[0, 1].
Args:
raw_inputs (list of Images... | Convert images into the format required by our model.
Our model requires that inputs be grayscale (mode 'L'), be resized to
`MNIST_DIM`, and be represented as float32 numpy arrays in range
[0, 1].
Args:
raw_inputs (list of Images): a list of PIL Image objects
Retur... |
def send_session_setup_result(self, result, app_uuid=None):
'''
Send the result of setting up a dictation session requested by the watch
:param result: result of setting up the session
:type result: .SetupResult
:param app_uuid: UUID of app that initiated the session
:t... | Send the result of setting up a dictation session requested by the watch
:param result: result of setting up the session
:type result: .SetupResult
:param app_uuid: UUID of app that initiated the session
:type app_uuid: uuid.UUID |
def detect_plates(step, vrms_surface, fids, time):
"""detect plates using derivative of horizontal velocity"""
vphi = step.fields['v2'][0, :, :, 0]
ph_coord = step.geom.p_coord
if step.sdat.par['boundaries']['air_layer']:
dsa = step.sdat.par['boundaries']['air_thickness']
# we are a bit... | detect plates using derivative of horizontal velocity |
async def SetStatusMessage(self, message):
'''
message : str
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='MigrationMaster',
request='SetStatusMessage',
version=1,
params... | message : str
Returns -> None |
def add_features(self, **features):
""" Add or update several features. """
for fname, fvalue in six.iteritems(features):
setattr(self, fname, fvalue)
self.features.add(fname) | Add or update several features. |
def project_update_event(self, proj_info):
"""Process project update event.
There could be change in project name. DCNM doesn't allow change in
project (a.k.a tenant). This event may be received for the DCI update.
If the change is for DCI, update the DCI portion of the project name
... | Process project update event.
There could be change in project name. DCNM doesn't allow change in
project (a.k.a tenant). This event may be received for the DCI update.
If the change is for DCI, update the DCI portion of the project name
and send the update event to the DCNM. |
def image_url(self, width=None, height=None):
"""
Returns URL to placeholder image
Example: http://placehold.it/640x480
"""
width_ = width or self.random_int(max=1024)
height_ = height or self.random_int(max=1024)
placeholder_url = self.random_element(self.image_p... | Returns URL to placeholder image
Example: http://placehold.it/640x480 |
def proximal_gradient(x, f, g, gamma, niter, callback=None, **kwargs):
r"""(Accelerated) proximal gradient algorithm for convex optimization.
Also known as "Iterative Soft-Thresholding Algorithm" (ISTA).
See `[Beck2009]`_ for more information.
This solver solves the convex optimization problem::
... | r"""(Accelerated) proximal gradient algorithm for convex optimization.
Also known as "Iterative Soft-Thresholding Algorithm" (ISTA).
See `[Beck2009]`_ for more information.
This solver solves the convex optimization problem::
min_{x in X} f(x) + g(x)
where the proximal operator of ``f`` is k... |
def decodetx(tx_hex, coin_symbol='btc', api_key=None):
'''
Takes a signed transaction hex binary (and coin_symbol) and decodes it to JSON.
Does NOT broadcast the transaction to the bitcoin network.
Especially useful for testing/debugging and sanity checking
'''
assert is_valid_coin_symbol(coin... | Takes a signed transaction hex binary (and coin_symbol) and decodes it to JSON.
Does NOT broadcast the transaction to the bitcoin network.
Especially useful for testing/debugging and sanity checking |
def _fix_file(parameters):
"""Helper function for optionally running fix_file() in parallel."""
if parameters[1].verbose:
print('[file:{0}]'.format(parameters[0]), file=sys.stderr)
try:
fix_file(*parameters)
except IOError as error:
print(unicode(error), file=sys.stderr) | Helper function for optionally running fix_file() in parallel. |
def make_pattern( patt, flags=0 ):
"""
returns a compile regular expression object
"""
# print('input',len(patt))
patt_letters = utf8.get_letters( patt )
patt_out = list()
idx = 0
# print('output',len(patt_letters))
patt = [None,None]
prev = None
LEN_PATT = len(patt_lette... | returns a compile regular expression object |
def decode(self):
"""Decode this report into a single reading
"""
fmt, _, stream, uuid, sent_timestamp, reading_timestamp, reading_value = unpack("<BBHLLLL", self.raw_report)
assert fmt == 0
# Estimate the UTC time when this device was turned on
time_base = self.receive... | Decode this report into a single reading |
def group_by(self, *fields):
"""
Clone the queryset using GroupByQuerySet.
:param fields:
:return:
"""
fields = self._expand_group_by_fields(self.model, fields)
clone = self._values(*fields)
clone._iterable_class = GroupByIterable
return clone | Clone the queryset using GroupByQuerySet.
:param fields:
:return: |
def inviteFriend(self, user, server, sections=None, allowSync=False, allowCameraUpload=False,
allowChannels=False, filterMovies=None, filterTelevision=None, filterMusic=None):
""" Share library content with the specified user.
Parameters:
user (str): MyPlexUser, username, ... | Share library content with the specified user.
Parameters:
user (str): MyPlexUser, username, email of the user to be added.
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
sections ([Section]): Library sec... |
def _publish_internal(self, push_messages):
"""Send push notifications
The server will validate any type of syntax errors and the client will
raise the proper exceptions for the user to handle.
Each notification is of the form:
{
'to': 'ExponentPushToken[xxx]',
... | Send push notifications
The server will validate any type of syntax errors and the client will
raise the proper exceptions for the user to handle.
Each notification is of the form:
{
'to': 'ExponentPushToken[xxx]',
'body': 'This text gets display in the notification... |
def shape(self) -> Tuple[int, ...]:
"""Shape of histogram's data.
Returns
-------
One-element tuple with the number of bins along each axis.
"""
return tuple(bins.bin_count for bins in self._binnings) | Shape of histogram's data.
Returns
-------
One-element tuple with the number of bins along each axis. |
def hash_file(fileobj):
"""
:param fileobj: a file object
:return: a hash of the file content
"""
hasher = hashlib.md5()
buf = fileobj.read(65536)
while len(buf) > 0:
hasher.update(buf)
buf = fileobj.read(65536)
return hasher.hexdigest() | :param fileobj: a file object
:return: a hash of the file content |
def _maybe_assert_valid_sample(self, x):
"""Checks the validity of a sample."""
if not self.validate_args:
return x
return distribution_util.with_dependencies([
assert_util.assert_positive(x, message="samples must be positive"),
assert_util.assert_near(
tf.ones([], dtype=se... | Checks the validity of a sample. |
def ising_to_qubo(h, J, offset=0.0):
"""Convert an Ising problem to a QUBO problem.
Map an Ising model defined on spins (variables with {-1, +1} values) to quadratic
unconstrained binary optimization (QUBO) formulation :math:`x' Q x` defined over
binary variables (0 or 1 values), where the linear ter... | Convert an Ising problem to a QUBO problem.
Map an Ising model defined on spins (variables with {-1, +1} values) to quadratic
unconstrained binary optimization (QUBO) formulation :math:`x' Q x` defined over
binary variables (0 or 1 values), where the linear term is contained along the diagonal of Q.
... |
def midPoint(self, point):
"""identify the midpoint between two mapPoints"""
x = (self.x + point.x)/2.0
y = (self.y + point.y)/2.0
z = (self.z + point.z)/2.0
return MapPoint(x,y,z) | identify the midpoint between two mapPoints |
def pretty_print_error(err_json):
"""Pretty print Flask-Potion error messages for the user."""
# Special case validation errors
if len(err_json) == 1 and "validationOf" in err_json[0]:
required_fields = ", ".join(err_json[0]["validationOf"]["required"])
return "Validation error. Requires pro... | Pretty print Flask-Potion error messages for the user. |
def segwit_address(self):
"""The public segwit nested in P2SH address you share with others to
receive funds."""
# Only make segwit address if public key is compressed
if self._segwit_address is None and self.is_compressed():
self._segwit_address = public_key_to_segwit_addres... | The public segwit nested in P2SH address you share with others to
receive funds. |
def plot_noncontiguous(ax, data, ind, color='black', label='', offset=0,
linewidth=0.5, linestyle='-'):
'''Plot non-contiguous slice of data
Args
----
data: ndarray
The data with non continguous regions to plot
ind: ndarray
indices of data to be plotted
color: matplotlib... | Plot non-contiguous slice of data
Args
----
data: ndarray
The data with non continguous regions to plot
ind: ndarray
indices of data to be plotted
color: matplotlib color
Color of plotted line
label: str
Name to be shown in legend
offset: int
The numb... |
def add_lun(self, luns):
"""A wrapper for modify method.
.. note:: This API only append luns to existing luns.
"""
curr_lun_ids, curr_smp_names = self._get_current_names()
luns = normalize_lun(luns, self._cli)
new_ids, new_smps = convert_lun(luns)
if new_ids:
... | A wrapper for modify method.
.. note:: This API only append luns to existing luns. |
def install(self,
package,
shutit_pexpect_child=None,
options=None,
timeout=shutit_global.shutit_global_object.default_timeout,
force=False,
check_exit=True,
echo=None,
reinstall=False,
background=False,... | Distro-independent install function.
Takes a package name and runs the relevant install function.
@param package: Package to install, which is run through package_map
@param shutit_pexpect_child: See send()
@param timeout: Timeout (s) to wait for finish of install. Defaults to 3600.
@param options... |
def titletable(html_doc, tofloat=True):
"""return a list of [(title, table), .....]
title = previous item with a <b> tag
table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..]"""
soup = BeautifulSoup(html_doc, "html.parser")
btables = soup.find_all(['b', 'table']) # find all the <b> and <tabl... | return a list of [(title, table), .....]
title = previous item with a <b> tag
table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..] |
def get_fields(self):
"""Returns the serializer's field set.
If `dynamic` is True, respects field inclusions/exlcusions.
Otherwise, reverts back to standard DRF behavior.
"""
all_fields = self.get_all_fields()
if self.dynamic is False:
return all_fields
... | Returns the serializer's field set.
If `dynamic` is True, respects field inclusions/exlcusions.
Otherwise, reverts back to standard DRF behavior. |
def copy(self):
"""
Create an inactive copy of the connection object, suitable for
passing to a background thread.
The returned copy is not connected; you must call reinit() before
using.
"""
c = copy.deepcopy(self)
# Python 3 doesn't copy custom attribut... | Create an inactive copy of the connection object, suitable for
passing to a background thread.
The returned copy is not connected; you must call reinit() before
using. |
def get_population(self, untracked: bool=False) -> pd.DataFrame:
"""Get a copy of the population state table."""
return self.population.get_population(untracked) | Get a copy of the population state table. |
def find_duplicates(items, k=2, key=None):
"""
Find all duplicate items in a list.
Search for all items that appear more than `k` times and return a mapping
from each (k)-duplicate item to the positions it appeared in.
Args:
items (Iterable): hashable items possibly containing duplicates
... | Find all duplicate items in a list.
Search for all items that appear more than `k` times and return a mapping
from each (k)-duplicate item to the positions it appeared in.
Args:
items (Iterable): hashable items possibly containing duplicates
k (int): only return items that appear at least ... |
def _call(self, x, out=None):
"""Linearly combine ``x`` and write to ``out`` if given."""
if out is None:
out = self.range.element()
out.lincomb(self.a, x[0], self.b, x[1])
return out | Linearly combine ``x`` and write to ``out`` if given. |
def get_dict_for_mongodb_queries(self):
"""
This function returns a dictionary with the attributes that will be
put in the mongodb document to facilitate the query.
Subclasses may want to replace or extend the default behaviour.
"""
d = {}
return d
# TODO
... | This function returns a dictionary with the attributes that will be
put in the mongodb document to facilitate the query.
Subclasses may want to replace or extend the default behaviour. |
def generate_pyxb_binding(self, args):
"""Args:
args:
"""
pyxbgen_args = []
pyxbgen_args.append('--schema-root=\'{}\''.format(self.schema_dir))
pyxbgen_args.append('--binding-root=\'{}\''.format(self.binding_dir))
pyxbgen_args.append(
'--schema-strip... | Args:
args: |
def check_format(cls, tags):
"""
Check the tags arg only contains valid type for tags
:param tags: output of create_tags_from_dict
:return: True if correct format, False otherwise
"""
common, _, _ = tags
for tag in common:
if tag.get_type() != 0: # Un... | Check the tags arg only contains valid type for tags
:param tags: output of create_tags_from_dict
:return: True if correct format, False otherwise |
def init_app(event_source, *, loop=None):
"""Init the application server.
Return:
An aiohttp application.
"""
dispatcher = Dispatcher(event_source)
# Schedule the dispatcher
loop.create_task(dispatcher.publish())
app = web.Application(loop=loop)
app['dispatcher'] = dispatcher... | Init the application server.
Return:
An aiohttp application. |
def get_cars_data():
"""
Load the cars dataset, split it into X and y, and then call the label encoder to get an integer y column.
:return:
"""
df = pd.read_csv('source_data/cars/car.data.txt')
X = df.reindex(columns=[x for x in df.columns.values if x != 'class'])
y = df.reindex(columns=['... | Load the cars dataset, split it into X and y, and then call the label encoder to get an integer y column.
:return: |
def delete(self):
"""
Delete a record from the database.
"""
if self._on_delete is not None:
return self._on_delete(self)
return self._query.delete() | Delete a record from the database. |
def return_dat(self, chan, begsam, endsam):
"""Return the data as 2D numpy.ndarray.
Parameters
----------
chan : int or list
index (indices) of the channels to read
begsam : int
index of the first sample
endsam : int
index of the last ... | Return the data as 2D numpy.ndarray.
Parameters
----------
chan : int or list
index (indices) of the channels to read
begsam : int
index of the first sample
endsam : int
index of the last sample
Returns
-------
numpy.n... |
def derivativeZ(self,mLvl,pLvl,MedShk):
'''
Evaluate the derivative of consumption and medical care with respect to
medical need shock at given levels of market resources, permanent income,
and medical need shocks.
Parameters
----------
mLvl : np.array
... | Evaluate the derivative of consumption and medical care with respect to
medical need shock at given levels of market resources, permanent income,
and medical need shocks.
Parameters
----------
mLvl : np.array
Market resource levels.
pLvl : np.array
... |
def edit(self, name=None, description=None, version=None, **kwargs):
"""
Edit Service details.
.. versionadded:: 1.13
:param name: (optional) name of the service to change.
:type name: basestring or None
:param description: (optional) description of the service.
... | Edit Service details.
.. versionadded:: 1.13
:param name: (optional) name of the service to change.
:type name: basestring or None
:param description: (optional) description of the service.
:type description: basestring or None
:param version: (optional) version number ... |
def singleton(the_class):
"""
Decorator for a class to make a singleton out of it.
@type the_class: class
@param the_class: the class that should work as a singleton
@rtype: decorator
@return: decorator
"""
class_instances = {}
def get_instance(*args, **kwargs):
"""
... | Decorator for a class to make a singleton out of it.
@type the_class: class
@param the_class: the class that should work as a singleton
@rtype: decorator
@return: decorator |
def get_firewall(self, firewall_id):
"""
Return a Firewall by its ID.
"""
return Firewall.get_object(
api_token=self.token,
firewall_id=firewall_id,
) | Return a Firewall by its ID. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.