func_code_string stringlengths 52 1.94M | func_documentation_string stringlengths 1 47.2k |
|---|---|
def _register_hid_notification(self):
# create structure, self initialized
notify_obj = DevBroadcastDevInterface()
h_notify = RegisterDeviceNotification(self.__hid_hwnd,
ctypes.byref(notify_obj), DEVICE_NOTIFY_WINDOW_HANDLE)
#
return int(h_notify) | Register HID notification events on any window (passed by window
handler), returns a notification handler |
def _unregister_hid_notification(self):
"Remove PnP notification handler"
if not int(self.__h_notify):
return #invalid
result = UnregisterDeviceNotification(self.__h_notify)
self.__h_notify = None
return int(result) | Remove PnP notification handler |
def write_documentation(self, output_file):
"Issue documentation report on output_file file like object"
if not self.is_opened():
raise helpers.HIDError("Device has to be opened to get documentation")
#format
class CompundVarDict(object):
def __init__(self, parent):
... | Issue documentation report on output_file file like object |
def hook_wnd_proc(self):
self.__local_wnd_proc_wrapped = WndProcType(self.local_wnd_proc)
self.__old_wnd_proc = SetWindowLong(self.__local_win_handle,
GWL_WNDPROC,
self.__local_wnd_proc_wrapped) | Attach to OS Window message handler |
def unhook_wnd_proc(self):
if not self.__local_wnd_proc_wrapped:
return
SetWindowLong(self.__local_win_handle,
GWL_WNDPROC,
self.__old_wnd_proc)
## Allow the ctypes wrapper to be garbage collected
self.__local... | Restore previous Window message handler |
def local_wnd_proc(self, h_wnd, msg, w_param, l_param):
# performance note: has_key is the fastest way to check for a key when
# the key is unlikely to be found (which is the case here, since most
# messages will not have handlers). This is called via a ctypes shim
# for e... | Call the handler if one exists. |
def read_values(target_usage):
# browse all devices
all_devices = hid.HidDeviceFilter().get_devices()
if not all_devices:
print("Can't find any non system HID device connected")
else:
# search for our target usage
usage_found = False
for device in all_devi... | read feature report values |
def set_mute(mute_value):
"Browse for mute usages and set value"
all_mutes = ( \
(0x8, 0x9), # LED page
(0x1, 0xA7), # desktop page
(0xb, 0x2f),
)
all_target_usages = [hid.get_full_usage_id(u[0], u[1]) for u in all_mutes]
# usually you'll find and open the target ... | Browse for mute usages and set value |
def winapi_result( result ):
if not result:
raise WinApiException("%d (%x): %s" % (ctypes.GetLastError(),
ctypes.GetLastError(), ctypes.FormatError()))
return result | Validate WINAPI BOOL result, raise exception if failed |
def enum_device_interfaces(h_info, guid):
dev_interface_data = SP_DEVICE_INTERFACE_DATA()
dev_interface_data.cb_size = sizeof(dev_interface_data)
device_index = 0
while SetupDiEnumDeviceInterfaces(h_info,
None,
byref(guid),
device_index,
by... | Function generator that returns a device_interface_data enumerator
for the given device interface info and GUID parameters |
def get_device_path(h_info, interface_data, ptr_info_data = None):
required_size = c_ulong(0)
dev_inter_detail_data = SP_DEVICE_INTERFACE_DETAIL_DATA()
dev_inter_detail_data.cb_size = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA)
# get actual storage requirement
SetupDiGetDeviceInte... | Returns Hardware device path
Parameters:
h_info, interface set info handler
interface_data, device interface enumeration data
ptr_info_data, pointer to SP_DEVINFO_DATA() instance to receive details |
def open(self):
self.h_info = SetupDiGetClassDevs(byref(self.guid), None, None,
(DIGCF.PRESENT | DIGCF.DEVICEINTERFACE) )
return self.h_info | Calls SetupDiGetClassDevs to obtain a handle to an opaque device
information set that describes the device interfaces supported by all
the USB collections currently installed in the system. The
application should specify DIGCF.PRESENT and DIGCF.INTERFACEDEVICE
in the Flags parameter ... |
def close(self):
if self.h_info and self.h_info != INVALID_HANDLE_VALUE:
# clean up
SetupDiDestroyDeviceInfoList(self.h_info)
self.h_info = None | Destroy allocated storage |
def click_signal(target_usage, target_vendor_id):
# usually you'll find and open the target device, here we'll browse for the
# current connected devices
all_devices = hid.HidDeviceFilter(vendor_id = target_vendor_id).get_devices()
if not all_devices:
print("Can't find target device... | This function will find a particular target_usage over output reports on
target_vendor_id related devices, then it will flip the signal to simulate
a 'click' event |
def update_old_names():
url = urlparse(ZONEINFO_URL)
log.info('Connecting to %s' % url.netloc)
ftp = ftplib.FTP(url.netloc)
ftp.login()
gzfile = BytesIO()
log.info('Fetching zoneinfo database')
ftp.retrbinary('RETR ' + url.path, gzfile.write)
gzfile.seek(0)
log.info('Extracting ... | Fetches the list of old tz names and returns a mapping |
def _normalize_str(self, string):
if string:
if not isinstance(string, str):
string = str(string, 'utf-8', 'replace')
return unicodedata.normalize('NFKD', string).encode(
'ASCII', 'ignore').decode('ASCII')
return '' | Remove special characters and strip spaces |
def permission_required(perm, queryset=None,
login_url=None, raise_exception=False):
def wrapper(cls):
def view_wrapper(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def inner(self, request, *args, **kwargs):
# get obj... | Permission check decorator for classbased generic view
This decorator works as class decorator
DO NOT use ``method_decorator`` or whatever while this decorator will use
``self`` argument for method of classbased generic view.
Parameters
----------
perm : string
A permission string
... |
def get_object_from_classbased_instance(
instance, queryset, request, *args, **kwargs):
from django.views.generic.edit import BaseCreateView
# initialize request, args, kwargs of classbased_instance
# most of methods of classbased view assumed these attributes
# but these attributes is init... | Get object from an instance of classbased generic view
Parameters
----------
instance : instance
An instance of classbased generic view
queryset : instance
A queryset instance
request : instance
A instance of HttpRequest
Returns
-------
instance
An insta... |
def has_perm(self, user_obj, perm, obj=None):
if not is_authenticated(user_obj):
return False
# construct the permission full name
add_permission = self.get_full_permission_string('add')
change_permission = self.get_full_permission_string('change')
delete_per... | Check if user have permission (of object)
If the user_obj is not authenticated, it return ``False``.
If no object is specified, it return ``True`` when the corresponding
permission was specified to ``True`` (changed from v0.7.0).
This behavior is based on the django system.
htt... |
def permission_required(perm, queryset=None,
login_url=None, raise_exception=False):
def wrapper(view_method):
@wraps(view_method, assigned=available_attrs(view_method))
def inner(self, request=None, *args, **kwargs):
if isinstance(self, HttpRequest):
... | Permission check decorator for classbased/functionbased generic view
This decorator works as method or function decorator
DO NOT use ``method_decorator`` or whatever while this decorator will use
``self`` argument for method of classbased generic view.
Parameters
----------
perm : string
... |
def field_lookup(obj, field_path):
if hasattr(obj, 'iterator'):
return (field_lookup(x, field_path) for x in obj.iterator())
elif isinstance(obj, Iterable):
return (field_lookup(x, field_path) for x in iter(obj))
# split the path
field_path = field_path.split('__', 1)
if len(fie... | Lookup django model field in similar way of django query lookup.
Args:
obj (instance): Django Model instance
field_path (str): '__' separated field path
Example:
>>> from django.db import model
>>> from django.contrib.auth.models import User
>>> class Article(models.Mod... |
def permission_required(perm, queryset=None,
login_url=None, raise_exception=False):
def wrapper(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def inner(request, *args, **kwargs):
_kwargs = copy.copy(kwargs)
# overwrite querys... | Permission check decorator for function-base generic view
This decorator works as function decorator
Parameters
----------
perm : string
A permission string
queryset : queryset or model
A queryset or model for finding object.
With classbased generic view, ``None`` for using... |
def get_object_from_list_detail_view(request, *args, **kwargs):
queryset = kwargs['queryset']
object_id = kwargs.get('object_id', None)
slug = kwargs.get('slug', None)
slug_field = kwargs.get('slug_field', 'slug')
if object_id:
obj = get_object_or_404(queryset, pk=object_id)
elif sl... | Get object from generic list_detail.detail view
Parameters
----------
request : instance
An instance of HttpRequest
Returns
-------
instance
An instance of model object or None |
def get_object_from_date_based_view(request, *args, **kwargs): # noqa
import time
import datetime
from django.http import Http404
from django.db.models.fields import DateTimeField
try:
from django.utils import timezone
datetime_now = timezone.now
except ImportError:
... | Get object from generic date_based.detail view
Parameters
----------
request : instance
An instance of HttpRequest
Returns
-------
instance
An instance of model object or None |
def register(self, model, handler=None):
from permission.handlers import PermissionHandler
if model._meta.abstract:
raise ImproperlyConfigured(
'The model %s is abstract, so it cannot be registered '
'with permission.' % model)
if mode... | Register a permission handler to the model
Parameters
----------
model : django model class
A django model class
handler : permission handler class, string, or None
A permission handler class or a dotted path
Raises
------
ImproperlyConfi... |
def unregister(self, model):
if model not in self._registry:
raise KeyError("A permission handler class have not been "
"registered for '%s' yet" % model)
# remove from registry
del self._registry[model] | Unregister a permission handler from the model
Parameters
----------
model : django model class
A django model class
Raises
------
KeyError
Raise when the model have not registered in registry yet. |
def _get_app_perms(self, *args):
if not hasattr(self, '_app_perms_cache'):
self._app_perms_cache = get_app_perms(self.app_label)
return self._app_perms_cache | Get permissions related to the application specified in constructor
Returns
-------
set
A set instance of `app_label.codename` formatted permission strings |
def _get_model_perms(self, *args):
if not hasattr(self, '_model_perms_cache'):
if self.model is None:
self._model_perms_cache = set()
else:
self._model_perms_cache = get_model_perms(self.model)
return self._model_perms_cache | Get permissions related to the model specified in constructor
Returns
-------
set
A set instance of `app_label.codename` formatted permission strings |
def get_supported_permissions(self):
if not hasattr(self, '_perms_cache'):
if (self.includes and
isinstance(self.includes, collections.Callable)):
includes = self.includes(self)
else:
includes = self.includes or []
... | Get permissions which this handler can treat.
Specified with :attr:`includes` and :attr:`excludes` of this instance.
Returns
-------
set
A set instance of `app_label.codename` formatted permission strings |
def get_supported_app_labels(self):
get_app_label = lambda x: x.split(".", 1)[0]
if not hasattr(self, '_app_labels_cache'):
perms = self.get_supported_permissions()
self._app_labels_cache = set([get_app_label(x) for x in perms])
return self._app_labels_cache | Get app labels which this handler can treat.
Specified with :attr:`includes` and :attr:`excludes` of this instance.
Returns
-------
set
A set instance of app_label |
def has_module_perms(self, user_obj, app_label):
cache_name = "_has_module_perms_%s_%s_cache" % (app_label, user_obj.pk)
if hasattr(self, cache_name):
return getattr(self, cache_name)
if self.app_label != app_label:
setattr(self, cache_name, False)
else:
... | Check if user have permission of specified app
Parameters
----------
user_obj : django user model instance
A django user model instance which be checked
app_label : string
Django application name
Returns
-------
boolean
Whethe... |
def has_perm(self, user_obj, perm, obj=None):
if perm not in self.get_supported_permissions():
return False
# use cache to reduce method call
CACHE_NAME = '_logical_perms_cache'
if not hasattr(user_obj, CACHE_NAME):
setattr(user_obj, CACHE_NAME, {})
... | Check if user have permission (of object) based on
specified models's ``_permission_logics`` attribute.
The result will be stored in user_obj as a cache to reduce method call.
Parameters
----------
user_obj : django user model instance
A django user model instance w... |
def permission_required(perm, queryset_or_model=None,
login_url=None, raise_exception=False):
# convert model to queryset
if queryset_or_model and issubclass(queryset_or_model, Model):
queryset_or_model = queryset_or_model._default_manager.all()
def wrapper(class_or_meth... | Permission check decorator for classbased/functional generic view
This decorator works as class, method or function decorator without any
modification.
DO NOT use ``method_decorator`` or whatever while this decorator will use
``self`` argument for method of classbased generic view.
Parameters
... |
def get_perm_codename(perm, fail_silently=True):
try:
perm = perm.split('.', 1)[1]
except IndexError as e:
if not fail_silently:
raise e
return perm | Get permission codename from permission-string.
Examples
--------
>>> get_perm_codename('app_label.codename_model')
'codename_model'
>>> get_perm_codename('app_label.codename')
'codename'
>>> get_perm_codename('codename_model')
'codename_model'
>>> get_perm_codename('codename')
... |
def permission_to_perm(permission):
app_label = permission.content_type.app_label
codename = permission.codename
return '%s.%s' % (app_label, codename) | Convert a permission instance to a permission-string.
Examples
--------
>>> permission = Permission.objects.get(
... content_type__app_label='auth',
... codename='add_user',
... )
>>> permission_to_perm(permission)
'auth.add_user' |
def perm_to_permission(perm):
from django.contrib.auth.models import Permission
try:
app_label, codename = perm.split('.', 1)
except (ValueError, IndexError):
raise AttributeError(
'The format of identifier string permission (perm) is wrong. '
"It should be in 'a... | Convert a permission-string to a permission instance.
Examples
--------
>>> permission = perm_to_permission('auth.add_user')
>>> permission.content_type.app_label
'auth'
>>> permission.codename
'add_user' |
def get_app_perms(model_or_app_label):
from django.contrib.auth.models import Permission
if isinstance(model_or_app_label, string_types):
app_label = model_or_app_label
else:
# assume model_or_app_label is model class
app_label = model_or_app_label._meta.app_label
qs = Permi... | Get permission-string list of the specified django application.
Parameters
----------
model_or_app_label : model class or string
A model class or app_label string to specify the particular django
application.
Returns
-------
set
A set of perms of the specified django ap... |
def get_model_perms(model):
from django.contrib.auth.models import Permission
app_label = model._meta.app_label
model_name = model._meta.object_name.lower()
qs = Permission.objects.filter(content_type__app_label=app_label,
content_type__model=model_name)
perms... | Get permission-string list of a specified django model.
Parameters
----------
model : model class
A model class to specify the particular django model.
Returns
-------
set
A set of perms of the specified django model.
Examples
--------
>>> sorted(get_model_perms(Pe... |
def has_perm(self, user_obj, perm, obj=None):
if not is_authenticated(user_obj):
return False
# construct the permission full name
change_permission = self.get_full_permission_string('change')
delete_permission = self.get_full_permission_string('delete')
if o... | Check if user have permission (of object)
If the user_obj is not authenticated, it return ``False``.
If no object is specified, it return ``True`` when the corresponding
permission was specified to ``True`` (changed from v0.7.0).
This behavior is based on the django system.
htt... |
def add_permission_logic(model, permission_logic):
if not isinstance(permission_logic, PermissionLogic):
raise AttributeError(
'`permission_logic` must be an instance of PermissionLogic')
if not hasattr(model, '_permission_logics'):
model._permission_logics = set()
if not hasatt... | Add permission logic to the model
Parameters
----------
model : django model class
A django model class which will be treated by the specified permission
logic
permission_logic : permission logic instance
A permission logic instance which will be used to determine permission
... |
def remove_permission_logic(model, permission_logic, fail_silently=True):
if not hasattr(model, '_permission_logics'):
model._permission_logics = set()
if not isinstance(permission_logic, PermissionLogic):
# remove all permission logic of related
remove_set = set()
for _perm... | Remove permission logic to the model
Parameters
----------
model : django model class
A django model class which will be treated by the specified permission
logic
permission_logic : permission logic class or instance
A permission logic class or instance which will be used to det... |
def autodiscover(module_name=None):
from django.utils.module_loading import module_has_submodule
from permission.compat import import_module
from permission.conf import settings
module_name = module_name or settings.PERMISSION_AUTODISCOVER_MODULE_NAME
app_names = (app.name for app in apps.app_c... | Autodiscover INSTALLED_APPS perms.py modules and fail silently when not
present. This forces an import on them to register any permissions bits
they may want. |
def discover(app, module_name=None):
from permission.compat import import_module
from permission.compat import get_model
from permission.conf import settings
from permission.utils.logics import add_permission_logic
variable_name = settings.PERMISSION_AUTODISCOVER_VARIABLE_NAME
module_name =... | Automatically apply the permission logics written in the specified
module.
Examples
--------
Assume if you have a ``perms.py`` in ``your_app`` as::
from permission.logics import AuthorPermissionLogic
PERMISSION_LOGICS = (
('your_app.your_model', AuthorPermissionLogic),
... |
def has_perm(self, user_obj, perm, obj=None):
if not is_authenticated(user_obj):
return False
# construct the permission full name
change_permission = self.get_full_permission_string('change')
delete_permission = self.get_full_permission_string('delete')
# ch... | Check if user have permission of himself
If the user_obj is not authenticated, it return ``False``.
If no object is specified, it return ``True`` when the corresponding
permission was specified to ``True`` (changed from v0.7.0).
This behavior is based on the django system.
http... |
def get_full_permission_string(self, perm):
if not getattr(self, 'model', None):
raise AttributeError("You need to use `add_permission_logic` to "
"register the instance to the model class "
"before calling this method.")
... | Return full permission string (app_label.perm_model) |
def redirect_to_login(request, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
path = request.build_absolute_uri()
# if the login url is the same scheme and net location then just
# use the path as the "next" url.
login_scheme, login_netloc = \
urlparse(l... | redirect to login |
def has_perm(self, user_obj, perm, obj=None):
if settings.PERMISSION_CHECK_PERMISSION_PRESENCE:
# get permission instance from string permission (perm)
# it raise ObjectDoesNotExists when the permission is not exists
try:
perm_to_permission(perm)
... | Check if user have permission (of object) based on registered handlers.
It will raise ``ObjectDoesNotExist`` exception when the specified
string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
Parameters
-------... |
def has_module_perms(self, user_obj, app_label):
# get permission handlers fot this perm
cache_name = '_%s_cache' % app_label
if hasattr(self, cache_name):
handlers = getattr(self, cache_name)
else:
handlers = [h for h in registry.get_handlers()
... | Check if user have permission of specified app based on registered
handlers.
It will raise ``ObjectDoesNotExist`` exception when the specified
string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
Parameters
... |
def of_operator(context, x, y):
return x.eval(context), y.eval(context) | 'of' operator of permission if
This operator is used to specify the target object of permission |
def has_operator(context, x, y):
user = x.eval(context)
perm = y.eval(context)
if isinstance(perm, (list, tuple)):
perm, obj = perm
else:
obj = None
return user.has_perm(perm, obj) | 'has' operator of permission if
This operator is used to specify the user object of permission |
def do_permissionif(parser, token):
bits = token.split_contents()
ELIF = "el%s" % bits[0]
ELSE = "else"
ENDIF = "end%s" % bits[0]
# {% if ... %}
bits = bits[1:]
condition = do_permissionif.Parser(parser, bits).parse()
nodelist = parser.parse((ELIF, ELSE, ENDIF))
conditions_nodel... | Permission if templatetag
Examples
--------
::
{% if user has 'blogs.add_article' %}
<p>This user have 'blogs.add_article' permission</p>
{% elif user has 'blog.change_article' of object %}
<p>This user have 'blogs.change_article' permission of {{object}}</p>
... |
def get_body_from_message(message, maintype, subtype):
body = six.text_type('')
for part in message.walk():
if part.get('content-disposition', '').startswith('attachment;'):
continue
if part.get_content_maintype() == maintype and \
part.get_content_subtype() == s... | Fetchs the body message matching main/sub content type. |
def diam_circle(AreaCircle):
ut.check_range([AreaCircle, ">0", "AreaCircle"])
return np.sqrt(4 * AreaCircle / np.pi) | Return the diameter of a circle. |
def density_water(temp):
ut.check_range([temp, ">0", "Temperature in Kelvin"])
rhointerpolated = interpolate.CubicSpline(WATER_DENSITY_TABLE[0],
WATER_DENSITY_TABLE[1])
return np.asscalar(rhointerpolated(temp)) | Return the density of water at a given temperature.
If given units, the function will automatically convert to Kelvin.
If not given units, the function will assume Kelvin. |
def viscosity_kinematic(temp):
ut.check_range([temp, ">0", "Temperature in Kelvin"])
return (viscosity_dynamic(temp).magnitude
/ density_water(temp).magnitude) | Return the kinematic viscosity of water at a given temperature.
If given units, the function will automatically convert to Kelvin.
If not given units, the function will assume Kelvin. |
def re_pipe(FlowRate, Diam, Nu):
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Diam, ">0", "Diameter"],
[Nu, ">0", "Nu"])
return (4 * FlowRate) / (np.pi * Diam * Nu) | Return the Reynolds Number for a pipe. |
def radius_hydraulic(Width, DistCenter, openchannel):
ut.check_range([Width, ">0", "Width"], [DistCenter, ">0", "DistCenter"],
[openchannel, "boolean", "openchannel"])
if openchannel:
return (Width*DistCenter) / (Width + 2*DistCenter)
# if openchannel is True, the channel... | Return the hydraulic radius.
Width and DistCenter are length values and openchannel is a boolean. |
def re_rect(FlowRate, Width, DistCenter, Nu, openchannel):
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([FlowRate, ">0", "Flow rate"], [Nu, ">0", "Nu"])
return (4 * FlowRate
* radius_hydraulic(Width, DistCenter, opencha... | Return the Reynolds Number for a rectangular channel. |
def re_general(Vel, Area, PerimWetted, Nu):
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([Vel, ">=0", "Velocity"], [Nu, ">0", "Nu"])
return 4 * radius_hydraulic_general(Area, PerimWetted).magnitude * Vel / Nu | Return the Reynolds Number for a general cross section. |
def fric(FlowRate, Diam, Nu, PipeRough):
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([PipeRough, "0-1", "Pipe roughness"])
if re_pipe(FlowRate, Diam, Nu) >= RE_TRANSITION_PIPE:
#Swamee-Jain friction factor for turbulent fl... | Return the friction factor for pipe flow.
This equation applies to both laminar and turbulent flows. |
def fric_rect(FlowRate, Width, DistCenter, Nu, PipeRough, openchannel):
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([PipeRough, "0-1", "Pipe roughness"])
if re_rect(FlowRate,Width,DistCenter,Nu,openchannel) >= RE_TRANSITION_PIPE:
... | Return the friction factor for a rectangular channel. |
def fric_general(Area, PerimWetted, Vel, Nu, PipeRough):
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([PipeRough, "0-1", "Pipe roughness"])
if re_general(Vel, Area, PerimWetted, Nu) >= RE_TRANSITION_PIPE:
#Swamee-Jain frict... | Return the friction factor for a general channel. |
def headloss_fric(FlowRate, Diam, Length, Nu, PipeRough):
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([Length, ">0", "Length"])
return (fric(FlowRate, Diam, Nu, PipeRough)
* 8 / (gravity.magnitude * np.pi**2)
... | Return the major head loss (due to wall shear) in a pipe.
This equation applies to both laminar and turbulent flows. |
def headloss_exp(FlowRate, Diam, KMinor):
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Diam, ">0", "Diameter"],
[KMinor, ">=0", "K minor"])
return KMinor * 8 / (gravity.magnitude * np.pi**2) * FlowRate**2 / Diam**4 | Return the minor head loss (due to expansions) in a pipe.
This equation applies to both laminar and turbulent flows. |
def headloss(FlowRate, Diam, Length, Nu, PipeRough, KMinor):
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
return (headloss_fric(FlowRate, Diam, Length, Nu, PipeRough).magnitude
+ headloss_exp(FlowRate, Diam, KMinor).magnitude) | Return the total head loss from major and minor losses in a pipe.
This equation applies to both laminar and turbulent flows. |
def headloss_fric_rect(FlowRate, Width, DistCenter, Length, Nu, PipeRough, openchannel):
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([Length, ">0", "Length"])
return (fric_rect(FlowRate, Width, DistCenter, Nu,
... | Return the major head loss due to wall shear in a rectangular channel.
This equation applies to both laminar and turbulent flows. |
def headloss_exp_rect(FlowRate, Width, DistCenter, KMinor):
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Width, ">0", "Width"],
[DistCenter, ">0", "DistCenter"], [KMinor, ">=0", "K minor"])
return (KMinor * FlowRate**2
/ (2 * gravity.magnitude *... | Return the minor head loss due to expansion in a rectangular channel.
This equation applies to both laminar and turbulent flows. |
def headloss_rect(FlowRate, Width, DistCenter, Length,
KMinor, Nu, PipeRough, openchannel):
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
return (headloss_exp_rect(FlowRate, Width, DistCenter, KMinor).magnitude
+ headl... | Return the total head loss in a rectangular channel.
Total head loss is a combination of the major and minor losses.
This equation applies to both laminar and turbulent flows. |
def headloss_fric_general(Area, PerimWetted, Vel, Length, Nu, PipeRough):
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([Length, ">0", "Length"])
return (fric_general(Area, PerimWetted, Vel, Nu, PipeRough) * Length
/ (4 ... | Return the major head loss due to wall shear in the general case.
This equation applies to both laminar and turbulent flows. |
def headloss_exp_general(Vel, KMinor):
#Checking input validity
ut.check_range([Vel, ">0", "Velocity"], [KMinor, '>=0', 'K minor'])
return KMinor * Vel**2 / (2*gravity.magnitude) | Return the minor head loss due to expansion in the general case.
This equation applies to both laminar and turbulent flows. |
def headloss_gen(Area, Vel, PerimWetted, Length, KMinor, Nu, PipeRough):
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
return (headloss_exp_general(Vel, KMinor).magnitude
+ headloss_fric_general(Area, PerimWetted, Vel,
... | Return the total head lossin the general case.
Total head loss is a combination of major and minor losses.
This equation applies to both laminar and turbulent flows. |
def headloss_manifold(FlowRate, Diam, Length, KMinor, Nu, PipeRough, NumOutlets):
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([NumOutlets, ">0, int", 'Number of outlets'])
return (headloss(FlowRate, Diam, Length, Nu, PipeRough, KM... | Return the total head loss through the manifold. |
def flow_orifice(Diam, Height, RatioVCOrifice):
#Checking input validity
ut.check_range([Diam, ">0", "Diameter"],
[RatioVCOrifice, "0-1", "VC orifice ratio"])
if Height > 0:
return (RatioVCOrifice * area_circle(Diam).magnitude
* np.sqrt(2 * gravity.magnitude *... | Return the flow rate of the orifice. |
def flow_orifice_vert(Diam, Height, RatioVCOrifice):
#Checking input validity
ut.check_range([RatioVCOrifice, "0-1", "VC orifice ratio"])
if Height > -Diam / 2:
flow_vert = integrate.quad(lambda z: (Diam * np.sin(np.arccos(z/(Diam/2)))
* np.sqr... | Return the vertical flow rate of the orifice. |
def head_orifice(Diam, RatioVCOrifice, FlowRate):
#Checking input validity
ut.check_range([Diam, ">0", "Diameter"], [FlowRate, ">0", "Flow rate"],
[RatioVCOrifice, "0-1", "VC orifice ratio"])
return ((FlowRate
/ (RatioVCOrifice * area_circle(Diam).magnitude)
... | Return the head of the orifice. |
def area_orifice(Height, RatioVCOrifice, FlowRate):
#Checking input validity
ut.check_range([Height, ">0", "Height"], [FlowRate, ">0", "Flow rate"],
[RatioVCOrifice, "0-1, >0", "VC orifice ratio"])
return FlowRate / (RatioVCOrifice * np.sqrt(2 * gravity.magnitude * Height)) | Return the area of the orifice. |
def num_orifices(FlowPlant, RatioVCOrifice, HeadLossOrifice, DiamOrifice):
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
return np.ceil(area_orifice(HeadLossOrifice, RatioVCOrifice,
FlowPlant).magnitude
... | Return the number of orifices. |
def flow_transition(Diam, Nu):
#Checking input validity
ut.check_range([Diam, ">0", "Diameter"], [Nu, ">0", "Nu"])
return np.pi * Diam * RE_TRANSITION_PIPE * Nu / 4 | Return the flow rate for the laminar/turbulent transition.
This equation is used in some of the other equations for flow. |
def flow_hagen(Diam, HeadLossFric, Length, Nu):
#Checking input validity
ut.check_range([Diam, ">0", "Diameter"], [Length, ">0", "Length"],
[HeadLossFric, ">=0", "Headloss due to friction"],
[Nu, ">0", "Nu"])
return (np.pi*Diam**4) / (128*Nu) * gravity.magnitude * ... | Return the flow rate for laminar flow with only major losses. |
def flow_swamee(Diam, HeadLossFric, Length, Nu, PipeRough):
#Checking input validity
ut.check_range([Diam, ">0", "Diameter"], [Length, ">0", "Length"],
[HeadLossFric, ">0", "Headloss due to friction"],
[Nu, ">0", "Nu"], [PipeRough, "0-1", "Pipe roughness"])
logterm... | Return the flow rate for turbulent flow with only major losses. |
def flow_pipemajor(Diam, HeadLossFric, Length, Nu, PipeRough):
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
FlowHagen = flow_hagen(Diam, HeadLossFric, Length, Nu).magnitude
if FlowHagen < flow_transition(Diam, Nu).magnitude:
return FlowH... | Return the flow rate with only major losses.
This function applies to both laminar and turbulent flows. |
def flow_pipeminor(Diam, HeadLossExpans, KMinor):
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([HeadLossExpans, ">=0", "Headloss due to expansion"],
[KMinor, ">0", "K minor"])
return (area_circle(Diam).magnitude ... | Return the flow rate with only minor losses.
This function applies to both laminar and turbulent flows. |
def flow_pipe(Diam, HeadLoss, Length, Nu, PipeRough, KMinor):
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
if KMinor == 0:
FlowRate = flow_pipemajor(Diam, HeadLoss, Length, Nu,
PipeRough).magnitude
else:... | Return the the flow in a straight pipe.
This function works for both major and minor losses and
works whether the flow is laminar or turbulent. |
def diam_swamee(FlowRate, HeadLossFric, Length, Nu, PipeRough):
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Length, ">0", "Length"],
[HeadLossFric, ">0", "Headloss due to friction"],
[Nu, ">0", "Nu"], [PipeRough, "0-1", "Pipe roughness"])
... | Return the inner diameter of a pipe.
The Swamee Jain equation is dimensionally correct and returns the
inner diameter of a pipe given the flow rate and the head loss due
to shear on the pipe walls. The Swamee Jain equation does NOT take
minor losses into account. This equation ONLY applies to turbulent... |
def diam_pipemajor(FlowRate, HeadLossFric, Length, Nu, PipeRough):
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
DiamLaminar = diam_hagen(FlowRate, HeadLossFric, Length, Nu).magnitude
if re_pipe(FlowRate, DiamLaminar, Nu) <= RE_TRANSITION_PIPE:
... | Return the pipe IDiam that would result in given major losses.
This function applies to both laminar and turbulent flow. |
def diam_pipeminor(FlowRate, HeadLossExpans, KMinor):
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [KMinor, ">=0", "K minor"],
[HeadLossExpans, ">0", "Headloss due to expansion"])
return (np.sqrt(4 * FlowRate / np.pi)
* (KMinor / (2 * gravity.mag... | Return the pipe ID that would result in the given minor losses.
This function applies to both laminar and turbulent flow. |
def diam_pipe(FlowRate, HeadLoss, Length, Nu, PipeRough, KMinor):
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
if KMinor == 0:
Diam = diam_pipemajor(FlowRate, HeadLoss, Length, Nu,
PipeRough).magnitude
else:... | Return the pipe ID that would result in the given total head loss.
This function applies to both laminar and turbulent flow and
incorporates both minor and major losses. |
def width_rect_weir(FlowRate, Height):
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Height, ">0", "Height"])
return ((3 / 2) * FlowRate
/ (con.VC_ORIFICE_RATIO * np.sqrt(2 * gravity.magnitude) * Height ** (3 / 2))
) | Return the width of a rectangular weir. |
def headloss_weir(FlowRate, Width):
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Width, ">0", "Width"])
return (((3/2) * FlowRate
/ (con.VC_ORIFICE_RATIO * np.sqrt(2 * gravity.magnitude) * Width)
) ** (2/3)) | Return the headloss of a weir. |
def flow_rect_weir(Height, Width):
#Checking input validity
ut.check_range([Height, ">0", "Height"], [Width, ">0", "Width"])
return ((2/3) * con.VC_ORIFICE_RATIO
* (np.sqrt(2*gravity.magnitude) * Height**(3/2))
* Width) | Return the flow of a rectangular weir. |
def height_water_critical(FlowRate, Width):
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Width, ">0", "Width"])
return (FlowRate / (Width * np.sqrt(gravity.magnitude))) ** (2/3) | Return the critical local water depth. |
def vel_horizontal(HeightWaterCritical):
#Checking input validity
ut.check_range([HeightWaterCritical, ">0", "Critical height of water"])
return np.sqrt(gravity.magnitude * HeightWaterCritical) | Return the horizontal velocity. |
def headloss_kozeny(Length, Diam, Vel, Porosity, Nu):
#Checking input validity
ut.check_range([Length, ">0", "Length"], [Diam, ">0", "Diam"],
[Vel, ">0", "Velocity"], [Nu, ">0", "Nu"],
[Porosity, "0-1", "Porosity"])
return (K_KOZENY * Length * Nu
/ grav... | Return the Carmen Kozeny Sand Bed head loss. |
def vol_per_rev_3_stop(color="", inner_diameter=0):
if color != "":
inner_diameter = ID_colored_tube(color)
term1 = (R_pump * 2 * np.pi - k_nonlinear * inner_diameter) / u.rev
term2 = np.pi * (inner_diameter ** 2) / 4
return (term1 * term2).to(u.mL/u.rev) | Return the volume per revolution of an Ismatec 6 roller pump
given the inner diameter (ID) of 3-stop tubing. The calculation is
interpolated from the table found at
http://www.ismatec.com/int_e/pumps/t_mini_s_ms_ca/tubing_msca2.htm.
Note:
1. Either input a string as the tubing color code or a numbe... |
def ID_colored_tube(color):
tubing_data_path = os.path.join(os.path.dirname(__file__), "data",
"3_stop_tubing.txt")
df = pd.read_csv(tubing_data_path, delimiter='\t')
idx = df["Color"] == color
return df[idx]['Diameter (mm)'].values[0] * u.mm | Look up the inner diameter of Ismatec 3-stop tubing given its color code.
:param color: Color of the 3-stop tubing
:type color: string
:returns: Inner diameter of the 3-stop tubing (mm)
:rtype: float
:Examples:
>>> from aguaclara.research.peristaltic_pump import ID_colored_tube
>>> from ... |
def vol_per_rev_LS(id_number):
tubing_data_path = os.path.join(os.path.dirname(__file__), "data",
"LS_tubing.txt")
df = pd.read_csv(tubing_data_path, delimiter='\t')
idx = df["Number"] == id_number
return df[idx]['Flow (mL/rev)'].values[0] * u.mL/u.turn | Look up the volume per revolution output by a Masterflex L/S pump
through L/S tubing of the given ID number.
:param id_number: Identification number of the L/S tubing. Valid numbers are 13-18, 24, 35, and 36.
:type id_number: int
:return: Volume per revolution output by a Masterflex L/S pump through t... |
def flow_rate(vol_per_rev, rpm):
return (vol_per_rev * rpm).to(u.mL/u.s) | Return the flow rate from a pump given the volume of fluid pumped per
revolution and the desired pump speed.
:param vol_per_rev: Volume of fluid output per revolution (dependent on pump and tubing)
:type vol_per_rev: float
:param rpm: Desired pump speed in revolutions per minute
:type rpm: float
... |
def k_value_expansion(ent_pipe_id, exit_pipe_id, q,
fitting_angle=180, rounded=False,
nu=con.WATER_NU, pipe_rough=mats.PVC_PIPE_ROUGH):
if ent_pipe_id > exit_pipe_id:
print('k_value_expansion: Entrance pipe\'s inner diameter is larger '
'than ex... | Calculates the minor loss coefficient (k-value) of a square,
tapered, or rounded expansion in a pipe. Defaults to square.
To use tapered, set angle to something that isn't 180.
To use rounded, set rounded to True.
Parameters:
ent_pipe_id: Entrance pipe's inner diameter from which fluid flows.... |
def k_value_reduction(ent_pipe_id, exit_pipe_id, q,
fitting_angle=180, rounded=False,
nu=con.WATER_NU, pipe_rough=mats.PVC_PIPE_ROUGH):
if ent_pipe_id < exit_pipe_id:
print('k_value_reduction: Entrance pipe\'s inner diameter is less than '
'exit... | Calculates the minor loss coefficient (k-value) of a square,
tapered, or rounded reduction in a pipe. Defaults to square.
To use tapered, set angle to something that isn't 180.
To use rounded, set rounded to True.
Parameters:
ent_pipe_id: Entrance pipe's inner diameter from which fluid flows.... |
def k_value_orifice(pipe_id, orifice_id, orifice_l, q,
nu=con.WATER_NU):
if orifice_id > pipe_id:
raise ValueError('The orifice\'s inner diameter cannot be larger than'
'that of the entrance pipe.')
re = pc.re_pipe(q, pipe_id, nu) # Entrance pipe's Reyn... | Calculates the minor loss coefficient of an orifice plate in a
pipe.
Parameters:
pipe_id: Entrance pipe's inner diameter from which fluid flows.
orifice_id: Orifice's inner diameter.
orifice_l: Orifice's length from start to end.
q: Fluid's q rate.
nu: Fluid's dynamic v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.