code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|
def register_nonzero_counter(network, stats):
if hasattr(network, "__counter_nonzero__"):
raise ValueError("nonzero counter was already registered for this network")
if not isinstance(stats, dict):
raise ValueError("stats must be a dictionary")
network.__counter_nonzero__ = stats
handles = []
for... | Register forward hooks to count the number of nonzero floating points
values from all the tensors used by the given network during inference.
:param network: The network to attach the counter
:param stats: Dictionary holding the counter. |
def get_final_version_string(release_mode, semver, commit_count=0):
version_string = ".".join(semver)
maybe_dev_version_string = version_string
updates = {}
if release_mode:
updates[Constants.RELEASE_FIELD] = config.RELEASED_VALUE
else:
maybe_dev_version_string... | Generates update dictionary entries for the version string |
def clone(self, id, name=None):
url = .format(id)
if name is None:
os.system(.format(url))
else:
os.system(.format(url, name)) | Clone a gist
Arguments:
id: the gist identifier
name: the name to give the cloned repo |
def call_with_context(func, context, *args):
return make_context_aware(func, len(args))(*args + (context,)) | Check if given function has more arguments than given. Call it with context
as last argument or without it. |
def authenticate(self, req, resp, resource):
username, password = self._extract_credentials(req)
user = self.user_loader(username, password)
if not user:
raise falcon.HTTPUnauthorized(
description=)
return user | Extract basic auth token from request `authorization` header, deocode the
token, verifies the username/password and return either a ``user``
object if successful else raise an `falcon.HTTPUnauthoried exception` |
def twofilter_smoothing(self, t, info, phi, loggamma, linear_cost=False,
return_ess=False, modif_forward=None,
modif_info=None):
ti = self.T - 2 - t
if t < 0 or t >= self.T - 1:
raise ValueError(
)
lwi... | Two-filter smoothing.
Parameters
----------
t: time, in range 0 <= t < T-1
info: SMC object
the information filter
phi: function
test function, a function of (X_t,X_{t+1})
loggamma: function
a function of (X_{t+1})
linear_cost... |
def account_update(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/accounts
api_path = "/api/v2/account"
return self.call(api_path, method="PUT", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/chat/accounts#update-account |
def list_objects(self, bucket_name=None, **kwargs):
if not bucket_name: bucket_name = self.bucket_name
return self.client.list_objects(Bucket=bucket_name, **kwargs) | This method is primarily for illustration and just calls the
boto3 client implementation of list_objects but is a common task
for first time Predix BlobStore users. |
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
*
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up) | Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
... |
def settings(self):
for table in self.tables:
if isinstance(table, SettingTable):
for statement in table.statements:
yield statement | Generator which returns all of the statements in all of the settings tables |
def install_package(self, name, index=None, force=False, update=False):
cmd =
if force:
cmd = .format(cmd, )
if update:
cmd = .format(cmd, )
if index:
cmd = .format(cmd, .format(index))
self.pip(.format(cmd, name)) | Install a given package.
Args:
name (str): The package name to install. This can be any valid
pip package specification.
index (str): The URL for a pypi index to use.
force (bool): For the reinstall of packages during updates.
update (bool): Updat... |
def rot(vm):
c = vm.pop()
b = vm.pop()
a = vm.pop()
vm.push(b)
vm.push(c)
vm.push(a) | Rotate topmost three items once to the left. ( a b c -- b c a ) |
def parsecommonarguments(object, doc, annotationtype, required, allowed, **kwargs):
object.doc = doc
if required is None:
required = tuple()
if allowed is None:
allowed = tuple()
supported = required + allowed
if in kwargs:
try:
kwargs[] = kwargs[].gen... | Internal function to parse common FoLiA attributes and sets up the instance accordingly. Do not invoke directly. |
def setup_signals(self, ):
self.browser.shot_taskfile_sel_changed.connect(self.shot_taskfile_sel_changed)
self.browser.asset_taskfile_sel_changed.connect(self.asset_taskfile_sel_changed)
self.shot_open_pb.clicked.connect(self.shot_open_callback)
self.asset_open_pb.clicked.conne... | Connect the signals with the slots to make the ui functional
:returns: None
:rtype: None
:raises: None |
def _arith_method_SERIES(cls, op, special):
str_rep = _get_opstr(op, cls)
op_name = _get_op_name(op, special)
eval_kwargs = _gen_eval_kwargs(op_name)
fill_zeros = _gen_fill_zeros(op_name)
construct_result = (_construct_divmod_result
if op in [divmod, rdivmod] else _const... | Wrapper function for Series arithmetic operations, to avoid
code duplication. |
def _fill_cropping(self, image_size, view_size):
def aspect_ratio(width, height):
return width / height
ar_view = aspect_ratio(*view_size)
ar_image = aspect_ratio(*image_size)
if ar_view < ar_image:
crop = (1.0 - (ar_view/ar_image)) / 2.0
... | Return a (left, top, right, bottom) 4-tuple containing the cropping
values required to display an image of *image_size* in *view_size*
when stretched proportionately. Each value is a percentage expressed
as a fraction of 1.0, e.g. 0.425 represents 42.5%. *image_size* and
*view_size* are ... |
def c_rho0(self, rho0):
if not hasattr(self, ):
c_array = np.linspace(0.1, 10, 100)
rho0_array = self.rho0_c(c_array)
from scipy import interpolate
self._c_rho0_interp = interpolate.InterpolatedUnivariateSpline(rho0_array, c_array, w=None, bbox=[None, Non... | computes the concentration given a comoving overdensity rho0 (inverse of function rho0_c)
:param rho0: density normalization in h^2/Mpc^3 (comoving)
:return: concentration parameter c |
def hierarchy_name(self, adjust_for_printing=True):
if adjust_for_printing: adjust = lambda x: adjust_name_for_printing(x)
else: adjust = lambda x: x
if self.has_parent():
return self._parent_.hierarchy_name() + "." + adjust(self.name)
return adjust(self.name) | return the name for this object with the parents names attached by dots.
:param bool adjust_for_printing: whether to call :func:`~adjust_for_printing()`
on the names, recursively |
def delete_free_shipping_coupon_by_id(cls, free_shipping_coupon_id, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._delete_free_shipping_coupon_by_id_with_http_info(free_shipping_coupon_id, **kwargs)
else:
(data) = cls._delete_free_shipping_coupon_by_id_w... | Delete FreeShippingCoupon
Delete an instance of FreeShippingCoupon by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_free_shipping_coupon_by_id(free_shipping_coupon_id, async=True)
... |
def jsName(path,name):
shortPath=path.replace(
"C:\\Users\\scheinerbock\\Desktop\\"+
"ideogram\\scrapeSource\\test\\","")
noDash = shortPath.replace("-","_dash_")
jsPath=noDash.replace("\\","_slash_").replace(".","_dot_")
jsName=jsPath++name
return jsName | Returns a name string without \, -, and . so that
the string will play nicely with javascript. |
def get_config(cls, key, default=None):
return cls._app.config.get(key, default) | Shortcut to access the application's config in your class
:param key: The key to access
:param default: The default value when None
:returns mixed: |
def add_done_callback(self, callback):
if self._done is None or self._done.is_set():
raise ValueError()
if callable(callback):
self.callbacks.append(callback) | Add a callback to run after the task completes.
The callable must take 1 argument which will be
the completed Task.
:param callback: a callable that takes a single argument which
will be the completed Task. |
async def from_href(self):
if not hasattr(self, ):
raise TypeError()
elif hasattr(self, ):
return await self.http.request((, self.href))
else:
cls = type(self)
try:
client = getattr(self, .format(cls.__name__))
except At... | Get the full object from spotify with a `href` attribute. |
def get_version(self, version_id=None):
return ObjectVersion.get(bucket=self.obj.bucket, key=self.obj.key,
version_id=version_id) | Return specific version ``ObjectVersion`` instance or HEAD.
:param version_id: Version ID of the object.
:returns: :class:`~invenio_files_rest.models.ObjectVersion` instance or
HEAD of the stored object. |
def alter_targets(self):
if self.is_derived():
return [], None
return self.fs.variant_dir_target_climb(self, self.dir, [self.name]) | Return any corresponding targets in a variant directory. |
def showDescription( self ):
plugin = self.currentPlugin()
if ( not plugin ):
self.uiDescriptionTXT.setText()
else:
self.uiDescriptionTXT.setText(plugin.description()) | Shows the description for the current plugin in the interface. |
def show_hist(self, props=[], bins=20, **kwargs):
r
if type(props) is str:
props = [props]
N = len(props)
if N == 1:
r = 1
c = 1
elif N < 4:
r = 1
c = N
else:
r = int(sp.ceil(N**0.5))
c = ... | r"""
Show a quick plot of key property distributions.
Parameters
----------
props : string or list of strings
The pore and/or throat properties to be plotted as histograms
bins : int or array_like
The number of bins to use when generating the histogram. ... |
def fetch_more(self, rows=False, columns=False):
if self.axis == 1 and self.total_rows > self.rows_loaded:
reminder = self.total_rows - self.rows_loaded
items_to_fetch = min(reminder, ROWS_TO_LOAD)
self.beginInsertRows(QModelIndex(), self.rows_loaded,
... | Get more columns or rows (based on axis). |
def boolean(value):
if isinstance(value, bool):
return value
if value == "":
return False
return strtobool(value) | Configuration-friendly boolean type converter.
Supports both boolean-valued and string-valued inputs (e.g. from env vars). |
def base64ToImage(imgData, out_path, out_file):
fh = open(os.path.join(out_path, out_file), "wb")
fh.write(imgData.decode())
fh.close()
del fh
return os.path.join(out_path, out_file) | converts a base64 string to a file |
def convertDate(date):
d, t = date.split()
return decimal_date(d, timeobs=t) | Convert DATE string into a decimal year. |
def settingsAsFacts(self, settings):
pattern = re.compile()
pairs = pattern.findall(settings)
for name, val in pairs:
self.set(name, val) | Parses a string of settings.
:param setting: String of settings in the form:
``set(name1, val1), set(name2, val2)...`` |
def scalar(self, tag, value, step=None):
value = float(onp.array(value))
if step is None:
step = self._step
else:
self._step = step
summary = Summary(value=[Summary.Value(tag=tag, simple_value=value)])
self.add_summary(summary, step) | Saves scalar value.
Args:
tag: str: label for this data
value: int/float: number to log
step: int: training step |
def StoreStat(self, responses):
index = responses.request_data["index"]
if not responses.success:
self.Log("Failed to stat file: %s", responses.status)
self._FileFetchFailed(index, responses.request_data["request_name"])
return
tracker = self.state.pending_hashes[index]
tr... | Stores stat entry in the flow's state. |
def config_default(option, default=None, type=None, section=cli.name):
def f(option=option, default=default, type=type, section=section):
config = read_config()
if type is None and default is not None:
type = builtins.type(default)
get_option = option_getter(typ... | Guesses a default value of a CLI option from the configuration.
::
@click.option('--locale', default=config_default('locale')) |
def spherical(cls, mag, theta, phi=0):
return cls(
mag * math.sin(phi) * math.cos(theta),
mag * math.sin(phi) * math.sin(theta),
mag * math.cos(phi)
) | Returns a Vector instance from spherical coordinates |
def GetAttributes(self, urns, age=NEWEST_TIME):
urns = set([utils.SmartUnicode(u) for u in urns])
to_read = {urn: self._MakeCacheInvariant(urn, age) for urn in urns}
if to_read:
for subject, values in data_store.DB.MultiResolvePrefix(
to_read,
AFF4_PREFIXES,
ti... | Retrieves all the attributes for all the urns. |
def mimebundle_to_html(bundle):
if isinstance(bundle, tuple):
data, metadata = bundle
else:
data = bundle
html = data.get(, )
if in data:
js = data[]
html += .format(js=js)
return html | Converts a MIME bundle into HTML. |
def save(self, p_todolist):
self._trim()
current_hash = hash_todolist(p_todolist)
list_todo = (self.todolist.print_todos()+).splitlines(True)
try:
list_archive = (self.archive.print_todos()+).splitlines(True)
except AttributeError:
list_archive =... | Saves a tuple with archive, todolist and command with its arguments
into the backup file with unix timestamp as the key. Tuple is then
indexed in backup file with combination of hash calculated from
p_todolist and unix timestamp. Backup file is closed afterwards. |
def add_path(self, w, h):
path = self._add_path()
path.w, path.h = w, h
return path | Return a newly created `a:path` child element. |
def instruction_PUL(self, opcode, m, register):
assert register in (self.system_stack_pointer, self.user_stack_pointer)
def pull(register_str, stack_pointer):
reg_obj = self.register_str2object[register_str]
reg_width = reg_obj.WIDTH
if reg_width == 8:
... | All, some, or none of the processor registers are pulled from stack
(with the exception of stack pointer itself).
A single register may be pulled from the stack with condition codes set
by doing an autoincrement load from the stack (example: LDX ,S++).
source code forms: b7 b6 b5 b4 b3... |
def addfield(self, pkt, s, val):
assert(val >= 0)
if isinstance(s, bytes):
assert self.size == 8,
return s + self.i2m(pkt, val)
if val >= self._max_value:
return s[0] + chb((s[2] << self.size) + self._... | An AbstractUVarIntField prefix always consumes the remaining bits
of a BitField;if no current BitField is in use (no tuple in
entry) then the prefix length is 8 bits and the whole byte is to
be consumed
@param packet.Packet|None pkt: the packet containing this field. Probably unuse... |
def volume_list(search_opts=None, profile=None, **kwargs):
*{"display_name": "myblock"}
conn = _auth(profile, **kwargs)
return conn.volume_list(search_opts=search_opts) | List storage volumes
search_opts
Dictionary of search options
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' nova.volume_list search_opts='{"display_name": "myblock"}' profile=openstack |
def expand_dates(df, columns=[]):
columns = df.columns.intersection(columns)
df2 = df.reindex(columns=set(df.columns).difference(columns))
for column in columns:
df2[column + ] = df[column].apply(lambda x: x.year)
df2[column + ] = df[column].apply(lambda x: x.month)
df2[column +... | generate year, month, day features from specified date features |
def healpixMap(nside, lon, lat, fill_value=0., nest=False):
lon_median, lat_median = np.median(lon), np.median(lat)
max_angsep = np.max(ugali.utils.projector.angsep(lon, lat, lon_median, lat_median))
pix = angToPix(nside, lon, lat, nest=nest)
if max_angsep < 10:
m = np.tile(f... | Input (lon, lat) in degrees instead of (theta, phi) in radians.
Returns HEALPix map at the desired resolution |
def getPermanence(self, columnIndex, permanence):
assert(columnIndex < self._numColumns)
permanence[:] = self._permanences[columnIndex] | Returns the permanence values for a given column. ``permanence`` size
must match the number of inputs.
:param columnIndex: (int) column index to get permanence for.
:param permanence: (list) will be overwritten with permanences. |
def getName(obj):
def sanitize(name):
return name.replace(".", "/")
if isinstance(obj, _BuildStepFactory):
klass = obj.factory
else:
klass = type(obj)
name = ""
klasses = (klass, ) + inspect.getmro(klass)
for klass in klasses:
if hasattr(klass, "__module... | This method finds the first parent class which is within the buildbot namespace
it prepends the name with as many ">" as the class is subclassed |
def run(self, cmd, *args, **kwargs):
runner = self.ctx.run if self.ctx else None
return run(cmd, runner=runner, *args, **kwargs) | Run a command. |
def eccentricity(self, **kw):
r
ra = self.apocenter(**kw)
rp = self.pericenter(**kw)
return (ra - rp) / (ra + rp) | r"""
Returns the eccentricity computed from the mean apocenter and
mean pericenter.
.. math::
e = \frac{r_{\rm apo} - r_{\rm per}}{r_{\rm apo} + r_{\rm per}}
Parameters
----------
**kw
Any keyword arguments passed to ``apocenter()`` and
... |
def set_title(self, title=None):
if not title:
title = self.get_file_short_name()
LOGGER.debug("> Setting editor title to .".format(title))
self.__title = title
self.setWindowTitle(title)
self.title_changed.emit()
... | Sets the editor title.
:param title: Editor title.
:type title: unicode
:return: Method success.
:rtype: bool |
def map(func):
if is_py2 and text == func:
func = unicode
def expand_kv(kv):
return func(*kv)
def map_values(value):
cls = type(value)
if isinstance(value, dict):
return cls(_map(expand_kv, value.items()))
else:
return cls... | Apply function to each value inside the sequence or dict.
Supports both dicts and sequences, key/value pairs are
expanded when applied to a dict. |
def clean(self):
bits = (self.data["content_type"], self.data["object_pk"])
request = self.request
self.current = "%s.%s" % bits
self.previous = request.COOKIES.get("yacms-rating", "").split(",")
already_rated = self.current in self.previous
if already_rated and ... | Check unauthenticated user's cookie as a light check to
prevent duplicate votes. |
def _build_context(self, request, customer_uuid):
enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid)
search_keyword = self.get_search_keyword(request)
linked_learners = self.get_enterprise_customer_user_queryset(request, search_keyword, customer_uuid)
... | Build common context parts used by different handlers in this view. |
def makevAndvPfuncs(self,policyFunc):
mCount = self.aXtraGrid.size
pCount = self.pLvlGrid.size
MedCount = self.MedShkVals.size
temp_grid = np.tile(np.reshape(self.aXtraGrid,(mCount,1,1)),(1,pCount,MedCount))
aMinGrid = np.tile(np.reshape(self.mL... | Constructs the marginal value function for this period.
Parameters
----------
policyFunc : function
Consumption and medical care function for this period, defined over
market resources, permanent income level, and the medical need shock.
Returns
-------
... |
def purge(self, jid, node):
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=jid,
payload=pubsub_xso.OwnerRequest(
pubsub_xso.OwnerPurge(
node
)
)
)
yield from self.client.s... | Delete all items from a node.
:param jid: JID of the PubSub service
:param node: Name of the PubSub node
:type node: :class:`str`
Requires :attr:`.xso.Feature.PURGE`. |
def is_readable(filename):
return os.path.isfile(filename) and os.access(filename, os.R_OK) | Check if file is a regular file and is readable. |
def _add(self, *rules):
for rule in rules:
if rule in self:
continue
self._validate_rule(rule)
for rule in rules:
for r in self._split_rules(rule):
for side in r.rule:
for s in side:
... | Add rules into the set. Each rule is validated and split if needed.
The method add the rules into dictionary, so the rule can be deleted with terminals or nonterminals.
:param rules: Rules to insert.
:return: Inserted rules.
:raise NotRuleException: If the parameter doesn't inherit from ... |
def write_json_to_temp_file(data):
fp = tempfile.NamedTemporaryFile(delete=False)
fp.write(json.dumps(data).encode())
fp.close()
return fp.name | Writes JSON data to a temporary file and returns the path to it |
def delete_subtrie(self, key):
validate_is_bytes(key)
self.root_hash = self._set(
self.root_hash,
encode_to_bin(key),
value=b,
if_delete_subtrie=True,
) | Given a key prefix, delete the whole subtrie that starts with the key prefix.
Key will be encoded into binary array format first.
It will call `_set` with `if_delete_subtrie` set to True. |
def AddTask(self,
target,
args=(),
name="Unnamed task",
blocking=True,
inline=True):
if not self.started:
raise ThreadPoolNotStartedError(self.name)
if self.max_threads == 0:
target(*args)
return
if inline:
... | Adds a task to be processed later.
Args:
target: A callable which should be processed by one of the workers.
args: A tuple of arguments to target.
name: The name of this task. Used to identify tasks in the log.
blocking: If True we block until the task is finished, otherwise we raise
... |
def partial_update(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=True, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
serializer.save()
if getattr(instance, , None):
i... | We do not include the mixin as we want only PATCH and no PUT |
def open_image(fn):
flags = cv2.IMREAD_UNCHANGED+cv2.IMREAD_ANYDEPTH+cv2.IMREAD_ANYCOLOR
if not os.path.exists(fn) and not str(fn).startswith("http"):
raise OSError(.format(fn))
elif os.path.isdir(fn) and not str(fn).startswith("http"):
raise OSError(.format(fn))
elif isdicom(fn):
... | Opens an image using OpenCV given the file path.
Arguments:
fn: the file path of the image
Returns:
The image in RGB format as numpy array of floats normalized to range between 0.0 - 1.0 |
def update(self, request, *args, **kwargs):
return super(PriceListItemViewSet, self).update(request, *args, **kwargs) | Run **PATCH** request against */api/price-list-items/<uuid>/* to update price list item.
Only item_type, key value and units can be updated.
Only customer owner and staff can update price items. |
def date_from_quarter(base_date, ordinal, year):
interval = 3
month_start = interval * (ordinal - 1)
if month_start < 0:
month_start = 9
month_end = month_start + interval
if month_start == 0:
month_start = 1
return [
datetime(year, month_start, 1),
datetime(... | Extract date from quarter of a year |
def fetch_all_droplet_neighbors(self):
r
for hood in self.paginate(, ):
yield list(map(self._droplet, hood)) | r"""
Returns a generator of all sets of multiple droplets that are running
on the same physical hardware
:rtype: generator of lists of `Droplet`\ s
:raises DOAPIError: if the API endpoint replies with an error |
def create_ramp_plan(err, ramp):
if ramp == 1:
yield int(err)
while True:
yield 0
n = np.abs(np.roots([.5, -.5, 0]).max())
niter = int(ramp // (2 * n))
MV = n
log.info(, extra=dict(
ramp_size=ramp, err=err, niter=niter))
for x in r... | Formulate and execute on a plan to slowly add heat or cooling to the system
`err` initial error (PV - SP)
`ramp` the size of the ramp
A ramp plan might yield MVs in this order at every timestep:
[5, 0, 4, 0, 3, 0, 2, 0, 1]
where err == 5 + 4 + 3 + 2 + 1 |
def create_attribute(self,column=None,listType=None,namespace=None, network=None, atype=None, verbose=False):
network=check_network(self,network,verbose=verbose)
PARAMS=set_param(["column","listType","namespace","network","type"],[column,listType,namespace,network,atype])
response=api(u... | Creates a new edge column.
:param column (string, optional): Unique name of column
:param listType (string, optional): Can be one of integer, long, double,
or string.
:param namespace (string, optional): Node, Edge, and Network objects
support the default, local, and hid... |
def eValueToBitScore(eValue, dbSize, dbSequenceCount, queryLength,
lengthAdjustment):
effectiveDbSize = (
(dbSize - dbSequenceCount * lengthAdjustment) *
(queryLength - lengthAdjustment)
)
return -1.0 * (log(eValue / effectiveDbSize) / _LOG2) | Convert an e-value to a bit score.
@param eValue: The C{float} e-value to convert.
@param dbSize: The C{int} total size of the database (i.e., the sum of
the lengths of all sequences in the BLAST database).
@param dbSequenceCount: The C{int} number of sequences in the database.
@param queryLeng... |
def _draw_content(self):
n_rows, n_cols = self.term.stdscr.getmaxyx()
window = self.term.stdscr.derwin(n_rows - self._row - 1, n_cols, self._row, 0)
window.erase()
win_n_rows, win_n_cols = window.getmaxyx()
self._subwindows = []
page_index, cursor_index, inverte... | Loop through submissions and fill up the content page. |
def is_associated_file(self):
associated
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError()
return self.file_flags & (1 << self.FILE_FLAG_ASSOCIATED_FILE_BIT) | A method to determine whether this file is 'associated' with another file
on the ISO.
Parameters:
None.
Returns:
True if this file is associated with another file on the ISO, False
otherwise. |
async def connect(host, port, ssl=None):
info = {: host, : port, : ssl}
reader, writer = await asyncio.open_connection(host, port, ssl=ssl)
return await Link.anit(reader, writer, info=info) | Async connect and return a Link(). |
def axis(origin_size=0.04,
transform=None,
origin_color=None,
axis_radius=None,
axis_length=None):
origin_size = float(origin_size)
if transform is None:
transform = np.eye(4)
if origin_color is None:
origin_color = [255, 255, 255, 255... | Return an XYZ axis marker as a Trimesh, which represents position
and orientation. If you set the origin size the other parameters
will be set relative to it.
Parameters
----------
transform : (4, 4) float
Transformation matrix
origin_size : float
Radius of sphere that represents t... |
def build_authorization_arg(authdict):
vallist = []
for k in authdict.keys():
vallist += [ % (k,authdict[k])]
return +.join(vallist) | Create an "Authorization" header value from an authdict (created by generate_response()). |
def strict_logical(self, value):
if value is not None:
if not isinstance(value, bool):
raise TypeError(
)
else:
self._strict_logical = value | Validate and set the strict logical flag. |
def _generate_examples(self, images_dir_path):
parent_dir = tf.io.gfile.listdir(images_dir_path)[0]
walk_dir = os.path.join(images_dir_path, parent_dir)
dirs = tf.io.gfile.listdir(walk_dir)
for d in dirs:
if tf.io.gfile.isdir(os.path.join(walk_dir, d)):
for full_path, _, fname in tf.... | Generate flower images and labels given the image directory path.
Args:
images_dir_path: path to the directory where the images are stored.
Yields:
The image path and its corresponding label. |
def blocks_to_mark_complete_on_view(self, blocks):
blocks = {block for block in blocks if self.can_mark_block_complete_on_view(block)}
completions = self.get_completions({block.location for block in blocks})
return {block for block in blocks if completions.get(block.location, 0) < 1.0} | Returns a set of blocks which should be marked complete on view and haven't been yet. |
def _find_usage_security_groups(self):
vpc_count = 0
paginator = self.conn.get_paginator()
for page in paginator.paginate():
for group in page[]:
if in group and group[] is not None:
vpc_count += 1
self.limits[]._add_curr... | find usage for security groups |
def pem(self):
bio = Membio()
if not libcrypto.PEM_write_bio_CMS(bio.bio, self.ptr):
raise CMSError("writing CMS to PEM")
return str(bio) | Serialize in PEM format |
def Read(f):
try:
yaml_data = yaml.load(f)
except yaml.YAMLError as e:
raise ParseError( % e)
except IOError as e:
raise YAMLLoadError( % e)
_CheckData(yaml_data)
try:
return Config(
yaml_data.get(, ()),
yaml_data.get(, ()))
except UnicodeDecodeError as e:
raise YAML... | Reads and returns Config data from a yaml file.
Args:
f: Yaml file to parse.
Returns:
Config object as defined in this file.
Raises:
Error (some subclass): If there is a problem loading or parsing the file. |
def clipped_area(ts, thresh=0, integrator=integrate.trapz):
integrator = get_integrator(integrator or 0)
ts = insert_crossings(ts, thresh) - thresh
ts = ts[ts >= 0]
return integrator(ts, ts.index.astype(np.int64)) / 1.0e9 | Total value * time above the starting value within a TimeSeries
Arguments:
ts (pandas.Series): Time series to be integrated.
thresh (float): Value to clip the tops off at (crossings will be interpolated)
References:
http://nbviewer.ipython.org/gist/kermit666/5720498
>>> t = ['2014-12-09... |
def _filter_by_statement(self, statement):
self.__class__._check_conditional_statement(statement, 1)
_filt_values, _filt_datetimes = [], []
for i, a in enumerate(self._values):
if eval(statement, {: a}):
_filt_values.append(a)
_filt_datetimes.... | Filter the data collection based on a conditional statement. |
def query(self, query, media=None, year=None, fields=None, extended=None, **kwargs):
if not media:
warnings.warn(
"\"media\" parameter is now required on the Trakt[].query() method",
DeprecationWarning, stacklevel=2
)
if fields a... | Search by titles, descriptions, translated titles, aliases, and people.
**Note:** Results are ordered by the most relevant score.
:param query: Search title or description
:type query: :class:`~python:str`
:param media: Desired media type (or :code:`None` to return all matching items)... |
def resize_file_to(self, in_path, out_path, keep_filename=False):
if keep_filename:
filename = path.join(out_path, path.basename(in_path))
else:
filename = path.join(out_path, self.get_thumbnail_name(in_path))
out_path = path.dirname(filename)
if not path... | Given a filename, resize and save the image per the specification into out_path
:param in_path: path to image file to save. Must be supported by PIL
:param out_path: path to the directory root for the outputted thumbnails to be stored
:return: None |
def get_number_unit(number):
n = str(float(number))
mult, submult = n.split()
if float(submult) != 0:
unit = + (len(submult)-1)* +
return float(unit)
else:
return float(1) | get the unit of number |
def html_scientific_notation_rate(rate):
precision =
if rate * 100 > 0:
decimal_rate = Decimal(precision % (rate * 100))
if decimal_rate == Decimal((precision % 0)):
decimal_rate = Decimal(str(rate * 100))
else:
decimal_rate = Decimal(str(rate * 100))
if decimal... | Helper for convert decimal rate using scientific notation.
For example we want to show the very detail value of fatality rate
because it might be a very small number.
:param rate: Rate value
:type rate: float
:return: Rate value with html tag to show the exponent
:rtype: str |
def docker_installed_rpms(broker):
ctx = broker[DockerImageContext]
root = ctx.root
fmt = DefaultSpecs.rpm_format
cmd = "/usr/bin/rpm -qa --root %s --qf " % (root, fmt)
result = ctx.shell_out(cmd)
return CommandOutputProvider(cmd, ctx, content=result) | Command: /usr/bin/rpm -qa --root `%s` --qf `%s` |
def as_batch_body(self):
if sys.version_info >= (3,) and isinstance(self.body, bytes):
body = self.body.decode()
else:
body = self.body
result = {: body}
if self.custom_properties:
result[] = {name: self._se... | return the current message as expected by batch body format |
def get_command_line_key_for_unknown_config_file_setting(self, key):
key_without_prefix_chars = key.strip(self.prefix_chars)
command_line_key = self.prefix_chars[0]*2 + key_without_prefix_chars
return command_line_key | Compute a commandline arg key to be used for a config file setting
that doesn't correspond to any defined configargparse arg (and so
doesn't have a user-specified commandline arg key).
Args:
key: The config file key that was being set. |
def compare_content_type(url, content_type):
try:
response = urllib2.urlopen(url)
except:
return False
return response.headers.type == content_type | Compare the content type header of url param with content_type param and returns boolean
@param url -> string e.g. http://127.0.0.1/index
@param content_type -> string e.g. text/html |
def match(self, keys, partial=True):
if not partial and len(keys) != self.length:
return False
c = 0
for k in keys:
if c >= self.length:
return False
a = self.keys[c]
if a != "*" and k != "*" and k != a:
ret... | Check if the value of this namespace is matched by
keys
'*' is treated as wildcard
Arguments:
keys -- list of keys
Examples:
ns = Namespace("a.b.c")
ns.match(["a"]) #True
ns.match(["a","b"]) #True
ns.match(["a","b","c"]) #True
... |
def remove_lb_nodes(self, lb_id, node_ids):
log.info("Removing load balancer nodes %s" % node_ids)
for node_id in node_ids:
self._request(, % (lb_id, node_id)) | Remove one or more nodes
:param string lb_id: Balancer id
:param list node_ids: List of node ids |
def tuple_of(*generators):
class TupleOfGenerators(ArbitraryInterface):
@classmethod
def arbitrary(cls):
return tuple([
arbitrary(generator) for generator in generators
if generator is not tuple
])
TupleOfGener... | Generates a tuple by generating values for each of the specified
generators.
This is a class factory, it makes a class which is a closure around the
specified generators. |
def uncompress_file(input_file_name, file_extension, dest_dir):
if file_extension.lower() not in (, ):
raise NotImplementedError("Received {} format. Only gz and bz2 "
"files can currently be uncompressed."
.format(file_extension))
... | Uncompress gz and bz2 files |
def reverse_lookup_from_nested_dict(values_dict):
reverse_lookup = defaultdict(list)
for column_key, column_dict in values_dict.items():
for row_key, value in column_dict.items():
entry = (column_key, value)
reverse_lookup[row_key].append(entry)
return reverse_lookup | Create reverse-lookup dictionary mapping each row key to a list of triplets:
[(column key, value), ...]
Parameters
----------
nested_values_dict : dict
column_key -> row_key -> value
weights_dict : dict
column_key -> row_key -> sample weight
Returns dictionary mapping row_key ... |
def selected(self):
self.selected_text = self.currentText()
self.valid.emit(True, True)
self.open_dir.emit(self.selected_text) | Action to be executed when a valid item has been selected |
def load_from_json(data):
if isinstance(data, str):
data = json.loads(data)
applications = [
ApplicationResponse.load_from_json(a) for a in data[]
] if data[] is not None else []
return RegistryResponse(
data[], data[],
data[], dat... | Load a :class:`RegistryReponse` from a dictionary or a string (that
will be parsed as json). |
def digest_content(self, rule):
data = OrderedDict()
current_key = None
for token in rule.content:
if token.type == :
name = token.value
if name.startswith():
name = name[1:]
... | Walk on rule content tokens to return a dict of properties.
This is pretty naive and will choke/fail on everything that is more
evolved than simple ``ident(string):value(string)``
Arguments:
rule (tinycss2.ast.QualifiedRule): Qualified rule object as
returned by ti... |
def walk_direction_preheel(self, data_frame):
data = data_frame.x.abs() + data_frame.y.abs() + data_frame.z.abs()
dummy, ipeaks_smooth = self.heel_strikes(data)
data = data.values
interpeak = compute_interpeak(data, self.sampling_frequency)
... | Estimate local walk (not cardinal) direction with pre-heel strike phase.
Inspired by Nirupam Roy's B.E. thesis: "WalkCompass: Finding Walking Direction Leveraging Smartphone's Inertial Sensors"
:param data_frame: The data frame. It should have x, y, and z columns.
:type data_frame:... |
def ctcp_reply(self, command, dst, message=None):
if message is None:
raw_cmd = u.format(command)
else:
raw_cmd = u.format(command, message)
self.notice(dst, raw_cmd) | Sends a reply to a CTCP request.
:param command: CTCP command to use.
:type command: str
:param dst: sender of the initial request.
:type dst: str
:param message: data to attach to the reply.
:type message: str |
def __set_style_sheet(self):
colors = map(
lambda x: "rgb({0}, {1}, {2}, {3})".format(x.red(), x.green(), x.blue(), int(self.__opacity * 255)),
(self.__color, self.__background_color, self.__border_color))
self.setStyleSheet(self.__style.format(*colors)) | Sets the Widget stylesheet. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.