repo
stringlengths 1
29
| path
stringlengths 24
332
| code
stringlengths 39
579k
|
---|---|---|
intelligent_tracker-0.1.1 | intelligent_tracker-0.1.1//intelligent_tracker/figures.pyfile:/intelligent_tracker/figures.py:function:_onpick/_onpick | def _onpick(event):
"""
pick function for interactive points
"""
scat = event.artist
poly = scat._polyline
pl = len(poly)
if scat._print:
msg = '{}'.format(poly)
if pl > 1:
msg += ' exactly in {}'.format(poly[event.ind])
print(msg)
scat._print = not scat._print
scat._facecolors[:, :3] = 1 - scat._facecolors[:, :3]
scat._edgecolors[:, :3] = 1 - scat._edgecolors[:, :3]
scat._sizes = scat._sizes * scat._sizes_offset
scat._sizes_offset = 1 / scat._sizes_offset
scat.figure.canvas.draw()
|
symmetric-3.4.2 | symmetric-3.4.2//symmetric/cli/core.pyfile:/symmetric/cli/core.py:function:generate_runner_subparser/generate_runner_subparser | def generate_runner_subparser(subparsers):
"""Generates the subparser for the run server option."""
runner_parser = subparsers.add_parser('run')
runner_parser.set_defaults(action='run')
runner_parser.add_argument('module', metavar='module', help=
'Name of the module that uses the symmetric object.')
runner_parser.add_argument('-s', '--server', dest='server', default=
'127.0.0.1', help='Server hostname in which the application will run.')
runner_parser.add_argument('-p', '--port', dest='port', type=int,
default=5000, help='Port for the webserver.')
runner_parser.add_argument('-d', '--no-debug', dest='debug', action=
'store_const', default=True, const=False, help=
'Do not run in debug mode.')
|
fake-bpy-module-2.78-20200428 | fake-bpy-module-2.78-20200428//bpy/ops/mesh.pyfile:/bpy/ops/mesh.py:function:customdata_custom_splitnormals_clear/customdata_custom_splitnormals_clear | def customdata_custom_splitnormals_clear():
"""Remove the custom split normals layer, if it exists
"""
pass
|
dynetx-0.2.2 | dynetx-0.2.2//dynetx/classes/function.pyfile:/dynetx/classes/function.py:function:temporal_snapshots_ids/temporal_snapshots_ids | def temporal_snapshots_ids(G):
"""Return the ordered list of snapshot ids present in the dynamic graph.
Parameters
----------
G : graph
A DyNetx graph.
Returns
-------
nd : list
a list of snapshot ids
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.add_path([0,4,5,6], t=1)
>>> G.add_path([7,1,2,3], t=2)
>>> dn.temporal_snapshots(G)
[0, 1, 2]
"""
return G.temporal_snapshots_ids()
|
fake-bpy-module-2.78-20200428 | fake-bpy-module-2.78-20200428//bpy/ops/outliner.pyfile:/bpy/ops/outliner.py:function:scene_drop/scene_drop | def scene_drop(object: str='Object', scene: str='Scene'):
"""Drag object to scene in Outliner
:param object: Object, Target Object
:type object: str
:param scene: Scene, Target Scene
:type scene: str
"""
pass
|
foliant | foliant//backends/confluence/extracter.pyfile:/backends/confluence/extracter.py:function:get_content_before_tag/get_content_before_tag | def get_content_before_tag(tag, include_tag=False) ->str:
"""
Get HTML-code before `tag` and return it as string.
Tag's not included by default.
"""
result = ''
bs = tag.previous_sibling
while bs is not None:
result = str(bs) + result
bs = bs.previous_sibling
return str(tag) + result if include_tag else result
|
kolibri | kolibri//dist/dateutil/utils.pyfile:/dist/dateutil/utils.py:function:default_tzinfo/default_tzinfo | def default_tzinfo(dt, tzinfo):
"""
Sets the the ``tzinfo`` parameter on naive datetimes only
This is useful for example when you are provided a datetime that may have
either an implicit or explicit time zone, such as when parsing a time zone
string.
.. doctest::
>>> from dateutil.tz import tzoffset
>>> from dateutil.parser import parse
>>> from dateutil.utils import default_tzinfo
>>> dflt_tz = tzoffset("EST", -18000)
>>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz))
2014-01-01 12:30:00+00:00
>>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz))
2014-01-01 12:30:00-05:00
:param dt:
The datetime on which to replace the time zone
:param tzinfo:
The :py:class:`datetime.tzinfo` subclass instance to assign to
``dt`` if (and only if) it is naive.
:return:
Returns an aware :py:class:`datetime.datetime`.
"""
if dt.tzinfo is not None:
return dt
else:
return dt.replace(tzinfo=tzinfo)
|
anyblok_pyramid-0.9.5 | anyblok_pyramid-0.9.5//anyblok_pyramid/security.pyfile:/anyblok_pyramid/security.py:function:group_finder/group_finder | def group_finder(userid, request):
"""Return groups from user ID
:param userid: the user id (login)
:param request: request from pyramid
"""
if hasattr(request, 'anyblok') and request.anyblok:
return request.anyblok.registry.User.get_roles(userid)
return userid
|
scrapy | scrapy//xlib/tx/interfaces.pyclass:IProcessProtocol/childDataReceived | def childDataReceived(childFD, data):
"""
Called when data arrives from the child process.
@type childFD: C{int}
@param childFD: The file descriptor from which the data was
received.
@type data: C{str}
@param data: The data read from the child's file descriptor.
"""
|
magic-wormhole-0.12.0 | magic-wormhole-0.12.0//versioneer.pyfile:/versioneer.py:function:plus_or_dot/plus_or_dot | def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if '+' in pieces.get('closest-tag', ''):
return '.'
return '+'
|
Biggus-0.14.0 | Biggus-0.14.0//biggus/_init.pyclass:BroadcastArray/broadcast_arrays | @classmethod
def broadcast_arrays(cls, array1, array2):
"""
Broadcast two arrays against each other.
Returns
-------
broadcast_array1 : array1 or a broadcast of array1
broadcast_array2 : array2 or a broadcast of array2
The returned arrays will be broadcast against each other.
Any array which is already in full broadcast shape will be
returned unchanged.
"""
shape, bcast_kwargs1, bcast_kwargs2 = cls._compute_broadcast_kwargs(array1
.shape, array2.shape)
if any(bcast_kwargs1.values()):
array1 = cls(array1, **bcast_kwargs1)
if any(bcast_kwargs2.values()):
array2 = cls(array2, **bcast_kwargs2)
return array1, array2
|
activity-monitor-0.13.5 | activity-monitor-0.13.5//activity_monitor/apps.pyfile:/activity_monitor/apps.py:function:register_app_activity/register_app_activity | def register_app_activity():
"""
Create watchers for models defined in settings.py.
Once created, they will be passed over
Activity.objects.follow_model(), which lives in managers.py
"""
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from .models import Activity
if not hasattr(settings, 'ACTIVITY_MONITOR_MODELS'):
return
for item in settings.ACTIVITY_MONITOR_MODELS:
try:
app_label, model = item['model'].split('.', 1)
content_type = ContentType.objects.get(app_label=app_label,
model=model)
model = content_type.model_class()
Activity.objects.follow_model(model)
except ContentType.DoesNotExist:
pass
|
souper-1.1.1 | souper-1.1.1//src/souper/interfaces.pyclass:ISoup/__delitem__ | def __delitem__(record):
"""Delete Record from soup.
If given record not contained in soup, raise ValueError.
@param record: IRecord implementation
@raise: ValueError if record not exists in this soup.
"""
|
pandas-1.0.3 | pandas-1.0.3//pandas/io/sql.pyfile:/pandas/io/sql.py:function:_engine_builder/_engine_builder | def _engine_builder(con):
"""
Returns a SQLAlchemy engine from a URI (if con is a string)
else it just return con without modifying it.
"""
global _SQLALCHEMY_INSTALLED
if isinstance(con, str):
try:
import sqlalchemy
except ImportError:
_SQLALCHEMY_INSTALLED = False
else:
con = sqlalchemy.create_engine(con)
return con
return con
|
zope.dublincore-4.2.0 | zope.dublincore-4.2.0//src/zope/dublincore/interfaces.pyclass:ICMFDublinCore/CreationDate | def CreationDate():
"""Return the creation date.
The value of the first Dublin Core `Date` element qualified by
'creation' is returned as a unicode string if a qualified
element is defined, otherwise, an empty unicode string is
returned. The string is formatted 'YYYY-MM-DD H24:MN:SS TZ'.
"""
|
pya2l-0.0.1 | pya2l-0.0.1//pya2l/parser/grammar/parser.pyclass:A2lParser/p_alignment_long | @staticmethod
def p_alignment_long(p):
"""alignment_long : ALIGNMENT_LONG NUMERIC"""
p[0] = p[2]
|
xlrd_demo | xlrd_demo//formatting.pyfile:/formatting.py:function:nearest_colour_index/nearest_colour_index | def nearest_colour_index(colour_map, rgb, debug=0):
"""
General purpose function. Uses Euclidean distance.
So far used only for pre-BIFF8 ``WINDOW2`` record.
Doesn't have to be fast.
Doesn't have to be fancy.
"""
best_metric = 3 * 256 * 256
best_colourx = 0
for colourx, cand_rgb in colour_map.items():
if cand_rgb is None:
continue
metric = 0
for v1, v2 in zip(rgb, cand_rgb):
metric += (v1 - v2) * (v1 - v2)
if metric < best_metric:
best_metric = metric
best_colourx = colourx
if metric == 0:
break
if 0 and debug:
print('nearest_colour_index for %r is %r -> %r; best_metric is %d' %
(rgb, best_colourx, colour_map[best_colourx], best_metric))
return best_colourx
|
capybara-py-0.1.6 | capybara-py-0.1.6//capybara/utils.pyfile:/capybara/utils.py:function:inner_content/inner_content | def inner_content(node):
"""
Returns the inner content of a given XML node, including tags.
Args:
node (lxml.etree.Element): The node whose inner content is desired.
Returns:
str: The inner content of the node.
"""
from lxml import etree
parts = [node.text]
for child in node.getchildren():
parts.append(etree.tostring(child, encoding='utf-8'))
parts.append(child.tail)
return ''.join(filter(None, parts))
|
dit-1.2.3 | dit-1.2.3//dit/math/combinatorics.pyfile:/dit/math/combinatorics.py:function:unitsum_tuples/unitsum_tuples | def unitsum_tuples(n, k, mn, mx):
"""Generates unitsum k-tuples with elements from mn to mx.
This function is more general than slots(n,k,normalized=True), as it can
return unitsum vectors with elements outside of (0,1).
In order to generate unitsum samples, the following must be satisfied:
1 = mx + (k-1) * mn
Parameters
----------
n : int
The number of increments to include between mn and mx. n >= 1. The
meaning of n is similar to the n in slots(n,k) and represents the
number of ``items'' to place in each slot.
k : int
The length of the tuples (equivalently, the number of slots).
mn : float
The minimum value in the unitsum samples.
mx : float
The maximum value in the unitsum samples.
Examples
--------
>>> s = unitsum_tuples(3, 2, .2, .8)
>>> s.next()
(0.20000000000000001, 0.80000000000000004)
>>> s.next()
(0.40000000000000008, 0.60000000000000009)
>>> s.next()
(0.60000000000000009, 0.40000000000000002)
>>> s.next()
(0.80000000000000004, 0.19999999999999996)
"""
s = mx + (k - 1) * mn
tol = 1e-09
if not abs(s - 1) <= tol:
msg = 'Specified min and max will not create unitsum tuples.'
e = Exception(msg)
raise e
n += 1
if mn < 0:
shift = float(abs(mn))
else:
shift = -float(mn)
seq, i = [mx + shift] * k + [0], k
while i:
t = tuple(seq[i] - seq[i + 1] - shift for i in range(k))
s = float(sum(t))
assert s > 0.001
yield tuple(t)
for idx, val in enumerate(seq):
if abs(val) < 1e-09:
i = idx - 1
break
seq[i:k] = [seq[i] - (mx - mn) / float(n - 1)] * (k - i)
|
thapbi_pict-0.7.0 | thapbi_pict-0.7.0//thapbi_pict/curated.pyfile:/thapbi_pict/curated.py:function:parse_fasta_entry/parse_fasta_entry | def parse_fasta_entry(text, known_species=None):
"""Split an entry of "Acession genus species etc" into fields.
Returns a two-tuple of taxid (always zero), genus-species.
>>> parse_fasta_entry('HQ013219 Phytophthora arenaria')
(0, 'Phytophthora arenaria')
>>> parse_fasta_entry('P13660 Phytophthora aff infestans')
(0, 'Phytophthora aff infestans')
"""
acc, sp = text.split(None, 1)
taxid = 0
return taxid, sp
|
modtools-1.0.2 | modtools-1.0.2//modtools/vcfreader.pyfile:/modtools/vcfreader.py:function:getGenotype/getGenotype | def getGenotype(genotypeStr):
"""
Return genotype index array from genotype string.
Indices are separated by / or |
e.g. '0/1' => ['0','1']
"""
if '/' in genotypeStr:
return genotypeStr.split('/')
if '|' in genotypeStr:
return genotypeStr.split('|')
return [genotypeStr]
|
ptvpy | ptvpy//_schema.pyfile:/_schema.py:function:_scalar_or_pair/_scalar_or_pair | def _scalar_or_pair(type_, **rules):
"""Expand scalar type to also allow a two-element list of the former.
Parameters
----------
type_ : str
The type string.
**rules
Additional rules to include.
Returns
-------
composite_type : dict
A dictionary that allows a scalar or two-element list of the former.
"""
return {'type': [type_, 'list'], 'schema': {'type': type_, **rules},
'minlength': 2, 'maxlength': 2, **rules}
|
akimous | akimous//modeling/temp/keras/keras/utils/generic_utils.pyfile:/modeling/temp/keras/keras/utils/generic_utils.py:function:unpack_singleton/unpack_singleton | def unpack_singleton(x):
"""Gets the first element if the iterable has only one value.
Otherwise return the iterable.
# Argument
x: A list or tuple.
# Returns
The same iterable or the first element.
"""
if len(x) == 1:
return x[0]
return x
|
kaplanmeier | kaplanmeier//_version.pyfile:/_version.py:function:render_git_describe_long/render_git_describe_long | def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
else:
rendered = pieces['short']
if pieces['dirty']:
rendered += '-dirty'
return rendered
|
gwpy-1.0.1 | gwpy-1.0.1//gwpy/timeseries/statevector.pyclass:StateVector/get | @classmethod
def get(cls, channel, start, end, bits=None, **kwargs):
"""Get data for this channel from frames or NDS
Parameters
----------
channel : `str`, `~gwpy.detector.Channel`
the name of the channel to read, or a `Channel` object.
start : `~gwpy.time.LIGOTimeGPS`, `float`, `str`
GPS start time of required data,
any input parseable by `~gwpy.time.to_gps` is fine
end : `~gwpy.time.LIGOTimeGPS`, `float`, `str`
GPS end time of required data,
any input parseable by `~gwpy.time.to_gps` is fine
bits : `Bits`, `list`, optional
definition of bits for this `StateVector`
pad : `float`, optional
value with which to fill gaps in the source data, only used if
gap is not given, or ``gap='pad'`` is given
dtype : `numpy.dtype`, `str`, `type`, or `dict`
numeric data type for returned data, e.g. `numpy.float`, or
`dict` of (`channel`, `dtype`) pairs
nproc : `int`, optional, default: `1`
number of parallel processes to use, serial process by
default.
verbose : `bool`, optional
print verbose output about NDS progress.
**kwargs
other keyword arguments to pass to either
:meth:`.find` (for direct GWF file access) or
:meth:`.fetch` for remote NDS2 access
See also
--------
StateVector.fetch
for grabbing data from a remote NDS2 server
StateVector.find
for discovering and reading data from local GWF files
"""
new = cls.DictClass.get([channel], start, end, **kwargs)[channel]
if bits:
new.bits = bits
return new
|
pywicta-0.4.dev3 | pywicta-0.4.dev3//utils/simtel_to_fits_nectarcam.pyfile:/utils/simtel_to_fits_nectarcam.py:function:quantity_to_tuple/quantity_to_tuple | def quantity_to_tuple(quantity, unit_str):
"""
Splits a quantity into a tuple of (value,unit) where unit is FITS complient.
Useful to write FITS header keywords with units in a comment.
Parameters
----------
quantity : astropy quantity
The Astropy quantity to split.
unit_str: str
Unit string representation readable by astropy.units (e.g. 'm', 'TeV', ...)
Returns
-------
tuple
A tuple containing the value and the quantity.
"""
return quantity.to(unit_str).value, quantity.to(unit_str).unit.to_string(
format='FITS')
|
Trionyx-2.1.3 | Trionyx-2.1.3//trionyx/trionyx/renderers.pyfile:/trionyx/trionyx/renderers.py:function:render_status/render_status | def render_status(model, *args, **kwargs):
"""Render level as label"""
mapping = {(10): 'warning', (50): 'success', (99): 'danger'}
return '<span class="label label-{}">{}</span>'.format(mapping.get(
model.status, 'info'), model.get_status_display().upper())
|
Pytzer-0.4.3 | Pytzer-0.4.3//pytzer/parameters.pyfile:/pytzer/parameters.py:function:psi_H_Mg_SO4_HMW84/psi_H_Mg_SO4_HMW84 | def psi_H_Mg_SO4_HMW84(T, P):
"""c-c'-a: hydrogen magnesium sulfate [HMW84]."""
psi = 0.0
valid = T == 298.15
return psi, valid
|
pandas-1.0.3 | pandas-1.0.3//pandas/core/generic.pyclass:NDFrame/_get_block_manager_axis | @classmethod
def _get_block_manager_axis(cls, axis):
"""Map the axis to the block_manager axis."""
axis = cls._get_axis_number(axis)
if cls._AXIS_REVERSED:
m = cls._AXIS_LEN - 1
return m - axis
return axis
|
nova-20.2.0 | nova-20.2.0//nova/api/openstack/common.pyfile:/nova/api/openstack/common.py:function:supports_port_resource_request_during_move/supports_port_resource_request_during_move | def supports_port_resource_request_during_move(req):
"""Check to see if the requested API version is high enough for support
port resource request during move operation.
NOTE: At the moment there is no such microversion that supports port
resource request during move. This function is added as a preparation for
that microversion (assuming there will be a new microversion, which is
yet to be decided).
:param req: The incoming API request
:returns: True if the requested API microversion is high enough for
port resource request move support, False otherwise.
"""
return False
|
Fortpy-1.7.7 | Fortpy-1.7.7//fortpy/interop/ftypes.pyfile:/fortpy/interop/ftypes.py:function:_ctypes_out/_ctypes_out | def _ctypes_out(parameter):
"""Returns a parameter variable declaration for an output variable for the specified
parameter.
"""
if (parameter.dimension is not None and ':' in parameter.dimension and
'out' in parameter.direction and ('allocatable' in parameter.
modifiers or 'pointer' in parameter.modifiers)):
if parameter.direction == '(inout)':
return 'type(C_PTR), intent(inout) :: {}_o'.format(parameter.name
), True
else:
return 'type(C_PTR), intent(inout) :: {}_c'.format(parameter.name
), True
|
abopt-0.0.15 | abopt-0.0.15//abopt/legacy/vmad.pyclass:VM/_add_to_graph | @staticmethod
def _add_to_graph(graph, init, list):
"""
add a list of microcodes to a graph. The init node is duplicated as needed
(because it may be used many times and mess up the diagram. It hurts to have
very long edges like that.
"""
source = {}
dest = {}
sans = {}
for vn in init:
source[vn] = '#INIT'
dest[vn] = '#OUT'
for i, record in enumerate(list):
microcode, kwargs = record[0], record[1]
graph.node(str(i) + str(id(microcode)), label=microcode.to_label(
kwargs, html=True))
for an in microcode.ain:
vn = kwargs.get(an, an)
from_init = []
if vn in source:
if vn == '':
continue
if source[vn] == '#INIT':
from_init.append(vn)
else:
san = sans[vn]
dan = an
attrs = {}
if san != vn:
attrs['taillabel'] = san + ':'
if dan != vn:
attrs['headlabel'] = ':' + dan
attrs['label'] = vn
graph.edge(source[vn], str(i) + str(id(microcode)), **attrs
)
dest[vn] = str(i) + str(id(microcode))
if len(from_init) > 0:
graph.node(str(i) + '#INIT', label='<<b>#</b>>')
for vn in from_init:
graph.edge(str(i) + '#INIT', str(i) + str(id(microcode)
), label=vn)
for an in microcode.aout:
vn = kwargs.get(an, an)
source[vn] = str(i) + str(id(microcode))
sans[vn] = an
dest[vn] = '#OUT'
for vn, node in dest.items():
if node != '#OUT':
continue
graph.node(source[vn] + '#OUT', label='<<b>#</b>>')
graph.edge(source[vn], source[vn] + '#OUT', label=vn)
|
GTC | GTC//reporting.pyfile:/reporting.py:function:v_bar/v_bar | def v_bar(cv):
"""Return the trace of ``cv`` divided by 2
:arg cv: a variance-covariance matrix
:type cv: 4-element sequence of float
:returns: float
**Example**::
>>> x1 = 1-.5j
>>> x2 = .2+7.1j
>>> z1 = ucomplex(x1,(1,.2))
>>> z2 = ucomplex(x2,(.2,1))
>>> y = z1 * z2
>>> y.v
VarianceCovariance(rr=2.3464, ri=1.8432, ir=1.8432, ii=51.4216)
>>> reporting.v_bar(y.v)
26.884
"""
assert len(cv) == 4, "'%s' a 4-element sequence is needed" % type(cv)
return (cv[0] + cv[3]) / 2.0
|
openfisca_france | openfisca_france//model/prelevements_obligatoires/impot_revenu/charges_deductibles.pyclass:cd1/formula_2014_01_01 | def formula_2014_01_01(foyer_fiscal, period, parameters):
"""
Renvoie la liste des charges déductibles avant rbg_int pour 2014
"""
pensions_alimentaires_deduites = foyer_fiscal(
'pensions_alimentaires_deduites', period)
cd_acc75a = foyer_fiscal('cd_acc75a', period)
cd_deddiv = foyer_fiscal('cd_deddiv', period)
cd_eparet = foyer_fiscal('cd_eparet', period)
grosses_reparations = foyer_fiscal('grosses_reparations', period)
niches1 = (pensions_alimentaires_deduites + cd_acc75a + cd_deddiv +
cd_eparet + grosses_reparations)
return niches1
|
trackhub-0.2.4 | trackhub-0.2.4//trackhub/helpers.pyfile:/trackhub/helpers.py:function:filter_composite_from_subgroups/filter_composite_from_subgroups | def filter_composite_from_subgroups(s):
"""
Given a sorted list of subgroups, return a string appropriate to provide as
the a composite track's `filterComposite` argument
>>> import trackhub
>>> trackhub.helpers.filter_composite_from_subgroups(['cell', 'ab', 'lab', 'knockdown'])
'dimA dimB'
Parameters
----------
s : list
A list representing the ordered subgroups, ideally the same list
provided to `dimensions_from_subgroups`. The values are not actually
used, just the number of items.
"""
dims = []
for letter, sg in zip('ABCDEFGHIJKLMNOPQRSTUVWZ', s[2:]):
dims.append('dim{0}'.format(letter))
if dims:
return ' '.join(dims)
|
virlutils-0.8.8 | virlutils-0.8.8//virl/generators/nso_payload.pyfile:/virl/generators/nso_payload.py:function:sim_info/sim_info | def sim_info(virl_xml, roster=None, interfaces=None, protocol='telnet'):
"""
common inventory info accross yaml/ini
"""
inventory = list()
for node_long_name, device in roster.items():
if 'managementIP' in device and 'NodeName' in device:
entry = dict()
entry['node_long_name'] = node_long_name
entry['address'] = device['managementIP']
entry['protocol'] = protocol
else:
continue
name = device['NodeName']
entry['name'] = name
entry['ned'] = 'unknown'
entry['ns'] = 'unkown'
try:
type = device['NodeSubtype']
if 'NX' in type:
entry['prefix'] = 'cisco-nx-id'
entry['ned'] = 'cisco-nx'
entry['ns'] = 'http://tail-f.com/ned/cisco-nx-id'
elif 'XR' in type:
entry['prefix'] = 'cisco-ios-xr-id'
entry['ned'] = 'cisco-ios-xr'
entry['ns'] = 'http://tail-f.com/ned/cisco-ios-xr-id'
elif 'CSR' in type or 'IOS' in type:
entry['prefix'] = 'ios-id'
entry['ned'] = 'cisco-ios'
entry['ns'] = 'urn:ios-id'
except KeyError:
pass
if entry.get('ned', None) not in ['unknown', None]:
inventory.append(entry)
return inventory
|
chromewhip-0.3.4 | chromewhip-0.3.4//chromewhip/protocol/media.pyclass:Media/enable | @classmethod
def enable(cls):
"""Enables the Media domain
"""
return cls.build_send_payload('enable', {}), None
|
pmx-2.0 | pmx-2.0//versioneer.pyfile:/versioneer.py:function:render_git_describe_long/render_git_describe_long | def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
else:
rendered = pieces['short']
if pieces['dirty']:
rendered += '-dirty'
return rendered
|
FAdo3-1.0 | FAdo3-1.0//FAdo/yappy_parser.pyfile:/FAdo/yappy_parser.py:function:DefaultSemRule/DefaultSemRule | def DefaultSemRule(sargs, context={}):
"""Default semantic rule"""
return sargs[0]
|
detect_secrets_server | detect_secrets_server//repos/base_tracked_repo.pyclass:BaseTrackedRepo/load_from_file | @classmethod
def load_from_file(cls, repo_name, base_directory, *args, **kwargs):
"""This will load a TrackedRepo to memory, from a given meta tracked
file. For automated management without a database.
The meta tracked file is in the format of self.__dict__
:type repo_name: str
:param repo_name: If the git URL is `[email protected]:yelp/detect-secrets`
this value will be `yelp/detect-secrets`
:rtype: TrackedRepo
:raises: FileNotFoundError
"""
storage = cls.initialize_storage(base_directory)
data = cls.get_tracked_repo_data(storage, repo_name)
output = cls(**data)
output.storage = storage.setup(output.repo)
return output
|
bibmanager-1.2.3 | bibmanager-1.2.3//bibmanager/utils/utils.pyfile:/bibmanager/utils/utils.py:function:repr_author/repr_author | def repr_author(Author):
"""
Get string representation of an Author namedtuple in the format:
von Last, jr., First.
Parameters
----------
Author: An Author() namedtuple
An author name.
Examples
--------
>>> from bibmanager.utils import repr_author, parse_name
>>> names = ['Last', 'First Last', 'First von Last', 'von Last, First',
>>> 'von Last, sr., First']
>>> for name in names:
>>> print(f"{name!r:22}: {repr_author(parse_name(name))}")
'Last' : Last
'First Last' : Last, First
'First von Last' : von Last, First
'von Last, First' : von Last, First
'von Last, sr., First': von Last, sr., First
"""
name = Author.last
if Author.von != '':
name = ' '.join([Author.von, name])
if Author.jr != '':
name += f', {Author.jr}'
if Author.first != '':
name += f', {Author.first}'
return name
|
consoleiotools-2.3.0 | consoleiotools-2.3.0//consoleiotools.pyfile:/consoleiotools.py:function:bye/bye | def bye(msg=''):
"""print msg and exit"""
exit(msg)
|
pymtl3 | pymtl3//passes/rtlir/behavioral/BehavioralRTLIRTypeCheckL1Pass.pyclass:BehavioralRTLIRTypeCheckVisitorL1/enter | def enter(s, blk, rtlir):
""" entry point for RTLIR type checking """
s.blk = blk
s.globals = blk.__globals__
s.closure = {}
for i, var in enumerate(blk.__code__.co_freevars):
try:
s.closure[var] = blk.__closure__[i].cell_contents
except ValueError:
pass
s.visit(rtlir)
|
intek | intek//application/model.pyclass:Parent/__format_phone_number | @staticmethod
def __format_phone_number(phone_number):
"""
Format a local Vietnamese phone number to its international
representation.
The function adds a leading digit `0` if the argument `phone_number`
is only composed of 9 digits.
:param phone_number: A local Vietnamese phone number composed of 9 or
10 digits.
:return: A string representation of an international phone number,
starting with `+84.`.
:raise ValueError: If the argument `phone_number` is not composed of
9 or 10 digits only.
"""
if not phone_number.isdigit():
raise ValueError(f'invalid phone number {phone_number}')
if len(phone_number) < 9:
raise ValueError(f'the phone number {phone_number} is missing digits')
return f'+84.{phone_number.zfill(10)}'
|
nms | nms//fast.pyfile:/fast.py:function:nms/nms | def nms(boxes, scores, **kwargs):
"""Do Non Maximal Suppression
As translated from the OpenCV c++ source in
`nms.inl.hpp <https://github.com/opencv/opencv/blob/ee1e1ce377aa61ddea47a6c2114f99951153bb4f/modules/dnn/src/nms.inl.hpp#L67>`__
which was in turn inspired by `Piotr Dollar's NMS implementation in EdgeBox. <https://goo.gl/jV3JYS>`_
This function is not usually called directly. Instead use :func:`nms.nms.boxes`, :func:`nms.nms.rboxes`,
or :func:`nms.nms.polygons`
:param boxes: the boxes to compare, the structure of the boxes must be compatible with the compare_function.
:type boxes: list
:param scores: the scores associated with boxes
:type scores: list
:param kwargs: optional keyword parameters
:type kwargs: dict (see below)
:returns: an list of indicies of the best boxes
:rtype: list
:kwargs:
* score_threshold (float): the minimum score necessary to be a viable solution, default 0.3
* nms_threshold (float): the minimum nms value to be a viable solution, default: 0.4
* compare_function (function): function that accepts two boxes and returns their overlap ratio, this function must
accept two boxes and return an overlap ratio
* eta (float): a coefficient in adaptive threshold formula: \\ |nmsi1|\\ =eta\\*\\ |nmsi0|\\ , default: 1.0
* top_k (int): if >0, keep at most top_k picked indices. default:0
.. |nmsi0| replace:: nms_threshold\\ :sub:`i`
.. |nmsi1| replace:: nms_threshold\\ :sub:`(i+1)`
"""
if 'eta' in kwargs:
eta = kwargs['eta']
else:
eta = 1.0
assert 0 < eta <= 1.0
if 'top_k' in kwargs:
top_k = kwargs['top_k']
else:
top_k = 0
assert 0 <= top_k
if 'score_threshold' in kwargs:
score_threshold = kwargs['score_threshold']
else:
score_threshold = 0.3
assert score_threshold > 0
if 'nms_threshold' in kwargs:
nms_threshold = kwargs['nms_threshold']
else:
nms_threshold = 0.4
assert 0 < nms_threshold < 1
if 'compare_function' in kwargs:
compare_function = kwargs['compare_function']
else:
compare_function = None
assert compare_function is not None
if len(boxes) == 0:
return []
assert len(scores) == len(boxes)
assert scores is not None
scores = help.get_max_score_index(scores, score_threshold, top_k)
adaptive_threshold = nms_threshold
indicies = []
for i in range(0, len(scores)):
idx = int(scores[i][1])
keep = True
for k in range(0, len(indicies)):
if not keep:
break
kept_idx = indicies[k]
overlap = compare_function(boxes[idx], boxes[kept_idx])
keep = overlap <= adaptive_threshold
if keep:
indicies.append(idx)
if keep and eta < 1 and adaptive_threshold > 0.5:
adaptive_threshold = adaptive_threshold * eta
return indicies
|
monobox-0.5.22 | monobox-0.5.22//monobox/main.pyfile:/monobox/main.py:function:expose_ports/expose_ports | def expose_ports():
"""
You specify exposed ports like this:
EXPOSE external_port : docker_port
"""
ports = []
with open('.monobox') as monobox:
for lines in monobox:
if lines.partition(' ')[0] == 'EXPOSE':
port_setting = lines.partition(' ')[2].rstrip()
ports.append('-p')
port_number = port_setting.partition(':')[0].rstrip()
try:
internal_port_number = port_setting.partition(':')[3
].rstrip()
except IndexError:
internal_port_number = port_number
ports.append(port_number + ':' + internal_port_number)
return ports
|
Jade-Application-Kit-3.5.0 | Jade-Application-Kit-3.5.0//bin/JAK/IPC.pyclass:Bind/listen | @staticmethod
def listen(data):
"""
* Do something with the data.
* :param data:
* :return: url output
"""
raise NotImplementedError()
|
efficientnet_pytorch-0.6.3 | efficientnet_pytorch-0.6.3//efficientnet_pytorch/utils.pyclass:BlockDecoder/_encode_block_string | @staticmethod
def _encode_block_string(block):
"""Encodes a block to a string."""
args = ['r%d' % block.num_repeat, 'k%d' % block.kernel_size, 's%d%d' %
(block.strides[0], block.strides[1]), 'e%s' % block.expand_ratio,
'i%d' % block.input_filters, 'o%d' % block.output_filters]
if 0 < block.se_ratio <= 1:
args.append('se%s' % block.se_ratio)
if block.id_skip is False:
args.append('noskip')
return '_'.join(args)
|
twitter.common.process-0.3.11 | twitter.common.process-0.3.11//src/twitter/common/process/process_provider.pyclass:ProcessProvider/_platform_compatible | @staticmethod
def _platform_compatible():
"""Returns true if this provider is compatible on the current platform."""
raise NotImplementedError
|
Firenado-0.1.8.3 | Firenado-0.1.8.3//firenado/config.pyfile:/firenado/config.py:function:get_class_from_module/get_class_from_module | def get_class_from_module(module, class_name):
""" Returns a class from a module and a class name parameters.
This function is used by get_class_from_config and get_class_from_name.
Example:
>>> get_class_from_module("my.module", "MyClass")
:param basestring module: The module name.
:param basestring class_name: The class name.
:return: The class resolved by the module and class name provided.
"""
import importlib
module = importlib.import_module(module)
return getattr(module, class_name)
|
publicdata-0.3.9 | publicdata-0.3.9//publicdata/nlsy/cdb.pyfile:/publicdata/nlsy/cdb.py:function:pair_slugify/pair_slugify | def pair_slugify(e):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.type(
"""
import re
import unicodedata
value = '{} {}'.format(*e)
value = str(value)
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore'
).decode('utf8').strip().lower()
value = re.sub('[^\\w\\s]', '', value)
value = re.sub('\\s+', ' ', value)
value = re.sub('[-\\s]+', '-', value)
return value
|
fake-bpy-module-2.78-20200428 | fake-bpy-module-2.78-20200428//bpy/ops/object.pyfile:/bpy/ops/object.py:function:origin_clear/origin_clear | def origin_clear():
"""Clear the object’s origin
"""
pass
|
bpy_nibbler-0.1 | bpy_nibbler-0.1//bpy_lambda/2.78/scripts/addons/io_curve_svg/import_svg.pyfile:/bpy_lambda/2.78/scripts/addons/io_curve_svg/import_svg.py:function:SVGFinishCurve/SVGFinishCurve | def SVGFinishCurve():
"""
Finish curve creation
"""
pass
|
pandas_datareader | pandas_datareader//data.pyfile:/data.py:function:get_dailysummary_iex/get_dailysummary_iex | def get_dailysummary_iex(*args, **kwargs):
"""
Returns a summary of daily market volume statistics. Without parameters,
this will return the most recent trading session by default.
Parameters
----------
start : string, int, date, datetime, Timestamp
The beginning of the date range.
end : string, int, date, datetime, Timestamp
The end of the date range.
Reference: https://www.iextrading.com/developer/docs/#historical-daily
:return: DataFrame
"""
from pandas_datareader.iex.stats import DailySummaryReader
return DailySummaryReader(*args, **kwargs).read()
|
social_core | social_core//storage.pyclass:AssociationMixin/remove | @classmethod
def remove(cls, ids_to_delete):
"""Remove an Association instance"""
raise NotImplementedError('Implement in subclass')
|
virga | virga//gas_properties.pyfile:/gas_properties.py:function:Al2O3/Al2O3 | def Al2O3(mw_atmos, mh=1):
"""Defines properties for Al2O3 as condensible"""
if mh != 1:
raise Exception(
'Alert: No M/H Dependence in Al2O3 Routine. Consult your local theorist to determine next steps.'
)
gas_mw = 101.961
gas_mmr = 2.51e-06 * (gas_mw / mw_atmos)
rho_p = 3.987
return gas_mw, gas_mmr, rho_p
|
ht-0.1.54 | ht-0.1.54//ht/conv_internal.pyfile:/ht/conv_internal.py:function:turbulent_Colburn/turbulent_Colburn | def turbulent_Colburn(Re, Pr):
"""Calculates internal convection Nusselt number for turbulent flows
in pipe according to [2]_ as in [1]_.
.. math::
Nu = 0.023Re^{0.8}Pr^{1/3}
Parameters
----------
Re : float
Reynolds number, [-]
Pr : float
Prandtl number, [-]
Returns
-------
Nu : float
Nusselt number, [-]
Notes
-----
Range according to [1]_ is 0.5 < Pr < 3 and 10^4 < Re < 10^5.
Examples
--------
>>> turbulent_Colburn(Re=1E5, Pr=1.2)
244.41147091200068
References
----------
.. [1] Rohsenow, Warren and James Hartnett and Young Cho. Handbook of Heat
Transfer, 3E. New York: McGraw-Hill, 1998.
.. [2] Colburn, Allan P. "A Method of Correlating Forced Convection
Heat-Transfer Data and a Comparison with Fluid Friction." International
Journal of Heat and Mass Transfer 7, no. 12 (December 1964): 1359-84.
doi:10.1016/0017-9310(64)90125-5.
"""
return 0.023 * Re ** 0.8 * Pr ** (1 / 3.0)
|
plot | plot//io/input/extract_data_error_bar.pyfile:/io/input/extract_data_error_bar.py:function:extract_data_error_bar/extract_data_error_bar | def extract_data_error_bar(data, params):
"""Return error bar arrays
Return error bar arrays along X and Y
Args:
data (ndarray): input data
params (dict): one entry of the 'data' parameter field
Returns:
(x_bars, y_bars) where x_bars and y_bars are 1-dimensional numpy arrays
"""
plot_type = params['plot_type']
row_begin = params[plot_type]['row_start']
ooo = []
for k in ['x', 'y']:
j = params['error_bar']['data_column'][k]
if j is None:
ooo.append(None)
else:
ooo.append(data[row_begin:, (j)])
return tuple(ooo)
|
bars | bars//std.pyclass:bars/format_interval | @staticmethod
def format_interval(t):
"""
Formats a number of seconds as a clock time, [H:]MM:SS
Parameters
----------
t : int
Number of seconds.
Returns
-------
out : str
[H:]MM:SS
"""
mins, s = divmod(int(t), 60)
h, m = divmod(mins, 60)
if h:
return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s)
else:
return '{0:02d}:{1:02d}'.format(m, s)
|
pepperedform-0.6.1 | pepperedform-0.6.1//pepperedform/renderutils.pyfile:/pepperedform/renderutils.py:function:mapping_getter/mapping_getter | def mapping_getter(items, name, if_missing=None):
""" A mapping should pass this function to its children to get their
defaults or errors.
"""
if items:
return items.get(name, if_missing)
return if_missing
|
ms_mint | ms_mint//_version.pyfile:/_version.py:function:render_pep440_pre/render_pep440_pre | def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
if pieces['distance']:
rendered += '.post.dev%d' % pieces['distance']
else:
rendered = '0.post.dev%d' % pieces['distance']
return rendered
|
fake-blender-api-2.79-0.3.1 | fake-blender-api-2.79-0.3.1//mathutils/geometry.pyfile:/mathutils/geometry.py:function:intersect_point_quad_2d/intersect_point_quad_2d | def intersect_point_quad_2d(pt, quad_p1, quad_p2, quad_p3, quad_p4):
"""Takes 5 vectors (using only the x and y coordinates): one is the point and the next 4 define the quad, only the x and y are used from the vectors. Returns 1 if the point is within the quad, otherwise 0. Works only with convex quads without singular edges.
Parameters:
pt (mathutils.Vector) – Point
quad_p1 (mathutils.Vector) – First point of the quad
quad_p2 (mathutils.Vector) – Second point of the quad
quad_p3 (mathutils.Vector) – Third point of the quad
quad_p4 (mathutils.Vector) – Fourth point of the quad
Return type: int"""
return 1
|
pytzer | pytzer//parameters.pyfile:/parameters.py:function:psi_Ca_H_CO3_HMW84/psi_Ca_H_CO3_HMW84 | def psi_Ca_H_CO3_HMW84(T, P):
"""c-c'-a: calcium hydrogen carbonate [HMW84]."""
psi = 0.0
valid = T == 298.15
return psi, valid
|
fake-bpy-module-2.78-20200428 | fake-bpy-module-2.78-20200428//bpy/props.pyfile:/bpy/props.py:function:BoolProperty/BoolProperty | def BoolProperty(name: str='', description: str='', default=False, options:
set={'ANIMATABLE'}, subtype: str='NONE', update=None, get=None, set=None):
"""Returns a new boolean property definition.
:param name: Name used in the user interface.
:type name: str
:param description: Text used for the tooltip and api documentation.
:type description: str
:param options: Enumerator in [‘HIDDEN’, ‘SKIP_SAVE’, ‘ANIMATABLE’, ‘LIBRARY_EDITABLE’, ‘PROPORTIONAL’,’TEXTEDIT_UPDATE’].
:type options: set
:param subtype: Enumerator in [‘PIXEL’, ‘UNSIGNED’, ‘PERCENTAGE’, ‘FACTOR’, ‘ANGLE’, ‘TIME’, ‘DISTANCE’, ‘NONE’].
:type subtype: str
:param update: Function to be called when this value is modified, This function must take 2 values (self, context) and return None. Warning there are no safety checks to avoid infinite recursion.
:param get: Function to be called when this value is ‘read’, This function must take 1 value (self) and return the value of the property.
:param set: Function to be called when this value is ‘written’, This function must take 2 values (self, value) and return None.
"""
pass
|
ZODB | ZODB//interfaces.pyclass:IConnection/add | def add(ob):
"""Add a new object 'obj' to the database and assign it an oid.
A persistent object is normally added to the database and
assigned an oid when it becomes reachable to an object already in
the database. In some cases, it is useful to create a new
object and use its oid (_p_oid) in a single transaction.
This method assigns a new oid regardless of whether the object
is reachable.
The object is added when the transaction commits. The object
must implement the IPersistent interface and must not
already be associated with a Connection.
Parameters:
obj: a Persistent object
Raises TypeError if obj is not a persistent object.
Raises InvalidObjectReference if obj is already associated with another
connection.
Raises ConnectionStateError if the connection is closed.
"""
|
golem-framework-0.9.0 | golem-framework-0.9.0//golem/core/utils.pyfile:/golem/core/utils.py:function:separate_file_from_parents/separate_file_from_parents | def separate_file_from_parents(full_filename):
"""Receives a full filename with parents (separated by dots)
Returns a duple, first element is the filename and second element
is the list of parents that might be empty"""
splitted = full_filename.split('.')
file = splitted.pop()
parents = splitted
return file, parents
|
Flask-Ask-0.9.8 | Flask-Ask-0.9.8//flask_ask/cache.pyfile:/flask_ask/cache.py:function:top_stream/top_stream | def top_stream(cache, user_id):
"""
Peek at the top of the stack in the cache.
:param cache: werkzeug BasicCache-like object
:param user_id: id of user, used as key in cache
:return: top item in user's cached stack, otherwise None
"""
if not user_id:
return None
stack = cache.get(user_id)
if stack is None:
return None
return stack.pop()
|
abilian | abilian//web/csrf.pyfile:/web/csrf.py:function:name/name | def name() ->str:
"""Field name expected to have CSRF token.
Useful for passing it to JavaScript for instance.
"""
return 'csrf_token'
|
cadnano | cadnano//color.pyfile:/color.py:function:intToColorHex/intToColorHex | def intToColorHex(color_number):
"""Convert an integer to a hexadecimal string compatible with :class:`QColor`
Args:
color_number (int): integer value of a RGB color
Returns:
str: QColor compatible hex string in format '#rrggbb'
"""
return '#%0.6x' % color_number
|
jubakit-0.6.2 | jubakit-0.6.2//jubakit/base.pyclass:BaseService/_client_class | @classmethod
def _client_class(cls):
"""
Subclasses must override this method and return the client class.
"""
raise NotImplementedError()
|
avclass | avclass//evaluate_clustering.pyfile:/evaluate_clustering.py:function:tp_fp_fn/tp_fp_fn | def tp_fp_fn(CORRECT_SET, GUESS_SET):
"""
INPUT: dictionary with the elements in the cluster from the ground truth
(CORRECT_SET) and dictionary with the elements from the estimated cluster
(ESTIMATED_SET).
OUTPUT: number of True Positives (elements in both clusters), False
Positives (elements only in the ESTIMATED_SET), False Negatives (elements
only in the CORRECT_SET).
"""
tp = 0
fp = 0
fn = 0
for elem in GUESS_SET:
if elem in CORRECT_SET:
tp += 1
else:
fp += 1
for elem in CORRECT_SET:
if elem not in GUESS_SET:
fn += 1
return tp, fp, fn
|
compiletools-4.1.73 | compiletools-4.1.73//ct/apptools.pyfile:/ct/apptools.py:function:_do_xxpend/_do_xxpend | def _do_xxpend(args, name):
""" For example, if name is CPPFLAGS, take the
args.prependcppflags and prepend them to args.CPPFLAGS.
Similarly for append.
"""
xxlist = 'prepend', 'append'
for xx in xxlist:
xxpendname = ''.join([xx, name.lower()])
if hasattr(args, xxpendname):
xxpendattr = getattr(args, xxpendname)
attr = getattr(args, name)
if xxpendattr:
extra = []
for flag in xxpendattr:
if flag not in attr:
extra.append(flag)
if xx == 'prepend':
attr = ' '.join(extra + [attr])
else:
attr = ' '.join([attr] + extra)
setattr(args, name, attr)
|
fake-bpy-module-2.80-20200428 | fake-bpy-module-2.80-20200428//bpy/ops/object.pyfile:/bpy/ops/object.py:function:hook_add_selob/hook_add_selob | def hook_add_selob(use_bone: bool=False):
"""Hook selected vertices to the first selected object
:param use_bone: Active Bone, Assign the hook to the hook objects active bone
:type use_bone: bool
"""
pass
|
astra-toolbox-1.8b5 | astra-toolbox-1.8b5//astra/pythonutils.pyfile:/astra/pythonutils.py:function:geom_size/geom_size | def geom_size(geom, dim=None):
"""Returns the size of a volume or sinogram, based on the projection or volume geometry.
:param geom: Geometry to calculate size from
:type geometry: :class:`dict`
:param dim: Optional axis index to return
:type dim: :class:`int`
"""
if 'GridSliceCount' in geom:
s = geom['GridSliceCount'], geom['GridRowCount'], geom['GridColCount']
elif 'GridColCount' in geom:
s = geom['GridRowCount'], geom['GridColCount']
elif geom['type'] == 'parallel' or geom['type'] == 'fanflat':
s = len(geom['ProjectionAngles']), geom['DetectorCount']
elif geom['type'] == 'parallel3d' or geom['type'] == 'cone':
s = geom['DetectorRowCount'], len(geom['ProjectionAngles']), geom[
'DetectorColCount']
elif geom['type'] == 'fanflat_vec':
s = geom['Vectors'].shape[0], geom['DetectorCount']
elif geom['type'] == 'parallel3d_vec' or geom['type'] == 'cone_vec':
s = geom['DetectorRowCount'], geom['Vectors'].shape[0], geom[
'DetectorColCount']
if dim != None:
s = s[dim]
return s
|
fake-blender-api-2.79-0.3.1 | fake-blender-api-2.79-0.3.1//bpy/ops/object.pyfile:/bpy/ops/object.py:function:scale_clear/scale_clear | def scale_clear(clear_delta: bool=False):
"""Clear the object’s scale
:param clear_delta: Clear Delta, Clear delta scale in addition to clearing the normal scale transform
:type clear_delta: bool
"""
pass
|
isatools | isatools//utils.pyfile:/utils.py:function:squashstr/squashstr | def squashstr(string):
"""Squashes a string by removing the spaces and lowering it"""
nospaces = ''.join(string.split())
return nospaces.lower()
|
pyboto3-1.4.4 | pyboto3-1.4.4//pyboto3/elasticloadbalancingv2.pyfile:/pyboto3/elasticloadbalancingv2.py:function:describe_ssl_policies/describe_ssl_policies | def describe_ssl_policies(Names=None, Marker=None, PageSize=None):
"""
Describes the specified policies or all policies used for SSL negotiation.
For more information, see Security Policies in the Application Load Balancers Guide .
See also: AWS API Documentation
Examples
This example describes the specified policy used for SSL negotiation.
Expected Output:
:example: response = client.describe_ssl_policies(
Names=[
'string',
],
Marker='string',
PageSize=123
)
:type Names: list
:param Names: The names of the policies.
(string) --
:type Marker: string
:param Marker: The marker for the next set of results. (You received this marker from a previous call.)
:type PageSize: integer
:param PageSize: The maximum number of results to return with this call.
:rtype: dict
:return: {
'SslPolicies': [
{
'SslProtocols': [
'string',
],
'Ciphers': [
{
'Name': 'string',
'Priority': 123
},
],
'Name': 'string'
},
],
'NextMarker': 'string'
}
:returns:
(string) --
"""
pass
|
octadist-2.6.1 | octadist-2.6.1//octadist/src/elements.pyfile:/octadist/src/elements.py:function:check_color/check_color | def check_color(x):
"""
Convert atomic number to color: 1-109.
Parameters
----------
x : int
Atomic number.
Returns
-------
atomic color[x] : str
Atomic color.
References
----------
http://jmol.sourceforge.net/jscolors/
Examples
--------
>>> check_color(2) # He
'#D9FFFF'
"""
atom_color = ['0', '#FFFFFF', '#D9FFFF', '#CC80FF', '#C2FF00',
'#FFB5B5', '#909090', '#3050F8', '#FF0D0D', '#90E050', '#B3E3F5',
'#AB5CF2', '#8AFF00', '#BFA6A6', '#F0C8A0', '#FF8000', '#FFFF30',
'#1FF01F', '#80D1E3', '#8F40D4', '#3DFF00', '#E6E6E6', '#BFC2C7',
'#A6A6AB', '#8A99C7', '#9C7AC7', '#E06633', '#F090A0', '#50D050',
'#C88033', '#7D80B0', '#C28F8F', '#668F8F', '#BD80E3', '#FFA100',
'#A62929', '#5CB8D1', '#702EB0', '#00FF00', '#94FFFF', '#94E0E0',
'#73C2C9', '#54B5B5', '#3B9E9E', '#248F8F', '#0A7D8C', '#006985',
'#C0C0C0', '#FFD98F', '#A67573', '#668080', '#9E63B5', '#D47A00',
'#940094', '#429EB0', '#57178F', '#00C900', '#70D4FF', '#FFFFC7',
'#D9FFC7', '#C7FFC7', '#A3FFC7', '#8FFFC7', '#61FFC7', '#45FFC7',
'#30FFC7', '#1FFFC7', '#00FF9C', '#00E675', '#00D452', '#00BF38',
'#00AB24', '#4DC2FF', '#4DA6FF', '#2194D6', '#267DAB', '#266696',
'#175487', '#D0D0E0', '#FFD123', '#B8B8D0', '#A6544D', '#575961',
'#9E4FB5', '#AB5C00', '#754F45', '#428296', '#420066', '#007D00',
'#70ABFA', '#00BAFF', '#00A1FF', '#008FFF', '#0080FF', '#006BFF',
'#545CF2', '#785CE3', '#8A4FE3', '#A136D4', '#B31FD4', '#B31FBA',
'#B30DA6', '#BD0D87', '#C70066', '#CC0059', '#D1004F', '#D90045',
'#E00038', '#E6002E', '#EB0026']
return atom_color[x]
|
anna | anna//adaptors.pyclass:JSONAdaptor/_convert_path_to_bare_tail_path | @classmethod
def _convert_path_to_bare_tail_path(cls, path):
"""
Strips the index (if present) from the last path element (i.e. ensuring
that it has a "bare tail").
Parameters
----------
path : unicode
The path to be converted (may contain indices).
Returns
-------
bare_tail_path : unicode
Similar as path but the last path element is guaranteed to be without index.
Examples
--------
>>> JSONAdaptor._convert_path_to_bare_tail_path('A/B/C')
'A/B/C'
>>> JSONAdaptor._convert_path_to_bare_tail_path('A[0]/B[1]/C[2]')
'A[0]/B[1]/C'
"""
if len(cls.split_path(path)) > 1:
head = cls.join_paths(*cls.split_path(path)[:-1])
tail = cls._parse_name_from_element_identifier(cls.split_path(path)[-1]
)
return cls.join_paths(head, tail)
else:
return cls._parse_name_from_element_identifier(path)
|
patoolib | patoolib//programs/zip.pyfile:/programs/zip.py:function:test_zip/test_zip | def test_zip(archive, compression, cmd, verbosity, interactive):
"""Test a ZIP archive."""
cmdlist = [cmd, '--test']
if verbosity > 1:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist
|
taskflow | taskflow//utils/misc.pyfile:/utils/misc.py:function:safe_copy_dict/safe_copy_dict | def safe_copy_dict(obj):
"""Copy an existing dictionary or default to empty dict...
This will return a empty dict if given object is falsey, otherwise it
will create a dict of the given object (which if provided a dictionary
object will make a shallow copy of that object).
"""
if not obj:
return {}
return dict(obj)
|
fake-bpy-module-2.79-20200428 | fake-bpy-module-2.79-20200428//bpy/ops/curve.pyfile:/bpy/ops/curve.py:function:select_less/select_less | def select_less():
"""Reduce current selection by deselecting boundary elements
"""
pass
|
fecon236 | fecon236//host/qdl.pyfile:/host/qdl.py:function:holtqdl/holtqdl | def holtqdl(data, h=24, alpha=0.26, beta=0.19):
"""DEPRECATED: Holt-Winters forecast h-periods ahead (quandlcode aware)."""
msg = 'holtqdl() DEPRECATED. Instead use get(), holt(), holtforecast().'
raise DeprecationWarning(msg)
|
ccxt | ccxt//static_dependencies/ecdsa/_version.pyfile:/static_dependencies/ecdsa/_version.py:function:render_git_describe_long/render_git_describe_long | def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
else:
rendered = pieces['short']
if pieces['dirty']:
rendered += '-dirty'
return rendered
|
ask_sdk_model | ask_sdk_model//interfaces/alexa/presentation/apl/listoperations/operation.pyclass:Operation/get_real_child_model | @classmethod
def get_real_child_model(cls, data):
"""Returns the real base class specified by the discriminator"""
discriminator_value = data[cls.json_discriminator_key]
return cls.discriminator_value_class_map.get(discriminator_value)
|
pyswmm | pyswmm//lidunits.pyfile:/lidunits.py:function:_flux_rate/_flux_rate | def _flux_rate(model, subcatchment, lid_index, layer):
"""
Get lid net inflow - outflow from previous time step for each lid layer
ONLY FOR for surface, soil, storage, pave
:param int layerIndex: layer type (toolkitapi.LidLayers member variable)
:return: Parameter Value
:rtype: double
"""
return model.getLidUFluxRates(subcatchment, lid_index, layer)
|
awscli | awscli//customizations/utils.pyfile:/customizations/utils.py:function:get_policy_arn_suffix/get_policy_arn_suffix | def get_policy_arn_suffix(region):
"""Method to return region value as expected by policy arn"""
region_string = region.lower()
if region_string.startswith('cn-'):
return 'aws-cn'
elif region_string.startswith('us-gov'):
return 'aws-us-gov'
else:
return 'aws'
|
easyirc-0.1.1 | easyirc-0.1.1//easyirc/util.pyfile:/easyirc/util.py:function:decolon/decolon | def decolon(item):
"""Colon has special usage in IRC protocol"""
if item[0] == ':':
return item[1:]
return item
|
redis-moment-0.0.6 | redis-moment-0.0.6//moment/utils.pyfile:/moment/utils.py:function:add_month/add_month | def add_month(year, month, delta):
"""
Helper function which adds `delta` months to current `(year, month)` tuple
and returns a new valid tuple `(year, month)`
"""
year, month = divmod(year * 12 + month + delta, 12)
if month == 0:
month = 12
year = year - 1
return year, month
|
bpy | bpy//ops/scene.pyfile:/ops/scene.py:function:render_view_remove/render_view_remove | def render_view_remove():
"""Remove the selected render view
"""
pass
|
noworkflow-1.12.0 | noworkflow-1.12.0//noworkflow/now/utils/bytecode/interpreter.pyfile:/noworkflow/now/utils/bytecode/interpreter.py:function:cord/cord | def cord(value):
"""Convert (str or int) to ord"""
if isinstance(value, str):
return ord(value)
return value
|
mlfinlab | mlfinlab//portfolio_optimization/returns_estimators.pyclass:ReturnsEstimation/calculate_exponential_historical_returns | @staticmethod
def calculate_exponential_historical_returns(asset_prices, resample_by=None,
frequency=252, span=500):
"""
Calculates the exponentially-weighted annualized mean of historical returns, giving
higher weight to more recent data.
:param asset_prices: (pd.DataFrame) Asset price data
:param resample_by: (str) Period to resample data ['D','W','M' etc.] None for no resampling
:param frequency: (int) Average number of observations per year
:param span: (int) Window length to use in pandas ewm function
:return: (pd.Series) Exponentially-weighted mean of historical returns
"""
if resample_by:
asset_prices = asset_prices.resample(resample_by).last()
returns = asset_prices.pct_change().dropna(how='all')
returns = returns.ewm(span=span).mean().iloc[-1] * frequency
return returns
|
vipertools-3.3.1 | vipertools-3.3.1//vipertools/sitepackages/qps/speclib/spectrallibraries.pyfile:/vipertools/sitepackages/qps/speclib/spectrallibraries.py:function:findTypeFromString/findTypeFromString | def findTypeFromString(value: str):
"""
Returns a fitting basic python data type of a string value, i.e.
:param value: string
:return: type out of [str, int or float]
"""
for t in (int, float, str):
try:
_ = t(value)
except ValueError:
continue
return t
return str
|
tryalgo-1.3.0 | tryalgo-1.3.0//tryalgo/rectangles_from_histogram.pyfile:/tryalgo/rectangles_from_histogram.py:function:rectangles_from_histogram/rectangles_from_histogram | def rectangles_from_histogram(H):
"""Largest Rectangular Area in a Histogram
:param H: histogram table
:returns: area, left, height, right, rect. is [0, height] * [left, right)
:complexity: linear
"""
best = float('-inf'), 0, 0, 0
S = []
H2 = H + [float('-inf')]
for right in range(len(H2)):
x = H2[right]
left = right
while len(S) > 0 and S[-1][1] >= x:
left, height = S.pop()
rect = height * (right - left), left, height, right
if rect > best:
best = rect
S.append((left, x))
return best
|
dotdrop | dotdrop//utils.pyfile:/utils.py:function:header/header | def header():
"""return dotdrop header"""
return 'This dotfile is managed using dotdrop'
|
perfmetrics-3.0.0 | perfmetrics-3.0.0//src/perfmetrics/pyramid.pyfile:/src/perfmetrics/pyramid.py:function:includeme/includeme | def includeme(config):
"""Pyramid configuration hook: activate the perfmetrics tween.
A statsd_uri should be in the settings.
"""
if config.registry.settings.get('statsd_uri'):
config.add_tween('perfmetrics.tween')
|
twisted | twisted//internet/interfaces.pyclass:IServiceCollection/removeService | def removeService(service):
"""
Remove a service from this collection.
"""
|
uszipcode-0.2.4 | uszipcode-0.2.4//uszipcode/pkg/sqlalchemy_mate/utils.pyfile:/uszipcode/pkg/sqlalchemy_mate/utils.py:function:execute_query_return_result_proxy/execute_query_return_result_proxy | def execute_query_return_result_proxy(query):
"""
Execute a query, yield result proxy.
:param query: :class:`sqlalchemy.orm.Query`,
has to be created from ``session.query(Object)``
:return: :class:`sqlalchemy.engine.result.ResultProxy`
"""
context = query._compile_context()
context.statement.use_labels = False
if query._autoflush and not query._populate_existing:
query.session._autoflush()
conn = query._get_bind_args(context, query._connection_from_session,
close_with_result=True)
return conn.execute(context.statement, query._params)
|
pyjoystick-1.1.2 | pyjoystick-1.1.2//pyjoystick/button_repeater.pyclass:Repeater/get_key_hash | @staticmethod
def get_key_hash(key):
"""Return the hash for the given key."""
if key.joystick:
return '{}:{} {}'.format(key.joystick, key.keytype, key.number)
else:
return '{} {}'.format(key.keytype, key.number)
|
scrapy | scrapy//xlib/tx/interfaces.pyclass:IResolver/lookupMailBox | def lookupMailBox(name, timeout=None):
"""
Perform an MB record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: L{Deferred}
@return: A L{Deferred} which fires with a three-tuple of lists of
L{twisted.names.dns.RRHeader} instances. The first element of the
tuple gives answers. The second element of the tuple gives
authorities. The third element of the tuple gives additional
information. The L{Deferred} may instead fail with one of the
exceptions defined in L{twisted.names.error} or with
C{NotImplementedError}.
"""
|