id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 51
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
1,400 | rene-aguirre/pywinusb | pywinusb/hid/core.py | ReportItem.set_value | def set_value(self, value):
"""Set usage value within report"""
if self.__is_value_array:
if len(value) == self.__report_count:
for index, item in enumerate(value):
self.__setitem__(index, item)
else:
raise ValueError("Value size should match report item size "\
"length" )
else:
self.__value = value & ((1 << self.__bit_size) - 1) | python | def set_value(self, value):
if self.__is_value_array:
if len(value) == self.__report_count:
for index, item in enumerate(value):
self.__setitem__(index, item)
else:
raise ValueError("Value size should match report item size "\
"length" )
else:
self.__value = value & ((1 << self.__bit_size) - 1) | [
"def",
"set_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"__is_value_array",
":",
"if",
"len",
"(",
"value",
")",
"==",
"self",
".",
"__report_count",
":",
"for",
"index",
",",
"item",
"in",
"enumerate",
"(",
"value",
")",
":",
"self",
".",
"__setitem__",
"(",
"index",
",",
"item",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Value size should match report item size \"",
"\"length\"",
")",
"else",
":",
"self",
".",
"__value",
"=",
"value",
"&",
"(",
"(",
"1",
"<<",
"self",
".",
"__bit_size",
")",
"-",
"1",
")"
] | Set usage value within report | [
"Set",
"usage",
"value",
"within",
"report"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1094-L1104 |
1,401 | rene-aguirre/pywinusb | pywinusb/hid/core.py | ReportItem.get_value | def get_value(self):
"""Retreive usage value within report"""
if self.__is_value_array:
if self.__bit_size == 8: #matching c_ubyte
return list(self.__value)
else:
result = []
for i in range(self.__report_count):
result.append(self.__getitem__(i))
return result
else:
return self.__value | python | def get_value(self):
if self.__is_value_array:
if self.__bit_size == 8: #matching c_ubyte
return list(self.__value)
else:
result = []
for i in range(self.__report_count):
result.append(self.__getitem__(i))
return result
else:
return self.__value | [
"def",
"get_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"__is_value_array",
":",
"if",
"self",
".",
"__bit_size",
"==",
"8",
":",
"#matching c_ubyte\r",
"return",
"list",
"(",
"self",
".",
"__value",
")",
"else",
":",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"__report_count",
")",
":",
"result",
".",
"append",
"(",
"self",
".",
"__getitem__",
"(",
"i",
")",
")",
"return",
"result",
"else",
":",
"return",
"self",
".",
"__value"
] | Retreive usage value within report | [
"Retreive",
"usage",
"value",
"within",
"report"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1106-L1117 |
1,402 | rene-aguirre/pywinusb | pywinusb/hid/core.py | HidReport.get_usages | def get_usages(self):
"Return a dictionary mapping full usages Ids to plain values"
result = dict()
for key, usage in self.items():
result[key] = usage.value
return result | python | def get_usages(self):
"Return a dictionary mapping full usages Ids to plain values"
result = dict()
for key, usage in self.items():
result[key] = usage.value
return result | [
"def",
"get_usages",
"(",
"self",
")",
":",
"result",
"=",
"dict",
"(",
")",
"for",
"key",
",",
"usage",
"in",
"self",
".",
"items",
"(",
")",
":",
"result",
"[",
"key",
"]",
"=",
"usage",
".",
"value",
"return",
"result"
] | Return a dictionary mapping full usages Ids to plain values | [
"Return",
"a",
"dictionary",
"mapping",
"full",
"usages",
"Ids",
"to",
"plain",
"values"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1295-L1300 |
1,403 | rene-aguirre/pywinusb | pywinusb/hid/core.py | HidReport.__alloc_raw_data | def __alloc_raw_data(self, initial_values=None):
"""Pre-allocate re-usagle memory"""
#allocate c_ubyte storage
if self.__raw_data == None: #first time only, create storage
raw_data_type = c_ubyte * self.__raw_report_size
self.__raw_data = raw_data_type()
elif initial_values == self.__raw_data:
# already
return
else:
#initialize
ctypes.memset(self.__raw_data, 0, len(self.__raw_data))
if initial_values:
for index in range(len(initial_values)):
self.__raw_data[index] = initial_values[index] | python | def __alloc_raw_data(self, initial_values=None):
#allocate c_ubyte storage
if self.__raw_data == None: #first time only, create storage
raw_data_type = c_ubyte * self.__raw_report_size
self.__raw_data = raw_data_type()
elif initial_values == self.__raw_data:
# already
return
else:
#initialize
ctypes.memset(self.__raw_data, 0, len(self.__raw_data))
if initial_values:
for index in range(len(initial_values)):
self.__raw_data[index] = initial_values[index] | [
"def",
"__alloc_raw_data",
"(",
"self",
",",
"initial_values",
"=",
"None",
")",
":",
"#allocate c_ubyte storage\r",
"if",
"self",
".",
"__raw_data",
"==",
"None",
":",
"#first time only, create storage\r",
"raw_data_type",
"=",
"c_ubyte",
"*",
"self",
".",
"__raw_report_size",
"self",
".",
"__raw_data",
"=",
"raw_data_type",
"(",
")",
"elif",
"initial_values",
"==",
"self",
".",
"__raw_data",
":",
"# already\r",
"return",
"else",
":",
"#initialize\r",
"ctypes",
".",
"memset",
"(",
"self",
".",
"__raw_data",
",",
"0",
",",
"len",
"(",
"self",
".",
"__raw_data",
")",
")",
"if",
"initial_values",
":",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"initial_values",
")",
")",
":",
"self",
".",
"__raw_data",
"[",
"index",
"]",
"=",
"initial_values",
"[",
"index",
"]"
] | Pre-allocate re-usagle memory | [
"Pre",
"-",
"allocate",
"re",
"-",
"usagle",
"memory"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1302-L1316 |
1,404 | rene-aguirre/pywinusb | pywinusb/hid/core.py | HidReport.get_raw_data | def get_raw_data(self):
"""Get raw HID report based on internal report item settings,
creates new c_ubytes storage
"""
if self.__report_kind != HidP_Output \
and self.__report_kind != HidP_Feature:
raise HIDError("Only for output or feature reports")
self.__prepare_raw_data()
#return read-only object for internal storage
return helpers.ReadOnlyList(self.__raw_data) | python | def get_raw_data(self):
if self.__report_kind != HidP_Output \
and self.__report_kind != HidP_Feature:
raise HIDError("Only for output or feature reports")
self.__prepare_raw_data()
#return read-only object for internal storage
return helpers.ReadOnlyList(self.__raw_data) | [
"def",
"get_raw_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"__report_kind",
"!=",
"HidP_Output",
"and",
"self",
".",
"__report_kind",
"!=",
"HidP_Feature",
":",
"raise",
"HIDError",
"(",
"\"Only for output or feature reports\"",
")",
"self",
".",
"__prepare_raw_data",
"(",
")",
"#return read-only object for internal storage\r",
"return",
"helpers",
".",
"ReadOnlyList",
"(",
"self",
".",
"__raw_data",
")"
] | Get raw HID report based on internal report item settings,
creates new c_ubytes storage | [
"Get",
"raw",
"HID",
"report",
"based",
"on",
"internal",
"report",
"item",
"settings",
"creates",
"new",
"c_ubytes",
"storage"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1454-L1463 |
1,405 | rene-aguirre/pywinusb | pywinusb/hid/core.py | HidReport.get | def get(self, do_process_raw_report = True):
"Read report from device"
assert(self.__hid_object.is_opened())
if self.__report_kind != HidP_Input and \
self.__report_kind != HidP_Feature:
raise HIDError("Only for input or feature reports")
# pre-alloc raw data
self.__alloc_raw_data()
# now use it
raw_data = self.__raw_data
raw_data[0] = self.__report_id
read_function = None
if self.__report_kind == HidP_Feature:
read_function = hid_dll.HidD_GetFeature
elif self.__report_kind == HidP_Input:
read_function = hid_dll.HidD_GetInputReport
if read_function and read_function(int(self.__hid_object.hid_handle),
byref(raw_data), len(raw_data)):
#success
if do_process_raw_report:
self.set_raw_data(raw_data)
self.__hid_object._process_raw_report(raw_data)
return helpers.ReadOnlyList(raw_data)
return helpers.ReadOnlyList([]) | python | def get(self, do_process_raw_report = True):
"Read report from device"
assert(self.__hid_object.is_opened())
if self.__report_kind != HidP_Input and \
self.__report_kind != HidP_Feature:
raise HIDError("Only for input or feature reports")
# pre-alloc raw data
self.__alloc_raw_data()
# now use it
raw_data = self.__raw_data
raw_data[0] = self.__report_id
read_function = None
if self.__report_kind == HidP_Feature:
read_function = hid_dll.HidD_GetFeature
elif self.__report_kind == HidP_Input:
read_function = hid_dll.HidD_GetInputReport
if read_function and read_function(int(self.__hid_object.hid_handle),
byref(raw_data), len(raw_data)):
#success
if do_process_raw_report:
self.set_raw_data(raw_data)
self.__hid_object._process_raw_report(raw_data)
return helpers.ReadOnlyList(raw_data)
return helpers.ReadOnlyList([]) | [
"def",
"get",
"(",
"self",
",",
"do_process_raw_report",
"=",
"True",
")",
":",
"assert",
"(",
"self",
".",
"__hid_object",
".",
"is_opened",
"(",
")",
")",
"if",
"self",
".",
"__report_kind",
"!=",
"HidP_Input",
"and",
"self",
".",
"__report_kind",
"!=",
"HidP_Feature",
":",
"raise",
"HIDError",
"(",
"\"Only for input or feature reports\"",
")",
"# pre-alloc raw data\r",
"self",
".",
"__alloc_raw_data",
"(",
")",
"# now use it\r",
"raw_data",
"=",
"self",
".",
"__raw_data",
"raw_data",
"[",
"0",
"]",
"=",
"self",
".",
"__report_id",
"read_function",
"=",
"None",
"if",
"self",
".",
"__report_kind",
"==",
"HidP_Feature",
":",
"read_function",
"=",
"hid_dll",
".",
"HidD_GetFeature",
"elif",
"self",
".",
"__report_kind",
"==",
"HidP_Input",
":",
"read_function",
"=",
"hid_dll",
".",
"HidD_GetInputReport",
"if",
"read_function",
"and",
"read_function",
"(",
"int",
"(",
"self",
".",
"__hid_object",
".",
"hid_handle",
")",
",",
"byref",
"(",
"raw_data",
")",
",",
"len",
"(",
"raw_data",
")",
")",
":",
"#success\r",
"if",
"do_process_raw_report",
":",
"self",
".",
"set_raw_data",
"(",
"raw_data",
")",
"self",
".",
"__hid_object",
".",
"_process_raw_report",
"(",
"raw_data",
")",
"return",
"helpers",
".",
"ReadOnlyList",
"(",
"raw_data",
")",
"return",
"helpers",
".",
"ReadOnlyList",
"(",
"[",
"]",
")"
] | Read report from device | [
"Read",
"report",
"from",
"device"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1501-L1525 |
1,406 | rene-aguirre/pywinusb | pywinusb/hid/helpers.py | logging_decorator | def logging_decorator(func):
"""Allow logging function calls"""
def you_will_never_see_this_name(*args, **kwargs):
"""Neither this docstring"""
print('calling %s ...' % func.__name__)
result = func(*args, **kwargs)
print('completed: %s' % func.__name__)
return result
return you_will_never_see_this_name | python | def logging_decorator(func):
def you_will_never_see_this_name(*args, **kwargs):
"""Neither this docstring"""
print('calling %s ...' % func.__name__)
result = func(*args, **kwargs)
print('completed: %s' % func.__name__)
return result
return you_will_never_see_this_name | [
"def",
"logging_decorator",
"(",
"func",
")",
":",
"def",
"you_will_never_see_this_name",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Neither this docstring\"\"\"",
"print",
"(",
"'calling %s ...'",
"%",
"func",
".",
"__name__",
")",
"result",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"print",
"(",
"'completed: %s'",
"%",
"func",
".",
"__name__",
")",
"return",
"result",
"return",
"you_will_never_see_this_name"
] | Allow logging function calls | [
"Allow",
"logging",
"function",
"calls"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/helpers.py#L46-L54 |
1,407 | rene-aguirre/pywinusb | pywinusb/hid/helpers.py | synchronized | def synchronized(lock):
""" Synchronization decorator.
Allos to set a mutex on any function
"""
@simple_decorator
def wrap(function_target):
"""Decorator wrapper"""
def new_function(*args, **kw):
"""Decorated function with Mutex"""
lock.acquire()
try:
return function_target(*args, **kw)
finally:
lock.release()
return new_function
return wrap | python | def synchronized(lock):
@simple_decorator
def wrap(function_target):
"""Decorator wrapper"""
def new_function(*args, **kw):
"""Decorated function with Mutex"""
lock.acquire()
try:
return function_target(*args, **kw)
finally:
lock.release()
return new_function
return wrap | [
"def",
"synchronized",
"(",
"lock",
")",
":",
"@",
"simple_decorator",
"def",
"wrap",
"(",
"function_target",
")",
":",
"\"\"\"Decorator wrapper\"\"\"",
"def",
"new_function",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"\"\"\"Decorated function with Mutex\"\"\"",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"return",
"function_target",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"finally",
":",
"lock",
".",
"release",
"(",
")",
"return",
"new_function",
"return",
"wrap"
] | Synchronization decorator.
Allos to set a mutex on any function | [
"Synchronization",
"decorator",
".",
"Allos",
"to",
"set",
"a",
"mutex",
"on",
"any",
"function"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/helpers.py#L56-L71 |
1,408 | rene-aguirre/pywinusb | pywinusb/hid/hid_pnp_mixin.py | HidPnPWindowMixin._on_hid_pnp | def _on_hid_pnp(self, w_param, l_param):
"Process WM_DEVICECHANGE system messages"
new_status = "unknown"
if w_param == DBT_DEVICEARRIVAL:
# hid device attached
notify_obj = None
if int(l_param):
# Disable this error since pylint doesn't reconize
# that from_address actually exists
# pylint: disable=no-member
notify_obj = DevBroadcastDevInterface.from_address(l_param)
#confirm if the right message received
if notify_obj and \
notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE:
#only connect if already disconnected
new_status = "connected"
elif w_param == DBT_DEVICEREMOVECOMPLETE:
# hid device removed
notify_obj = None
if int(l_param):
# Disable this error since pylint doesn't reconize
# that from_address actually exists
# pylint: disable=no-member
notify_obj = DevBroadcastDevInterface.from_address(l_param)
if notify_obj and \
notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE:
#only connect if already disconnected
new_status = "disconnected"
#verify if need to call event handler
if new_status != "unknown" and new_status != self.current_status:
self.current_status = new_status
self.on_hid_pnp(self.current_status)
#
return True | python | def _on_hid_pnp(self, w_param, l_param):
"Process WM_DEVICECHANGE system messages"
new_status = "unknown"
if w_param == DBT_DEVICEARRIVAL:
# hid device attached
notify_obj = None
if int(l_param):
# Disable this error since pylint doesn't reconize
# that from_address actually exists
# pylint: disable=no-member
notify_obj = DevBroadcastDevInterface.from_address(l_param)
#confirm if the right message received
if notify_obj and \
notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE:
#only connect if already disconnected
new_status = "connected"
elif w_param == DBT_DEVICEREMOVECOMPLETE:
# hid device removed
notify_obj = None
if int(l_param):
# Disable this error since pylint doesn't reconize
# that from_address actually exists
# pylint: disable=no-member
notify_obj = DevBroadcastDevInterface.from_address(l_param)
if notify_obj and \
notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE:
#only connect if already disconnected
new_status = "disconnected"
#verify if need to call event handler
if new_status != "unknown" and new_status != self.current_status:
self.current_status = new_status
self.on_hid_pnp(self.current_status)
#
return True | [
"def",
"_on_hid_pnp",
"(",
"self",
",",
"w_param",
",",
"l_param",
")",
":",
"new_status",
"=",
"\"unknown\"",
"if",
"w_param",
"==",
"DBT_DEVICEARRIVAL",
":",
"# hid device attached\r",
"notify_obj",
"=",
"None",
"if",
"int",
"(",
"l_param",
")",
":",
"# Disable this error since pylint doesn't reconize\r",
"# that from_address actually exists\r",
"# pylint: disable=no-member\r",
"notify_obj",
"=",
"DevBroadcastDevInterface",
".",
"from_address",
"(",
"l_param",
")",
"#confirm if the right message received\r",
"if",
"notify_obj",
"and",
"notify_obj",
".",
"dbcc_devicetype",
"==",
"DBT_DEVTYP_DEVICEINTERFACE",
":",
"#only connect if already disconnected\r",
"new_status",
"=",
"\"connected\"",
"elif",
"w_param",
"==",
"DBT_DEVICEREMOVECOMPLETE",
":",
"# hid device removed\r",
"notify_obj",
"=",
"None",
"if",
"int",
"(",
"l_param",
")",
":",
"# Disable this error since pylint doesn't reconize\r",
"# that from_address actually exists\r",
"# pylint: disable=no-member\r",
"notify_obj",
"=",
"DevBroadcastDevInterface",
".",
"from_address",
"(",
"l_param",
")",
"if",
"notify_obj",
"and",
"notify_obj",
".",
"dbcc_devicetype",
"==",
"DBT_DEVTYP_DEVICEINTERFACE",
":",
"#only connect if already disconnected\r",
"new_status",
"=",
"\"disconnected\"",
"#verify if need to call event handler\r",
"if",
"new_status",
"!=",
"\"unknown\"",
"and",
"new_status",
"!=",
"self",
".",
"current_status",
":",
"self",
".",
"current_status",
"=",
"new_status",
"self",
".",
"on_hid_pnp",
"(",
"self",
".",
"current_status",
")",
"#\r",
"return",
"True"
] | Process WM_DEVICECHANGE system messages | [
"Process",
"WM_DEVICECHANGE",
"system",
"messages"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/hid_pnp_mixin.py#L96-L130 |
1,409 | rene-aguirre/pywinusb | pywinusb/hid/hid_pnp_mixin.py | HidPnPWindowMixin._unregister_hid_notification | 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) | python | 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) | [
"def",
"_unregister_hid_notification",
"(",
"self",
")",
":",
"if",
"not",
"int",
"(",
"self",
".",
"__h_notify",
")",
":",
"return",
"#invalid\r",
"result",
"=",
"UnregisterDeviceNotification",
"(",
"self",
".",
"__h_notify",
")",
"self",
".",
"__h_notify",
"=",
"None",
"return",
"int",
"(",
"result",
")"
] | Remove PnP notification handler | [
"Remove",
"PnP",
"notification",
"handler"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/hid_pnp_mixin.py#L142-L148 |
1,410 | rene-aguirre/pywinusb | pywinusb/hid/wnd_hook_mixin.py | WndProcHookMixin.hook_wnd_proc | def hook_wnd_proc(self):
"""Attach to OS Window message handler"""
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) | python | 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) | [
"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 | [
"Attach",
"to",
"OS",
"Window",
"message",
"handler"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/wnd_hook_mixin.py#L73-L78 |
1,411 | rene-aguirre/pywinusb | pywinusb/hid/wnd_hook_mixin.py | WndProcHookMixin.unhook_wnd_proc | def unhook_wnd_proc(self):
"""Restore previous Window message handler"""
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_wnd_proc_wrapped = None | python | 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_wnd_proc_wrapped = None | [
"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\r",
"self",
".",
"__local_wnd_proc_wrapped",
"=",
"None"
] | Restore previous Window message handler | [
"Restore",
"previous",
"Window",
"message",
"handler"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/wnd_hook_mixin.py#L79-L88 |
1,412 | rene-aguirre/pywinusb | pywinusb/hid/wnd_hook_mixin.py | WndProcHookMixin.local_wnd_proc | def local_wnd_proc(self, h_wnd, msg, w_param, l_param):
"""
Call the handler if one exists.
"""
# 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 every single windows message so dispatch speed is important
if msg in self.__msg_dict:
# if the handler returns false, we terminate the message here Note
# that we don't pass the hwnd or the message along Handlers should
# be really, really careful about returning false here
if self.__msg_dict[msg](w_param, l_param) == False:
return
# Restore the old WndProc on Destroy.
if msg == WM_DESTROY:
self.unhook_wnd_proc()
return CallWindowProc(self.__old_wnd_proc,
h_wnd, msg, w_param, l_param) | python | 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 every single windows message so dispatch speed is important
if msg in self.__msg_dict:
# if the handler returns false, we terminate the message here Note
# that we don't pass the hwnd or the message along Handlers should
# be really, really careful about returning false here
if self.__msg_dict[msg](w_param, l_param) == False:
return
# Restore the old WndProc on Destroy.
if msg == WM_DESTROY:
self.unhook_wnd_proc()
return CallWindowProc(self.__old_wnd_proc,
h_wnd, msg, w_param, l_param) | [
"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\r",
"# the key is unlikely to be found (which is the case here, since most\r",
"# messages will not have handlers). This is called via a ctypes shim\r",
"# for every single windows message so dispatch speed is important\r",
"if",
"msg",
"in",
"self",
".",
"__msg_dict",
":",
"# if the handler returns false, we terminate the message here Note\r",
"# that we don't pass the hwnd or the message along Handlers should\r",
"# be really, really careful about returning false here\r",
"if",
"self",
".",
"__msg_dict",
"[",
"msg",
"]",
"(",
"w_param",
",",
"l_param",
")",
"==",
"False",
":",
"return",
"# Restore the old WndProc on Destroy.\r",
"if",
"msg",
"==",
"WM_DESTROY",
":",
"self",
".",
"unhook_wnd_proc",
"(",
")",
"return",
"CallWindowProc",
"(",
"self",
".",
"__old_wnd_proc",
",",
"h_wnd",
",",
"msg",
",",
"w_param",
",",
"l_param",
")"
] | Call the handler if one exists. | [
"Call",
"the",
"handler",
"if",
"one",
"exists",
"."
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/wnd_hook_mixin.py#L94-L114 |
1,413 | rene-aguirre/pywinusb | examples/simple_feature.py | read_values | def read_values(target_usage):
"""read feature report values"""
# 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_devices:
try:
device.open()
# browse feature reports
for report in device.find_feature_reports():
if target_usage in report:
# we found our usage
report.get()
# print result
print("The value:", list(report[target_usage]))
print("All the report: {0}".format(report.get_raw_data()))
usage_found = True
finally:
device.close()
if not usage_found:
print("The target device was found, but the requested usage does not exist!\n") | python | 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_devices:
try:
device.open()
# browse feature reports
for report in device.find_feature_reports():
if target_usage in report:
# we found our usage
report.get()
# print result
print("The value:", list(report[target_usage]))
print("All the report: {0}".format(report.get_raw_data()))
usage_found = True
finally:
device.close()
if not usage_found:
print("The target device was found, but the requested usage does not exist!\n") | [
"def",
"read_values",
"(",
"target_usage",
")",
":",
"# browse all devices\r",
"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\r",
"usage_found",
"=",
"False",
"for",
"device",
"in",
"all_devices",
":",
"try",
":",
"device",
".",
"open",
"(",
")",
"# browse feature reports\r",
"for",
"report",
"in",
"device",
".",
"find_feature_reports",
"(",
")",
":",
"if",
"target_usage",
"in",
"report",
":",
"# we found our usage\r",
"report",
".",
"get",
"(",
")",
"# print result\r",
"print",
"(",
"\"The value:\"",
",",
"list",
"(",
"report",
"[",
"target_usage",
"]",
")",
")",
"print",
"(",
"\"All the report: {0}\"",
".",
"format",
"(",
"report",
".",
"get_raw_data",
"(",
")",
")",
")",
"usage_found",
"=",
"True",
"finally",
":",
"device",
".",
"close",
"(",
")",
"if",
"not",
"usage_found",
":",
"print",
"(",
"\"The target device was found, but the requested usage does not exist!\\n\"",
")"
] | read feature report values | [
"read",
"feature",
"report",
"values"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/examples/simple_feature.py#L9-L34 |
1,414 | rene-aguirre/pywinusb | pywinusb/hid/winapi.py | winapi_result | def winapi_result( result ):
"""Validate WINAPI BOOL result, raise exception if failed"""
if not result:
raise WinApiException("%d (%x): %s" % (ctypes.GetLastError(),
ctypes.GetLastError(), ctypes.FormatError()))
return result | python | def winapi_result( result ):
if not result:
raise WinApiException("%d (%x): %s" % (ctypes.GetLastError(),
ctypes.GetLastError(), ctypes.FormatError()))
return result | [
"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 | [
"Validate",
"WINAPI",
"BOOL",
"result",
"raise",
"exception",
"if",
"failed"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/winapi.py#L28-L33 |
1,415 | rene-aguirre/pywinusb | pywinusb/hid/winapi.py | enum_device_interfaces | def enum_device_interfaces(h_info, guid):
"""Function generator that returns a device_interface_data enumerator
for the given device interface info and GUID parameters
"""
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,
byref(dev_interface_data) ):
yield dev_interface_data
device_index += 1
del dev_interface_data | python | 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,
byref(dev_interface_data) ):
yield dev_interface_data
device_index += 1
del dev_interface_data | [
"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",
",",
"byref",
"(",
"dev_interface_data",
")",
")",
":",
"yield",
"dev_interface_data",
"device_index",
"+=",
"1",
"del",
"dev_interface_data"
] | Function generator that returns a device_interface_data enumerator
for the given device interface info and GUID parameters | [
"Function",
"generator",
"that",
"returns",
"a",
"device_interface_data",
"enumerator",
"for",
"the",
"given",
"device",
"interface",
"info",
"and",
"GUID",
"parameters"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/winapi.py#L467-L482 |
1,416 | rene-aguirre/pywinusb | pywinusb/hid/winapi.py | DeviceInterfaceSetInfo.open | def open(self):
"""
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 passed to SetupDiGetClassDevs.
"""
self.h_info = SetupDiGetClassDevs(byref(self.guid), None, None,
(DIGCF.PRESENT | DIGCF.DEVICEINTERFACE) )
return self.h_info | python | def open(self):
self.h_info = SetupDiGetClassDevs(byref(self.guid), None, None,
(DIGCF.PRESENT | DIGCF.DEVICEINTERFACE) )
return self.h_info | [
"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 passed to SetupDiGetClassDevs. | [
"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",
"passed",
"to",
"SetupDiGetClassDevs",
"."
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/winapi.py#L443-L454 |
1,417 | rene-aguirre/pywinusb | pywinusb/hid/winapi.py | DeviceInterfaceSetInfo.close | def close(self):
"""Destroy allocated storage"""
if self.h_info and self.h_info != INVALID_HANDLE_VALUE:
# clean up
SetupDiDestroyDeviceInfoList(self.h_info)
self.h_info = None | python | def close(self):
if self.h_info and self.h_info != INVALID_HANDLE_VALUE:
# clean up
SetupDiDestroyDeviceInfoList(self.h_info)
self.h_info = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"h_info",
"and",
"self",
".",
"h_info",
"!=",
"INVALID_HANDLE_VALUE",
":",
"# clean up\r",
"SetupDiDestroyDeviceInfoList",
"(",
"self",
".",
"h_info",
")",
"self",
".",
"h_info",
"=",
"None"
] | Destroy allocated storage | [
"Destroy",
"allocated",
"storage"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/winapi.py#L460-L465 |
1,418 | rene-aguirre/pywinusb | examples/simple_send.py | click_signal | def click_signal(target_usage, target_vendor_id):
"""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"""
# 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 (vendor_id = 0x%04x)!" % target_vendor_id)
else:
# search for our target usage
# target pageId, usageId
for device in all_devices:
try:
device.open()
# browse output reports, we could search over feature reports also,
# changing find_output_reports() to find_feature_reports()
for report in device.find_output_reports():
if target_usage in report:
# found out target!
report[target_usage] = 1 # yes, changing values is that easy
# at this point you could change different usages at a time...
# and finally send the prepared output report
report.send()
# now toggle back the signal
report[target_usage] = 0
report.send()
print("\nUsage clicked!\n")
return
finally:
device.close()
print("The target device was found, but the requested usage does not exist!\n") | python | 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 (vendor_id = 0x%04x)!" % target_vendor_id)
else:
# search for our target usage
# target pageId, usageId
for device in all_devices:
try:
device.open()
# browse output reports, we could search over feature reports also,
# changing find_output_reports() to find_feature_reports()
for report in device.find_output_reports():
if target_usage in report:
# found out target!
report[target_usage] = 1 # yes, changing values is that easy
# at this point you could change different usages at a time...
# and finally send the prepared output report
report.send()
# now toggle back the signal
report[target_usage] = 0
report.send()
print("\nUsage clicked!\n")
return
finally:
device.close()
print("The target device was found, but the requested usage does not exist!\n") | [
"def",
"click_signal",
"(",
"target_usage",
",",
"target_vendor_id",
")",
":",
"# usually you'll find and open the target device, here we'll browse for the\r",
"# current connected devices\r",
"all_devices",
"=",
"hid",
".",
"HidDeviceFilter",
"(",
"vendor_id",
"=",
"target_vendor_id",
")",
".",
"get_devices",
"(",
")",
"if",
"not",
"all_devices",
":",
"print",
"(",
"\"Can't find target device (vendor_id = 0x%04x)!\"",
"%",
"target_vendor_id",
")",
"else",
":",
"# search for our target usage\r",
"# target pageId, usageId\r",
"for",
"device",
"in",
"all_devices",
":",
"try",
":",
"device",
".",
"open",
"(",
")",
"# browse output reports, we could search over feature reports also,\r",
"# changing find_output_reports() to find_feature_reports()\r",
"for",
"report",
"in",
"device",
".",
"find_output_reports",
"(",
")",
":",
"if",
"target_usage",
"in",
"report",
":",
"# found out target!\r",
"report",
"[",
"target_usage",
"]",
"=",
"1",
"# yes, changing values is that easy\r",
"# at this point you could change different usages at a time...\r",
"# and finally send the prepared output report\r",
"report",
".",
"send",
"(",
")",
"# now toggle back the signal\r",
"report",
"[",
"target_usage",
"]",
"=",
"0",
"report",
".",
"send",
"(",
")",
"print",
"(",
"\"\\nUsage clicked!\\n\"",
")",
"return",
"finally",
":",
"device",
".",
"close",
"(",
")",
"print",
"(",
"\"The target device was found, but the requested usage does not exist!\\n\"",
")"
] | 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 | [
"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"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/examples/simple_send.py#L7-L40 |
1,419 | regebro/tzlocal | update_windows_mappings.py | update_old_names | def update_old_names():
"""Fetches the list of old tz names and returns a mapping"""
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 backwards data')
archive = tarfile.open(mode="r:gz", fileobj=gzfile)
backward = {}
for line in archive.extractfile('backward').readlines():
if line[0] == '#':
continue
if len(line.strip()) == 0:
continue
parts = line.split()
if parts[0] != b'Link':
continue
backward[parts[2].decode('ascii')] = parts[1].decode('ascii')
return backward | python | 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 backwards data')
archive = tarfile.open(mode="r:gz", fileobj=gzfile)
backward = {}
for line in archive.extractfile('backward').readlines():
if line[0] == '#':
continue
if len(line.strip()) == 0:
continue
parts = line.split()
if parts[0] != b'Link':
continue
backward[parts[2].decode('ascii')] = parts[1].decode('ascii')
return backward | [
"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 backwards data'",
")",
"archive",
"=",
"tarfile",
".",
"open",
"(",
"mode",
"=",
"\"r:gz\"",
",",
"fileobj",
"=",
"gzfile",
")",
"backward",
"=",
"{",
"}",
"for",
"line",
"in",
"archive",
".",
"extractfile",
"(",
"'backward'",
")",
".",
"readlines",
"(",
")",
":",
"if",
"line",
"[",
"0",
"]",
"==",
"'#'",
":",
"continue",
"if",
"len",
"(",
"line",
".",
"strip",
"(",
")",
")",
"==",
"0",
":",
"continue",
"parts",
"=",
"line",
".",
"split",
"(",
")",
"if",
"parts",
"[",
"0",
"]",
"!=",
"b'Link'",
":",
"continue",
"backward",
"[",
"parts",
"[",
"2",
"]",
".",
"decode",
"(",
"'ascii'",
")",
"]",
"=",
"parts",
"[",
"1",
"]",
".",
"decode",
"(",
"'ascii'",
")",
"return",
"backward"
] | Fetches the list of old tz names and returns a mapping | [
"Fetches",
"the",
"list",
"of",
"old",
"tz",
"names",
"and",
"returns",
"a",
"mapping"
] | b73a692c8eec1255e9018717d391aaa78bad00e7 | https://github.com/regebro/tzlocal/blob/b73a692c8eec1255e9018717d391aaa78bad00e7/update_windows_mappings.py#L26-L53 |
1,420 | lambdalisue/django-permission | src/permission/decorators/classbase.py | permission_required | def permission_required(perm, queryset=None,
login_url=None, raise_exception=False):
"""
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
queryset : queryset or model
A queryset or model for finding object.
With classbased generic view, ``None`` for using view default queryset.
When the view does not define ``get_queryset``, ``queryset``,
``get_object``, or ``object`` then ``obj=None`` is used to check
permission.
With functional generic view, ``None`` for using passed queryset.
When non queryset was passed then ``obj=None`` is used to check
permission.
Examples
--------
>>> @permission_required('auth.change_user')
>>> class UpdateAuthUserView(UpdateView):
... pass
"""
def wrapper(cls):
def view_wrapper(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def inner(self, request, *args, **kwargs):
# get object
obj = get_object_from_classbased_instance(
self, queryset, request, *args, **kwargs
)
if not request.user.has_perm(perm, obj=obj):
if raise_exception:
raise PermissionDenied
else:
return redirect_to_login(request, login_url)
return view_func(self, request, *args, **kwargs)
return inner
cls.dispatch = view_wrapper(cls.dispatch)
return cls
return wrapper | python | 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 object
obj = get_object_from_classbased_instance(
self, queryset, request, *args, **kwargs
)
if not request.user.has_perm(perm, obj=obj):
if raise_exception:
raise PermissionDenied
else:
return redirect_to_login(request, login_url)
return view_func(self, request, *args, **kwargs)
return inner
cls.dispatch = view_wrapper(cls.dispatch)
return cls
return wrapper | [
"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 object",
"obj",
"=",
"get_object_from_classbased_instance",
"(",
"self",
",",
"queryset",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"request",
".",
"user",
".",
"has_perm",
"(",
"perm",
",",
"obj",
"=",
"obj",
")",
":",
"if",
"raise_exception",
":",
"raise",
"PermissionDenied",
"else",
":",
"return",
"redirect_to_login",
"(",
"request",
",",
"login_url",
")",
"return",
"view_func",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"inner",
"cls",
".",
"dispatch",
"=",
"view_wrapper",
"(",
"cls",
".",
"dispatch",
")",
"return",
"cls",
"return",
"wrapper"
] | 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
queryset : queryset or model
A queryset or model for finding object.
With classbased generic view, ``None`` for using view default queryset.
When the view does not define ``get_queryset``, ``queryset``,
``get_object``, or ``object`` then ``obj=None`` is used to check
permission.
With functional generic view, ``None`` for using passed queryset.
When non queryset was passed then ``obj=None`` is used to check
permission.
Examples
--------
>>> @permission_required('auth.change_user')
>>> class UpdateAuthUserView(UpdateView):
... pass | [
"Permission",
"check",
"decorator",
"for",
"classbased",
"generic",
"view"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/decorators/classbase.py#L11-L58 |
1,421 | lambdalisue/django-permission | src/permission/decorators/classbase.py | get_object_from_classbased_instance | def get_object_from_classbased_instance(
instance, queryset, request, *args, **kwargs):
"""
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 instance of model object or None
"""
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 initialized in ``dispatch`` method.
instance.request = request
instance.args = args
instance.kwargs = kwargs
# get queryset from class if ``queryset_or_model`` is not specified
if hasattr(instance, 'get_queryset') and not queryset:
queryset = instance.get_queryset()
elif hasattr(instance, 'queryset') and not queryset:
queryset = instance.queryset
elif hasattr(instance, 'model') and not queryset:
queryset = instance.model._default_manager.all()
# get object
if hasattr(instance, 'get_object'):
try:
obj = instance.get_object(queryset)
except AttributeError as e:
# CreateView has ``get_object`` method but CreateView
# should not have any object before thus simply set
# None
if isinstance(instance, BaseCreateView):
obj = None
else:
raise e
elif hasattr(instance, 'object'):
obj = instance.object
else:
obj = None
return obj | python | 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 initialized in ``dispatch`` method.
instance.request = request
instance.args = args
instance.kwargs = kwargs
# get queryset from class if ``queryset_or_model`` is not specified
if hasattr(instance, 'get_queryset') and not queryset:
queryset = instance.get_queryset()
elif hasattr(instance, 'queryset') and not queryset:
queryset = instance.queryset
elif hasattr(instance, 'model') and not queryset:
queryset = instance.model._default_manager.all()
# get object
if hasattr(instance, 'get_object'):
try:
obj = instance.get_object(queryset)
except AttributeError as e:
# CreateView has ``get_object`` method but CreateView
# should not have any object before thus simply set
# None
if isinstance(instance, BaseCreateView):
obj = None
else:
raise e
elif hasattr(instance, 'object'):
obj = instance.object
else:
obj = None
return obj | [
"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 initialized in ``dispatch`` method.",
"instance",
".",
"request",
"=",
"request",
"instance",
".",
"args",
"=",
"args",
"instance",
".",
"kwargs",
"=",
"kwargs",
"# get queryset from class if ``queryset_or_model`` is not specified",
"if",
"hasattr",
"(",
"instance",
",",
"'get_queryset'",
")",
"and",
"not",
"queryset",
":",
"queryset",
"=",
"instance",
".",
"get_queryset",
"(",
")",
"elif",
"hasattr",
"(",
"instance",
",",
"'queryset'",
")",
"and",
"not",
"queryset",
":",
"queryset",
"=",
"instance",
".",
"queryset",
"elif",
"hasattr",
"(",
"instance",
",",
"'model'",
")",
"and",
"not",
"queryset",
":",
"queryset",
"=",
"instance",
".",
"model",
".",
"_default_manager",
".",
"all",
"(",
")",
"# get object",
"if",
"hasattr",
"(",
"instance",
",",
"'get_object'",
")",
":",
"try",
":",
"obj",
"=",
"instance",
".",
"get_object",
"(",
"queryset",
")",
"except",
"AttributeError",
"as",
"e",
":",
"# CreateView has ``get_object`` method but CreateView",
"# should not have any object before thus simply set",
"# None",
"if",
"isinstance",
"(",
"instance",
",",
"BaseCreateView",
")",
":",
"obj",
"=",
"None",
"else",
":",
"raise",
"e",
"elif",
"hasattr",
"(",
"instance",
",",
"'object'",
")",
":",
"obj",
"=",
"instance",
".",
"object",
"else",
":",
"obj",
"=",
"None",
"return",
"obj"
] | 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 instance of model object or None | [
"Get",
"object",
"from",
"an",
"instance",
"of",
"classbased",
"generic",
"view"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/decorators/classbase.py#L61-L112 |
1,422 | lambdalisue/django-permission | src/permission/utils/field_lookup.py | field_lookup | def field_lookup(obj, field_path):
"""
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.Model):
>>> title = models.CharField('title', max_length=200)
>>> author = models.ForeignKey(User, null=True,
>>> related_name='permission_test_articles_author')
>>> editors = models.ManyToManyField(User,
>>> related_name='permission_test_articles_editors')
>>> user = User.objects.create_user('test_user', 'password')
>>> article = Article.objects.create(title='test_article',
... author=user)
>>> article.editors.add(user)
>>> assert 'test_article' == field_lookup(article, 'title')
>>> assert 'test_user' == field_lookup(article, 'user__username')
>>> assert ['test_user'] == list(field_lookup(article,
... 'editors__username'))
"""
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(field_path) == 1:
return getattr(obj, field_path[0], None)
return field_lookup(field_lookup(obj, field_path[0]), field_path[1]) | python | 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(field_path) == 1:
return getattr(obj, field_path[0], None)
return field_lookup(field_lookup(obj, field_path[0]), field_path[1]) | [
"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",
"(",
"field_path",
")",
"==",
"1",
":",
"return",
"getattr",
"(",
"obj",
",",
"field_path",
"[",
"0",
"]",
",",
"None",
")",
"return",
"field_lookup",
"(",
"field_lookup",
"(",
"obj",
",",
"field_path",
"[",
"0",
"]",
")",
",",
"field_path",
"[",
"1",
"]",
")"
] | 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.Model):
>>> title = models.CharField('title', max_length=200)
>>> author = models.ForeignKey(User, null=True,
>>> related_name='permission_test_articles_author')
>>> editors = models.ManyToManyField(User,
>>> related_name='permission_test_articles_editors')
>>> user = User.objects.create_user('test_user', 'password')
>>> article = Article.objects.create(title='test_article',
... author=user)
>>> article.editors.add(user)
>>> assert 'test_article' == field_lookup(article, 'title')
>>> assert 'test_user' == field_lookup(article, 'user__username')
>>> assert ['test_user'] == list(field_lookup(article,
... 'editors__username')) | [
"Lookup",
"django",
"model",
"field",
"in",
"similar",
"way",
"of",
"django",
"query",
"lookup",
"."
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/utils/field_lookup.py#L6-L40 |
1,423 | lambdalisue/django-permission | src/permission/decorators/functionbase.py | permission_required | def permission_required(perm, queryset=None,
login_url=None, raise_exception=False):
"""
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 view default queryset.
When the view does not define ``get_queryset``, ``queryset``,
``get_object``, or ``object`` then ``obj=None`` is used to check
permission.
With functional generic view, ``None`` for using passed queryset.
When non queryset was passed then ``obj=None`` is used to check
permission.
Examples
--------
>>> @permission_required('auth.change_user')
>>> def update_auth_user(request, *args, **kwargs):
... pass
"""
def wrapper(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def inner(request, *args, **kwargs):
_kwargs = copy.copy(kwargs)
# overwrite queryset if specified
if queryset:
_kwargs['queryset'] = queryset
# get object from view
if 'date_field' in _kwargs:
fn = get_object_from_date_based_view
else:
fn = get_object_from_list_detail_view
if fn.validate(request, *args, **_kwargs):
obj = fn(request, *args, **_kwargs)
else:
# required arguments is not passed
obj = None
if not request.user.has_perm(perm, obj=obj):
if raise_exception:
raise PermissionDenied
else:
return redirect_to_login(request, login_url)
return view_func(request, *args, **_kwargs)
return inner
return wrapper | python | 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 queryset if specified
if queryset:
_kwargs['queryset'] = queryset
# get object from view
if 'date_field' in _kwargs:
fn = get_object_from_date_based_view
else:
fn = get_object_from_list_detail_view
if fn.validate(request, *args, **_kwargs):
obj = fn(request, *args, **_kwargs)
else:
# required arguments is not passed
obj = None
if not request.user.has_perm(perm, obj=obj):
if raise_exception:
raise PermissionDenied
else:
return redirect_to_login(request, login_url)
return view_func(request, *args, **_kwargs)
return inner
return wrapper | [
"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 queryset if specified",
"if",
"queryset",
":",
"_kwargs",
"[",
"'queryset'",
"]",
"=",
"queryset",
"# get object from view",
"if",
"'date_field'",
"in",
"_kwargs",
":",
"fn",
"=",
"get_object_from_date_based_view",
"else",
":",
"fn",
"=",
"get_object_from_list_detail_view",
"if",
"fn",
".",
"validate",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"_kwargs",
")",
":",
"obj",
"=",
"fn",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"_kwargs",
")",
"else",
":",
"# required arguments is not passed",
"obj",
"=",
"None",
"if",
"not",
"request",
".",
"user",
".",
"has_perm",
"(",
"perm",
",",
"obj",
"=",
"obj",
")",
":",
"if",
"raise_exception",
":",
"raise",
"PermissionDenied",
"else",
":",
"return",
"redirect_to_login",
"(",
"request",
",",
"login_url",
")",
"return",
"view_func",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"_kwargs",
")",
"return",
"inner",
"return",
"wrapper"
] | 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 view default queryset.
When the view does not define ``get_queryset``, ``queryset``,
``get_object``, or ``object`` then ``obj=None`` is used to check
permission.
With functional generic view, ``None`` for using passed queryset.
When non queryset was passed then ``obj=None`` is used to check
permission.
Examples
--------
>>> @permission_required('auth.change_user')
>>> def update_auth_user(request, *args, **kwargs):
... pass | [
"Permission",
"check",
"decorator",
"for",
"function",
"-",
"base",
"generic",
"view"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/decorators/functionbase.py#L13-L66 |
1,424 | lambdalisue/django-permission | src/permission/decorators/functionbase.py | get_object_from_list_detail_view | def get_object_from_list_detail_view(request, *args, **kwargs):
"""
Get object from generic list_detail.detail view
Parameters
----------
request : instance
An instance of HttpRequest
Returns
-------
instance
An instance of model object or None
"""
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 slug and slug_field:
obj = get_object_or_404(queryset, **{slug_field: slug})
else:
raise AttributeError(
"Generic detail view must be called with either an "
"object_id or a slug/slug_field."
)
return obj | python | 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 slug and slug_field:
obj = get_object_or_404(queryset, **{slug_field: slug})
else:
raise AttributeError(
"Generic detail view must be called with either an "
"object_id or a slug/slug_field."
)
return obj | [
"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",
"slug",
"and",
"slug_field",
":",
"obj",
"=",
"get_object_or_404",
"(",
"queryset",
",",
"*",
"*",
"{",
"slug_field",
":",
"slug",
"}",
")",
"else",
":",
"raise",
"AttributeError",
"(",
"\"Generic detail view must be called with either an \"",
"\"object_id or a slug/slug_field.\"",
")",
"return",
"obj"
] | Get object from generic list_detail.detail view
Parameters
----------
request : instance
An instance of HttpRequest
Returns
-------
instance
An instance of model object or None | [
"Get",
"object",
"from",
"generic",
"list_detail",
".",
"detail",
"view"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/decorators/functionbase.py#L69-L96 |
1,425 | lambdalisue/django-permission | src/permission/decorators/functionbase.py | get_object_from_date_based_view | def get_object_from_date_based_view(request, *args, **kwargs): # noqa
"""
Get object from generic date_based.detail view
Parameters
----------
request : instance
An instance of HttpRequest
Returns
-------
instance
An instance of model object or None
"""
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:
datetime_now = datetime.datetime.now
year, month, day = kwargs['year'], kwargs['month'], kwargs['day']
month_format = kwargs.get('month_format', '%b')
day_format = kwargs.get('day_format', '%d')
date_field = kwargs['date_field']
queryset = kwargs['queryset']
object_id = kwargs.get('object_id', None)
slug = kwargs.get('slug', None)
slug_field = kwargs.get('slug_field', 'slug')
try:
tt = time.strptime(
'%s-%s-%s' % (year, month, day),
'%s-%s-%s' % ('%Y', month_format, day_format)
)
date = datetime.date(*tt[:3])
except ValueError:
raise Http404
model = queryset.model
if isinstance(model._meta.get_field(date_field), DateTimeField):
lookup_kwargs = {
'%s__range' % date_field: (
datetime.datetime.combine(date, datetime.time.min),
datetime.datetime.combine(date, datetime.time.max),
)}
else:
lookup_kwargs = {date_field: date}
now = datetime_now()
if date >= now.date() and not kwargs.get('allow_future', False):
lookup_kwargs['%s__lte' % date_field] = now
if object_id:
lookup_kwargs['pk'] = object_id
elif slug and slug_field:
lookup_kwargs['%s__exact' % slug_field] = slug
else:
raise AttributeError(
"Generic detail view must be called with either an "
"object_id or a slug/slug_field."
)
return get_object_or_404(queryset, **lookup_kwargs) | python | 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:
datetime_now = datetime.datetime.now
year, month, day = kwargs['year'], kwargs['month'], kwargs['day']
month_format = kwargs.get('month_format', '%b')
day_format = kwargs.get('day_format', '%d')
date_field = kwargs['date_field']
queryset = kwargs['queryset']
object_id = kwargs.get('object_id', None)
slug = kwargs.get('slug', None)
slug_field = kwargs.get('slug_field', 'slug')
try:
tt = time.strptime(
'%s-%s-%s' % (year, month, day),
'%s-%s-%s' % ('%Y', month_format, day_format)
)
date = datetime.date(*tt[:3])
except ValueError:
raise Http404
model = queryset.model
if isinstance(model._meta.get_field(date_field), DateTimeField):
lookup_kwargs = {
'%s__range' % date_field: (
datetime.datetime.combine(date, datetime.time.min),
datetime.datetime.combine(date, datetime.time.max),
)}
else:
lookup_kwargs = {date_field: date}
now = datetime_now()
if date >= now.date() and not kwargs.get('allow_future', False):
lookup_kwargs['%s__lte' % date_field] = now
if object_id:
lookup_kwargs['pk'] = object_id
elif slug and slug_field:
lookup_kwargs['%s__exact' % slug_field] = slug
else:
raise AttributeError(
"Generic detail view must be called with either an "
"object_id or a slug/slug_field."
)
return get_object_or_404(queryset, **lookup_kwargs) | [
"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",
":",
"datetime_now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"year",
",",
"month",
",",
"day",
"=",
"kwargs",
"[",
"'year'",
"]",
",",
"kwargs",
"[",
"'month'",
"]",
",",
"kwargs",
"[",
"'day'",
"]",
"month_format",
"=",
"kwargs",
".",
"get",
"(",
"'month_format'",
",",
"'%b'",
")",
"day_format",
"=",
"kwargs",
".",
"get",
"(",
"'day_format'",
",",
"'%d'",
")",
"date_field",
"=",
"kwargs",
"[",
"'date_field'",
"]",
"queryset",
"=",
"kwargs",
"[",
"'queryset'",
"]",
"object_id",
"=",
"kwargs",
".",
"get",
"(",
"'object_id'",
",",
"None",
")",
"slug",
"=",
"kwargs",
".",
"get",
"(",
"'slug'",
",",
"None",
")",
"slug_field",
"=",
"kwargs",
".",
"get",
"(",
"'slug_field'",
",",
"'slug'",
")",
"try",
":",
"tt",
"=",
"time",
".",
"strptime",
"(",
"'%s-%s-%s'",
"%",
"(",
"year",
",",
"month",
",",
"day",
")",
",",
"'%s-%s-%s'",
"%",
"(",
"'%Y'",
",",
"month_format",
",",
"day_format",
")",
")",
"date",
"=",
"datetime",
".",
"date",
"(",
"*",
"tt",
"[",
":",
"3",
"]",
")",
"except",
"ValueError",
":",
"raise",
"Http404",
"model",
"=",
"queryset",
".",
"model",
"if",
"isinstance",
"(",
"model",
".",
"_meta",
".",
"get_field",
"(",
"date_field",
")",
",",
"DateTimeField",
")",
":",
"lookup_kwargs",
"=",
"{",
"'%s__range'",
"%",
"date_field",
":",
"(",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"date",
",",
"datetime",
".",
"time",
".",
"min",
")",
",",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"date",
",",
"datetime",
".",
"time",
".",
"max",
")",
",",
")",
"}",
"else",
":",
"lookup_kwargs",
"=",
"{",
"date_field",
":",
"date",
"}",
"now",
"=",
"datetime_now",
"(",
")",
"if",
"date",
">=",
"now",
".",
"date",
"(",
")",
"and",
"not",
"kwargs",
".",
"get",
"(",
"'allow_future'",
",",
"False",
")",
":",
"lookup_kwargs",
"[",
"'%s__lte'",
"%",
"date_field",
"]",
"=",
"now",
"if",
"object_id",
":",
"lookup_kwargs",
"[",
"'pk'",
"]",
"=",
"object_id",
"elif",
"slug",
"and",
"slug_field",
":",
"lookup_kwargs",
"[",
"'%s__exact'",
"%",
"slug_field",
"]",
"=",
"slug",
"else",
":",
"raise",
"AttributeError",
"(",
"\"Generic detail view must be called with either an \"",
"\"object_id or a slug/slug_field.\"",
")",
"return",
"get_object_or_404",
"(",
"queryset",
",",
"*",
"*",
"lookup_kwargs",
")"
] | Get object from generic date_based.detail view
Parameters
----------
request : instance
An instance of HttpRequest
Returns
-------
instance
An instance of model object or None | [
"Get",
"object",
"from",
"generic",
"date_based",
".",
"detail",
"view"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/decorators/functionbase.py#L107-L171 |
1,426 | lambdalisue/django-permission | src/permission/utils/handlers.py | PermissionHandlerRegistry.register | def register(self, model, handler=None):
"""
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
------
ImproperlyConfigured
Raise when the model is abstract model
KeyError
Raise when the model is already registered in registry
The model cannot have more than one handler.
"""
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 model in self._registry:
raise KeyError("A permission handler class is already "
"registered for '%s'" % model)
if handler is None:
handler = settings.PERMISSION_DEFAULT_PERMISSION_HANDLER
if isstr(handler):
handler = import_string(handler)
if not inspect.isclass(handler):
raise AttributeError(
"`handler` attribute must be a class. "
"An instance was specified.")
if not issubclass(handler, PermissionHandler):
raise AttributeError(
"`handler` attribute must be a subclass of "
"`permission.handlers.PermissionHandler`")
# Instantiate the handler to save in the registry
instance = handler(model)
self._registry[model] = instance | python | 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 model in self._registry:
raise KeyError("A permission handler class is already "
"registered for '%s'" % model)
if handler is None:
handler = settings.PERMISSION_DEFAULT_PERMISSION_HANDLER
if isstr(handler):
handler = import_string(handler)
if not inspect.isclass(handler):
raise AttributeError(
"`handler` attribute must be a class. "
"An instance was specified.")
if not issubclass(handler, PermissionHandler):
raise AttributeError(
"`handler` attribute must be a subclass of "
"`permission.handlers.PermissionHandler`")
# Instantiate the handler to save in the registry
instance = handler(model)
self._registry[model] = instance | [
"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",
"model",
"in",
"self",
".",
"_registry",
":",
"raise",
"KeyError",
"(",
"\"A permission handler class is already \"",
"\"registered for '%s'\"",
"%",
"model",
")",
"if",
"handler",
"is",
"None",
":",
"handler",
"=",
"settings",
".",
"PERMISSION_DEFAULT_PERMISSION_HANDLER",
"if",
"isstr",
"(",
"handler",
")",
":",
"handler",
"=",
"import_string",
"(",
"handler",
")",
"if",
"not",
"inspect",
".",
"isclass",
"(",
"handler",
")",
":",
"raise",
"AttributeError",
"(",
"\"`handler` attribute must be a class. \"",
"\"An instance was specified.\"",
")",
"if",
"not",
"issubclass",
"(",
"handler",
",",
"PermissionHandler",
")",
":",
"raise",
"AttributeError",
"(",
"\"`handler` attribute must be a subclass of \"",
"\"`permission.handlers.PermissionHandler`\"",
")",
"# Instantiate the handler to save in the registry",
"instance",
"=",
"handler",
"(",
"model",
")",
"self",
".",
"_registry",
"[",
"model",
"]",
"=",
"instance"
] | 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
------
ImproperlyConfigured
Raise when the model is abstract model
KeyError
Raise when the model is already registered in registry
The model cannot have more than one handler. | [
"Register",
"a",
"permission",
"handler",
"to",
"the",
"model"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/utils/handlers.py#L20-L62 |
1,427 | lambdalisue/django-permission | src/permission/utils/handlers.py | PermissionHandlerRegistry.unregister | def unregister(self, 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.
"""
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] | python | 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] | [
"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. | [
"Unregister",
"a",
"permission",
"handler",
"from",
"the",
"model"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/utils/handlers.py#L64-L82 |
1,428 | lambdalisue/django-permission | src/permission/handlers.py | PermissionHandler._get_app_perms | def _get_app_perms(self, *args):
"""
Get permissions related to the application specified in constructor
Returns
-------
set
A set instance of `app_label.codename` formatted permission strings
"""
if not hasattr(self, '_app_perms_cache'):
self._app_perms_cache = get_app_perms(self.app_label)
return self._app_perms_cache | python | 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 | [
"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 | [
"Get",
"permissions",
"related",
"to",
"the",
"application",
"specified",
"in",
"constructor"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/handlers.py#L59-L70 |
1,429 | lambdalisue/django-permission | src/permission/handlers.py | PermissionHandler._get_model_perms | def _get_model_perms(self, *args):
"""
Get permissions related to the model specified in constructor
Returns
-------
set
A set instance of `app_label.codename` formatted permission strings
"""
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 | python | 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 | [
"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 | [
"Get",
"permissions",
"related",
"to",
"the",
"model",
"specified",
"in",
"constructor"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/handlers.py#L72-L86 |
1,430 | lambdalisue/django-permission | src/permission/handlers.py | PermissionHandler.has_module_perms | def has_module_perms(self, user_obj, app_label):
"""
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
Whether the specified user have any permissions of specified app
"""
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:
for permission in self.get_supported_permissions():
if user_obj.has_perm(permission):
setattr(self, cache_name, True)
return True
setattr(self, cache_name, False)
return False | python | 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:
for permission in self.get_supported_permissions():
if user_obj.has_perm(permission):
setattr(self, cache_name, True)
return True
setattr(self, cache_name, False)
return False | [
"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",
":",
"for",
"permission",
"in",
"self",
".",
"get_supported_permissions",
"(",
")",
":",
"if",
"user_obj",
".",
"has_perm",
"(",
"permission",
")",
":",
"setattr",
"(",
"self",
",",
"cache_name",
",",
"True",
")",
"return",
"True",
"setattr",
"(",
"self",
",",
"cache_name",
",",
"False",
")",
"return",
"False"
] | 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
Whether the specified user have any permissions of specified app | [
"Check",
"if",
"user",
"have",
"permission",
"of",
"specified",
"app"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/handlers.py#L158-L186 |
1,431 | lambdalisue/django-permission | src/permission/utils/permissions.py | get_perm_codename | def get_perm_codename(perm, fail_silently=True):
"""
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')
'codename'
>>> get_perm_codename('app_label.app_label.codename_model')
'app_label.codename_model'
"""
try:
perm = perm.split('.', 1)[1]
except IndexError as e:
if not fail_silently:
raise e
return perm | python | 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 | [
"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')
'codename'
>>> get_perm_codename('app_label.app_label.codename_model')
'app_label.codename_model' | [
"Get",
"permission",
"codename",
"from",
"permission",
"-",
"string",
"."
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/utils/permissions.py#L12-L34 |
1,432 | lambdalisue/django-permission | src/permission/utils/permissions.py | permission_to_perm | def permission_to_perm(permission):
"""
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'
"""
app_label = permission.content_type.app_label
codename = permission.codename
return '%s.%s' % (app_label, codename) | python | def permission_to_perm(permission):
app_label = permission.content_type.app_label
codename = permission.codename
return '%s.%s' % (app_label, 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' | [
"Convert",
"a",
"permission",
"instance",
"to",
"a",
"permission",
"-",
"string",
"."
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/utils/permissions.py#L37-L52 |
1,433 | lambdalisue/django-permission | src/permission/utils/permissions.py | perm_to_permission | def perm_to_permission(perm):
"""
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'
"""
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 'app_label.codename'."
)
else:
permission = Permission.objects.get(
content_type__app_label=app_label,
codename=codename
)
return permission | python | 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 'app_label.codename'."
)
else:
permission = Permission.objects.get(
content_type__app_label=app_label,
codename=codename
)
return permission | [
"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 'app_label.codename'.\"",
")",
"else",
":",
"permission",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"content_type__app_label",
"=",
"app_label",
",",
"codename",
"=",
"codename",
")",
"return",
"permission"
] | 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' | [
"Convert",
"a",
"permission",
"-",
"string",
"to",
"a",
"permission",
"instance",
"."
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/utils/permissions.py#L55-L80 |
1,434 | lambdalisue/django-permission | src/permission/utils/permissions.py | get_app_perms | def get_app_perms(model_or_app_label):
"""
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 application.
Examples
--------
>>> perms1 = get_app_perms('auth')
>>> perms2 = get_app_perms(Permission)
>>> perms1 == perms2
True
"""
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 = Permission.objects.filter(content_type__app_label=app_label)
perms = ('%s.%s' % (app_label, p.codename) for p in qs.iterator())
return set(perms) | python | 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 = Permission.objects.filter(content_type__app_label=app_label)
perms = ('%s.%s' % (app_label, p.codename) for p in qs.iterator())
return set(perms) | [
"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",
"=",
"Permission",
".",
"objects",
".",
"filter",
"(",
"content_type__app_label",
"=",
"app_label",
")",
"perms",
"=",
"(",
"'%s.%s'",
"%",
"(",
"app_label",
",",
"p",
".",
"codename",
")",
"for",
"p",
"in",
"qs",
".",
"iterator",
"(",
")",
")",
"return",
"set",
"(",
"perms",
")"
] | 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 application.
Examples
--------
>>> perms1 = get_app_perms('auth')
>>> perms2 = get_app_perms(Permission)
>>> perms1 == perms2
True | [
"Get",
"permission",
"-",
"string",
"list",
"of",
"the",
"specified",
"django",
"application",
"."
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/utils/permissions.py#L83-L113 |
1,435 | lambdalisue/django-permission | src/permission/utils/permissions.py | get_model_perms | def get_model_perms(model):
"""
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(Permission)) == [
... 'auth.add_permission',
... 'auth.change_permission',
... 'auth.delete_permission'
... ]
True
"""
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 = ('%s.%s' % (app_label, p.codename) for p in qs.iterator())
return set(perms) | python | 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 = ('%s.%s' % (app_label, p.codename) for p in qs.iterator())
return set(perms) | [
"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",
"=",
"(",
"'%s.%s'",
"%",
"(",
"app_label",
",",
"p",
".",
"codename",
")",
"for",
"p",
"in",
"qs",
".",
"iterator",
"(",
")",
")",
"return",
"set",
"(",
"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(Permission)) == [
... 'auth.add_permission',
... 'auth.change_permission',
... 'auth.delete_permission'
... ]
True | [
"Get",
"permission",
"-",
"string",
"list",
"of",
"a",
"specified",
"django",
"model",
"."
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/utils/permissions.py#L116-L145 |
1,436 | lambdalisue/django-permission | src/permission/utils/logics.py | add_permission_logic | def add_permission_logic(model, permission_logic):
"""
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
of the model
Examples
--------
>>> from django.db import models
>>> from permission.logics import PermissionLogic
>>> class Mock(models.Model):
... name = models.CharField('name', max_length=120)
>>> add_permission_logic(Mock, PermissionLogic())
"""
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 hasattr(model, '_permission_handler'):
from permission.utils.handlers import registry
# register default permission handler
registry.register(model, handler=None)
model._permission_logics.add(permission_logic)
# store target model to the permission_logic instance
permission_logic.model = model | python | 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 hasattr(model, '_permission_handler'):
from permission.utils.handlers import registry
# register default permission handler
registry.register(model, handler=None)
model._permission_logics.add(permission_logic)
# store target model to the permission_logic instance
permission_logic.model = model | [
"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",
"hasattr",
"(",
"model",
",",
"'_permission_handler'",
")",
":",
"from",
"permission",
".",
"utils",
".",
"handlers",
"import",
"registry",
"# register default permission handler",
"registry",
".",
"register",
"(",
"model",
",",
"handler",
"=",
"None",
")",
"model",
".",
"_permission_logics",
".",
"add",
"(",
"permission_logic",
")",
"# store target model to the permission_logic instance",
"permission_logic",
".",
"model",
"=",
"model"
] | 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
of the model
Examples
--------
>>> from django.db import models
>>> from permission.logics import PermissionLogic
>>> class Mock(models.Model):
... name = models.CharField('name', max_length=120)
>>> add_permission_logic(Mock, PermissionLogic()) | [
"Add",
"permission",
"logic",
"to",
"the",
"model"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/utils/logics.py#L9-L41 |
1,437 | lambdalisue/django-permission | src/permission/utils/logics.py | remove_permission_logic | def remove_permission_logic(model, permission_logic, fail_silently=True):
"""
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 determine
permission of the model
fail_silently : boolean
If `True` then do not raise KeyError even the specified permission logic
have not registered.
Examples
--------
>>> from django.db import models
>>> from permission.logics import PermissionLogic
>>> class Mock(models.Model):
... name = models.CharField('name', max_length=120)
>>> logic = PermissionLogic()
>>> add_permission_logic(Mock, logic)
>>> remove_permission_logic(Mock, logic)
"""
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 _permission_logic in model._permission_logics:
if _permission_logic.__class__ == permission_logic:
remove_set.add(_permission_logic)
# difference
model._permission_logics = model._permission_logics.difference(remove_set)
else:
if fail_silently and permission_logic not in model._permission_logics:
pass
else:
model._permission_logics.remove(permission_logic) | python | 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 _permission_logic in model._permission_logics:
if _permission_logic.__class__ == permission_logic:
remove_set.add(_permission_logic)
# difference
model._permission_logics = model._permission_logics.difference(remove_set)
else:
if fail_silently and permission_logic not in model._permission_logics:
pass
else:
model._permission_logics.remove(permission_logic) | [
"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",
"_permission_logic",
"in",
"model",
".",
"_permission_logics",
":",
"if",
"_permission_logic",
".",
"__class__",
"==",
"permission_logic",
":",
"remove_set",
".",
"add",
"(",
"_permission_logic",
")",
"# difference",
"model",
".",
"_permission_logics",
"=",
"model",
".",
"_permission_logics",
".",
"difference",
"(",
"remove_set",
")",
"else",
":",
"if",
"fail_silently",
"and",
"permission_logic",
"not",
"in",
"model",
".",
"_permission_logics",
":",
"pass",
"else",
":",
"model",
".",
"_permission_logics",
".",
"remove",
"(",
"permission_logic",
")"
] | 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 determine
permission of the model
fail_silently : boolean
If `True` then do not raise KeyError even the specified permission logic
have not registered.
Examples
--------
>>> from django.db import models
>>> from permission.logics import PermissionLogic
>>> class Mock(models.Model):
... name = models.CharField('name', max_length=120)
>>> logic = PermissionLogic()
>>> add_permission_logic(Mock, logic)
>>> remove_permission_logic(Mock, logic) | [
"Remove",
"permission",
"logic",
"to",
"the",
"model"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/utils/logics.py#L44-L84 |
1,438 | lambdalisue/django-permission | src/permission/utils/autodiscover.py | autodiscover | def autodiscover(module_name=None):
"""
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.
"""
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_configs.values())
for app in app_names:
mod = import_module(app)
# Attempt to import the app's perms module
try:
# discover the permission module
discover(app, module_name=module_name)
except:
# Decide whether to bubble up this error. If the app just doesn't
# have an perms module, we can just ignore the error attempting
# to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, module_name):
raise | python | 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_configs.values())
for app in app_names:
mod = import_module(app)
# Attempt to import the app's perms module
try:
# discover the permission module
discover(app, module_name=module_name)
except:
# Decide whether to bubble up this error. If the app just doesn't
# have an perms module, we can just ignore the error attempting
# to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, module_name):
raise | [
"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_configs",
".",
"values",
"(",
")",
")",
"for",
"app",
"in",
"app_names",
":",
"mod",
"=",
"import_module",
"(",
"app",
")",
"# Attempt to import the app's perms module",
"try",
":",
"# discover the permission module",
"discover",
"(",
"app",
",",
"module_name",
"=",
"module_name",
")",
"except",
":",
"# Decide whether to bubble up this error. If the app just doesn't",
"# have an perms module, we can just ignore the error attempting",
"# to import it, otherwise we want it to bubble up.",
"if",
"module_has_submodule",
"(",
"mod",
",",
"module_name",
")",
":",
"raise"
] | 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. | [
"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",
"."
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/utils/autodiscover.py#L7-L31 |
1,439 | lambdalisue/django-permission | src/permission/utils/autodiscover.py | discover | def discover(app, module_name=None):
"""
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),
)
Use this method to apply the permission logics enumerated in
``PERMISSION_LOGICS`` variable like:
>>> discover('your_app')
"""
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 = module_name or settings.PERMISSION_AUTODISCOVER_MODULE_NAME
# import the module
m = import_module('%s.%s' % (app, module_name))
# check if the module have PERMISSION_LOGICS variable
if hasattr(m, variable_name):
# apply permission logics automatically
permission_logic_set = getattr(m, variable_name)
for model, permission_logic in permission_logic_set:
if isinstance(model, six.string_types):
# convert model string to model instance
model = get_model(*model.split('.', 1))
add_permission_logic(model, permission_logic) | python | 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 = module_name or settings.PERMISSION_AUTODISCOVER_MODULE_NAME
# import the module
m = import_module('%s.%s' % (app, module_name))
# check if the module have PERMISSION_LOGICS variable
if hasattr(m, variable_name):
# apply permission logics automatically
permission_logic_set = getattr(m, variable_name)
for model, permission_logic in permission_logic_set:
if isinstance(model, six.string_types):
# convert model string to model instance
model = get_model(*model.split('.', 1))
add_permission_logic(model, permission_logic) | [
"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",
"=",
"module_name",
"or",
"settings",
".",
"PERMISSION_AUTODISCOVER_MODULE_NAME",
"# import the module",
"m",
"=",
"import_module",
"(",
"'%s.%s'",
"%",
"(",
"app",
",",
"module_name",
")",
")",
"# check if the module have PERMISSION_LOGICS variable",
"if",
"hasattr",
"(",
"m",
",",
"variable_name",
")",
":",
"# apply permission logics automatically",
"permission_logic_set",
"=",
"getattr",
"(",
"m",
",",
"variable_name",
")",
"for",
"model",
",",
"permission_logic",
"in",
"permission_logic_set",
":",
"if",
"isinstance",
"(",
"model",
",",
"six",
".",
"string_types",
")",
":",
"# convert model string to model instance",
"model",
"=",
"get_model",
"(",
"*",
"model",
".",
"split",
"(",
"'.'",
",",
"1",
")",
")",
"add_permission_logic",
"(",
"model",
",",
"permission_logic",
")"
] | 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),
)
Use this method to apply the permission logics enumerated in
``PERMISSION_LOGICS`` variable like:
>>> discover('your_app') | [
"Automatically",
"apply",
"the",
"permission",
"logics",
"written",
"in",
"the",
"specified",
"module",
"."
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/utils/autodiscover.py#L34-L72 |
1,440 | lambdalisue/django-permission | src/permission/logics/oneself.py | OneselfPermissionLogic.has_perm | def has_perm(self, user_obj, perm, obj=None):
"""
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.
https://code.djangoproject.com/wiki/RowLevelPermissions
If an object is specified, it will return ``True`` if the object is the
user.
So users can change or delete themselves (you can change this behavior
to set ``any_permission``, ``change_permissino`` or
``delete_permission`` attributes of this instance).
Parameters
----------
user_obj : django user model instance
A django user model instance which be checked
perm : string
`app_label.codename` formatted permission string
obj : None or django model instance
None or django model instance for object permission
Returns
-------
boolean
Whether the specified user have specified permission (of specified
object).
"""
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')
# check if the user is authenticated
if obj is None:
# object permission without obj should return True
# Ref: https://code.djangoproject.com/wiki/RowLevelPermissions
if self.any_permission:
return True
if self.change_permission and perm == change_permission:
return True
if self.delete_permission and perm == delete_permission:
return True
return False
elif user_obj.is_active:
# check if the user trying to interact with himself
if obj == user_obj:
if self.any_permission:
# have any kind of permissions to himself
return True
if (self.change_permission and
perm == change_permission):
return True
if (self.delete_permission and
perm == delete_permission):
return True
return False | python | 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')
# check if the user is authenticated
if obj is None:
# object permission without obj should return True
# Ref: https://code.djangoproject.com/wiki/RowLevelPermissions
if self.any_permission:
return True
if self.change_permission and perm == change_permission:
return True
if self.delete_permission and perm == delete_permission:
return True
return False
elif user_obj.is_active:
# check if the user trying to interact with himself
if obj == user_obj:
if self.any_permission:
# have any kind of permissions to himself
return True
if (self.change_permission and
perm == change_permission):
return True
if (self.delete_permission and
perm == delete_permission):
return True
return False | [
"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'",
")",
"# check if the user is authenticated",
"if",
"obj",
"is",
"None",
":",
"# object permission without obj should return True",
"# Ref: https://code.djangoproject.com/wiki/RowLevelPermissions",
"if",
"self",
".",
"any_permission",
":",
"return",
"True",
"if",
"self",
".",
"change_permission",
"and",
"perm",
"==",
"change_permission",
":",
"return",
"True",
"if",
"self",
".",
"delete_permission",
"and",
"perm",
"==",
"delete_permission",
":",
"return",
"True",
"return",
"False",
"elif",
"user_obj",
".",
"is_active",
":",
"# check if the user trying to interact with himself",
"if",
"obj",
"==",
"user_obj",
":",
"if",
"self",
".",
"any_permission",
":",
"# have any kind of permissions to himself",
"return",
"True",
"if",
"(",
"self",
".",
"change_permission",
"and",
"perm",
"==",
"change_permission",
")",
":",
"return",
"True",
"if",
"(",
"self",
".",
"delete_permission",
"and",
"perm",
"==",
"delete_permission",
")",
":",
"return",
"True",
"return",
"False"
] | 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.
https://code.djangoproject.com/wiki/RowLevelPermissions
If an object is specified, it will return ``True`` if the object is the
user.
So users can change or delete themselves (you can change this behavior
to set ``any_permission``, ``change_permissino`` or
``delete_permission`` attributes of this instance).
Parameters
----------
user_obj : django user model instance
A django user model instance which be checked
perm : string
`app_label.codename` formatted permission string
obj : None or django model instance
None or django model instance for object permission
Returns
-------
boolean
Whether the specified user have specified permission (of specified
object). | [
"Check",
"if",
"user",
"have",
"permission",
"of",
"himself"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/logics/oneself.py#L58-L118 |
1,441 | lambdalisue/django-permission | src/permission/decorators/utils.py | redirect_to_login | def redirect_to_login(request, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
"""redirect to login"""
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(login_url or settings.LOGIN_URL)[:2]
current_scheme, current_netloc = urlparse(path)[:2]
if ((not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
from django.contrib.auth.views import \
redirect_to_login as auth_redirect_to_login
return auth_redirect_to_login(path, login_url, redirect_field_name) | python | 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(login_url or settings.LOGIN_URL)[:2]
current_scheme, current_netloc = urlparse(path)[:2]
if ((not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
from django.contrib.auth.views import \
redirect_to_login as auth_redirect_to_login
return auth_redirect_to_login(path, login_url, redirect_field_name) | [
"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",
"(",
"login_url",
"or",
"settings",
".",
"LOGIN_URL",
")",
"[",
":",
"2",
"]",
"current_scheme",
",",
"current_netloc",
"=",
"urlparse",
"(",
"path",
")",
"[",
":",
"2",
"]",
"if",
"(",
"(",
"not",
"login_scheme",
"or",
"login_scheme",
"==",
"current_scheme",
")",
"and",
"(",
"not",
"login_netloc",
"or",
"login_netloc",
"==",
"current_netloc",
")",
")",
":",
"path",
"=",
"request",
".",
"get_full_path",
"(",
")",
"from",
"django",
".",
"contrib",
".",
"auth",
".",
"views",
"import",
"redirect_to_login",
"as",
"auth_redirect_to_login",
"return",
"auth_redirect_to_login",
"(",
"path",
",",
"login_url",
",",
"redirect_field_name",
")"
] | redirect to login | [
"redirect",
"to",
"login"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/decorators/utils.py#L13-L27 |
1,442 | lambdalisue/django-permission | src/permission/backends.py | PermissionBackend.has_module_perms | def has_module_perms(self, user_obj, app_label):
"""
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
----------
user_obj : django user model instance
A django user model instance which is checked
app_label : string
`app_label.codename` formatted permission string
Returns
-------
boolean
Whether the specified user have specified permission.
Raises
------
django.core.exceptions.ObjectDoesNotExist
If the specified string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
"""
# 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()
if app_label in h.get_supported_app_labels()]
setattr(self, cache_name, handlers)
for handler in handlers:
if handler.has_module_perms(user_obj, app_label):
return True
return False | python | 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()
if app_label in h.get_supported_app_labels()]
setattr(self, cache_name, handlers)
for handler in handlers:
if handler.has_module_perms(user_obj, app_label):
return True
return False | [
"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",
"(",
")",
"if",
"app_label",
"in",
"h",
".",
"get_supported_app_labels",
"(",
")",
"]",
"setattr",
"(",
"self",
",",
"cache_name",
",",
"handlers",
")",
"for",
"handler",
"in",
"handlers",
":",
"if",
"handler",
".",
"has_module_perms",
"(",
"user_obj",
",",
"app_label",
")",
":",
"return",
"True",
"return",
"False"
] | 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
----------
user_obj : django user model instance
A django user model instance which is checked
app_label : string
`app_label.codename` formatted permission string
Returns
-------
boolean
Whether the specified user have specified permission.
Raises
------
django.core.exceptions.ObjectDoesNotExist
If the specified string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module. | [
"Check",
"if",
"user",
"have",
"permission",
"of",
"specified",
"app",
"based",
"on",
"registered",
"handlers",
"."
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/backends.py#L81-L121 |
1,443 | lambdalisue/django-permission | src/permission/templatetags/permissionif.py | of_operator | def of_operator(context, x, y):
"""
'of' operator of permission if
This operator is used to specify the target object of permission
"""
return x.eval(context), y.eval(context) | python | def of_operator(context, x, y):
return x.eval(context), y.eval(context) | [
"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 | [
"of",
"operator",
"of",
"permission",
"if"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/templatetags/permissionif.py#L17-L23 |
1,444 | lambdalisue/django-permission | src/permission/templatetags/permissionif.py | has_operator | def has_operator(context, x, y):
"""
'has' operator of permission if
This operator is used to specify the user object of permission
"""
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) | python | 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) | [
"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 | [
"has",
"operator",
"of",
"permission",
"if"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/templatetags/permissionif.py#L26-L38 |
1,445 | lambdalisue/django-permission | src/permission/templatetags/permissionif.py | do_permissionif | def do_permissionif(parser, token):
"""
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>
{% endif %}
{# If you set 'PERMISSION_REPLACE_BUILTIN_IF = False' in settings #}
{% permission user has 'blogs.add_article' %}
<p>This user have 'blogs.add_article' permission</p>
{% elpermission user has 'blog.change_article' of object %}
<p>This user have 'blogs.change_article' permission of {{object}}</p>
{% endpermission %}
"""
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_nodelists = [(condition, nodelist)]
token = parser.next_token()
# {% elif ... %} (repeatable)
while token.contents.startswith(ELIF):
bits = token.split_contents()[1:]
condition = do_permissionif.Parser(parser, bits).parse()
nodelist = parser.parse((ELIF, ELSE, ENDIF))
conditions_nodelists.append((condition, nodelist))
token = parser.next_token()
# {% else %} (optional)
if token.contents == ELSE:
nodelist = parser.parse((ENDIF,))
conditions_nodelists.append((None, nodelist))
token = parser.next_token()
# {% endif %}
assert token.contents == ENDIF
return IfNode(conditions_nodelists) | python | 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_nodelists = [(condition, nodelist)]
token = parser.next_token()
# {% elif ... %} (repeatable)
while token.contents.startswith(ELIF):
bits = token.split_contents()[1:]
condition = do_permissionif.Parser(parser, bits).parse()
nodelist = parser.parse((ELIF, ELSE, ENDIF))
conditions_nodelists.append((condition, nodelist))
token = parser.next_token()
# {% else %} (optional)
if token.contents == ELSE:
nodelist = parser.parse((ENDIF,))
conditions_nodelists.append((None, nodelist))
token = parser.next_token()
# {% endif %}
assert token.contents == ENDIF
return IfNode(conditions_nodelists) | [
"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_nodelists",
"=",
"[",
"(",
"condition",
",",
"nodelist",
")",
"]",
"token",
"=",
"parser",
".",
"next_token",
"(",
")",
"# {% elif ... %} (repeatable)",
"while",
"token",
".",
"contents",
".",
"startswith",
"(",
"ELIF",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"[",
"1",
":",
"]",
"condition",
"=",
"do_permissionif",
".",
"Parser",
"(",
"parser",
",",
"bits",
")",
".",
"parse",
"(",
")",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"ELIF",
",",
"ELSE",
",",
"ENDIF",
")",
")",
"conditions_nodelists",
".",
"append",
"(",
"(",
"condition",
",",
"nodelist",
")",
")",
"token",
"=",
"parser",
".",
"next_token",
"(",
")",
"# {% else %} (optional)",
"if",
"token",
".",
"contents",
"==",
"ELSE",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"ENDIF",
",",
")",
")",
"conditions_nodelists",
".",
"append",
"(",
"(",
"None",
",",
"nodelist",
")",
")",
"token",
"=",
"parser",
".",
"next_token",
"(",
")",
"# {% endif %}",
"assert",
"token",
".",
"contents",
"==",
"ENDIF",
"return",
"IfNode",
"(",
"conditions_nodelists",
")"
] | 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>
{% endif %}
{# If you set 'PERMISSION_REPLACE_BUILTIN_IF = False' in settings #}
{% permission user has 'blogs.add_article' %}
<p>This user have 'blogs.add_article' permission</p>
{% elpermission user has 'blog.change_article' of object %}
<p>This user have 'blogs.change_article' permission of {{object}}</p>
{% endpermission %} | [
"Permission",
"if",
"templatetag"
] | 580f7a1f857701d06ccf41163f188ac04fbc4fac | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/templatetags/permissionif.py#L77-L128 |
1,446 | AguaClara/aguaclara | aguaclara/core/physchem.py | diam_circle | def diam_circle(AreaCircle):
"""Return the diameter of a circle."""
ut.check_range([AreaCircle, ">0", "AreaCircle"])
return np.sqrt(4 * AreaCircle / np.pi) | python | def diam_circle(AreaCircle):
ut.check_range([AreaCircle, ">0", "AreaCircle"])
return np.sqrt(4 * AreaCircle / np.pi) | [
"def",
"diam_circle",
"(",
"AreaCircle",
")",
":",
"ut",
".",
"check_range",
"(",
"[",
"AreaCircle",
",",
"\">0\"",
",",
"\"AreaCircle\"",
"]",
")",
"return",
"np",
".",
"sqrt",
"(",
"4",
"*",
"AreaCircle",
"/",
"np",
".",
"pi",
")"
] | Return the diameter of a circle. | [
"Return",
"the",
"diameter",
"of",
"a",
"circle",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L27-L30 |
1,447 | AguaClara/aguaclara | aguaclara/core/physchem.py | density_water | def density_water(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.
"""
ut.check_range([temp, ">0", "Temperature in Kelvin"])
rhointerpolated = interpolate.CubicSpline(WATER_DENSITY_TABLE[0],
WATER_DENSITY_TABLE[1])
return np.asscalar(rhointerpolated(temp)) | python | 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)) | [
"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. | [
"Return",
"the",
"density",
"of",
"water",
"at",
"a",
"given",
"temperature",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L63-L72 |
1,448 | AguaClara/aguaclara | aguaclara/core/physchem.py | viscosity_kinematic | def viscosity_kinematic(temp):
"""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.
"""
ut.check_range([temp, ">0", "Temperature in Kelvin"])
return (viscosity_dynamic(temp).magnitude
/ density_water(temp).magnitude) | python | def viscosity_kinematic(temp):
ut.check_range([temp, ">0", "Temperature in Kelvin"])
return (viscosity_dynamic(temp).magnitude
/ density_water(temp).magnitude) | [
"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. | [
"Return",
"the",
"kinematic",
"viscosity",
"of",
"water",
"at",
"a",
"given",
"temperature",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L76-L84 |
1,449 | AguaClara/aguaclara | aguaclara/core/physchem.py | re_pipe | def re_pipe(FlowRate, Diam, Nu):
"""Return the Reynolds Number for a pipe."""
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Diam, ">0", "Diameter"],
[Nu, ">0", "Nu"])
return (4 * FlowRate) / (np.pi * Diam * Nu) | python | 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) | [
"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. | [
"Return",
"the",
"Reynolds",
"Number",
"for",
"a",
"pipe",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L88-L93 |
1,450 | AguaClara/aguaclara | aguaclara/core/physchem.py | radius_hydraulic | def radius_hydraulic(Width, DistCenter, openchannel):
"""Return the hydraulic radius.
Width and DistCenter are length values and openchannel is a boolean.
"""
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 is open. Otherwise, the channel
# is assumed to have a top.
else:
return (Width*DistCenter) / (2 * (Width+DistCenter)) | python | 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 is open. Otherwise, the channel
# is assumed to have a top.
else:
return (Width*DistCenter) / (2 * (Width+DistCenter)) | [
"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 is open. Otherwise, the channel",
"# is assumed to have a top.",
"else",
":",
"return",
"(",
"Width",
"*",
"DistCenter",
")",
"/",
"(",
"2",
"*",
"(",
"Width",
"+",
"DistCenter",
")",
")"
] | Return the hydraulic radius.
Width and DistCenter are length values and openchannel is a boolean. | [
"Return",
"the",
"hydraulic",
"radius",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L98-L110 |
1,451 | AguaClara/aguaclara | aguaclara/core/physchem.py | re_rect | def re_rect(FlowRate, Width, DistCenter, Nu, openchannel):
"""Return the Reynolds Number for a rectangular channel."""
#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, openchannel).magnitude
/ (Width * DistCenter * Nu)) | python | 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, openchannel).magnitude
/ (Width * DistCenter * Nu)) | [
"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",
",",
"openchannel",
")",
".",
"magnitude",
"/",
"(",
"Width",
"*",
"DistCenter",
"*",
"Nu",
")",
")"
] | Return the Reynolds Number for a rectangular channel. | [
"Return",
"the",
"Reynolds",
"Number",
"for",
"a",
"rectangular",
"channel",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L121-L128 |
1,452 | AguaClara/aguaclara | aguaclara/core/physchem.py | re_general | def re_general(Vel, Area, PerimWetted, Nu):
"""Return the Reynolds Number for a general cross section."""
#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 | python | 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 | [
"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. | [
"Return",
"the",
"Reynolds",
"Number",
"for",
"a",
"general",
"cross",
"section",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L134-L139 |
1,453 | AguaClara/aguaclara | aguaclara/core/physchem.py | fric | def fric(FlowRate, Diam, Nu, PipeRough):
"""Return the friction factor for pipe flow.
This equation applies to both laminar and turbulent flows.
"""
#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 flow; best for
#Re>3000 and ε/Diam < 0.02
f = (0.25 / (np.log10(PipeRough / (3.7 * Diam)
+ 5.74 / re_pipe(FlowRate, Diam, Nu) ** 0.9
)
) ** 2
)
else:
f = 64 / re_pipe(FlowRate, Diam, Nu)
return f | python | 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 flow; best for
#Re>3000 and ε/Diam < 0.02
f = (0.25 / (np.log10(PipeRough / (3.7 * Diam)
+ 5.74 / re_pipe(FlowRate, Diam, Nu) ** 0.9
)
) ** 2
)
else:
f = 64 / re_pipe(FlowRate, Diam, Nu)
return f | [
"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 flow; best for",
"#Re>3000 and ε/Diam < 0.02",
"f",
"=",
"(",
"0.25",
"/",
"(",
"np",
".",
"log10",
"(",
"PipeRough",
"/",
"(",
"3.7",
"*",
"Diam",
")",
"+",
"5.74",
"/",
"re_pipe",
"(",
"FlowRate",
",",
"Diam",
",",
"Nu",
")",
"**",
"0.9",
")",
")",
"**",
"2",
")",
"else",
":",
"f",
"=",
"64",
"/",
"re_pipe",
"(",
"FlowRate",
",",
"Diam",
",",
"Nu",
")",
"return",
"f"
] | Return the friction factor for pipe flow.
This equation applies to both laminar and turbulent flows. | [
"Return",
"the",
"friction",
"factor",
"for",
"pipe",
"flow",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L143-L161 |
1,454 | AguaClara/aguaclara | aguaclara/core/physchem.py | fric_rect | def fric_rect(FlowRate, Width, DistCenter, Nu, PipeRough, openchannel):
"""Return the friction factor for a rectangular channel."""
#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:
#Swamee-Jain friction factor adapted for rectangular channel.
#Diam = 4*R_h in this case.
return (0.25
/ (np.log10((PipeRough
/ (3.7 * 4
* radius_hydraulic(Width, DistCenter,
openchannel).magnitude
)
)
+ (5.74 / (re_rect(FlowRate, Width, DistCenter,
Nu, openchannel) ** 0.9)
)
)
) ** 2
)
else:
return 64 / re_rect(FlowRate, Width, DistCenter, Nu, openchannel) | python | 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:
#Swamee-Jain friction factor adapted for rectangular channel.
#Diam = 4*R_h in this case.
return (0.25
/ (np.log10((PipeRough
/ (3.7 * 4
* radius_hydraulic(Width, DistCenter,
openchannel).magnitude
)
)
+ (5.74 / (re_rect(FlowRate, Width, DistCenter,
Nu, openchannel) ** 0.9)
)
)
) ** 2
)
else:
return 64 / re_rect(FlowRate, Width, DistCenter, Nu, openchannel) | [
"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",
":",
"#Swamee-Jain friction factor adapted for rectangular channel.",
"#Diam = 4*R_h in this case.",
"return",
"(",
"0.25",
"/",
"(",
"np",
".",
"log10",
"(",
"(",
"PipeRough",
"/",
"(",
"3.7",
"*",
"4",
"*",
"radius_hydraulic",
"(",
"Width",
",",
"DistCenter",
",",
"openchannel",
")",
".",
"magnitude",
")",
")",
"+",
"(",
"5.74",
"/",
"(",
"re_rect",
"(",
"FlowRate",
",",
"Width",
",",
"DistCenter",
",",
"Nu",
",",
"openchannel",
")",
"**",
"0.9",
")",
")",
")",
")",
"**",
"2",
")",
"else",
":",
"return",
"64",
"/",
"re_rect",
"(",
"FlowRate",
",",
"Width",
",",
"DistCenter",
",",
"Nu",
",",
"openchannel",
")"
] | Return the friction factor for a rectangular channel. | [
"Return",
"the",
"friction",
"factor",
"for",
"a",
"rectangular",
"channel",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L166-L188 |
1,455 | AguaClara/aguaclara | aguaclara/core/physchem.py | fric_general | def fric_general(Area, PerimWetted, Vel, Nu, PipeRough):
"""Return the friction factor for a general channel."""
#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 friction factor adapted for any cross-section.
#Diam = 4*R*h
f= (0.25 /
(np.log10((PipeRough
/ (3.7 * 4
* radius_hydraulic_general(Area, PerimWetted).magnitude
)
)
+ (5.74
/ re_general(Vel, Area, PerimWetted, Nu) ** 0.9
)
)
) ** 2
)
else:
f = 64 / re_general(Vel, Area, PerimWetted, Nu)
return f | python | 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 friction factor adapted for any cross-section.
#Diam = 4*R*h
f= (0.25 /
(np.log10((PipeRough
/ (3.7 * 4
* radius_hydraulic_general(Area, PerimWetted).magnitude
)
)
+ (5.74
/ re_general(Vel, Area, PerimWetted, Nu) ** 0.9
)
)
) ** 2
)
else:
f = 64 / re_general(Vel, Area, PerimWetted, Nu)
return f | [
"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 friction factor adapted for any cross-section.",
"#Diam = 4*R*h",
"f",
"=",
"(",
"0.25",
"/",
"(",
"np",
".",
"log10",
"(",
"(",
"PipeRough",
"/",
"(",
"3.7",
"*",
"4",
"*",
"radius_hydraulic_general",
"(",
"Area",
",",
"PerimWetted",
")",
".",
"magnitude",
")",
")",
"+",
"(",
"5.74",
"/",
"re_general",
"(",
"Vel",
",",
"Area",
",",
"PerimWetted",
",",
"Nu",
")",
"**",
"0.9",
")",
")",
")",
"**",
"2",
")",
"else",
":",
"f",
"=",
"64",
"/",
"re_general",
"(",
"Vel",
",",
"Area",
",",
"PerimWetted",
",",
"Nu",
")",
"return",
"f"
] | Return the friction factor for a general channel. | [
"Return",
"the",
"friction",
"factor",
"for",
"a",
"general",
"channel",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L193-L215 |
1,456 | AguaClara/aguaclara | aguaclara/core/physchem.py | headloss | def headloss(FlowRate, Diam, Length, Nu, PipeRough, KMinor):
"""Return the total head loss from major and minor losses in a pipe.
This equation applies to both laminar and turbulent flows.
"""
#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) | python | 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) | [
"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. | [
"Return",
"the",
"total",
"head",
"loss",
"from",
"major",
"and",
"minor",
"losses",
"in",
"a",
"pipe",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L246-L254 |
1,457 | AguaClara/aguaclara | aguaclara/core/physchem.py | headloss_fric_rect | def headloss_fric_rect(FlowRate, Width, DistCenter, Length, Nu, PipeRough, openchannel):
"""Return the major head loss due to wall shear in a rectangular channel.
This equation applies to both laminar and turbulent flows.
"""
#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,
PipeRough, openchannel)
* Length
/ (4 * radius_hydraulic(Width, DistCenter, openchannel).magnitude)
* FlowRate**2
/ (2 * gravity.magnitude * (Width*DistCenter)**2)
) | python | 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,
PipeRough, openchannel)
* Length
/ (4 * radius_hydraulic(Width, DistCenter, openchannel).magnitude)
* FlowRate**2
/ (2 * gravity.magnitude * (Width*DistCenter)**2)
) | [
"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",
",",
"PipeRough",
",",
"openchannel",
")",
"*",
"Length",
"/",
"(",
"4",
"*",
"radius_hydraulic",
"(",
"Width",
",",
"DistCenter",
",",
"openchannel",
")",
".",
"magnitude",
")",
"*",
"FlowRate",
"**",
"2",
"/",
"(",
"2",
"*",
"gravity",
".",
"magnitude",
"*",
"(",
"Width",
"*",
"DistCenter",
")",
"**",
"2",
")",
")"
] | Return the major head loss due to wall shear in a rectangular channel.
This equation applies to both laminar and turbulent flows. | [
"Return",
"the",
"major",
"head",
"loss",
"due",
"to",
"wall",
"shear",
"in",
"a",
"rectangular",
"channel",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L258-L272 |
1,458 | AguaClara/aguaclara | aguaclara/core/physchem.py | headloss_exp_rect | def headloss_exp_rect(FlowRate, Width, DistCenter, KMinor):
"""Return the minor head loss due to expansion in a rectangular channel.
This equation applies to both laminar and turbulent flows.
"""
#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 * (Width*DistCenter)**2)
) | python | 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 * (Width*DistCenter)**2)
) | [
"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",
"*",
"(",
"Width",
"*",
"DistCenter",
")",
"**",
"2",
")",
")"
] | Return the minor head loss due to expansion in a rectangular channel.
This equation applies to both laminar and turbulent flows. | [
"Return",
"the",
"minor",
"head",
"loss",
"due",
"to",
"expansion",
"in",
"a",
"rectangular",
"channel",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L276-L286 |
1,459 | AguaClara/aguaclara | aguaclara/core/physchem.py | headloss_rect | def headloss_rect(FlowRate, Width, DistCenter, Length,
KMinor, Nu, PipeRough, openchannel):
"""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.
"""
#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
+ headloss_fric_rect(FlowRate, Width, DistCenter, Length,
Nu, PipeRough, openchannel).magnitude) | python | 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
+ headloss_fric_rect(FlowRate, Width, DistCenter, Length,
Nu, PipeRough, openchannel).magnitude) | [
"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",
"+",
"headloss_fric_rect",
"(",
"FlowRate",
",",
"Width",
",",
"DistCenter",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
",",
"openchannel",
")",
".",
"magnitude",
")"
] | 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. | [
"Return",
"the",
"total",
"head",
"loss",
"in",
"a",
"rectangular",
"channel",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L290-L301 |
1,460 | AguaClara/aguaclara | aguaclara/core/physchem.py | headloss_fric_general | def headloss_fric_general(Area, PerimWetted, Vel, Length, Nu, PipeRough):
"""Return the major head loss due to wall shear in the general case.
This equation applies to both laminar and turbulent flows.
"""
#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 * radius_hydraulic_general(Area, PerimWetted).magnitude)
* Vel**2 / (2*gravity.magnitude)
) | python | 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 * radius_hydraulic_general(Area, PerimWetted).magnitude)
* Vel**2 / (2*gravity.magnitude)
) | [
"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",
"*",
"radius_hydraulic_general",
"(",
"Area",
",",
"PerimWetted",
")",
".",
"magnitude",
")",
"*",
"Vel",
"**",
"2",
"/",
"(",
"2",
"*",
"gravity",
".",
"magnitude",
")",
")"
] | Return the major head loss due to wall shear in the general case.
This equation applies to both laminar and turbulent flows. | [
"Return",
"the",
"major",
"head",
"loss",
"due",
"to",
"wall",
"shear",
"in",
"the",
"general",
"case",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L305-L316 |
1,461 | AguaClara/aguaclara | aguaclara/core/physchem.py | headloss_exp_general | def headloss_exp_general(Vel, KMinor):
"""Return the minor head loss due to expansion in the general case.
This equation applies to both laminar and turbulent flows.
"""
#Checking input validity
ut.check_range([Vel, ">0", "Velocity"], [KMinor, '>=0', 'K minor'])
return KMinor * Vel**2 / (2*gravity.magnitude) | python | 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) | [
"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. | [
"Return",
"the",
"minor",
"head",
"loss",
"due",
"to",
"expansion",
"in",
"the",
"general",
"case",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L320-L327 |
1,462 | AguaClara/aguaclara | aguaclara/core/physchem.py | headloss_gen | def headloss_gen(Area, Vel, PerimWetted, Length, KMinor, Nu, PipeRough):
"""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.
"""
#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,
Length, Nu, PipeRough).magnitude) | python | 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,
Length, Nu, PipeRough).magnitude) | [
"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",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
")",
".",
"magnitude",
")"
] | 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. | [
"Return",
"the",
"total",
"head",
"lossin",
"the",
"general",
"case",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L331-L341 |
1,463 | AguaClara/aguaclara | aguaclara/core/physchem.py | headloss_manifold | def headloss_manifold(FlowRate, Diam, Length, KMinor, Nu, PipeRough, NumOutlets):
"""Return the total head loss through the manifold."""
#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, KMinor).magnitude
* ((1/3 )
+ (1 / (2*NumOutlets))
+ (1 / (6*NumOutlets**2))
)
) | python | 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, KMinor).magnitude
* ((1/3 )
+ (1 / (2*NumOutlets))
+ (1 / (6*NumOutlets**2))
)
) | [
"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",
",",
"KMinor",
")",
".",
"magnitude",
"*",
"(",
"(",
"1",
"/",
"3",
")",
"+",
"(",
"1",
"/",
"(",
"2",
"*",
"NumOutlets",
")",
")",
"+",
"(",
"1",
"/",
"(",
"6",
"*",
"NumOutlets",
"**",
"2",
")",
")",
")",
")"
] | Return the total head loss through the manifold. | [
"Return",
"the",
"total",
"head",
"loss",
"through",
"the",
"manifold",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L346-L356 |
1,464 | AguaClara/aguaclara | aguaclara/core/physchem.py | flow_orifice | def flow_orifice(Diam, Height, RatioVCOrifice):
"""Return the flow rate of the orifice."""
#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 * Height))
else:
return 0 | python | 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 * Height))
else:
return 0 | [
"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",
"*",
"Height",
")",
")",
"else",
":",
"return",
"0"
] | Return the flow rate of the orifice. | [
"Return",
"the",
"flow",
"rate",
"of",
"the",
"orifice",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L361-L370 |
1,465 | AguaClara/aguaclara | aguaclara/core/physchem.py | flow_orifice_vert | def flow_orifice_vert(Diam, Height, RatioVCOrifice):
"""Return the vertical flow rate of the orifice."""
#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.sqrt(Height - z)
),
- Diam / 2,
min(Diam/2, Height))
return flow_vert[0] * RatioVCOrifice * np.sqrt(2 * gravity.magnitude)
else:
return 0 | python | 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.sqrt(Height - z)
),
- Diam / 2,
min(Diam/2, Height))
return flow_vert[0] * RatioVCOrifice * np.sqrt(2 * gravity.magnitude)
else:
return 0 | [
"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",
".",
"sqrt",
"(",
"Height",
"-",
"z",
")",
")",
",",
"-",
"Diam",
"/",
"2",
",",
"min",
"(",
"Diam",
"/",
"2",
",",
"Height",
")",
")",
"return",
"flow_vert",
"[",
"0",
"]",
"*",
"RatioVCOrifice",
"*",
"np",
".",
"sqrt",
"(",
"2",
"*",
"gravity",
".",
"magnitude",
")",
"else",
":",
"return",
"0"
] | Return the vertical flow rate of the orifice. | [
"Return",
"the",
"vertical",
"flow",
"rate",
"of",
"the",
"orifice",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L376-L388 |
1,466 | AguaClara/aguaclara | aguaclara/core/physchem.py | head_orifice | def head_orifice(Diam, RatioVCOrifice, FlowRate):
"""Return the head of the orifice."""
#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)
)**2
/ (2*gravity.magnitude)
) | python | 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)
)**2
/ (2*gravity.magnitude)
) | [
"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",
")",
")",
"**",
"2",
"/",
"(",
"2",
"*",
"gravity",
".",
"magnitude",
")",
")"
] | Return the head of the orifice. | [
"Return",
"the",
"head",
"of",
"the",
"orifice",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L392-L401 |
1,467 | AguaClara/aguaclara | aguaclara/core/physchem.py | area_orifice | def area_orifice(Height, RatioVCOrifice, FlowRate):
"""Return the area of the orifice."""
#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)) | python | 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)) | [
"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. | [
"Return",
"the",
"area",
"of",
"the",
"orifice",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L405-L410 |
1,468 | AguaClara/aguaclara | aguaclara/core/physchem.py | num_orifices | def num_orifices(FlowPlant, RatioVCOrifice, HeadLossOrifice, DiamOrifice):
"""Return the number of orifices."""
#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
/ area_circle(DiamOrifice).magnitude) | python | 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
/ area_circle(DiamOrifice).magnitude) | [
"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",
"/",
"area_circle",
"(",
"DiamOrifice",
")",
".",
"magnitude",
")"
] | Return the number of orifices. | [
"Return",
"the",
"number",
"of",
"orifices",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L414-L420 |
1,469 | AguaClara/aguaclara | aguaclara/core/physchem.py | flow_hagen | def flow_hagen(Diam, HeadLossFric, Length, Nu):
"""Return the flow rate for laminar flow with only major losses."""
#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 * HeadLossFric / Length | python | 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 * HeadLossFric / Length | [
"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",
"*",
"HeadLossFric",
"/",
"Length"
] | Return the flow rate for laminar flow with only major losses. | [
"Return",
"the",
"flow",
"rate",
"for",
"laminar",
"flow",
"with",
"only",
"major",
"losses",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L436-L442 |
1,470 | AguaClara/aguaclara | aguaclara/core/physchem.py | flow_swamee | def flow_swamee(Diam, HeadLossFric, Length, Nu, PipeRough):
"""Return the flow rate for turbulent flow with only major losses."""
#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 = np.log10(PipeRough / (3.7 * Diam)
+ 2.51 * Nu * np.sqrt(Length / (2 * gravity.magnitude
* HeadLossFric
* Diam**3)
)
)
return ((-np.pi / np.sqrt(2)) * Diam**(5/2) * logterm
* np.sqrt(gravity.magnitude * HeadLossFric / Length)
) | python | 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 = np.log10(PipeRough / (3.7 * Diam)
+ 2.51 * Nu * np.sqrt(Length / (2 * gravity.magnitude
* HeadLossFric
* Diam**3)
)
)
return ((-np.pi / np.sqrt(2)) * Diam**(5/2) * logterm
* np.sqrt(gravity.magnitude * HeadLossFric / Length)
) | [
"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",
"=",
"np",
".",
"log10",
"(",
"PipeRough",
"/",
"(",
"3.7",
"*",
"Diam",
")",
"+",
"2.51",
"*",
"Nu",
"*",
"np",
".",
"sqrt",
"(",
"Length",
"/",
"(",
"2",
"*",
"gravity",
".",
"magnitude",
"*",
"HeadLossFric",
"*",
"Diam",
"**",
"3",
")",
")",
")",
"return",
"(",
"(",
"-",
"np",
".",
"pi",
"/",
"np",
".",
"sqrt",
"(",
"2",
")",
")",
"*",
"Diam",
"**",
"(",
"5",
"/",
"2",
")",
"*",
"logterm",
"*",
"np",
".",
"sqrt",
"(",
"gravity",
".",
"magnitude",
"*",
"HeadLossFric",
"/",
"Length",
")",
")"
] | Return the flow rate for turbulent flow with only major losses. | [
"Return",
"the",
"flow",
"rate",
"for",
"turbulent",
"flow",
"with",
"only",
"major",
"losses",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L446-L460 |
1,471 | AguaClara/aguaclara | aguaclara/core/physchem.py | flow_pipemajor | def flow_pipemajor(Diam, HeadLossFric, Length, Nu, PipeRough):
"""Return the flow rate with only major losses.
This function applies to both laminar and turbulent flows.
"""
#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 FlowHagen
else:
return flow_swamee(Diam, HeadLossFric, Length, Nu, PipeRough).magnitude | python | 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 FlowHagen
else:
return flow_swamee(Diam, HeadLossFric, Length, Nu, PipeRough).magnitude | [
"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",
"FlowHagen",
"else",
":",
"return",
"flow_swamee",
"(",
"Diam",
",",
"HeadLossFric",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
")",
".",
"magnitude"
] | Return the flow rate with only major losses.
This function applies to both laminar and turbulent flows. | [
"Return",
"the",
"flow",
"rate",
"with",
"only",
"major",
"losses",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L465-L476 |
1,472 | AguaClara/aguaclara | aguaclara/core/physchem.py | flow_pipeminor | def flow_pipeminor(Diam, HeadLossExpans, KMinor):
"""Return the flow rate with only minor losses.
This function applies to both laminar and turbulent flows.
"""
#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 * np.sqrt(2 * gravity.magnitude
* HeadLossExpans
/ KMinor)
) | python | 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 * np.sqrt(2 * gravity.magnitude
* HeadLossExpans
/ KMinor)
) | [
"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",
"*",
"np",
".",
"sqrt",
"(",
"2",
"*",
"gravity",
".",
"magnitude",
"*",
"HeadLossExpans",
"/",
"KMinor",
")",
")"
] | Return the flow rate with only minor losses.
This function applies to both laminar and turbulent flows. | [
"Return",
"the",
"flow",
"rate",
"with",
"only",
"minor",
"losses",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L480-L492 |
1,473 | AguaClara/aguaclara | aguaclara/core/physchem.py | flow_pipe | def flow_pipe(Diam, HeadLoss, Length, Nu, PipeRough, KMinor):
"""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.
"""
#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:
FlowRatePrev = 0
err = 1.0
FlowRate = min(flow_pipemajor(Diam, HeadLoss, Length,
Nu, PipeRough).magnitude,
flow_pipeminor(Diam, HeadLoss, KMinor).magnitude
)
while err > 0.01:
FlowRatePrev = FlowRate
HLFricNew = (HeadLoss * headloss_fric(FlowRate, Diam, Length,
Nu, PipeRough).magnitude
/ (headloss_fric(FlowRate, Diam, Length,
Nu, PipeRough).magnitude
+ headloss_exp(FlowRate, Diam, KMinor).magnitude
)
)
FlowRate = flow_pipemajor(Diam, HLFricNew, Length,
Nu, PipeRough).magnitude
if FlowRate == 0:
err = 0.0
else:
err = (abs(FlowRate - FlowRatePrev)
/ ((FlowRate + FlowRatePrev) / 2)
)
return FlowRate | python | 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:
FlowRatePrev = 0
err = 1.0
FlowRate = min(flow_pipemajor(Diam, HeadLoss, Length,
Nu, PipeRough).magnitude,
flow_pipeminor(Diam, HeadLoss, KMinor).magnitude
)
while err > 0.01:
FlowRatePrev = FlowRate
HLFricNew = (HeadLoss * headloss_fric(FlowRate, Diam, Length,
Nu, PipeRough).magnitude
/ (headloss_fric(FlowRate, Diam, Length,
Nu, PipeRough).magnitude
+ headloss_exp(FlowRate, Diam, KMinor).magnitude
)
)
FlowRate = flow_pipemajor(Diam, HLFricNew, Length,
Nu, PipeRough).magnitude
if FlowRate == 0:
err = 0.0
else:
err = (abs(FlowRate - FlowRatePrev)
/ ((FlowRate + FlowRatePrev) / 2)
)
return FlowRate | [
"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",
":",
"FlowRatePrev",
"=",
"0",
"err",
"=",
"1.0",
"FlowRate",
"=",
"min",
"(",
"flow_pipemajor",
"(",
"Diam",
",",
"HeadLoss",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
")",
".",
"magnitude",
",",
"flow_pipeminor",
"(",
"Diam",
",",
"HeadLoss",
",",
"KMinor",
")",
".",
"magnitude",
")",
"while",
"err",
">",
"0.01",
":",
"FlowRatePrev",
"=",
"FlowRate",
"HLFricNew",
"=",
"(",
"HeadLoss",
"*",
"headloss_fric",
"(",
"FlowRate",
",",
"Diam",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
")",
".",
"magnitude",
"/",
"(",
"headloss_fric",
"(",
"FlowRate",
",",
"Diam",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
")",
".",
"magnitude",
"+",
"headloss_exp",
"(",
"FlowRate",
",",
"Diam",
",",
"KMinor",
")",
".",
"magnitude",
")",
")",
"FlowRate",
"=",
"flow_pipemajor",
"(",
"Diam",
",",
"HLFricNew",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
")",
".",
"magnitude",
"if",
"FlowRate",
"==",
"0",
":",
"err",
"=",
"0.0",
"else",
":",
"err",
"=",
"(",
"abs",
"(",
"FlowRate",
"-",
"FlowRatePrev",
")",
"/",
"(",
"(",
"FlowRate",
"+",
"FlowRatePrev",
")",
"/",
"2",
")",
")",
"return",
"FlowRate"
] | 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. | [
"Return",
"the",
"the",
"flow",
"in",
"a",
"straight",
"pipe",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L499-L534 |
1,474 | AguaClara/aguaclara | aguaclara/core/physchem.py | diam_swamee | def diam_swamee(FlowRate, HeadLossFric, Length, Nu, PipeRough):
"""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
flow.
"""
#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"])
a = ((PipeRough ** 1.25)
* ((Length * FlowRate**2)
/ (gravity.magnitude * HeadLossFric)
)**4.75
)
b = (Nu * FlowRate**9.4
* (Length / (gravity.magnitude * HeadLossFric)) ** 5.2
)
return 0.66 * (a+b)**0.04 | python | 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"])
a = ((PipeRough ** 1.25)
* ((Length * FlowRate**2)
/ (gravity.magnitude * HeadLossFric)
)**4.75
)
b = (Nu * FlowRate**9.4
* (Length / (gravity.magnitude * HeadLossFric)) ** 5.2
)
return 0.66 * (a+b)**0.04 | [
"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\"",
"]",
")",
"a",
"=",
"(",
"(",
"PipeRough",
"**",
"1.25",
")",
"*",
"(",
"(",
"Length",
"*",
"FlowRate",
"**",
"2",
")",
"/",
"(",
"gravity",
".",
"magnitude",
"*",
"HeadLossFric",
")",
")",
"**",
"4.75",
")",
"b",
"=",
"(",
"Nu",
"*",
"FlowRate",
"**",
"9.4",
"*",
"(",
"Length",
"/",
"(",
"gravity",
".",
"magnitude",
"*",
"HeadLossFric",
")",
")",
"**",
"5.2",
")",
"return",
"0.66",
"*",
"(",
"a",
"+",
"b",
")",
"**",
"0.04"
] | 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
flow. | [
"Return",
"the",
"inner",
"diameter",
"of",
"a",
"pipe",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L549-L570 |
1,475 | AguaClara/aguaclara | aguaclara/core/physchem.py | diam_pipemajor | def diam_pipemajor(FlowRate, HeadLossFric, Length, Nu, PipeRough):
"""Return the pipe IDiam that would result in given major losses.
This function applies to both laminar and turbulent flow.
"""
#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 DiamLaminar
else:
return diam_swamee(FlowRate, HeadLossFric, Length,
Nu, PipeRough).magnitude | python | 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 DiamLaminar
else:
return diam_swamee(FlowRate, HeadLossFric, Length,
Nu, PipeRough).magnitude | [
"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",
"DiamLaminar",
"else",
":",
"return",
"diam_swamee",
"(",
"FlowRate",
",",
"HeadLossFric",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
")",
".",
"magnitude"
] | Return the pipe IDiam that would result in given major losses.
This function applies to both laminar and turbulent flow. | [
"Return",
"the",
"pipe",
"IDiam",
"that",
"would",
"result",
"in",
"given",
"major",
"losses",
".",
"This",
"function",
"applies",
"to",
"both",
"laminar",
"and",
"turbulent",
"flow",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L575-L586 |
1,476 | AguaClara/aguaclara | aguaclara/core/physchem.py | diam_pipeminor | def diam_pipeminor(FlowRate, HeadLossExpans, KMinor):
"""Return the pipe ID that would result in the given minor losses.
This function applies to both laminar and turbulent flow.
"""
#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.magnitude * HeadLossExpans)) ** (1/4)
) | python | 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.magnitude * HeadLossExpans)) ** (1/4)
) | [
"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",
".",
"magnitude",
"*",
"HeadLossExpans",
")",
")",
"**",
"(",
"1",
"/",
"4",
")",
")"
] | Return the pipe ID that would result in the given minor losses.
This function applies to both laminar and turbulent flow. | [
"Return",
"the",
"pipe",
"ID",
"that",
"would",
"result",
"in",
"the",
"given",
"minor",
"losses",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L589-L599 |
1,477 | AguaClara/aguaclara | aguaclara/core/physchem.py | diam_pipe | def diam_pipe(FlowRate, HeadLoss, Length, Nu, PipeRough, KMinor):
"""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.
"""
#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:
Diam = max(diam_pipemajor(FlowRate, HeadLoss,
Length, Nu, PipeRough).magnitude,
diam_pipeminor(FlowRate, HeadLoss, KMinor).magnitude)
err = 1.00
while err > 0.001:
DiamPrev = Diam
HLFricNew = (HeadLoss * headloss_fric(FlowRate, Diam, Length,
Nu, PipeRough
).magnitude
/ (headloss_fric(FlowRate, Diam, Length,
Nu, PipeRough
).magnitude
+ headloss_exp(FlowRate,
Diam, KMinor
).magnitude
)
)
Diam = diam_pipemajor(FlowRate, HLFricNew, Length, Nu, PipeRough
).magnitude
err = abs(Diam - DiamPrev) / ((Diam + DiamPrev) / 2)
return Diam | python | 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:
Diam = max(diam_pipemajor(FlowRate, HeadLoss,
Length, Nu, PipeRough).magnitude,
diam_pipeminor(FlowRate, HeadLoss, KMinor).magnitude)
err = 1.00
while err > 0.001:
DiamPrev = Diam
HLFricNew = (HeadLoss * headloss_fric(FlowRate, Diam, Length,
Nu, PipeRough
).magnitude
/ (headloss_fric(FlowRate, Diam, Length,
Nu, PipeRough
).magnitude
+ headloss_exp(FlowRate,
Diam, KMinor
).magnitude
)
)
Diam = diam_pipemajor(FlowRate, HLFricNew, Length, Nu, PipeRough
).magnitude
err = abs(Diam - DiamPrev) / ((Diam + DiamPrev) / 2)
return Diam | [
"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",
":",
"Diam",
"=",
"max",
"(",
"diam_pipemajor",
"(",
"FlowRate",
",",
"HeadLoss",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
")",
".",
"magnitude",
",",
"diam_pipeminor",
"(",
"FlowRate",
",",
"HeadLoss",
",",
"KMinor",
")",
".",
"magnitude",
")",
"err",
"=",
"1.00",
"while",
"err",
">",
"0.001",
":",
"DiamPrev",
"=",
"Diam",
"HLFricNew",
"=",
"(",
"HeadLoss",
"*",
"headloss_fric",
"(",
"FlowRate",
",",
"Diam",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
")",
".",
"magnitude",
"/",
"(",
"headloss_fric",
"(",
"FlowRate",
",",
"Diam",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
")",
".",
"magnitude",
"+",
"headloss_exp",
"(",
"FlowRate",
",",
"Diam",
",",
"KMinor",
")",
".",
"magnitude",
")",
")",
"Diam",
"=",
"diam_pipemajor",
"(",
"FlowRate",
",",
"HLFricNew",
",",
"Length",
",",
"Nu",
",",
"PipeRough",
")",
".",
"magnitude",
"err",
"=",
"abs",
"(",
"Diam",
"-",
"DiamPrev",
")",
"/",
"(",
"(",
"Diam",
"+",
"DiamPrev",
")",
"/",
"2",
")",
"return",
"Diam"
] | 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. | [
"Return",
"the",
"pipe",
"ID",
"that",
"would",
"result",
"in",
"the",
"given",
"total",
"head",
"loss",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L604-L636 |
1,478 | AguaClara/aguaclara | aguaclara/core/physchem.py | width_rect_weir | def width_rect_weir(FlowRate, Height):
"""Return the width of a rectangular weir."""
#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))
) | python | 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))
) | [
"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. | [
"Return",
"the",
"width",
"of",
"a",
"rectangular",
"weir",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L640-L646 |
1,479 | AguaClara/aguaclara | aguaclara/core/physchem.py | headloss_weir | def headloss_weir(FlowRate, Width):
"""Return the headloss of a weir."""
#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)) | python | 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)) | [
"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. | [
"Return",
"the",
"headloss",
"of",
"a",
"weir",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L653-L659 |
1,480 | AguaClara/aguaclara | aguaclara/core/physchem.py | flow_rect_weir | def flow_rect_weir(Height, Width):
"""Return the flow of a rectangular weir."""
#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) | python | 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) | [
"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. | [
"Return",
"the",
"flow",
"of",
"a",
"rectangular",
"weir",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L663-L669 |
1,481 | AguaClara/aguaclara | aguaclara/core/physchem.py | height_water_critical | def height_water_critical(FlowRate, Width):
"""Return the critical local water depth."""
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Width, ">0", "Width"])
return (FlowRate / (Width * np.sqrt(gravity.magnitude))) ** (2/3) | python | 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) | [
"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. | [
"Return",
"the",
"critical",
"local",
"water",
"depth",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L673-L677 |
1,482 | AguaClara/aguaclara | aguaclara/core/physchem.py | vel_horizontal | def vel_horizontal(HeightWaterCritical):
"""Return the horizontal velocity."""
#Checking input validity
ut.check_range([HeightWaterCritical, ">0", "Critical height of water"])
return np.sqrt(gravity.magnitude * HeightWaterCritical) | python | def vel_horizontal(HeightWaterCritical):
#Checking input validity
ut.check_range([HeightWaterCritical, ">0", "Critical height of water"])
return np.sqrt(gravity.magnitude * HeightWaterCritical) | [
"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. | [
"Return",
"the",
"horizontal",
"velocity",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L681-L685 |
1,483 | AguaClara/aguaclara | aguaclara/core/physchem.py | headloss_kozeny | def headloss_kozeny(Length, Diam, Vel, Porosity, Nu):
"""Return the Carmen Kozeny Sand Bed head loss."""
#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
/ gravity.magnitude * (1-Porosity)**2
/ Porosity**3 * 36 * Vel
/ Diam ** 2) | python | 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
/ gravity.magnitude * (1-Porosity)**2
/ Porosity**3 * 36 * Vel
/ Diam ** 2) | [
"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",
"/",
"gravity",
".",
"magnitude",
"*",
"(",
"1",
"-",
"Porosity",
")",
"**",
"2",
"/",
"Porosity",
"**",
"3",
"*",
"36",
"*",
"Vel",
"/",
"Diam",
"**",
"2",
")"
] | Return the Carmen Kozeny Sand Bed head loss. | [
"Return",
"the",
"Carmen",
"Kozeny",
"Sand",
"Bed",
"head",
"loss",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L689-L698 |
1,484 | AguaClara/aguaclara | aguaclara/research/peristaltic_pump.py | ID_colored_tube | def ID_colored_tube(color):
"""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 aguaclara.core.units import unit_registry as u
>>> ID_colored_tube("yellow-blue")
<Quantity(1.52, 'millimeter')>
>>> ID_colored_tube("orange-yellow")
<Quantity(0.51, 'millimeter')>
>>> ID_colored_tube("purple-white")
<Quantity(2.79, 'millimeter')>
"""
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 | python | 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 | [
"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 aguaclara.core.units import unit_registry as u
>>> ID_colored_tube("yellow-blue")
<Quantity(1.52, 'millimeter')>
>>> ID_colored_tube("orange-yellow")
<Quantity(0.51, 'millimeter')>
>>> ID_colored_tube("purple-white")
<Quantity(2.79, 'millimeter')> | [
"Look",
"up",
"the",
"inner",
"diameter",
"of",
"Ismatec",
"3",
"-",
"stop",
"tubing",
"given",
"its",
"color",
"code",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/peristaltic_pump.py#L51-L75 |
1,485 | AguaClara/aguaclara | aguaclara/research/peristaltic_pump.py | flow_rate | def flow_rate(vol_per_rev, rpm):
"""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
:return: Flow rate of the pump (mL/s)
:rtype: float
:Examples:
>>> from aguaclara.research.peristaltic_pump import flow_rate
>>> from aguaclara.core.units import unit_registry as u
>>> flow_rate(3*u.mL/u.rev, 5*u.rev/u.min)
<Quantity(0.25, 'milliliter / second')>
"""
return (vol_per_rev * rpm).to(u.mL/u.s) | python | def flow_rate(vol_per_rev, rpm):
return (vol_per_rev * rpm).to(u.mL/u.s) | [
"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
:return: Flow rate of the pump (mL/s)
:rtype: float
:Examples:
>>> from aguaclara.research.peristaltic_pump import flow_rate
>>> from aguaclara.core.units import unit_registry as u
>>> flow_rate(3*u.mL/u.rev, 5*u.rev/u.min)
<Quantity(0.25, 'milliliter / second')> | [
"Return",
"the",
"flow",
"rate",
"from",
"a",
"pump",
"given",
"the",
"volume",
"of",
"fluid",
"pumped",
"per",
"revolution",
"and",
"the",
"desired",
"pump",
"speed",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/peristaltic_pump.py#L104-L123 |
1,486 | AguaClara/aguaclara | aguaclara/core/head_loss.py | k_value_orifice | def k_value_orifice(pipe_id, orifice_id, orifice_l, q,
nu=con.WATER_NU):
"""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 viscosity of the fluid. Default: room
temperature water (1 * 10**-6 * m**2/s)
Returns:
k-value at the orifice.
"""
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 Reynolds number.
orifice_type = _get_orifice_type(orifice_l, orifice_id)
if orifice_type == 'thin':
return _k_value_thin_sharp_orifice(pipe_id, orifice_id, re)
elif orifice_type == 'thick':
return _k_value_thick_orifice(pipe_id, orifice_id, orifice_l, re)
elif orifice_type == 'oversize':
return k_value_reduction(pipe_id, orifice_id, q) \
+ k_value_expansion(orifice_id, pipe_id, q) | python | 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 Reynolds number.
orifice_type = _get_orifice_type(orifice_l, orifice_id)
if orifice_type == 'thin':
return _k_value_thin_sharp_orifice(pipe_id, orifice_id, re)
elif orifice_type == 'thick':
return _k_value_thick_orifice(pipe_id, orifice_id, orifice_l, re)
elif orifice_type == 'oversize':
return k_value_reduction(pipe_id, orifice_id, q) \
+ k_value_expansion(orifice_id, pipe_id, q) | [
"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 Reynolds number.",
"orifice_type",
"=",
"_get_orifice_type",
"(",
"orifice_l",
",",
"orifice_id",
")",
"if",
"orifice_type",
"==",
"'thin'",
":",
"return",
"_k_value_thin_sharp_orifice",
"(",
"pipe_id",
",",
"orifice_id",
",",
"re",
")",
"elif",
"orifice_type",
"==",
"'thick'",
":",
"return",
"_k_value_thick_orifice",
"(",
"pipe_id",
",",
"orifice_id",
",",
"orifice_l",
",",
"re",
")",
"elif",
"orifice_type",
"==",
"'oversize'",
":",
"return",
"k_value_reduction",
"(",
"pipe_id",
",",
"orifice_id",
",",
"q",
")",
"+",
"k_value_expansion",
"(",
"orifice_id",
",",
"pipe_id",
",",
"q",
")"
] | 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 viscosity of the fluid. Default: room
temperature water (1 * 10**-6 * m**2/s)
Returns:
k-value at the orifice. | [
"Calculates",
"the",
"minor",
"loss",
"coefficient",
"of",
"an",
"orifice",
"plate",
"in",
"a",
"pipe",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/head_loss.py#L123-L155 |
1,487 | AguaClara/aguaclara | aguaclara/core/head_loss.py | _k_value_square_reduction | def _k_value_square_reduction(ent_pipe_id, exit_pipe_id, re, f):
"""Returns the minor loss coefficient for a square reducer.
Parameters:
ent_pipe_id: Entrance pipe's inner diameter.
exit_pipe_id: Exit pipe's inner diameter.
re: Reynold's number.
f: Darcy friction factor.
"""
if re < 2500:
return (1.2 + (160 / re)) * ((ent_pipe_id / exit_pipe_id) ** 4)
else:
return (0.6 + 0.48 * f) * (ent_pipe_id / exit_pipe_id) ** 2\
* ((ent_pipe_id / exit_pipe_id) ** 2 - 1) | python | def _k_value_square_reduction(ent_pipe_id, exit_pipe_id, re, f):
if re < 2500:
return (1.2 + (160 / re)) * ((ent_pipe_id / exit_pipe_id) ** 4)
else:
return (0.6 + 0.48 * f) * (ent_pipe_id / exit_pipe_id) ** 2\
* ((ent_pipe_id / exit_pipe_id) ** 2 - 1) | [
"def",
"_k_value_square_reduction",
"(",
"ent_pipe_id",
",",
"exit_pipe_id",
",",
"re",
",",
"f",
")",
":",
"if",
"re",
"<",
"2500",
":",
"return",
"(",
"1.2",
"+",
"(",
"160",
"/",
"re",
")",
")",
"*",
"(",
"(",
"ent_pipe_id",
"/",
"exit_pipe_id",
")",
"**",
"4",
")",
"else",
":",
"return",
"(",
"0.6",
"+",
"0.48",
"*",
"f",
")",
"*",
"(",
"ent_pipe_id",
"/",
"exit_pipe_id",
")",
"**",
"2",
"*",
"(",
"(",
"ent_pipe_id",
"/",
"exit_pipe_id",
")",
"**",
"2",
"-",
"1",
")"
] | Returns the minor loss coefficient for a square reducer.
Parameters:
ent_pipe_id: Entrance pipe's inner diameter.
exit_pipe_id: Exit pipe's inner diameter.
re: Reynold's number.
f: Darcy friction factor. | [
"Returns",
"the",
"minor",
"loss",
"coefficient",
"for",
"a",
"square",
"reducer",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/head_loss.py#L158-L172 |
1,488 | AguaClara/aguaclara | aguaclara/core/head_loss.py | _k_value_tapered_reduction | def _k_value_tapered_reduction(ent_pipe_id, exit_pipe_id, fitting_angle, re, f):
"""Returns the minor loss coefficient for a tapered reducer.
Parameters:
ent_pipe_id: Entrance pipe's inner diameter.
exit_pipe_id: Exit pipe's inner diameter.
fitting_angle: Fitting angle between entrance and exit pipes.
re: Reynold's number.
f: Darcy friction factor.
"""
k_value_square_reduction = _k_value_square_reduction(ent_pipe_id, exit_pipe_id,
re, f)
if 45 < fitting_angle <= 180:
return k_value_square_reduction * np.sqrt(np.sin(fitting_angle / 2))
elif 0 < fitting_angle <= 45:
return k_value_square_reduction * 1.6 * np.sin(fitting_angle / 2)
else:
raise ValueError('k_value_tapered_reduction: The reducer angle ('
+ fitting_angle + ') cannot be outside of [0,180].') | python | def _k_value_tapered_reduction(ent_pipe_id, exit_pipe_id, fitting_angle, re, f):
k_value_square_reduction = _k_value_square_reduction(ent_pipe_id, exit_pipe_id,
re, f)
if 45 < fitting_angle <= 180:
return k_value_square_reduction * np.sqrt(np.sin(fitting_angle / 2))
elif 0 < fitting_angle <= 45:
return k_value_square_reduction * 1.6 * np.sin(fitting_angle / 2)
else:
raise ValueError('k_value_tapered_reduction: The reducer angle ('
+ fitting_angle + ') cannot be outside of [0,180].') | [
"def",
"_k_value_tapered_reduction",
"(",
"ent_pipe_id",
",",
"exit_pipe_id",
",",
"fitting_angle",
",",
"re",
",",
"f",
")",
":",
"k_value_square_reduction",
"=",
"_k_value_square_reduction",
"(",
"ent_pipe_id",
",",
"exit_pipe_id",
",",
"re",
",",
"f",
")",
"if",
"45",
"<",
"fitting_angle",
"<=",
"180",
":",
"return",
"k_value_square_reduction",
"*",
"np",
".",
"sqrt",
"(",
"np",
".",
"sin",
"(",
"fitting_angle",
"/",
"2",
")",
")",
"elif",
"0",
"<",
"fitting_angle",
"<=",
"45",
":",
"return",
"k_value_square_reduction",
"*",
"1.6",
"*",
"np",
".",
"sin",
"(",
"fitting_angle",
"/",
"2",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'k_value_tapered_reduction: The reducer angle ('",
"+",
"fitting_angle",
"+",
"') cannot be outside of [0,180].'",
")"
] | Returns the minor loss coefficient for a tapered reducer.
Parameters:
ent_pipe_id: Entrance pipe's inner diameter.
exit_pipe_id: Exit pipe's inner diameter.
fitting_angle: Fitting angle between entrance and exit pipes.
re: Reynold's number.
f: Darcy friction factor. | [
"Returns",
"the",
"minor",
"loss",
"coefficient",
"for",
"a",
"tapered",
"reducer",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/head_loss.py#L175-L195 |
1,489 | AguaClara/aguaclara | aguaclara/unit_process_design/ent_tank.py | drain_OD | def drain_OD(q_plant, T, depth_end, SDR):
"""Return the nominal diameter of the entrance tank drain pipe. Depth at the
end of the flocculator is used for headloss and length calculation inputs in
the diam_pipe calculation.
Parameters
----------
q_plant: float
Plant flow rate
T: float
Design temperature
depth_end: float
The depth of water at the end of the flocculator
SDR: float
Standard dimension ratio
Returns
-------
float
?
Examples
--------
>>> from aguaclara.play import*
??
"""
nu = pc.viscosity_kinematic(T)
K_minor = con.PIPE_ENTRANCE_K_MINOR + con.PIPE_EXIT_K_MINOR + con.EL90_K_MINOR
drain_ID = pc.diam_pipe(q_plant, depth_end, depth_end, nu, mat.PVC_PIPE_ROUGH, K_minor)
drain_ND = pipe.SDR_available_ND(drain_ID, SDR)
return pipe.OD(drain_ND).magnitude | python | def drain_OD(q_plant, T, depth_end, SDR):
nu = pc.viscosity_kinematic(T)
K_minor = con.PIPE_ENTRANCE_K_MINOR + con.PIPE_EXIT_K_MINOR + con.EL90_K_MINOR
drain_ID = pc.diam_pipe(q_plant, depth_end, depth_end, nu, mat.PVC_PIPE_ROUGH, K_minor)
drain_ND = pipe.SDR_available_ND(drain_ID, SDR)
return pipe.OD(drain_ND).magnitude | [
"def",
"drain_OD",
"(",
"q_plant",
",",
"T",
",",
"depth_end",
",",
"SDR",
")",
":",
"nu",
"=",
"pc",
".",
"viscosity_kinematic",
"(",
"T",
")",
"K_minor",
"=",
"con",
".",
"PIPE_ENTRANCE_K_MINOR",
"+",
"con",
".",
"PIPE_EXIT_K_MINOR",
"+",
"con",
".",
"EL90_K_MINOR",
"drain_ID",
"=",
"pc",
".",
"diam_pipe",
"(",
"q_plant",
",",
"depth_end",
",",
"depth_end",
",",
"nu",
",",
"mat",
".",
"PVC_PIPE_ROUGH",
",",
"K_minor",
")",
"drain_ND",
"=",
"pipe",
".",
"SDR_available_ND",
"(",
"drain_ID",
",",
"SDR",
")",
"return",
"pipe",
".",
"OD",
"(",
"drain_ND",
")",
".",
"magnitude"
] | Return the nominal diameter of the entrance tank drain pipe. Depth at the
end of the flocculator is used for headloss and length calculation inputs in
the diam_pipe calculation.
Parameters
----------
q_plant: float
Plant flow rate
T: float
Design temperature
depth_end: float
The depth of water at the end of the flocculator
SDR: float
Standard dimension ratio
Returns
-------
float
?
Examples
--------
>>> from aguaclara.play import*
?? | [
"Return",
"the",
"nominal",
"diameter",
"of",
"the",
"entrance",
"tank",
"drain",
"pipe",
".",
"Depth",
"at",
"the",
"end",
"of",
"the",
"flocculator",
"is",
"used",
"for",
"headloss",
"and",
"length",
"calculation",
"inputs",
"in",
"the",
"diam_pipe",
"calculation",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/unit_process_design/ent_tank.py#L9-L42 |
1,490 | AguaClara/aguaclara | aguaclara/unit_process_design/ent_tank.py | num_plates_ET | def num_plates_ET(q_plant, W_chan):
"""Return the number of plates in the entrance tank.
This number minimizes the total length of the plate settler unit.
Parameters
----------
q_plant: float
Plant flow rate
W_chan: float
Width of channel
Returns
-------
float
?
Examples
--------
>>> from aguaclara.play import*
>>> num_plates_ET(20*u.L/u.s,2*u.m)
1.0
"""
num_plates = np.ceil(np.sqrt(q_plant / (design.ent_tank.CENTER_PLATE_DIST.magnitude
* W_chan * design.ent_tank.CAPTURE_BOD_VEL.magnitude * np.sin(
design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude))))
return num_plates | python | def num_plates_ET(q_plant, W_chan):
num_plates = np.ceil(np.sqrt(q_plant / (design.ent_tank.CENTER_PLATE_DIST.magnitude
* W_chan * design.ent_tank.CAPTURE_BOD_VEL.magnitude * np.sin(
design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude))))
return num_plates | [
"def",
"num_plates_ET",
"(",
"q_plant",
",",
"W_chan",
")",
":",
"num_plates",
"=",
"np",
".",
"ceil",
"(",
"np",
".",
"sqrt",
"(",
"q_plant",
"/",
"(",
"design",
".",
"ent_tank",
".",
"CENTER_PLATE_DIST",
".",
"magnitude",
"*",
"W_chan",
"*",
"design",
".",
"ent_tank",
".",
"CAPTURE_BOD_VEL",
".",
"magnitude",
"*",
"np",
".",
"sin",
"(",
"design",
".",
"ent_tank",
".",
"PLATE_ANGLE",
".",
"to",
"(",
"u",
".",
"rad",
")",
".",
"magnitude",
")",
")",
")",
")",
"return",
"num_plates"
] | Return the number of plates in the entrance tank.
This number minimizes the total length of the plate settler unit.
Parameters
----------
q_plant: float
Plant flow rate
W_chan: float
Width of channel
Returns
-------
float
?
Examples
--------
>>> from aguaclara.play import*
>>> num_plates_ET(20*u.L/u.s,2*u.m)
1.0 | [
"Return",
"the",
"number",
"of",
"plates",
"in",
"the",
"entrance",
"tank",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/unit_process_design/ent_tank.py#L45-L72 |
1,491 | AguaClara/aguaclara | aguaclara/unit_process_design/ent_tank.py | L_plate_ET | def L_plate_ET(q_plant, W_chan):
"""Return the length of the plates in the entrance tank.
Parameters
----------
q_plant: float
Plant flow rate
W_chan: float
Width of channel
Returns
-------
float
?
Examples
--------
>>> from aguaclara.play import*
>>> L_plate_ET(20*u.L/u.s,2*u.m)
0.00194
"""
L_plate = (q_plant / (num_plates_ET(q_plant, W_chan) * W_chan *
design.ent_tank.CAPTURE_BOD_VEL.magnitude * np.cos(
design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude)))
- (design.ent_tank.PLATE_S.magnitude * np.tan(design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude))
return L_plate | python | def L_plate_ET(q_plant, W_chan):
L_plate = (q_plant / (num_plates_ET(q_plant, W_chan) * W_chan *
design.ent_tank.CAPTURE_BOD_VEL.magnitude * np.cos(
design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude)))
- (design.ent_tank.PLATE_S.magnitude * np.tan(design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude))
return L_plate | [
"def",
"L_plate_ET",
"(",
"q_plant",
",",
"W_chan",
")",
":",
"L_plate",
"=",
"(",
"q_plant",
"/",
"(",
"num_plates_ET",
"(",
"q_plant",
",",
"W_chan",
")",
"*",
"W_chan",
"*",
"design",
".",
"ent_tank",
".",
"CAPTURE_BOD_VEL",
".",
"magnitude",
"*",
"np",
".",
"cos",
"(",
"design",
".",
"ent_tank",
".",
"PLATE_ANGLE",
".",
"to",
"(",
"u",
".",
"rad",
")",
".",
"magnitude",
")",
")",
")",
"-",
"(",
"design",
".",
"ent_tank",
".",
"PLATE_S",
".",
"magnitude",
"*",
"np",
".",
"tan",
"(",
"design",
".",
"ent_tank",
".",
"PLATE_ANGLE",
".",
"to",
"(",
"u",
".",
"rad",
")",
".",
"magnitude",
")",
")",
"return",
"L_plate"
] | Return the length of the plates in the entrance tank.
Parameters
----------
q_plant: float
Plant flow rate
W_chan: float
Width of channel
Returns
-------
float
?
Examples
--------
>>> from aguaclara.play import*
>>> L_plate_ET(20*u.L/u.s,2*u.m)
0.00194 | [
"Return",
"the",
"length",
"of",
"the",
"plates",
"in",
"the",
"entrance",
"tank",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/unit_process_design/ent_tank.py#L75-L101 |
1,492 | AguaClara/aguaclara | aguaclara/research/environmental_processes_analysis.py | Gran | def Gran(data_file_path):
"""Extract the data from a ProCoDA Gran plot file. The file must be the original tab delimited file.
:param data_file_path: The path to the file. If the file is in the working directory, then the file name is sufficient.
:return: collection of
* **V_titrant** (*float*) - Volume of titrant in mL
* **ph_data** (*numpy.array*) - pH of the sample
* **V_sample** (*float*) - Volume of the original sample that was titrated in mL
* **Normality_titrant** (*float*) - Normality of the acid used to titrate the sample in mole/L
* **V_equivalent** (*float*) - Volume of acid required to consume all of the ANC in mL
* **ANC** (*float*) - Acid Neutralizing Capacity of the sample in mole/L
"""
df = pd.read_csv(data_file_path, delimiter='\t', header=5)
V_t = np.array(pd.to_numeric(df.iloc[0:, 0]))*u.mL
pH = np.array(pd.to_numeric(df.iloc[0:, 1]))
df = pd.read_csv(data_file_path, delimiter='\t', header=-1, nrows=5)
V_S = pd.to_numeric(df.iloc[0, 1])*u.mL
N_t = pd.to_numeric(df.iloc[1, 1])*u.mole/u.L
V_eq = pd.to_numeric(df.iloc[2, 1])*u.mL
ANC_sample = pd.to_numeric(df.iloc[3, 1])*u.mole/u.L
Gran_collection = collections.namedtuple('Gran_results', 'V_titrant ph_data V_sample Normality_titrant V_equivalent ANC')
Gran = Gran_collection(V_titrant=V_t, ph_data=pH, V_sample=V_S,
Normality_titrant=N_t, V_equivalent=V_eq,
ANC=ANC_sample)
return Gran | python | def Gran(data_file_path):
df = pd.read_csv(data_file_path, delimiter='\t', header=5)
V_t = np.array(pd.to_numeric(df.iloc[0:, 0]))*u.mL
pH = np.array(pd.to_numeric(df.iloc[0:, 1]))
df = pd.read_csv(data_file_path, delimiter='\t', header=-1, nrows=5)
V_S = pd.to_numeric(df.iloc[0, 1])*u.mL
N_t = pd.to_numeric(df.iloc[1, 1])*u.mole/u.L
V_eq = pd.to_numeric(df.iloc[2, 1])*u.mL
ANC_sample = pd.to_numeric(df.iloc[3, 1])*u.mole/u.L
Gran_collection = collections.namedtuple('Gran_results', 'V_titrant ph_data V_sample Normality_titrant V_equivalent ANC')
Gran = Gran_collection(V_titrant=V_t, ph_data=pH, V_sample=V_S,
Normality_titrant=N_t, V_equivalent=V_eq,
ANC=ANC_sample)
return Gran | [
"def",
"Gran",
"(",
"data_file_path",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"data_file_path",
",",
"delimiter",
"=",
"'\\t'",
",",
"header",
"=",
"5",
")",
"V_t",
"=",
"np",
".",
"array",
"(",
"pd",
".",
"to_numeric",
"(",
"df",
".",
"iloc",
"[",
"0",
":",
",",
"0",
"]",
")",
")",
"*",
"u",
".",
"mL",
"pH",
"=",
"np",
".",
"array",
"(",
"pd",
".",
"to_numeric",
"(",
"df",
".",
"iloc",
"[",
"0",
":",
",",
"1",
"]",
")",
")",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"data_file_path",
",",
"delimiter",
"=",
"'\\t'",
",",
"header",
"=",
"-",
"1",
",",
"nrows",
"=",
"5",
")",
"V_S",
"=",
"pd",
".",
"to_numeric",
"(",
"df",
".",
"iloc",
"[",
"0",
",",
"1",
"]",
")",
"*",
"u",
".",
"mL",
"N_t",
"=",
"pd",
".",
"to_numeric",
"(",
"df",
".",
"iloc",
"[",
"1",
",",
"1",
"]",
")",
"*",
"u",
".",
"mole",
"/",
"u",
".",
"L",
"V_eq",
"=",
"pd",
".",
"to_numeric",
"(",
"df",
".",
"iloc",
"[",
"2",
",",
"1",
"]",
")",
"*",
"u",
".",
"mL",
"ANC_sample",
"=",
"pd",
".",
"to_numeric",
"(",
"df",
".",
"iloc",
"[",
"3",
",",
"1",
"]",
")",
"*",
"u",
".",
"mole",
"/",
"u",
".",
"L",
"Gran_collection",
"=",
"collections",
".",
"namedtuple",
"(",
"'Gran_results'",
",",
"'V_titrant ph_data V_sample Normality_titrant V_equivalent ANC'",
")",
"Gran",
"=",
"Gran_collection",
"(",
"V_titrant",
"=",
"V_t",
",",
"ph_data",
"=",
"pH",
",",
"V_sample",
"=",
"V_S",
",",
"Normality_titrant",
"=",
"N_t",
",",
"V_equivalent",
"=",
"V_eq",
",",
"ANC",
"=",
"ANC_sample",
")",
"return",
"Gran"
] | Extract the data from a ProCoDA Gran plot file. The file must be the original tab delimited file.
:param data_file_path: The path to the file. If the file is in the working directory, then the file name is sufficient.
:return: collection of
* **V_titrant** (*float*) - Volume of titrant in mL
* **ph_data** (*numpy.array*) - pH of the sample
* **V_sample** (*float*) - Volume of the original sample that was titrated in mL
* **Normality_titrant** (*float*) - Normality of the acid used to titrate the sample in mole/L
* **V_equivalent** (*float*) - Volume of acid required to consume all of the ANC in mL
* **ANC** (*float*) - Acid Neutralizing Capacity of the sample in mole/L | [
"Extract",
"the",
"data",
"from",
"a",
"ProCoDA",
"Gran",
"plot",
"file",
".",
"The",
"file",
"must",
"be",
"the",
"original",
"tab",
"delimited",
"file",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L206-L232 |
1,493 | AguaClara/aguaclara | aguaclara/research/environmental_processes_analysis.py | E_CMFR_N | def E_CMFR_N(t, N):
"""Calculate a dimensionless measure of the output tracer concentration
from a spike input to a series of completely mixed flow reactors.
:param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR.
:type t: float or numpy.array
:param N: The number of completely mixed flow reactors (CMFRS) in series. Must be greater than 1.
:type N: int
:return: Dimensionless measure of the output tracer concentration (concentration * volume of 1 CMFR) / (mass of tracer)
:rtype: float
:Examples:
>>> from aguaclara.research.environmental_processes_analysis import E_CMFR_N
>>> round(E_CMFR_N(0.5, 3), 7)
0.7530643
>>> round(E_CMFR_N(0.1, 1), 7)
0.9048374
"""
return (N**N)/special.gamma(N) * (t**(N-1))*np.exp(-N*t) | python | def E_CMFR_N(t, N):
return (N**N)/special.gamma(N) * (t**(N-1))*np.exp(-N*t) | [
"def",
"E_CMFR_N",
"(",
"t",
",",
"N",
")",
":",
"return",
"(",
"N",
"**",
"N",
")",
"/",
"special",
".",
"gamma",
"(",
"N",
")",
"*",
"(",
"t",
"**",
"(",
"N",
"-",
"1",
")",
")",
"*",
"np",
".",
"exp",
"(",
"-",
"N",
"*",
"t",
")"
] | Calculate a dimensionless measure of the output tracer concentration
from a spike input to a series of completely mixed flow reactors.
:param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR.
:type t: float or numpy.array
:param N: The number of completely mixed flow reactors (CMFRS) in series. Must be greater than 1.
:type N: int
:return: Dimensionless measure of the output tracer concentration (concentration * volume of 1 CMFR) / (mass of tracer)
:rtype: float
:Examples:
>>> from aguaclara.research.environmental_processes_analysis import E_CMFR_N
>>> round(E_CMFR_N(0.5, 3), 7)
0.7530643
>>> round(E_CMFR_N(0.1, 1), 7)
0.9048374 | [
"Calculate",
"a",
"dimensionless",
"measure",
"of",
"the",
"output",
"tracer",
"concentration",
"from",
"a",
"spike",
"input",
"to",
"a",
"series",
"of",
"completely",
"mixed",
"flow",
"reactors",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L266-L286 |
1,494 | AguaClara/aguaclara | aguaclara/research/environmental_processes_analysis.py | E_Advective_Dispersion | def E_Advective_Dispersion(t, Pe):
"""Calculate a dimensionless measure of the output tracer concentration from
a spike input to reactor with advection and dispersion.
:param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR.
:type t: float or numpy.array
:param Pe: The ratio of advection to dispersion ((mean fluid velocity)/(Dispersion*flow path length))
:type Pe: float
:return: dimensionless measure of the output tracer concentration (concentration * volume of reactor) / (mass of tracer)
:rtype: float
:Examples:
>>> from aguaclara.research.environmental_processes_analysis import E_Advective_Dispersion
>>> round(E_Advective_Dispersion(0.5, 5), 7)
0.4774864
"""
# replace any times at zero with a number VERY close to zero to avoid
# divide by zero errors
if isinstance(t, list):
t[t == 0] = 10**(-10)
return (Pe/(4*np.pi*t))**(0.5)*np.exp((-Pe*((1-t)**2))/(4*t)) | python | def E_Advective_Dispersion(t, Pe):
# replace any times at zero with a number VERY close to zero to avoid
# divide by zero errors
if isinstance(t, list):
t[t == 0] = 10**(-10)
return (Pe/(4*np.pi*t))**(0.5)*np.exp((-Pe*((1-t)**2))/(4*t)) | [
"def",
"E_Advective_Dispersion",
"(",
"t",
",",
"Pe",
")",
":",
"# replace any times at zero with a number VERY close to zero to avoid",
"# divide by zero errors",
"if",
"isinstance",
"(",
"t",
",",
"list",
")",
":",
"t",
"[",
"t",
"==",
"0",
"]",
"=",
"10",
"**",
"(",
"-",
"10",
")",
"return",
"(",
"Pe",
"/",
"(",
"4",
"*",
"np",
".",
"pi",
"*",
"t",
")",
")",
"**",
"(",
"0.5",
")",
"*",
"np",
".",
"exp",
"(",
"(",
"-",
"Pe",
"*",
"(",
"(",
"1",
"-",
"t",
")",
"**",
"2",
")",
")",
"/",
"(",
"4",
"*",
"t",
")",
")"
] | Calculate a dimensionless measure of the output tracer concentration from
a spike input to reactor with advection and dispersion.
:param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR.
:type t: float or numpy.array
:param Pe: The ratio of advection to dispersion ((mean fluid velocity)/(Dispersion*flow path length))
:type Pe: float
:return: dimensionless measure of the output tracer concentration (concentration * volume of reactor) / (mass of tracer)
:rtype: float
:Examples:
>>> from aguaclara.research.environmental_processes_analysis import E_Advective_Dispersion
>>> round(E_Advective_Dispersion(0.5, 5), 7)
0.4774864 | [
"Calculate",
"a",
"dimensionless",
"measure",
"of",
"the",
"output",
"tracer",
"concentration",
"from",
"a",
"spike",
"input",
"to",
"reactor",
"with",
"advection",
"and",
"dispersion",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L289-L311 |
1,495 | AguaClara/aguaclara | aguaclara/play.py | set_sig_figs | def set_sig_figs(n=4):
"""Set the number of significant figures used to print Pint, Pandas, and
NumPy quantities.
Args:
n (int): Number of significant figures to display.
"""
u.default_format = '.' + str(n) + 'g'
pd.options.display.float_format = ('{:,.' + str(n) + '}').format | python | def set_sig_figs(n=4):
u.default_format = '.' + str(n) + 'g'
pd.options.display.float_format = ('{:,.' + str(n) + '}').format | [
"def",
"set_sig_figs",
"(",
"n",
"=",
"4",
")",
":",
"u",
".",
"default_format",
"=",
"'.'",
"+",
"str",
"(",
"n",
")",
"+",
"'g'",
"pd",
".",
"options",
".",
"display",
".",
"float_format",
"=",
"(",
"'{:,.'",
"+",
"str",
"(",
"n",
")",
"+",
"'}'",
")",
".",
"format"
] | Set the number of significant figures used to print Pint, Pandas, and
NumPy quantities.
Args:
n (int): Number of significant figures to display. | [
"Set",
"the",
"number",
"of",
"significant",
"figures",
"used",
"to",
"print",
"Pint",
"Pandas",
"and",
"NumPy",
"quantities",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/play.py#L43-L51 |
1,496 | AguaClara/aguaclara | aguaclara/research/procoda_parser.py | remove_notes | def remove_notes(data):
"""Omit notes from a DataFrame object, where notes are identified as rows with non-numerical entries in the first column.
:param data: DataFrame object to remove notes from
:type data: Pandas.DataFrame
:return: DataFrame object with no notes
:rtype: Pandas.DataFrame
"""
has_text = data.iloc[:, 0].astype(str).str.contains('(?!e-)[a-zA-Z]')
text_rows = list(has_text.index[has_text])
return data.drop(text_rows) | python | def remove_notes(data):
has_text = data.iloc[:, 0].astype(str).str.contains('(?!e-)[a-zA-Z]')
text_rows = list(has_text.index[has_text])
return data.drop(text_rows) | [
"def",
"remove_notes",
"(",
"data",
")",
":",
"has_text",
"=",
"data",
".",
"iloc",
"[",
":",
",",
"0",
"]",
".",
"astype",
"(",
"str",
")",
".",
"str",
".",
"contains",
"(",
"'(?!e-)[a-zA-Z]'",
")",
"text_rows",
"=",
"list",
"(",
"has_text",
".",
"index",
"[",
"has_text",
"]",
")",
"return",
"data",
".",
"drop",
"(",
"text_rows",
")"
] | Omit notes from a DataFrame object, where notes are identified as rows with non-numerical entries in the first column.
:param data: DataFrame object to remove notes from
:type data: Pandas.DataFrame
:return: DataFrame object with no notes
:rtype: Pandas.DataFrame | [
"Omit",
"notes",
"from",
"a",
"DataFrame",
"object",
"where",
"notes",
"are",
"identified",
"as",
"rows",
"with",
"non",
"-",
"numerical",
"entries",
"in",
"the",
"first",
"column",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L53-L64 |
1,497 | AguaClara/aguaclara | aguaclara/research/procoda_parser.py | day_fraction | def day_fraction(time):
"""Convert a 24-hour time to a fraction of a day.
For example, midnight corresponds to 0.0, and noon to 0.5.
:param time: Time in the form of 'HH:MM' (24-hour time)
:type time: string
:return: A day fraction
:rtype: float
:Examples:
.. code-block:: python
day_fraction("18:30")
"""
hour = int(time.split(":")[0])
minute = int(time.split(":")[1])
return hour/24 + minute/1440 | python | def day_fraction(time):
hour = int(time.split(":")[0])
minute = int(time.split(":")[1])
return hour/24 + minute/1440 | [
"def",
"day_fraction",
"(",
"time",
")",
":",
"hour",
"=",
"int",
"(",
"time",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
")",
"minute",
"=",
"int",
"(",
"time",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
"]",
")",
"return",
"hour",
"/",
"24",
"+",
"minute",
"/",
"1440"
] | Convert a 24-hour time to a fraction of a day.
For example, midnight corresponds to 0.0, and noon to 0.5.
:param time: Time in the form of 'HH:MM' (24-hour time)
:type time: string
:return: A day fraction
:rtype: float
:Examples:
.. code-block:: python
day_fraction("18:30") | [
"Convert",
"a",
"24",
"-",
"hour",
"time",
"to",
"a",
"fraction",
"of",
"a",
"day",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L67-L86 |
1,498 | AguaClara/aguaclara | aguaclara/research/procoda_parser.py | time_column_index | def time_column_index(time, time_column):
"""Return the index of lowest time in the column of times that is greater
than or equal to the given time.
:param time: the time to index from the column of time; a day fraction
:type time: float
:param time_column: a list of times (in day fractions), must be increasing and equally spaced
:type time_column: float list
:return: approximate index of the time from the column of times
:rtype: int
"""
interval = time_column[1]-time_column[0]
return int(round((time - time_column[0])/interval + .5)) | python | def time_column_index(time, time_column):
interval = time_column[1]-time_column[0]
return int(round((time - time_column[0])/interval + .5)) | [
"def",
"time_column_index",
"(",
"time",
",",
"time_column",
")",
":",
"interval",
"=",
"time_column",
"[",
"1",
"]",
"-",
"time_column",
"[",
"0",
"]",
"return",
"int",
"(",
"round",
"(",
"(",
"time",
"-",
"time_column",
"[",
"0",
"]",
")",
"/",
"interval",
"+",
".5",
")",
")"
] | Return the index of lowest time in the column of times that is greater
than or equal to the given time.
:param time: the time to index from the column of time; a day fraction
:type time: float
:param time_column: a list of times (in day fractions), must be increasing and equally spaced
:type time_column: float list
:return: approximate index of the time from the column of times
:rtype: int | [
"Return",
"the",
"index",
"of",
"lowest",
"time",
"in",
"the",
"column",
"of",
"times",
"that",
"is",
"greater",
"than",
"or",
"equal",
"to",
"the",
"given",
"time",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L89-L102 |
1,499 | AguaClara/aguaclara | aguaclara/research/procoda_parser.py | data_from_dates | def data_from_dates(path, dates):
"""Return list DataFrames representing the ProCoDA datalogs stored in
the given path and recorded on the given dates.
:param path: The path to the folder containing the ProCoDA data file(s)
:type path: string
:param dates: A single date or list of dates for which data was recorded, formatted "M-D-YYYY"
:type dates: string or string list
:return: a list DataFrame objects representing the ProCoDA datalogs corresponding with the given dates
:rtype: pandas.DataFrame list
"""
if path[-1] != os.path.sep:
path += os.path.sep
if not isinstance(dates, list):
dates = [dates]
data = []
for d in dates:
filepath = path + 'datalog ' + d + '.xls'
data.append(remove_notes(pd.read_csv(filepath, delimiter='\t')))
return data | python | def data_from_dates(path, dates):
if path[-1] != os.path.sep:
path += os.path.sep
if not isinstance(dates, list):
dates = [dates]
data = []
for d in dates:
filepath = path + 'datalog ' + d + '.xls'
data.append(remove_notes(pd.read_csv(filepath, delimiter='\t')))
return data | [
"def",
"data_from_dates",
"(",
"path",
",",
"dates",
")",
":",
"if",
"path",
"[",
"-",
"1",
"]",
"!=",
"os",
".",
"path",
".",
"sep",
":",
"path",
"+=",
"os",
".",
"path",
".",
"sep",
"if",
"not",
"isinstance",
"(",
"dates",
",",
"list",
")",
":",
"dates",
"=",
"[",
"dates",
"]",
"data",
"=",
"[",
"]",
"for",
"d",
"in",
"dates",
":",
"filepath",
"=",
"path",
"+",
"'datalog '",
"+",
"d",
"+",
"'.xls'",
"data",
".",
"append",
"(",
"remove_notes",
"(",
"pd",
".",
"read_csv",
"(",
"filepath",
",",
"delimiter",
"=",
"'\\t'",
")",
")",
")",
"return",
"data"
] | Return list DataFrames representing the ProCoDA datalogs stored in
the given path and recorded on the given dates.
:param path: The path to the folder containing the ProCoDA data file(s)
:type path: string
:param dates: A single date or list of dates for which data was recorded, formatted "M-D-YYYY"
:type dates: string or string list
:return: a list DataFrame objects representing the ProCoDA datalogs corresponding with the given dates
:rtype: pandas.DataFrame list | [
"Return",
"list",
"DataFrames",
"representing",
"the",
"ProCoDA",
"datalogs",
"stored",
"in",
"the",
"given",
"path",
"and",
"recorded",
"on",
"the",
"given",
"dates",
"."
] | 8dd4e734768b166a7fc2b60388a24df2f93783fc | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L105-L128 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.