code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def paint(str,color='r'):
'''Utility func, for printing colorful logs in console...
@args:
--
str : String to be modified.
color : color code to which the string will be formed. default is 'r'=RED
@returns:
--
str : final modified string with foreground color as per parameters.
''... | Utility func, for printing colorful logs in console...
@args:
--
str : String to be modified.
color : color code to which the string will be formed. default is 'r'=RED
@returns:
--
str : final modified string with foreground color as per parameters. |
def lomb_scargle_fast(t, y, dy=1, f0=0, df=None, Nf=None,
center_data=True, fit_offset=True,
use_fft=True, freq_oversampling=5, nyquist_factor=2,
trig_sum_kwds=None):
"""Compute a lomb-scargle periodogram for the given data
This implements both ... | Compute a lomb-scargle periodogram for the given data
This implements both an O[N^2] method if use_fft==False, or an
O[NlogN] method if use_fft==True.
Parameters
----------
t, y, dy : array_like
times, values, and errors of the data points. These should be
broadcastable to the same... |
def open_repository(path, spor_dir='.spor'):
"""Open an existing repository.
Args:
path: Path to any file or directory within the repository.
spor_dir: The name of the directory containing spor data.
Returns: A `Repository` instance.
Raises:
ValueError: No repository is found.... | Open an existing repository.
Args:
path: Path to any file or directory within the repository.
spor_dir: The name of the directory containing spor data.
Returns: A `Repository` instance.
Raises:
ValueError: No repository is found. |
def draw(self, drawDC=None):
"""
Render the figure using RendererWx instance renderer, or using a
previously defined renderer if none is specified.
"""
DEBUG_MSG("draw()", 1, self)
self.renderer = RendererWx(self.bitmap, self.figure.dpi)
self.figure.draw(self.rend... | Render the figure using RendererWx instance renderer, or using a
previously defined renderer if none is specified. |
def get_username(details, backend, response, *args, **kwargs):
"""Sets the `username` argument.
If the user exists already, use the existing username. Otherwise
generate username from the `new_uuid` using the
`helusers.utils.uuid_to_username` function.
"""
user = details.get('user')
if not... | Sets the `username` argument.
If the user exists already, use the existing username. Otherwise
generate username from the `new_uuid` using the
`helusers.utils.uuid_to_username` function. |
def lf_empirical_accuracies(L, Y):
"""Return the **empirical accuracy** against a set of labels Y (e.g. dev
set) for each LF.
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate
Y: an [n] or [n, 1] np.ndarray of gold labels
... | Return the **empirical accuracy** against a set of labels Y (e.g. dev
set) for each LF.
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate
Y: an [n] or [n, 1] np.ndarray of gold labels |
def vcenter_activate(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vcenter = ET.SubElement(config, "vcenter", xmlns="urn:brocade.com:mgmt:brocade-vswitch")
id_key = ET.SubElement(vcenter, "id")
id_key.text = kwargs.pop('id')
activate = ... | Auto Generated Code |
def opt_with_frequency_flattener(cls,
qchem_command,
multimode="openmp",
input_file="mol.qin",
output_file="mol.qout",
qclog_file="mol.... | Optimize a structure and calculate vibrational frequencies to check if the
structure is in a true minima. If a frequency is negative, iteratively
perturbe the geometry, optimize, and recalculate frequencies until all are
positive, aka a true minima has been found.
Args:
qche... |
def _assertIndex(self, index):
"""Raise TypeError or IndexError if index is not an integer or out of
range for the number of elements in this array, respectively.
"""
if type(index) is not int:
raise TypeError('list indices must be integers')
if index < 0 or index >= ... | Raise TypeError or IndexError if index is not an integer or out of
range for the number of elements in this array, respectively. |
def main():
"""
This function obtains hosts from core and starts a nessus scan on these hosts.
The nessus tag is appended to the host tags.
"""
config = Config()
core = HostSearch()
hosts = core.get_hosts(tags=['!nessus'], up=True)
hosts = [host for host in hosts]
host_ips = ... | This function obtains hosts from core and starts a nessus scan on these hosts.
The nessus tag is appended to the host tags. |
def get_examples(self, compact=False):
"""
Returns an OrderedDict mapping labels to Example objects.
Args:
compact (bool): If True, union members of void type are converted
to their compact representation: no ".tag" key or containing
dict, just the ta... | Returns an OrderedDict mapping labels to Example objects.
Args:
compact (bool): If True, union members of void type are converted
to their compact representation: no ".tag" key or containing
dict, just the tag as a string. |
def assign_statement(self):
"""
assign smt : variable ASSIGN expression(;)
Feature Type Array adds:
| variable SETITEM expression(;)
"""
left = self.variable()
op = self.cur_token
self.eat(TokenTypes.ASSIGN)
right = self.expression()
... | assign smt : variable ASSIGN expression(;)
Feature Type Array adds:
| variable SETITEM expression(;) |
def mail_session(self, name, host, username, mail_from, props):
"""
Domain mail session.
:param str name:
Mail session name.
:param str host:
Mail host.
:param str username:
Mail username.
:param str mail_from:
Mail "from" address.
:param dict props:
Extra properties.
:rtyp... | Domain mail session.
:param str name:
Mail session name.
:param str host:
Mail host.
:param str username:
Mail username.
:param str mail_from:
Mail "from" address.
:param dict props:
Extra properties.
:rtype:
MailSession |
def help_center_article_translation_update(self, article_id, locale, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/translations#update-translation"
api_path = "/api/v2/help_center/articles/{article_id}/translations/{locale}.json"
api_path = api_path.format(article_id=... | https://developer.zendesk.com/rest_api/docs/help_center/translations#update-translation |
def _init_data_map(self):
""" Default data map initialization: MUST be overridden in children """
if self._data_map is None:
self._data_map = {'_root': None}
self._data_map.update({}.fromkeys(self._metadata_props)) | Default data map initialization: MUST be overridden in children |
def adb_cmd(self, command, **kwargs):
'''
Run adb command, for example: adb(['pull', '/data/local/tmp/a.png'])
Args:
command: string or list of string
Returns:
command output
'''
kwargs['timeout'] = kwargs.get('timeout', self._adb_shell_timeout)
... | Run adb command, for example: adb(['pull', '/data/local/tmp/a.png'])
Args:
command: string or list of string
Returns:
command output |
def dos_plot_data(self, yscale=1, xmin=-6., xmax=6., colours=None,
plot_total=True, legend_cutoff=3, subplot=False,
zero_to_efermi=True, cache=None):
"""Get the plotting data.
Args:
yscale (:obj:`float`, optional): Scaling factor for the y-axis.
... | Get the plotting data.
Args:
yscale (:obj:`float`, optional): Scaling factor for the y-axis.
xmin (:obj:`float`, optional): The minimum energy to mask the
energy and density of states data (reduces plotting load).
xmax (:obj:`float`, optional): The maximum en... |
async def shuffle_participants(self):
""" Shuffle participants' seeds
|methcoro|
Note:
|from_api| Randomize seeds among participants. Only applicable before a tournament has started.
Raises:
APIException
"""
res = await self.connection('POST', ... | Shuffle participants' seeds
|methcoro|
Note:
|from_api| Randomize seeds among participants. Only applicable before a tournament has started.
Raises:
APIException |
def process_response(self, request, response):
"""Sets the cache, if needed."""
# never cache headers + ETag
add_never_cache_headers(response)
if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache:
# We don't need to update the cache, just return... | Sets the cache, if needed. |
def cbpdnmd_xstep(k):
"""Do the X step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables.
"""
YU0 = mp_Z_Y0[k] + mp_S[k] - mp_Z_U0[k]
YU1 = mp_Z_Y1[k] - mp_Z_U1[k]
if mp_cri.Cd == 1:
... | Do the X step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables. |
def stops(freq, interval=1, count=None, wkst=None, bysetpos=None,
bymonth=None, bymonthday=None, byyearday=None, byeaster=None,
byweekno=None, byweekday=None, byhour=None, byminute=None,
bysecond=None, timezone='UTC', start=None, stop=None):
"""
This will create a list of delorean ... | This will create a list of delorean objects the apply to
setting possed in. |
def ch_duration(self, *channels: List[Channel]) -> int:
"""Return duration of supplied channels.
Args:
*channels: Supplied channels
"""
return self.timeslots.ch_duration(*channels) | Return duration of supplied channels.
Args:
*channels: Supplied channels |
def tracked(self, tag=None, fromdate=None, todate=None):
"""
Gets a total count of emails you’ve sent with open tracking or link tracking enabled.
"""
return self.call("GET", "/stats/outbound/tracked", tag=tag, fromdate=fromdate, todate=todate) | Gets a total count of emails you’ve sent with open tracking or link tracking enabled. |
def _copy_hdxobjects(self, hdxobjects, hdxobjectclass, attribute_to_copy=None):
# type: (List[HDXObjectUpperBound], type, Optional[str]) -> List[HDXObjectUpperBound]
"""Helper function to make a deep copy of a supplied list of HDX objects
Args:
hdxobjects (List[T <= HDXObject]): lis... | Helper function to make a deep copy of a supplied list of HDX objects
Args:
hdxobjects (List[T <= HDXObject]): list of HDX objects to copy
hdxobjectclass (type): Type of the HDX Objects to be copied
attribute_to_copy (Optional[str]): An attribute to copy over from the HDX ob... |
def _gatherLookupIndexes(gpos):
"""
Gather a mapping of script to lookup indexes
referenced by the kern feature for each script.
Returns a dictionary of this structure:
{
"latn" : [0],
"DFLT" : [0]
}
"""
# gather the indexes of the kern features
kernFe... | Gather a mapping of script to lookup indexes
referenced by the kern feature for each script.
Returns a dictionary of this structure:
{
"latn" : [0],
"DFLT" : [0]
} |
def series64bitto32bit(s):
"""
Convert a Pandas series from 64 bit types to 32 bit types to save
memory or disk space.
Parameters
----------
s : The series to convert
Returns
-------
The converted series
"""
if s.dtype == np.float64:
return s.astype('float32')
e... | Convert a Pandas series from 64 bit types to 32 bit types to save
memory or disk space.
Parameters
----------
s : The series to convert
Returns
-------
The converted series |
def makestate(im, pos, rad, slab=None, mem_level='hi'):
"""
Workhorse for creating & optimizing states with an initial centroid
guess.
This is an example function that works for a particular microscope. For
your own microscope, you'll need to change particulars such as the psf
type and the orde... | Workhorse for creating & optimizing states with an initial centroid
guess.
This is an example function that works for a particular microscope. For
your own microscope, you'll need to change particulars such as the psf
type and the orders of the background and illumination.
Parameters
---------... |
def get_personal_module(self):
"""
Instantiate the :class:`~fluent_dashboard.modules.PersonalModule` for use in the dashboard.
"""
return PersonalModule(
layout='inline',
draggable=False,
deletable=False,
collapsible=False,
) | Instantiate the :class:`~fluent_dashboard.modules.PersonalModule` for use in the dashboard. |
def evalSamples(self, x):
'''Evalautes the samples of quantity of interest and its gradient
(if supplied) at the given values of the design variables
:param iterable x: values of the design variables, this is passed as
the first argument to the function fqoi
:return: (value... | Evalautes the samples of quantity of interest and its gradient
(if supplied) at the given values of the design variables
:param iterable x: values of the design variables, this is passed as
the first argument to the function fqoi
:return: (values of the quantity of interest, values... |
def user_admin_urlname(action):
"""
Return the admin URLs for the user app used.
"""
user = get_user_model()
return 'admin:%s_%s_%s' % (
user._meta.app_label, user._meta.model_name,
action) | Return the admin URLs for the user app used. |
def train_local(self, closest_point, label_vector_description=None, N=None,
pivot=True, **kwargs):
"""
Train the model in a Cannon-like fashion using the grid points as labels
and the intensities as normalsied rest-frame fluxes within some local
regime.
"""
lv = ... | Train the model in a Cannon-like fashion using the grid points as labels
and the intensities as normalsied rest-frame fluxes within some local
regime. |
def loadFromDisk(self, calculation):
"""
Read the spectra from the files generated by Quanty and store them
as a list of spectum objects.
"""
suffixes = {
'Isotropic': 'iso',
'Circular Dichroism (R-L)': 'cd',
'Right Polarized (R)': 'r',
... | Read the spectra from the files generated by Quanty and store them
as a list of spectum objects. |
def get_template(self, R):
"""Compute a template on latent factors
Parameters
----------
R : 2D array, in format [n_voxel, n_dim]
The scanner coordinate matrix of one subject's fMRI data
Returns
-------
template_prior : 1D array
The templ... | Compute a template on latent factors
Parameters
----------
R : 2D array, in format [n_voxel, n_dim]
The scanner coordinate matrix of one subject's fMRI data
Returns
-------
template_prior : 1D array
The template prior.
template_centers_c... |
def visdom_send_metrics(vis, metrics, update='replace'):
""" Send set of metrics to visdom """
visited = {}
sorted_metrics = sorted(metrics.columns, key=_column_original_name)
for metric_basename, metric_list in it.groupby(sorted_metrics, key=_column_original_name):
metric_list = list(metric_li... | Send set of metrics to visdom |
def bookmark(ctx):
"""Bookmark group.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon group bookmark
```
\b
```bash
$ polyaxon group -g 2 bookmark
```
"""
user, project_name, _group = get_project_group_or_local(ctx.obj.get('projec... | Bookmark group.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon group bookmark
```
\b
```bash
$ polyaxon group -g 2 bookmark
``` |
def maskedEqual(array, missingValue):
""" Mask an array where equal to a given (missing)value.
Unfortunately ma.masked_equal does not work with structured arrays. See:
https://mail.scipy.org/pipermail/numpy-discussion/2011-July/057669.html
If the data is a structured array the mask is appl... | Mask an array where equal to a given (missing)value.
Unfortunately ma.masked_equal does not work with structured arrays. See:
https://mail.scipy.org/pipermail/numpy-discussion/2011-July/057669.html
If the data is a structured array the mask is applied for every field (i.e. forming a
lo... |
def __decrypt_assertion(self, dom):
"""
Decrypts the Assertion
:raises: Exception if no private key available
:param dom: Encrypted Assertion
:type dom: Element
:returns: Decrypted Assertion
:rtype: Element
"""
key = self.__settings.get_sp_key()... | Decrypts the Assertion
:raises: Exception if no private key available
:param dom: Encrypted Assertion
:type dom: Element
:returns: Decrypted Assertion
:rtype: Element |
def properties_from_mapping(self, bt_addr):
"""Retrieve properties (namespace, instance) for the specified bt address."""
for addr, properties in self.eddystone_mappings:
if addr == bt_addr:
return properties
return None | Retrieve properties (namespace, instance) for the specified bt address. |
def Decode(self, encoded_data):
"""Decode the encoded data.
Args:
encoded_data (byte): encoded data.
Returns:
tuple(bytes, bytes): decoded data and remaining encoded data.
Raises:
BackEndError: if the base64 stream cannot be decoded.
"""
try:
# TODO: replace by libuna ... | Decode the encoded data.
Args:
encoded_data (byte): encoded data.
Returns:
tuple(bytes, bytes): decoded data and remaining encoded data.
Raises:
BackEndError: if the base64 stream cannot be decoded. |
def fromfuncs(funcs, n_sessions, eqdata, **kwargs):
"""
Generate features using a list of functions to apply to input data
Parameters
----------
funcs : list of function
Functions to apply to eqdata. Each function is expected
to output a dataframe with index identical to a slice of ... | Generate features using a list of functions to apply to input data
Parameters
----------
funcs : list of function
Functions to apply to eqdata. Each function is expected
to output a dataframe with index identical to a slice of `eqdata`.
The slice must include at least `eqdata.index[... |
def _F(self, X):
"""
analytic solution of the projection integral
:param x: R/Rs
:type x: float >0
"""
if isinstance(X, int) or isinstance(X, float):
if X < 1 and X > 0:
a = 1/(X**2-1)*(1-2/np.sqrt(1-X**2)*np.arctanh(np.sqrt((1-X)/(1+X))))
... | analytic solution of the projection integral
:param x: R/Rs
:type x: float >0 |
def _is_unpacked_egg(path):
"""
Determine if given path appears to be an unpacked egg.
"""
return (
_is_egg_path(path) and
os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO'))
) | Determine if given path appears to be an unpacked egg. |
def remove(self):
'''
a method to remove all records in the collection
NOTE: this method removes all the files in the collection, but the
collection folder itself created by oauth2 cannot be removed.
only the user can remove access to the app fold... | a method to remove all records in the collection
NOTE: this method removes all the files in the collection, but the
collection folder itself created by oauth2 cannot be removed.
only the user can remove access to the app folder
:return: string with con... |
def load_raw(path):
"""
Load image using PIL/Pillow without any processing. This is particularly
useful for palette images, which will be loaded using their palette index
values as opposed to `load` which will convert them to RGB.
Parameters
----------
path : str
Path to image file.... | Load image using PIL/Pillow without any processing. This is particularly
useful for palette images, which will be loaded using their palette index
values as opposed to `load` which will convert them to RGB.
Parameters
----------
path : str
Path to image file. |
def _broadcast_arg(U, arg, argtype, name):
"""Broadcasts plotting option `arg` to all factors.
Args:
U : KTensor
arg : argument provided by the user
argtype : expected type for arg
name : name of the variable, used for error handling
Returns:
iterable version of arg... | Broadcasts plotting option `arg` to all factors.
Args:
U : KTensor
arg : argument provided by the user
argtype : expected type for arg
name : name of the variable, used for error handling
Returns:
iterable version of arg of length U.ndim |
def to_decimal(self):
"""Returns an instance of :class:`decimal.Decimal` for this
:class:`Decimal128`.
"""
high = self.__high
low = self.__low
sign = 1 if (high & _SIGN) else 0
if (high & _SNAN) == _SNAN:
return decimal.Decimal((sign, (), 'N'))
... | Returns an instance of :class:`decimal.Decimal` for this
:class:`Decimal128`. |
def text(self):
"""Formatted param definition
Equivalent to ``self.template.format(name=self.name, type=self.type)``.
"""
return self.template.format(name=self.name, type=self.type) | Formatted param definition
Equivalent to ``self.template.format(name=self.name, type=self.type)``. |
def _inputrc_enables_vi_mode():
'''
Emulate a small bit of readline behavior.
Returns:
(bool) True if current user enabled vi mode ("set editing-mode vi") in .inputrc
'''
for filepath in (os.path.expanduser('~/.inputrc'), '/etc/inputrc'):
try:
with open(filepath) as f:
... | Emulate a small bit of readline behavior.
Returns:
(bool) True if current user enabled vi mode ("set editing-mode vi") in .inputrc |
def _get_tcntobj(goids, go2obj, **kws):
"""Get a TermCounts object if the user provides an annotation file, otherwise None."""
# kws: gaf (gene2go taxid)
if 'gaf' in kws or 'gene2go' in kws:
# Get a reduced go2obj set for TermCounts
_gosubdag = GoSubDag(goids, go2obj, rcn... | Get a TermCounts object if the user provides an annotation file, otherwise None. |
def find_vasp_calculations():
"""
Returns a list of all subdirectories that contain either a vasprun.xml file
or a compressed vasprun.xml.gz file.
Args:
None
Returns:
(List): list of all VASP calculation subdirectories.
"""
dir_list = [ './' + re.sub( r'vasprun\.xml', '', p... | Returns a list of all subdirectories that contain either a vasprun.xml file
or a compressed vasprun.xml.gz file.
Args:
None
Returns:
(List): list of all VASP calculation subdirectories. |
def encodeMotorInput(self, motorInput):
"""
Encode motor command to bit vector.
@param motorInput (1D numpy.array)
Motor command to be encoded.
@return (1D numpy.array)
Encoded motor command.
"""
if not hasattr(motorInput, "__iter__"):
motorInput = list([motorIn... | Encode motor command to bit vector.
@param motorInput (1D numpy.array)
Motor command to be encoded.
@return (1D numpy.array)
Encoded motor command. |
def db_dp990(self, value=None):
""" Corresponds to IDD Field `db_dp990`
mean coincident drybulb temperature corresponding to
Dew-point temperature corresponding to 90.0% annual cumulative
frequency of occurrence (cold conditions)
Args:
value (float): value for IDD F... | Corresponds to IDD Field `db_dp990`
mean coincident drybulb temperature corresponding to
Dew-point temperature corresponding to 90.0% annual cumulative
frequency of occurrence (cold conditions)
Args:
value (float): value for IDD Field `db_dp990`
Unit: C
... |
def get_token_settings(cls, token, default=None):
""" Get the value for a specific token as a dictionary or replace with default
:param token: str, token to query the nomenclate for
:param default: object, substitution if the token is not found
:return: (dict, object, None), token setti... | Get the value for a specific token as a dictionary or replace with default
:param token: str, token to query the nomenclate for
:param default: object, substitution if the token is not found
:return: (dict, object, None), token setting dictionary or default |
def to_equivalent(self, unit, equivalence, **kwargs):
"""
Return a copy of the unyt_array in the units specified units, assuming
the given equivalency. The dimensions of the specified units and the
dimensions of the original array need not match so long as there is an
appropriate... | Return a copy of the unyt_array in the units specified units, assuming
the given equivalency. The dimensions of the specified units and the
dimensions of the original array need not match so long as there is an
appropriate conversion in the specified equivalency.
Parameters
----... |
def get_likes(self, likable_type, likable_id):
"""
likable_type: 'Comment', 'Press', 'Review', 'StartupRole', 'StatusUpdate'
likable_id: id of the object that the likes of it you are interested
"""
return _get_request(_LIKES.format(c_api=_C_API_BEGINNING,
... | likable_type: 'Comment', 'Press', 'Review', 'StartupRole', 'StatusUpdate'
likable_id: id of the object that the likes of it you are interested |
def start(self, interval=None, iterations=None):
"""Start the timer.
A timeout event will be generated every *interval* seconds.
If *interval* is None, then self.interval will be used.
If *iterations* is specified, the timer will stop after
emitting that number of events. If un... | Start the timer.
A timeout event will be generated every *interval* seconds.
If *interval* is None, then self.interval will be used.
If *iterations* is specified, the timer will stop after
emitting that number of events. If unspecified, then
the previous value of self.iteration... |
def Laliberte_density_i(T, w_w, c0, c1, c2, c3, c4):
r'''Calculate the density of a solute using the form proposed by Laliberte [1]_.
Parameters are needed, and a temperature, and water fraction. Units are Kelvin and Pa*s.
.. math::
\rho_{app,i} = \frac{(c_0[1-w_w]+c_1)\exp(10^{-6}[t+c_4]^2)}
... | r'''Calculate the density of a solute using the form proposed by Laliberte [1]_.
Parameters are needed, and a temperature, and water fraction. Units are Kelvin and Pa*s.
.. math::
\rho_{app,i} = \frac{(c_0[1-w_w]+c_1)\exp(10^{-6}[t+c_4]^2)}
{(1-w_w) + c_2 + c_3 t}
Parameters
----------... |
def version(self):
"""
:return: The version of the server when initialized as 'auto',
otherwise the version passed in at initialization
"""
if self._version != 'auto':
return self._version
if self._version == 'auto':
try:
data... | :return: The version of the server when initialized as 'auto',
otherwise the version passed in at initialization |
def instruction_DEC_register(self, opcode, register):
""" Decrement accumulator """
a = register.value
r = self.DEC(a)
# log.debug("$%x DEC %s value $%x -1 = $%x" % (
# self.program_counter,
# register.name, a, r
# ))
register.set(r) | Decrement accumulator |
def create_client_socket(self, config):
""" Create client broadcast socket
:param config: client configuration
:return: socket.socket
"""
client_socket = WUDPNetworkNativeTransport.create_client_socket(self, config)
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
return client_socket | Create client broadcast socket
:param config: client configuration
:return: socket.socket |
def _drop_oldest_chunk(self):
'''
To handle the case when the items comming in the chunk
is more than the maximum capacity of the chunk. Our intent
behind is to remove the oldest chunk. So that the items come
flowing in.
>>> s = StreamCounter(5,5)
>>> data_stream ... | To handle the case when the items comming in the chunk
is more than the maximum capacity of the chunk. Our intent
behind is to remove the oldest chunk. So that the items come
flowing in.
>>> s = StreamCounter(5,5)
>>> data_stream = ['a','b','c','d']
>>> for item in data_s... |
def Place(self, x, flags):
"""
Place prepends a value specified by `flags` to the Builder,
without checking for available space.
"""
N.enforce_number(x, flags)
self.head = self.head - flags.bytewidth
encode.Write(flags.packer_type, self.Bytes, self.Head(), x) | Place prepends a value specified by `flags` to the Builder,
without checking for available space. |
def getParameters(self):
"""
Get all the parameters declared.
"""
parameters = lock_and_call(
lambda: self._impl.getParameters(),
self._lock
)
return EntityMap(parameters, Parameter) | Get all the parameters declared. |
def get_sockaddr(host, port, family):
"""Return a fully qualified socket address that can be passed to
:func:`socket.bind`."""
if family == af_unix:
return host.split("://", 1)[1]
try:
res = socket.getaddrinfo(
host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP
... | Return a fully qualified socket address that can be passed to
:func:`socket.bind`. |
def _aggregations(search, definitions):
"""Add aggregations to query."""
if definitions:
for name, agg in definitions.items():
search.aggs[name] = agg if not callable(agg) else agg()
return search | Add aggregations to query. |
def categorical_to_numeric(table):
"""Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with ca... | Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
... |
def update_distribution(
name,
config,
tags=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Update the config (and optionally tags) for the CloudFront distribution with the given name.
name
Name of the CloudFront distribution
config
Configurati... | Update the config (and optionally tags) for the CloudFront distribution with the given name.
name
Name of the CloudFront distribution
config
Configuration for the distribution
tags
Tags to associate with the distribution
region
Region to connect to
key
Se... |
def write_err(self, text):
"""Write error text in the terminal without breaking the spinner."""
stderr = self.stderr
if self.stderr.closed:
stderr = sys.stderr
stderr.write(decode_output(u"\r", target_stream=stderr))
stderr.write(decode_output(CLEAR_LINE, target_strea... | Write error text in the terminal without breaking the spinner. |
def ris(self):
"""Bibliographic entry in RIS (Research Information System Format)
format.
Returns
-------
ris : str
The RIS string representing an item.
Raises
------
ValueError : If the item's aggregationType is not Journal.
"""
... | Bibliographic entry in RIS (Research Information System Format)
format.
Returns
-------
ris : str
The RIS string representing an item.
Raises
------
ValueError : If the item's aggregationType is not Journal. |
def _parse_line(self, line):
"""
Parsed result::
{'timestamp':'May 18 14:24:14',
'procname': 'kernel',
'hostname':'lxc-rhel68-sat56',
'message': '...',
'raw_message': '...: ...'
}
"""
msg_info = {'raw_message': ... | Parsed result::
{'timestamp':'May 18 14:24:14',
'procname': 'kernel',
'hostname':'lxc-rhel68-sat56',
'message': '...',
'raw_message': '...: ...'
} |
def _traverse(summary, function, *args):
"""Traverse all objects of a summary and call function with each as a
parameter.
Using this function, the following objects will be traversed:
- the summary
- each row
- each item of a row
"""
function(summary, *args)
for row in summary:
... | Traverse all objects of a summary and call function with each as a
parameter.
Using this function, the following objects will be traversed:
- the summary
- each row
- each item of a row |
def create_couchdb_admin(username, password):
'''
Create a CouchDB user
'''
curl_couchdb('/_config/admins/{}'.format(username),
method='PUT',
data='"{}"'.format(password)) | Create a CouchDB user |
def destroy(self):
""" A reimplemented destructor.
This destructor will clear the reference to the toolkit widget
and set its parent to None.
"""
widget = self.widget
if widget is not None:
del self.widget
super(UiKitToolkitObject, self).destroy() | A reimplemented destructor.
This destructor will clear the reference to the toolkit widget
and set its parent to None. |
def search(self,
query,
category,
uid=None,
latitude=None,
longitude=None,
city=None,
region=None):
"""
发送语义理解请求
详情请参考
http://mp.weixin.qq.com/wiki/0/0ce78b3c9524811fee34aba3e33f3448.... | 发送语义理解请求
详情请参考
http://mp.weixin.qq.com/wiki/0/0ce78b3c9524811fee34aba3e33f3448.html
:param query: 输入文本串
:param category: 需要使用的服务类型,多个可传入列表
:param uid: 可选,用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid)
:param latitude: 可选,纬度坐标,与经度同时传入;与城市二选一传入
:param longitude: 可选,经度坐... |
def synchelp(f):
'''
The synchelp decorator allows the transparent execution of
a coroutine using the global loop from a thread other than
the event loop. In both use cases, teh actual work is done
by the global event loop.
Examples:
Use as a decorator::
@s_glob.synchelp
... | The synchelp decorator allows the transparent execution of
a coroutine using the global loop from a thread other than
the event loop. In both use cases, teh actual work is done
by the global event loop.
Examples:
Use as a decorator::
@s_glob.synchelp
async def stuff(x... |
def get_level(level_string):
"""
Returns an appropriate logging level integer from a string name
"""
levels = {'debug': logging.DEBUG, 'info': logging.INFO,
'warning': logging.WARNING, 'error': logging.ERROR,
'critical': logging.CRITICAL}
try:
level = levels[level... | Returns an appropriate logging level integer from a string name |
def is_excluded_path(args, filepath):
"""Returns true if the filepath is under the one of the exclude path."""
# Try regular expressions first.
for regexp_exclude_path in args.regexp:
if re.match(regexp_exclude_path, filepath):
return True
abspath = os.path.abspath(filepath)
if a... | Returns true if the filepath is under the one of the exclude path. |
def add(self, transport, address=None):
"""
add a new recipient to be addressable by this MessageDispatcher
generate a new uuid address if one is not specified
"""
if not address:
address = str(uuid.uuid1())
if address in self.recipients:
... | add a new recipient to be addressable by this MessageDispatcher
generate a new uuid address if one is not specified |
def set_options(pool_or_cursor,row_instance):
"for connection-level options that need to be set on Row instances"
# todo: move around an Options object instead
for option in ('JSON_READ',): setattr(row_instance,option,getattr(pool_or_cursor,option,None))
return row_instance | for connection-level options that need to be set on Row instances |
def get_viewer(self, v_id, viewer_class=None, width=512, height=512,
force_new=False):
"""
Get an existing viewer by viewer id. If the viewer does not yet
exist, make a new one.
"""
if not force_new:
try:
return self.viewers[v_id]
... | Get an existing viewer by viewer id. If the viewer does not yet
exist, make a new one. |
def clean_columns(columns, valid_regex=r'\w', lower=True, max_len=32):
""" Ensure all column name strings are valid python variable/attribute names
>>> df = pd.DataFrame(np.zeros((2, 3)), columns=['WAT??', "Don't do th!s, way too long. ya-think????", 'ok-this123.456'])
>>> df.columns = clean_columns(df.co... | Ensure all column name strings are valid python variable/attribute names
>>> df = pd.DataFrame(np.zeros((2, 3)), columns=['WAT??', "Don't do th!s, way too long. ya-think????", 'ok-this123.456'])
>>> df.columns = clean_columns(df.columns, max_len=12)
>>> df.head()
wat dont_do_ths_ okthis123456
... |
def compress_to(self, archive_path=None):
""" Compress the directory with gzip using tarlib.
:type archive_path: str
:param archive_path: Path to the archive, if None, a tempfile is created
"""
if archive_path is None:
archive = tempfile.NamedTemporaryFile(delete=Fa... | Compress the directory with gzip using tarlib.
:type archive_path: str
:param archive_path: Path to the archive, if None, a tempfile is created |
def member(self, phlo_id, node_id,
member_id, action,
node_type='conference_bridge'):
"""
:param phlo_id:
:param node_id:
:param member_id:
:param action:
:param node_type: default value `conference_bridge`
:return:
"""
... | :param phlo_id:
:param node_id:
:param member_id:
:param action:
:param node_type: default value `conference_bridge`
:return: |
def iter_list_market_book(self, market_ids, chunk_size, **kwargs):
"""Split call to `list_market_book` into separate requests.
:param list market_ids: List of market IDs
:param int chunk_size: Number of records per chunk
:param dict kwargs: Arguments passed to `list_market_book`
... | Split call to `list_market_book` into separate requests.
:param list market_ids: List of market IDs
:param int chunk_size: Number of records per chunk
:param dict kwargs: Arguments passed to `list_market_book` |
def project(self, project, entity=None):
"""Retrive project
Args:
project (str): The project to get details for
entity (str, optional): The entity to scope this project to.
Returns:
[{"id","name","repo","dockerImage","description"}]
"""
q... | Retrive project
Args:
project (str): The project to get details for
entity (str, optional): The entity to scope this project to.
Returns:
[{"id","name","repo","dockerImage","description"}] |
def _importSNPs_CasavaSNP(setName, species, genomeSource, snpsFile) :
"This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based"
printf('importing SNP set %s for species %s...' % (setName, species))
snpData = SNPsTxtFile(snpsFile)
CasavaSNP.dropIndex(('s... | This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based |
def __store_record(self, record):
""" Save record in a internal storage
:param record: record to save
:return: None
"""
if isinstance(record, WSimpleTrackerStorage.Record) is False:
raise TypeError('Invalid record type was')
limit = self.record_limit()
if limit is not None and len(self.__registry) >=... | Save record in a internal storage
:param record: record to save
:return: None |
def generate_matches(self, nodes):
"""
Generator yielding matches for a sequence of nodes.
Args:
nodes: sequence of nodes
Yields:
(count, results) tuples where:
count: the match comprises nodes[:count];
results: dict containing named subm... | Generator yielding matches for a sequence of nodes.
Args:
nodes: sequence of nodes
Yields:
(count, results) tuples where:
count: the match comprises nodes[:count];
results: dict containing named submatches. |
def create_alarm(deployment_id, metric_name, data, api_key=None, profile="telemetry"):
'''
create an telemetry alarms.
data is a dict of alert configuration data.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion telemetry.create_alarm rs-ds033197 {} profile=telemetry... | create an telemetry alarms.
data is a dict of alert configuration data.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion telemetry.create_alarm rs-ds033197 {} profile=telemetry |
def get_current(self, channel, unit='A'):
'''Reading current
'''
values = self._get_adc_value(address=self._ch_map[channel]['ADCI']['address'])
raw = values[self._ch_map[channel]['ADCI']['adc_ch']]
dac_offset = self._ch_cal[channel]['ADCI']['offset']
dac_gain = self._ch_c... | Reading current |
def validate_allowed_to_pay(self):
''' Passes cleanly if we're allowed to pay, otherwise raise
a ValidationError. '''
self._refresh()
if not self.invoice.is_unpaid:
raise ValidationError("You can only pay for unpaid invoices.")
if not self.invoice.cart:
... | Passes cleanly if we're allowed to pay, otherwise raise
a ValidationError. |
def fromdeltas(cls, deltas):
"""
Construct an offsetvector from a dictionary of offset
deltas as returned by the .deltas attribute.
Example:
>>> x = offsetvector({"H1": 0, "L1": 10, "V1": 20})
>>> y = offsetvector.fromdeltas(x.deltas)
>>> y
offsetvector({'V1': 20, 'H1': 0, 'L1': 10})
>>> y == x
Tr... | Construct an offsetvector from a dictionary of offset
deltas as returned by the .deltas attribute.
Example:
>>> x = offsetvector({"H1": 0, "L1": 10, "V1": 20})
>>> y = offsetvector.fromdeltas(x.deltas)
>>> y
offsetvector({'V1': 20, 'H1': 0, 'L1': 10})
>>> y == x
True
See also .deltas, .fromkeys() |
def license_is_oa(license):
"""Return True if license is compatible with Open Access"""
for oal in OA_LICENSES:
if re.search(oal, license):
return True
return False | Return True if license is compatible with Open Access |
def nodal_production_balance(
network,
snapshot='all',
scaling=0.00001,
filename=None):
"""
Plots the nodal difference between generation and consumption.
Parameters
----------
network : PyPSA network container
Holds topology of grid including results ... | Plots the nodal difference between generation and consumption.
Parameters
----------
network : PyPSA network container
Holds topology of grid including results from powerflow analysis
snapshot : int or 'all'
Snapshot to plot.
default 'all'
scaling : int
Scaling t... |
def can_update_topics_to_sticky_topics(self, forum, user):
""" Given a forum, checks whether the user can change its topic types to sticky topics. """
return (
self._perform_basic_permission_check(forum, user, 'can_edit_posts') and
self._perform_basic_permission_check(forum, user... | Given a forum, checks whether the user can change its topic types to sticky topics. |
def _check_rules(browser, rules_js, config):
"""
Run an accessibility audit on the page using the axe-core ruleset.
Args:
browser: a browser instance.
rules_js: the ruleset JavaScript as a string.
config: an AxsAuditConfig instance.
Returns:
... | Run an accessibility audit on the page using the axe-core ruleset.
Args:
browser: a browser instance.
rules_js: the ruleset JavaScript as a string.
config: an AxsAuditConfig instance.
Returns:
A list of violations.
Related documentation:
... |
def ahrs_send(self, omegaIx, omegaIy, omegaIz, accel_weight, renorm_val, error_rp, error_yaw, force_mavlink1=False):
'''
Status of DCM attitude estimator
omegaIx : X gyro drift estimate rad/s (float)
omegaIy : Y gyro dr... | Status of DCM attitude estimator
omegaIx : X gyro drift estimate rad/s (float)
omegaIy : Y gyro drift estimate rad/s (float)
omegaIz : Z gyro drift estimate rad/s (float)
accel_weight : av... |
def is_enum_type(type_):
""" Checks if the given type is an enum type.
:param type_: The type to check
:return: True if the type is a enum type, otherwise False
:rtype: bool
"""
return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM))) | Checks if the given type is an enum type.
:param type_: The type to check
:return: True if the type is a enum type, otherwise False
:rtype: bool |
def fms(x, y, z, context=None):
"""
Return (x * y) - z, with a single rounding according to the current
context.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_fms,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
... | Return (x * y) - z, with a single rounding according to the current
context. |
def actions_delete():
"""
DEPRECATED (v 1.9.4)
delete an ontology from the local repo
"""
filename = action_listlocal()
ONTOSPY_LOCAL_MODELS = get_home_location()
if filename:
fullpath = ONTOSPY_LOCAL_MODELS + filename
if os.path.exists(fullpath):
... | DEPRECATED (v 1.9.4)
delete an ontology from the local repo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.