repo
stringlengths 1
29
| path
stringlengths 24
332
| code
stringlengths 39
579k
|
---|---|---|
elephasy | elephasy//utils/functional_utils.pyfile:/utils/functional_utils.py:function:add_params/add_params | def add_params(p1, p2):
"""
Add two lists of parameters
"""
res = []
for x, y in zip(p1, p2):
res.append(x + y)
return res
|
pyschoof-0.1 | pyschoof-0.1//pyschoof/fields/finite/naive.pyclass:FiniteField/size | @classmethod
def size(cls):
"""
Return the number of elements in the field.
"""
return cls.characteristic() ** cls.power()
|
horovod-0.19.1 | horovod-0.19.1//horovod/tensorflow/compression.pyclass:Compressor/compress | @staticmethod
def compress(tensor):
"""Compresses a tensor and returns it with the context needed to decompress it."""
pass
|
Products.CMFPlone-5.2.1 | Products.CMFPlone-5.2.1//Products/CMFPlone/interfaces/controlpanel.pyclass:IControlPanel/registerConfiglet | def registerConfiglet(id, name, action, condition='', permission='',
category='Plone', visible=1, appId=None, imageUrl=None, description='',
REQUEST=None):
""" Registration of a Configlet """
|
dropbox | dropbox//team_log.pyclass:EventDetails/file_requests_emails_enabled_details | @classmethod
def file_requests_emails_enabled_details(cls, val):
"""
Create an instance of this class set to the
``file_requests_emails_enabled_details`` tag with value ``val``.
:param FileRequestsEmailsEnabledDetails val:
:rtype: EventDetails
"""
return cls('file_requests_emails_enabled_details', val)
|
fake-blender-api-2.79-0.3.1 | fake-blender-api-2.79-0.3.1//bpy/ops/group.pyfile:/bpy/ops/group.py:function:create/create | def create(name: str='Group'):
"""Create an object group from selected objects
:param name: Name, Name of the new group
:type name: str
"""
pass
|
py4j | py4j//finalizer.pyclass:ThreadSafeFinalizer/add_finalizer | @classmethod
def add_finalizer(cls, id, weak_ref):
"""Registers a finalizer with an id.
:param id: The id of the object referenced by the weak reference.
:param weak_ref: The weak reference to register.
"""
with cls.lock:
cls.finalizers[id] = weak_ref
|
mlflowhelper-1.1.0 | mlflowhelper-1.1.0//src/mlflowhelper/tracking/fluent.pyfile:/src/mlflowhelper/tracking/fluent.py:function:_tracking_uri/_tracking_uri | def _tracking_uri(tracking_uri):
"""Helper function for URI shorthands.
Parameters
----------
tracking_uri: str
"file" will translate to `None`,
"localhost" to "http://localhost:5000", and
"localhost-2" to "http://localhost:5002".
Returns
-------
str or None
"""
if tracking_uri == 'file':
tracking_uri = None
elif tracking_uri is not None and tracking_uri.startswith('localhost'):
split = tracking_uri.split('-')
port = 5000
if len(split) > 1:
port += int(split[1])
tracking_uri = 'http://localhost:{}'.format(port)
else:
tracking_uri = tracking_uri
return tracking_uri
|
lifelib | lifelib//projects/nestedlife/projection.pyfile:/projects/nestedlife/projection.py:function:PolsOther/PolsOther | def PolsOther(t):
"""Number of policies: Other benefits"""
return 0
|
PyDSD-1.0.5.2 | PyDSD-1.0.5.2//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 '+'
|
fsleyes | fsleyes//overlay.pyfile:/overlay.py:function:findMeshReferenceImage/findMeshReferenceImage | def findMeshReferenceImage(overlayList, overlay):
"""Searches the :class:`.OverlayList` and tries to identify a reference
image for the given :class:`.Mesh` overlay. Returns the identified
overlay, or ``None`` if one can't be found.
"""
import fsl.data.vtk as fslvtk
if not isinstance(overlay, fslvtk.VTKMesh):
return None
try:
prefix = fslvtk.getFIRSTPrefix(overlay.dataSource)
for ovl in overlayList:
if prefix.startswith(ovl.name):
return ovl
except Exception:
pass
return None
|
pydruid-0.5.9 | pydruid-0.5.9//env/lib/python3.7/operator.pyfile:/env/lib/python3.7/operator.py:function:iconcat/iconcat | def iconcat(a, b):
"""Same as a += b, for a and b sequences."""
if not hasattr(a, '__getitem__'):
msg = "'%s' object can't be concatenated" % type(a).__name__
raise TypeError(msg)
a += b
return a
|
xpybutil | xpybutil//xinerama.pyfile:/xinerama.py:function:get_physical_mapping/get_physical_mapping | def get_physical_mapping(monitors):
"""
Returns a list of Xinerama screen indices in their physical order.
Where physical order is defined as left-to-right and then top-to-bottom.
:param monitors: List of (x, y, w, h) rectangles
:rtype: List of Xinerama indices
"""
retval = []
tosort = []
for i, (x, y, w, h) in enumerate(monitors):
tosort.append((x, y, i))
for x, y, xscreen in sorted(tosort):
retval.append(xscreen)
return retval
|
stock_pandas | stock_pandas//command_presets.pyfile:/command_presets.py:function:sma/sma | def sma(df, s, period, column):
"""Gets simple moving average
Args:
df (DataFrame): data
s (slice): the slice object
period (int): size of the moving period
column (str): column name to calculate
Returns:
pandas.Series
"""
return df[column][s].rolling(min_periods=period, window=period, center=
False).mean(), period
|
sonicprobe | sonicprobe//libs/xys.pyfile:/libs/xys.py:function:seqlen/seqlen | def seqlen(lst, schema, min_len, max_len):
"""
!~~seqlen(min,max)
corresponding sequences in documents must have a length between
min and max, included.
"""
return min_len <= len(lst) <= max_len
|
djmodels | djmodels//contrib/gis/db/backends/postgis/models.pyclass:PostGISGeometryColumns/table_name_col | @classmethod
def table_name_col(cls):
"""
Return the name of the metadata column used to store the feature table
name.
"""
return 'f_table_name'
|
metpy | metpy//io/nexrad.pyfile:/io/nexrad.py:function:version/version | def version(val):
"""Calculate a string version from an integer value."""
if val / 100.0 > 2.0:
ver = val / 100.0
else:
ver = val / 10.0
return '{:.1f}'.format(ver)
|
dropbox | dropbox//sharing.pyclass:JobError/remove_folder_member_error | @classmethod
def remove_folder_member_error(cls, val):
"""
Create an instance of this class set to the
``remove_folder_member_error`` tag with value ``val``.
:param RemoveFolderMemberError val:
:rtype: JobError
"""
return cls('remove_folder_member_error', val)
|
hatchet-1.1.0 | hatchet-1.1.0//hatchet/graphframe.pyclass:GraphFrame/from_caliper | @staticmethod
def from_caliper(filename, query):
"""Read in a Caliper `cali` file.
Args:
filename (str): name of a Caliper output file in `.cali` format
query (str): cali-query in CalQL format
"""
from .readers.caliper_reader import CaliperReader
return CaliperReader(filename, query).read()
|
fake-bpy-module-2.78-20200428 | fake-bpy-module-2.78-20200428//bpy/ops/wm.pyfile:/bpy/ops/wm.py:function:context_scale_float/context_scale_float | def context_scale_float(data_path: str='', value: float=1.0):
"""Scale a float context value
:param data_path: Context Attributes, RNA context string
:type data_path: str
:param value: Value, Assign value
:type value: float
"""
pass
|
collective.taskqueue-1.0 | collective.taskqueue-1.0//src/collective/taskqueue/interfaces.pyclass:ITaskQueue/put | def put(task):
"""Put task into queue; Called by transaction data manager"""
|
izir-1.0.1 | izir-1.0.1//izi/introspect.pyfile:/izi/introspect.py:function:is_coroutine/is_coroutine | def is_coroutine(function):
"""Returns True if the passed in function is a coroutine"""
return function.__code__.co_flags & 128 or getattr(function,
'_is_coroutine', False)
|
Circle-Map-1.1.4 | Circle-Map-1.1.4//circlemap/utils.pyfile:/circlemap/utils.py:function:is_soft_clipped/is_soft_clipped | def is_soft_clipped(read):
"""Function that checks the CIGAR string of the sam file and returns true if the read is soft-clipped"""
match = 0
for cigar in read.cigar:
if cigar[0] == 4:
match += 1
else:
pass
if match > 0:
return True
else:
return False
|
octadist-2.6.1 | octadist-2.6.1//octadist/src/molecule.pyfile:/octadist/src/molecule.py:function:is_orca/is_orca | def is_orca(f):
"""
Check if the input file is ORCA file format.
Parameters
----------
f : str
User input filename.
Returns
-------
bool : bool
If file is ORCA output file, return True.
See Also
--------
get_coord_orca :
Find atomic coordinates of molecule from ORCA file.
Examples
--------
>>> orca.out
---------------------------------
CARTESIAN COORDINATES (ANGSTROEM)
---------------------------------
C 0.009657 0.000000 0.005576
C 0.009657 -0.000000 1.394424
C 1.212436 -0.000000 2.088849
C 2.415214 0.000000 1.394425
C 2.415214 -0.000000 0.005575
...
"""
orca_file = open(f, 'r')
nline = orca_file.readlines()
for i in range(len(nline)):
if 'CARTESIAN COORDINATES (ANGSTROEM)' in nline[i]:
return True
return False
|
zope.server-4.0.2 | zope.server-4.0.2//src/zope/server/interfaces/logger.pyclass:IRequestLogger/logRequest | def logRequest(ip, message):
"""Logs the ip address and message at the appropriate place."""
|
pypiscout-2.0.1 | pypiscout-2.0.1//pypiscout/SCout_Logger.pyclass:Logger/_checkVerbosity | @staticmethod
def _checkVerbosity(invVerbosity):
"""
Check for valid values of invVerbosity (if invalid an exception is thrown)
:param invVerbosity: [int or str]
:return: None
"""
if type(invVerbosity) is str:
if invVerbosity == '':
raise ValueError('Passed empty string!')
if invVerbosity.isdigit():
pass
elif invVerbosity[0] == '-':
if invVerbosity[1:].isdigit():
pass
else:
raise ValueError('Passed str could not be converted to int!')
else:
raise ValueError('Passed invalid str!')
elif type(invVerbosity) is int:
pass
else:
raise TypeError('Type must be either str or int!')
|
dryer | dryer//_version.pyfile:/_version.py:function:render_pep440_old/render_pep440_old | def render_pep440_old(pieces):
"""TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
if pieces['distance'] or pieces['dirty']:
rendered += '.post%d' % pieces['distance']
if pieces['dirty']:
rendered += '.dev0'
else:
rendered = '0.post%d' % pieces['distance']
if pieces['dirty']:
rendered += '.dev0'
return rendered
|
firebase_admin | firebase_admin//_auth_utils.pyfile:/_auth_utils.py:function:validate_boolean/validate_boolean | def validate_boolean(value, label):
"""Validates that the given value is a boolean."""
if not isinstance(value, bool):
raise ValueError('Invalid type for {0}: {1}.'.format(label, value))
return value
|
bookkeep-0.5.7 | bookkeep-0.5.7//bookkeep/_smart_book.pyclass:SmartBook/_warning | @staticmethod
def _warning(source, msg, category=Warning):
"""Return a Warning object with source description."""
if isinstance(source, str):
msg = f'@{source}: ' + msg
elif source:
msg = f'@{type(source).__name__} {str(source)}: ' + msg
return category(msg)
|
enablebanking | enablebanking//models/alm_brand_connector_settings.pyclass:AlmBrandConnectorSettings/__ne__ | def __ne__(A, other):
"""Returns true if both objects are not equal"""
return not A == other
|
biopandas | biopandas//pdb/pandas_pdb.pyclass:PandasPdb/_get_mainchain | @staticmethod
def _get_mainchain(df, invert):
"""Return only main chain atom entries from a DataFrame"""
if invert:
mc = df[(df['atom_name'] != 'C') & (df['atom_name'] != 'O') & (df[
'atom_name'] != 'N') & (df['atom_name'] != 'CA')]
else:
mc = df[(df['atom_name'] == 'C') | (df['atom_name'] == 'O') | (df[
'atom_name'] == 'N') | (df['atom_name'] == 'CA')]
return mc
|
dask-image-0.2.0 | dask-image-0.2.0//versioneer.pyfile:/versioneer.py:function:render_pep440_old/render_pep440_old | def render_pep440_old(pieces):
"""TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
if pieces['distance'] or pieces['dirty']:
rendered += '.post%d' % pieces['distance']
if pieces['dirty']:
rendered += '.dev0'
else:
rendered = '0.post%d' % pieces['distance']
if pieces['dirty']:
rendered += '.dev0'
return rendered
|
plato-draw-1.10.0 | plato-draw-1.10.0//plato/geometry.pyfile:/plato/geometry.py:function:twiceTriangleArea/twiceTriangleArea | def twiceTriangleArea(p0, p1, p2):
"""Returns twice the signed area of the triangle specified by the
2D numpy points (p0, p1, p2)."""
p1 = p1 - p0
p2 = p2 - p0
return p1[0] * p2[1] - p2[0] * p1[1]
|
pyFreenet3-0.4.7 | pyFreenet3-0.4.7//freenet_passlib_170/handlers/bcrypt.pyfile:/freenet_passlib_170/handlers/bcrypt.py:function:_detect_pybcrypt/_detect_pybcrypt | def _detect_pybcrypt():
"""
internal helper which tries to distinguish pybcrypt vs bcrypt.
:returns:
True if cext-based py-bcrypt,
False if ffi-based bcrypt,
None if 'bcrypt' module not found.
.. versionchanged:: 1.6.3
Now assuming bcrypt installed, unless py-bcrypt explicitly detected.
Previous releases assumed py-bcrypt by default.
Making this change since py-bcrypt is (apparently) unmaintained and static,
whereas bcrypt is being actively maintained, and it's internal structure may shift.
"""
try:
import bcrypt
except ImportError:
return None
try:
from bcrypt._bcrypt import __version__
except ImportError:
return False
return True
|
scrapy | scrapy//xlib/tx/interfaces.pyclass:IResolver/lookupNameservers | def lookupNameservers(name, timeout=None):
"""
Perform an NS 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}.
"""
|
pandas_streaming | pandas_streaming//df/dataframe_helpers.pyfile:/df/dataframe_helpers.py:function:pandas_fillna/pandas_fillna | def pandas_fillna(df, by, hasna=None, suffix=None):
"""
Replaces the :epkg:`nan` values for something not :epkg:`nan`.
Mostly used by @see fn pandas_groupby_nan.
@param df dataframe
@param by list of columns for which we need to replace nan
@param hasna None or list of columns for which we need to replace NaN
@param suffix use a prefix for the NaN value
@return list of values chosen for each column, new dataframe (new copy)
"""
suffix = suffix if suffix else '²'
df = df.copy()
rep = {}
for c in by:
if hasna is not None and c not in hasna:
continue
if df[c].dtype in (str, bytes, object):
se = set(df[c].dropna())
val = se.pop()
if isinstance(val, str):
cst = suffix
val = ''
elif isinstance(val, bytes):
cst = b'_'
else:
raise TypeError(
"Unable to determine a constant for type='{0}' dtype='{1}'"
.format(val, df[c].dtype))
val += cst
while val in se:
val += suffix
df[c].fillna(val, inplace=True)
rep[c] = val
else:
dr = df[c].dropna()
mi = abs(dr.min())
ma = abs(dr.max())
val = ma + mi
if val <= ma:
raise ValueError(
"Unable to find a different value for column '{0}': min={1} max={2}"
.format(val, mi, ma))
df[c].fillna(val, inplace=True)
rep[c] = val
return rep, df
|
mxnet | mxnet//symbol/gen_op.pyfile:/symbol/gen_op.py:function:elemwise_div/elemwise_div | def elemwise_div(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
"""Divides arguments element-wise.
The storage type of ``elemwise_div`` output is always dense
Parameters
----------
lhs : Symbol
first input
rhs : Symbol
second input
name : string, optional.
Name of the resulting symbol.
Returns
-------
Symbol
The result symbol.
"""
return 0,
|
BuyProxiesAPI-0.22 | BuyProxiesAPI-0.22//buyproxies_api/buyproxies_api.pyclass:BuyProxiesAPI/__to_list | @staticmethod
def __to_list(text):
"""
Convert string to list by spliting it on new line
:param text: string with proxies each proxy on new line
:return: list of strings
"""
return text.split('\n')
|
seantis.reservation-1.4.0 | seantis.reservation-1.4.0//seantis/reservation/exports/reservations.pyfile:/seantis/reservation/exports/reservations.py:function:fieldkey/fieldkey | def fieldkey(form, field):
""" Returns the fieldkey for any given json data field + form. """
return '%s.%s' % (form['desc'], field['desc'])
|
fitlins-0.5.1 | fitlins-0.5.1//versioneer.pyfile:/versioneer.py:function:scan_setup_py/scan_setup_py | def scan_setup_py():
"""Validate the contents of setup.py against Versioneer's expectations."""
found = set()
setters = False
errors = 0
with open('setup.py', 'r') as f:
for line in f.readlines():
if 'import versioneer' in line:
found.add('import')
if 'versioneer.get_cmdclass()' in line:
found.add('cmdclass')
if 'versioneer.get_version()' in line:
found.add('get_version')
if 'versioneer.VCS' in line:
setters = True
if 'versioneer.versionfile_source' in line:
setters = True
if len(found) != 3:
print('')
print('Your setup.py appears to be missing some important items')
print('(but I might be wrong). Please make sure it has something')
print('roughly like the following:')
print('')
print(' import versioneer')
print(' setup( version=versioneer.get_version(),')
print(' cmdclass=versioneer.get_cmdclass(), ...)')
print('')
errors += 1
if setters:
print("You should remove lines like 'versioneer.VCS = ' and")
print("'versioneer.versionfile_source = ' . This configuration")
print('now lives in setup.cfg, and should be removed from setup.py')
print('')
errors += 1
return errors
|
ghhu-0.1 | ghhu-0.1//ghhu/github.pyfile:/ghhu/github.py:function:repositorios/repositorios | def repositorios(nome):
"""
Retornar a lista de repos do usuário
:param nome: nome do usuário
:return: list
"""
|
izzy-0.3.37 | izzy-0.3.37//izzy/features/transform.pyfile:/izzy/features/transform.py:function:woeify/woeify | def woeify(x, y, bins=10, mode='equal'):
"""
Transforms x into weight of evidence
Parameters
----------
x
y
bins
mode
Returns
-------
"""
pass
|
mindspore | mindspore//_checkparam.pyfile:/_checkparam.py:function:check_bool/check_bool | def check_bool(input_param):
"""Bool type judgment."""
if isinstance(input_param, bool):
return input_param
raise TypeError('Input type must be bool!')
|
ac-0.3-alpha | ac-0.3-alpha//src/ac/ac.pyfile:/src/ac/ac.py:function:remove_empty/remove_empty | def remove_empty(entry):
"""
Filters all empty strings and 'None' entries from a list
"""
return entry != None and entry != ''
|
nive | nive//views.pyfile:/views.py:function:PreflightRequest/PreflightRequest | def PreflightRequest(request, allowOrigins='*', allowMethods=
'POST, GET, DELETE, OPTIONS', allowHeaders='', allowCredentials=True,
maxAge=3600, response=None):
"""
Handles Access-Control preflight requests.
:param request: The current request.
:param allowOrigins: Either '*' (all allowed) or a list of hosts e.g ('http://mydomain.com')
:param allowMethods: 'POST, GET, DELETE, OPTIONS'. Allowed http methods as string.
:param allowHeaders: Custom headers passed in a request as string.
:param allowCredentials: True/False. Credentials are made accessible in the client application.
:param response: The response to be returned. if None `request.response` is used.
:return: response
"""
response = response or request.response
origin = request.headers.get('Origin')
if origin is None:
return response
if allowOrigins != '*':
if not origin in allowOrigins and not '*' in allowOrigins:
response.status = '405 Not Allowed'
return response
headers = [('Access-Control-Allow-Origin', origin), (
'Access-Control-Allow-Methods', allowMethods), (
'Access-Control-Allow-Credentials', str(allowCredentials).lower()),
('Access-Control-Max-Age', maxAge), ('Access-Control-Allow-Headers',
allowHeaders), ('Vary', 'Accept-Encoding, Origin')]
if hasattr(response, 'headerlist'):
headers += list(response.headerlist)
response.headerlist = headers
return response
|
wagtailinvoices-0.4.3 | wagtailinvoices-0.4.3//wagtailinvoices/permissions.pyfile:/wagtailinvoices/permissions.py:function:user_can_edit_invoice_type/user_can_edit_invoice_type | def user_can_edit_invoice_type(user, content_type):
""" true if user has any permission related to this content type """
if user.is_active and user.is_superuser:
return True
permission_codenames = content_type.permission_set.values_list('codename',
flat=True)
for codename in permission_codenames:
permission_name = '%s.%s' % (content_type.app_label, codename)
if user.has_perm(permission_name):
return True
return False
|
counterparty-lib-9.55.4 | counterparty-lib-9.55.4//counterpartylib/lib/transaction.pyfile:/counterpartylib/lib/transaction.py:function:chunks/chunks | def chunks(l, n):
""" Yield successive n‐sized chunks from l.
"""
for i in range(0, len(l), n):
yield l[i:i + n]
|
obdlib-0.2 | obdlib-0.2//obdlib/obd/protocols/protocols.pyclass:Protocols/_get_frame_params | @staticmethod
def _get_frame_params(frame):
"""
Retrieves some params from the frame
:param frame - the OBD frame
:return tuple of ecu_number, response_mode
"""
return frame[4:6], int(frame[6:8])
|
dulwichTest-0.18.7 | dulwichTest-0.18.7//dulwich/ignore.pyfile:/dulwich/ignore.py:function:read_ignore_patterns/read_ignore_patterns | def read_ignore_patterns(f):
"""Read a git ignore file.
:param f: File-like object to read from
:return: List of patterns
"""
for line in f:
line = line.rstrip(b'\r\n')
if not line:
continue
if line.startswith(b'#'):
continue
while line.endswith(b' ') and not line.endswith(b'\\ '):
line = line[:-1]
line = line.replace(b'\\ ', b' ')
yield line
|
parametrization_clean | parametrization_clean//domain/mutation/factory.pyclass:MutationFactory/register | @classmethod
def register(cls, algorithm_name: str, mutation_class):
"""Register a class with a string key."""
cls.REGISTRY[algorithm_name] = mutation_class
return mutation_class
|
manticore-0.3.3 | manticore-0.3.3//manticore/core/parser/parser.pyfile:/manticore/core/parser/parser.py:function:p_expression_neg/p_expression_neg | def p_expression_neg(p):
"""expression : NEG expression """
p[0] = ~p[1]
|
pop_build | pop_build//pop_build/pkg/init.pyfile:/pop_build/pkg/init.py:function:build/build | def build(hub, bname):
"""
Given the build arguments, Make a package!
"""
pkg_builder = hub.OPT['pop_build']['pkg_builder']
getattr(hub, f'pop_build.pkg.{pkg_builder}.build')(bname)
|
rref | rref//helpers/utils_.pyfile:/helpers/utils_.py:function:ABS/ABS | def ABS(n):
"""Returns absolute value of a number."""
return n if n >= 0 else n * -1
|
aggregation_builder-0.0.4 | aggregation_builder-0.0.4//aggregation_builder/operators/group.pyfile:/aggregation_builder/operators/group.py:function:SUM/SUM | def SUM(*expression):
"""
Calculates and returns the sum of numeric values.
See https://docs.mongodb.com/manual/reference/operator/aggregation/sum/
for more details
:param expression: expression or variables
:return: Aggregation operator
"""
return {'$sum': list(expression)} if len(expression) > 1 else {'$sum':
expression[0]} if expression else {}
|
code_monkey-0.0.3 | code_monkey-0.0.3//code_monkey/utils.pyfile:/code_monkey/utils.py:function:safe_docstring/safe_docstring | def safe_docstring(input):
"""Takes a docstring input, and returns a version with all ':' characters
replaced with ' '.
':' characters will confuse the method we use to scan for the beginning of a
class or function body (basically, looking backwards from the first element
until we find the ':' from the signature), which is why we do this.
It's safe to sub in safe_docstring for docstring in a copy of the source,
because even if the docstring text appears elsewhere in the file, the
scanner won't hit it, and it will take up the same number of characters.
We could fool this by have a docstring whose text appears at the end of the
signature as well. Hopefully, that's a rare case, but: TODO: fix that."""
return input.replace(':', ' ')
|
loopyCryptor-0.1.1 | loopyCryptor-0.1.1//loopyCryptor/Serializer.pyfile:/loopyCryptor/Serializer.py:function:byte_to_str/byte_to_str | def byte_to_str(text, do_convert=True):
"""
make sure `text` is string if `do_convert`
:raise AttributeError: Text is not processable
"""
if not do_convert:
return text
elif isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode()
else:
raise AttributeError(
'Unable to convert {} to string.Text should be string or bytes'
.format(type(text)))
|
co2mpas | co2mpas//model/physical/electrics/electrics_prediction.pyfile:/model/physical/electrics/electrics_prediction.py:function:calculate_alternator_current/calculate_alternator_current | def calculate_alternator_current(alternator_status, on_engine,
gear_box_power_in, max_alternator_current, alternator_current_model,
engine_start_current, prev_battery_state_of_charge, acceleration, time):
"""
Calculates the alternator current [A].
:param alternator_status:
When the alternator is on due to 1:state of charge or 2:BERS [-].
:type alternator_status: int
:param on_engine:
If the engine is on [-].
:type on_engine: bool
:param gear_box_power_in:
Gear box power [kW].
:type gear_box_power_in: float
:param max_alternator_current:
Max feasible alternator current [A].
:type max_alternator_current: float
:param alternator_current_model:
Alternator current model.
:type alternator_current_model: callable
:param engine_start_current:
Current demand to start the engine [A].
:type engine_start_current: float
:param prev_battery_state_of_charge:
Previous state of charge of the battery [%].
.. note::
`prev_battery_state_of_charge` = 99 is equivalent to 99%.
:type prev_battery_state_of_charge: float
:param acceleration:
Acceleration [m/s2].
:type acceleration: float
:param time:
Time [s].
:type time: float
:return:
Alternator current [A].
:rtype: float
"""
if alternator_status and on_engine and engine_start_current == 0:
a_c = alternator_current_model(time, prev_battery_state_of_charge,
alternator_status, gear_box_power_in, acceleration)
a_c = max(a_c, -max_alternator_current)
else:
a_c = 0.0
return a_c - engine_start_current
|
pdfCropMargins-0.2.6 | pdfCropMargins-0.2.6//src/pdfCropMargins/gui.pyfile:/src/pdfCropMargins/gui.py:function:to_int_or_NA/to_int_or_NA | def to_int_or_NA(value):
"""Convert to float unless the value is 'N/A', which is left unchanged."""
if value == 'N/A':
return 'N/A'
else:
return int(value)
|
pya2l-0.0.1 | pya2l-0.0.1//pya2l/parser/grammar/parser.pyclass:A2lParser/p_ref_group_optional_list | @staticmethod
def p_ref_group_optional_list(p):
"""ref_group_optional_list : ref_group_optional
| ref_group_optional ref_group_optional_list"""
try:
p[0] = [p[1]] + p[2]
except IndexError:
p[0] = [p[1]]
|
batchflow | batchflow//models/tf/resnet.pyclass:ResNet/default_layout | @classmethod
def default_layout(cls, bottleneck, **kwargs):
""" Define conv block layout """
_ = kwargs
reps = 3 if bottleneck else 2
return 'cna' * reps
|
django-meetup-1.0.7 | django-meetup-1.0.7//meetup/sync_utils.pyfile:/meetup/sync_utils.py:function:to_meetup_geo/to_meetup_geo | def to_meetup_geo(geo):
""" from geo location to Meetup data geo """
return geo
|
networking-vsphere-2015.1.1 | networking-vsphere-2015.1.1//networking_vsphere/utils/vim_util.pyfile:/networking_vsphere/utils/vim_util.py:function:get_obj_spec/get_obj_spec | def get_obj_spec(client_factory, obj, select_set=None):
"""Builds the Object Spec object."""
obj_spec = client_factory.create('ns0:ObjectSpec')
obj_spec.obj = obj
obj_spec.skip = False
if select_set is not None:
obj_spec.selectSet = select_set
return obj_spec
|
gtimelog | gtimelog//timelog.pyfile:/timelog.py:function:uniq/uniq | def uniq(l):
"""Return list with consecutive duplicates removed."""
result = l[:1]
for item in l[1:]:
if item != result[-1]:
result.append(item)
return result
|
micca-1.7.2 | micca-1.7.2//micca/table.pyfile:/micca/table.py:function:write/write | def write(output_fn, table):
"""Write OTU/Taxa tables.
"""
table.to_csv(output_fn, sep='\t')
|
Oasys-Widget-Core-1.0.0 | Oasys-Widget-Core-1.0.0//orangewidget/settings.pyclass:ContextHandler/add_context | @staticmethod
def add_context(widget, setting):
"""Add the context to the top of the list."""
s = widget.context_settings
s.insert(0, setting)
del s[len(s):]
|
fake-bpy-module-2.78-20200428 | fake-bpy-module-2.78-20200428//bpy/ops/screen.pyfile:/bpy/ops/screen.py:function:delete/delete | def delete():
"""Delete active screen
"""
pass
|
nmrglue | nmrglue//analysis/lineshapes1d.pyfile:/analysis/lineshapes1d.py:function:sim_lorentz_gamma/sim_lorentz_gamma | def sim_lorentz_gamma(x, x0, gamma):
"""
Simulate a Lorentzian lineshape with unit height at the center.
Simulates discrete points of the continuous Cauchy-Lorentz (Breit-Wigner)
distribution with unit height at the center. Gamma (the half-width at
half-maximum, HWHM) is used as the scale parameter.
Functional form:
f(x; x0, gamma) = g ^ 2 / ((x-x0) ^ 2 + g ^ 2)
Parameters
----------
x : ndarray
Array of values at which to evaluate distribution.
x0 : float
Center of the distribution.
gamma : float
Scale parameter, half-width at half-maximum, of distribution.
Returns
-------
f : ndarray
Distribution evaluated at points in x.
"""
return gamma ** 2 / (gamma ** 2 + (x - x0) ** 2)
|
manukaclient | manukaclient//base.pyfile:/base.py:function:getid/getid | def getid(obj):
"""Get obj's id or object itself if no id
Abstracts the common pattern of allowing both an object or
an object's ID as a parameter when dealing with relationships.
"""
try:
return obj.id
except AttributeError:
return obj
|
pymodbus-2.3.0 | pymodbus-2.3.0//pymodbus/utilities.pyfile:/pymodbus/utilities.py:function:dict_property/dict_property | def dict_property(store, index):
""" Helper to create class properties from a dictionary.
Basically this allows you to remove a lot of possible
boilerplate code.
:param store: The store store to pull from
:param index: The index into the store to close over
:returns: An initialized property set
"""
if hasattr(store, '__call__'):
getter = lambda self: store(self)[index]
setter = lambda self, value: store(self).__setitem__(index, value)
elif isinstance(store, str):
getter = lambda self: self.__getattribute__(store)[index]
setter = lambda self, value: self.__getattribute__(store).__setitem__(
index, value)
else:
getter = lambda self: store[index]
setter = lambda self, value: store.__setitem__(index, value)
return property(getter, setter)
|
numdoclint | numdoclint//helper.pyfile:/helper.py:function:_get_func_start_line_index/_get_func_start_line_index | def _get_func_start_line_index(line_splitted_list, func_name):
"""
Get the start line index of the target function.
Parameters
----------
line_splitted_list : list of str
A list of strings separated by line.
func_name : str
Target function name.
Returns
-------
func_start_line_index : int
The start line index of the target function. If target
function name not found, -1 will be set.
"""
search_str = 'def %s' % func_name
for i, line_str in enumerate(line_splitted_list):
is_in = search_str in line_str
if not is_in:
continue
if i + 1 >= len(line_splitted_list):
continue
next_line_str = line_splitted_list[i + 1]
concatenated_str = line_str + next_line_str
concatenated_str = concatenated_str.replace('\n', '')
concatenated_str = concatenated_str.strip()
is_in = 'def %s(' % func_name in concatenated_str
if not is_in:
continue
return i
return -1
|
pyvim-3.0.2 | pyvim-3.0.2//pyvim/commands/handler.pyfile:/pyvim/commands/handler.py:function:_go_to_line/_go_to_line | def _go_to_line(editor, line):
"""
Move cursor to this line in the current buffer.
"""
b = editor.application.current_buffer
b.cursor_position = b.document.translate_row_col_to_index(max(0, int(
line) - 1), 0)
|
kolibri | kolibri//dist/more_itertools/more.pyfile:/dist/more_itertools/more.py:function:always_reversible/always_reversible | def always_reversible(iterable):
"""An extension of :func:`reversed` that supports all iterables, not
just those which implement the ``Reversible`` or ``Sequence`` protocols.
>>> print(*always_reversible(x for x in range(3)))
2 1 0
If the iterable is already reversible, this function returns the
result of :func:`reversed()`. If the iterable is not reversible,
this function will cache the remaining items in the iterable and
yield them in reverse order, which may require significant storage.
"""
try:
return reversed(iterable)
except TypeError:
return reversed(list(iterable))
|
soma-base-4.6.4 | soma-base-4.6.4//python/soma/utils/loader.pyfile:/python/soma/utils/loader.py:function:insert_tool/insert_tool | def insert_tool(tools, tool, allowed_instances):
""" Add tool to list if tool is sub class
of one item in allowed_instances
"""
allowed_instances = allowed_instances or [object]
for check_instance in allowed_instances:
if isinstance(tool, type) and issubclass(tool, check_instance):
tools.append(tool)
break
|
pure-cdb-3.1.0 | pure-cdb-3.1.0//cdblib/djb_hash.pyfile:/cdblib/djb_hash.py:function:djb_hash/djb_hash | def djb_hash(s):
"""Return the value of DJB's hash function for byte string *s*"""
h = 5381
for c in s:
h = ((h << 5) + h ^ c) & 4294967295
return h
|
vsc-base-3.1.4 | vsc-base-3.1.4//lib/vsc/utils/py2vs3/py3.pyfile:/lib/vsc/utils/py2vs3/py3.py:function:ensure_ascii_string/ensure_ascii_string | def ensure_ascii_string(value):
"""
Convert the provided value to an ASCII string (no Unicode characters).
"""
if isinstance(value, bytes):
value = value.decode('ascii', 'backslashreplace')
else:
value = bytes(str(value), encoding='utf-8').decode(encoding='ascii',
errors='backslashreplace')
return value
|
bam | bam//blend/blendfile_path_walker.pyclass:utils/splitpath | @staticmethod
def splitpath(path):
"""
Splits the path using either slashes
"""
split1 = path.rpartition(b'/')
split2 = path.rpartition(b'\\')
if len(split1[0]) > len(split2[0]):
return split1
else:
return split2
|
nbdev-0.2.18 | nbdev-0.2.18//nbdev/merge.pyfile:/nbdev/merge.py:function:extract_cells/extract_cells | def extract_cells(raw_txt):
"""Manually extract cells in potential broken json `raw_txt`"""
lines = raw_txt.split('\n')
cells = []
i = 0
while not lines[i].startswith(' "cells"'):
i += 1
i += 1
start = '\n'.join(lines[:i])
while lines[i] != ' ],':
while lines[i] != ' {':
i += 1
j = i
while not lines[j].startswith(' }'):
j += 1
c = '\n'.join(lines[i:j + 1])
if not c.endswith(','):
c = c + ','
cells.append(c)
i = j + 1
end = '\n'.join(lines[i:])
return start, cells, end
|
basil-0.1 | basil-0.1//basil/v0/base_template.pyclass:BaseTemplate/get_prereq_pip_packages | @staticmethod
def get_prereq_pip_packages():
"""Should return either a string path to a requirements file, or a list
of pip packages to be installed before creating the project.
Each package should either be:
* A string representing the package (with optional version).
* A os_api.PipPackage object.
"""
return []
|
stoqlib | stoqlib//lib/interfaces.pyclass:IPermissionManager/can_search | def can_search(key):
"""Returns if the user has permission to search the given feature"""
|
autobahn | autobahn//websocket/protocol.pyfile:/websocket/protocol.py:function:parseHttpHeader/parseHttpHeader | def parseHttpHeader(data):
"""
Parses the beginning of a HTTP request header (the data up to the
line) into a pair
of status line and HTTP headers dictionary.
Header keys are normalized to all-lower-case.
FOR INTERNAL USE ONLY!
:param data: The HTTP header data up to the
line.
:type data: bytes
:returns: tuple -- Tuple of HTTP status line, headers and headers count.
"""
raw = data.decode('iso-8859-1').splitlines()
http_status_line = raw[0].strip()
http_headers = {}
http_headers_cnt = {}
for h in raw[1:]:
i = h.find(':')
if i > 0:
key = h[:i].strip().lower()
value = h[i + 1:].strip()
if key in http_headers:
http_headers[key] += ', %s' % value
http_headers_cnt[key] += 1
else:
http_headers[key] = value
http_headers_cnt[key] = 1
else:
pass
return http_status_line, http_headers, http_headers_cnt
|
apitest | apitest//util.pyfile:/util.py:function:attr_from_obj/attr_from_obj | def attr_from_obj(obj, name):
"""Return the value of the attribute name.
Parameters
----------
obj: object
Object with attribute name
name: str
Attribute name to return
"""
return getattr(obj, name)
|
md_utils-0.10.0 | md_utils-0.10.0//md_utils/md_common.pyfile:/md_utils/md_common.py:function:unique_list/unique_list | def unique_list(a_list):
""" Creates an ordered list from a list of tuples or other hashable items.
From https://code.activestate.com/recipes/576694/#c6
"""
m_map = {}
o_set = []
for item in a_list:
if item not in m_map:
m_map[item] = 1
o_set.append(item)
return o_set
|
pype3 | pype3//vals.pyfile:/vals.py:function:is_bookmark/is_bookmark | def is_bookmark(fArg):
"""
This is a weird hack - I couldn't get isinstance to work on NameBookmark for some
odd reason.
"""
return 'NameBookmark' in str(fArg.__class__)
|
ibm-cos-sdk-core-2.6.2 | ibm-cos-sdk-core-2.6.2//ibm_botocore/docs/method.pyfile:/ibm_botocore/docs/method.py:function:document_model_driven_signature/document_model_driven_signature | def document_model_driven_signature(section, name, operation_model, include
=None, exclude=None):
"""Documents the signature of a model-driven method
:param section: The section to write the documentation to.
:param name: The name of the method
:param operation_model: The operation model for the method
:type include: Dictionary where keys are parameter names and
values are the shapes of the parameter names.
:param include: The parameter shapes to include in the documentation.
:type exclude: List of the names of the parameters to exclude.
:param exclude: The names of the parameters to exclude from
documentation.
"""
params = {}
if operation_model.input_shape:
params = operation_model.input_shape.members
parameter_names = list(params.keys())
if include is not None:
for member in include:
parameter_names.append(member.name)
if exclude is not None:
for member in exclude:
if member in parameter_names:
parameter_names.remove(member)
signature_params = ''
if parameter_names:
signature_params = '**kwargs'
section.style.start_sphinx_py_method(name, signature_params)
|
dns-lexicon-3.3.22 | dns-lexicon-3.3.22//lexicon/providers/aliyun.pyfile:/lexicon/providers/aliyun.py:function:provider_parser/provider_parser | def provider_parser(subparser):
"""Module provider for Aliyun"""
subparser.description = """
Aliyun Provider requires an access key id and access secret with full rights on dns.
Better to use RAM on Aliyun cloud to create a specified user for the dns operation.
The referrence for Aliyun DNS production:
https://help.aliyun.com/product/29697.html"""
subparser.add_argument('--auth-key-id', help=
'specify access key id for authentication')
subparser.add_argument('--auth-secret', help=
'specify access secret for authentication')
|
darglint-1.3.0 | darglint-1.3.0//darglint/function_description.pyfile:/darglint/function_description.py:function:get_line_number_from_function/get_line_number_from_function | def get_line_number_from_function(fn):
"""Get the line number for the end of the function signature.
The function signature can be farther down when the parameter
list is split across multiple lines.
Args:
fn: The function from which we are getting the line number.
Returns:
The line number for the start of the docstring for this
function.
"""
line_number = fn.lineno
if hasattr(fn, 'args') and fn.args.args:
last_arg = fn.args.args[-1]
line_number = last_arg.lineno
return line_number
|
pyplis | pyplis//plumebackground.pyfile:/plumebackground.py:function:_mean_in_rect/_mean_in_rect | def _mean_in_rect(img_array, rect=None):
"""Get mean and standard deviation of pixels within rectangle.
:param ndarray imgarray: the image data
:param rect: rectanglular area ``[x0, y0, x1, y1]` where x0 < x1, y0 < y1
"""
if rect is None:
sub = img_array
else:
sub = img_array[rect[1]:rect[3], rect[0]:rect[2]]
return sub.mean(), sub.std()
|
pynusmv_tools | pynusmv_tools//fairctl/explain.pyfile:/fairctl/explain.py:function:explain_ag/explain_ag | def explain_ag(fsm, state, phi):
"""
Explain why state of fsm satisfies AG phi.
fsm -- the fsm;
state -- a state of fsm satisfying AG phi;
phi -- the set of states of fsm satifying phi.
"""
pass
|
marble-1.0 | marble-1.0//marble/clustering.pyfile:/marble/clustering.py:function:_single_clustering/_single_clustering | def _single_clustering(Nu, Nc):
"""Compute clustering index
Parameters
----------
Nu: int
Number of units
Nc: int
Number of clusters
Returns
-------
clust: float
0 if units are not clustered (checkerboard)
1 if units form a single cluster
"""
clust = 1 - (Nc / Nu - 1 / Nu) / (1 - 1 / Nu)
return clust
|
keras-retinanet-0.5.1 | keras-retinanet-0.5.1//keras_retinanet/utils/model.pyfile:/keras_retinanet/utils/model.py:function:freeze/freeze | def freeze(model):
""" Set all layers in a model to non-trainable.
The weights for these layers will not be updated during training.
This function modifies the given model in-place,
but it also returns the modified model to allow easy chaining with other functions.
"""
for layer in model.layers:
layer.trainable = False
return model
|
getorg | getorg//orgmap.pyfile:/orgmap.py:function:merge_location_dict/merge_location_dict | def merge_location_dict(location_dict_list):
"""
Takes a list of location_dicts and returns a single location_dict with all the
users and locations. Automatically merges duplicates. Requires unique user ids/names.
"""
assert type(location_dict_list) is list, 'Must be passed a list of dicts'
merged_loc_dict = {}
for loc_dict in location_dict_list:
for user, loc in loc_dict.items():
merged_loc_dict[user] = loc
return merged_loc_dict
|
streamlink-1.4.1 | streamlink-1.4.1//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
|
evilmc-0.26 | evilmc-0.26//evilmc/evilmc.pyfile:/evilmc/evilmc.py:function:_calc_eclipse_time/_calc_eclipse_time | def _calc_eclipse_time(params):
"""Calculates mid-eclipse time -
I've included this function here in anticipation of using eccentric orbits
in the near future.
"""
T0 = params.T0
per = params.per
return T0 + 0.5 * per
|
buildbot | buildbot//interfaces.pyclass:IBuildRequestControl/subscribe | def subscribe(observer):
"""Register a callable that will be invoked (with a single
IBuildControl object) for each Build that is created to satisfy this
request. There may be multiple Builds created in an attempt to handle
the request: they may be interrupted by the user or abandoned due to
a lost worker. The last Build (the one which actually gets to run to
completion) is said to 'satisfy' the BuildRequest. The observer will
be called once for each of these Builds, both old and new."""
|
nbsite-0.6.7 | nbsite-0.6.7//nbsite/examples/sites/holoviews/holoviews/util/parser.pyclass:Parser/_strip_commas | @classmethod
def _strip_commas(cls, kw):
"""Strip out any leading/training commas from the token"""
kw = kw[:-1] if kw[-1] == ',' else kw
return kw[1:] if kw[0] == ',' else kw
|
expectlib-0.2.0 | expectlib-0.2.0//expectlib/comparison.pyclass:Comparison/on_init | @staticmethod
def on_init(comparison):
"""
Callback function called on initialization
:return:
"""
pass
|
Enarksh-0.9.0 | Enarksh-0.9.0//enarksh/controller/Schedule.pyclass:Schedule/queue_compare | @staticmethod
def queue_compare(node1, node2):
"""
Compares two nodes for sorting queued nodes.
:param enarksh.controller.node.Node node1:
:param enarksh.controller.node.Node node2:
:rtype: int
"""
cmp = node2.scheduling_weight - node1.scheduling_weight
if cmp == 0:
if node1.name.lower() < node2.name.lower():
cmp = -1
elif node1.name.lower() > node2.name.lower():
cmp = 1
else:
cmp = 0
return cmp
|
zc.table-0.10.0 | zc.table-0.10.0//src/zc/table/interfaces.pyclass:ISortableColumn/reversesort | def reversesort(items, formatter, start, stop, sorters):
"""Return a list of items in reverse sorted order.
Formatter is passed to aid calculation of sort parameters. Start and
stop are passed in order to provide a hint as to the range needed, if
the algorithm can optimize. Sorters are a list of zero or more
sub-sort callables with the same signature as this method, which may
be used if desired to sub-sort values with equivalent sort values
according to this column.
The original items sequence should not be mutated."""
|
keystoneclient | keystoneclient//auth/base.pyclass:BaseAuthPlugin/register_conf_options | @classmethod
def register_conf_options(cls, conf, group):
"""Register the oslo_config options that are needed for a plugin.
:param conf: A config object.
:type conf: oslo_config.cfg.ConfigOpts
:param string group: The group name that options should be read from.
"""
plugin_opts = cls.get_options()
conf.register_opts(plugin_opts, group=group)
|
Products.CMFCore-2.4.6 | Products.CMFCore-2.4.6//Products/CMFCore/interfaces/_tools.pyclass:IMembershipTool/getHomeFolder | def getHomeFolder(id=None, verifyPermission=False):
""" Return a member's home folder object or None.
o 'id', if passed, is the ID of the member whose folder should be
returned; if not passed, use the currently-authenticated member.
o If 'verifyPermission' is True, return None when the user
doesn't have the View permission on the folder.
o Permission: Public
"""
|