text stringlengths 81 112k |
|---|
Legacy acl format kept for bw. compatibility
:param permissions:
:return:
def permission_to_04_acls(permissions):
"""
Legacy acl format kept for bw. compatibility
:param permissions:
:return:
"""
acls = []
for perm in permissions:
if perm.type == "user":
acls.app... |
Returns a list of permissions in a format understood by pyramid
:param permissions:
:return:
def permission_to_pyramid_acls(permissions):
"""
Returns a list of permissions in a format understood by pyramid
:param permissions:
:return:
"""
acls = []
for perm in permissions:
i... |
[
{
'self': [1, 1, 3, 3, 1, 1],
'f': lambda x: x%2,
'assert': lambda ret: ret == [[1, 1], [3, 3], [1, 1]]
}
]
def ChunkBy(self, f=None):
"""
[
{
'self': [1, 1, 3, 3, 1, 1],
'f': lambda x: x%2,
'assert': lambda ... |
[
{
'self': [1, 2, 3],
'f': lambda x: x%2,
'assert': lambda ret: ret[0] == [2] and ret[1] == [1, 3]
}
]
def GroupBy(self: Iterable, f=None):
"""
[
{
'self': [1, 2, 3],
'f': lambda x: x%2,
'assert': lambda ret: ... |
[
{
'self': [1, 2, 3],
'n': 2,
'assert': lambda ret: list(ret) == [1, 2]
}
]
def Take(self: Iterable, n):
"""
[
{
'self': [1, 2, 3],
'n': 2,
'assert': lambda ret: list(ret) == [1, 2]
}
]
"""
... |
[
{
'self': [1, 2, 3],
'f': lambda e: e%2,
'assert': lambda ret: list(ret) == [1, 3]
}
]
def TakeIf(self: Iterable, f):
"""
[
{
'self': [1, 2, 3],
'f': lambda e: e%2,
'assert': lambda ret: list(ret) == [1, 3]... |
[
{
'self': [1, 2, 3, 4, 5],
'f': lambda x: x < 4,
'assert': lambda ret: list(ret) == [1, 2, 3]
}
]
def TakeWhile(self: Iterable, f):
"""
[
{
'self': [1, 2, 3, 4, 5],
'f': lambda x: x < 4,
'assert': lambda ret... |
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [1, 2]
}
]
def Drop(self: Iterable, n):
"""
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [1, 2]
}
... |
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [4, 5]
}
]
def Skip(self: Iterable, n):
"""
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lam... |
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [4, 5, 1, 2, 3]
}
]
def Shift(self, n):
"""
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [4, 5, 1, 2, 3]
... |
[
{
'self': [1, 2, 3],
':args': [[4, 5, 6], [7, 8, 9]],
'assert': lambda ret: list(ret) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
}
]
def Concat(self: Iterable, *others):
"""
[
{
'self': [1, 2, 3],
':args': [[4, 5, 6], [7, 8, 9]],
... |
Checks if an attribute is being accessed throught the default
queryset manager, ie: MyClass.objects.filter(some='value')
def _called_thru_default_qs(self, node):
"""Checks if an attribute is being accessed throught the default
queryset manager, ie: MyClass.objects.filter(some='value')"""
... |
returns all objects of specific type - will work correctly with
sqlalchemy inheritance models, you should normally use models
base_query() instead of this function its for bw. compat purposes
:param klass:
:param db_session:
:return:
def all(cls, klass, db_session=None):
... |
returns base query for specific service
:param db_session:
:return: query
def base_query(cls, db_session=None):
"""
returns base query for specific service
:param db_session:
:return: query
"""
db_session = get_db_session(db_session)
return db_s... |
Event method wrapper for bot mixins. When a bot is constructed,
its metaclass inspects all members of all base classes, and
looks for methods marked with an event attribute which is assigned
via this wrapper. It then stores all the methods in a dict
that maps event names to lists of these methods, which... |
utility function that attempts to return sqlalchemy session that could
have been created/passed in one of few ways:
* It first tries to read session attached to instance
if object argument was passed
* then it tries to return session passed as argument
* finally tries to read pylons-like threa... |
return dictionary of keys and values corresponding to this model's
data - if include_keys is null the function will return all keys
:param exclude_keys: (optional) is a list of columns from model that
should not be returned by this function
:param include_keys: (optional) is a list of c... |
return list of tuples keys and values corresponding to this model's
data
def get_appstruct(self):
""" return list of tuples keys and values corresponding to this model's
data """
result = []
for k in self._get_keys():
result.append((k, getattr(self, k)))
retu... |
updates instance properties *for column names that exist*
for this model and are keys present in passed dictionary
:param appstruct: (dictionary)
:param exclude_keys: (optional) is a list of columns from model that
should not be updated by this function
:param include_keys: (opt... |
updates instance properties *for column names that exist*
for this model and are properties present in passed dictionary
:param instance:
:param exclude_keys: (optional) is a list of columns from model that
should not be updated by this function
:param include_keys: (optional) i... |
Deletes the object via session, this will permanently delete the
object from storage on commit
:param db_session:
:return:
def delete(self, db_session=None):
"""
Deletes the object via session, this will permanently delete the
object from storage on commit
:par... |
turn off the HX711
:return: always True
:rtype bool
def power_down(self):
"""
turn off the HX711
:return: always True
:rtype bool
"""
GPIO.output(self._pd_sck, False)
GPIO.output(self._pd_sck, True)
time.sleep(0.01)
return True |
power up the HX711
:return: always True
:rtype bool
def power_up(self):
"""
power up the HX711
:return: always True
:rtype bool
"""
GPIO.output(self._pd_sck, False)
time.sleep(0.01)
return True |
reset the HX711 and prepare it for the next reading
:return: True on success
:rtype bool
:raises GenericHX711Exception
def reset(self):
"""
reset the HX711 and prepare it for the next reading
:return: True on success
:rtype bool
:raises GenericHX711Ex... |
check if "times" is within the borders defined in the class
:param times: "times" to check
:type times: int
def _validate_measure_count(self, times):
"""
check if "times" is within the borders defined in the class
:param times: "times" to check
:type times: int
... |
validate a given value for gain_A
:type gain_A: int
:raises: ValueError
def _validate_gain_A_value(self, gain_A):
"""
validate a given value for gain_A
:type gain_A: int
:raises: ValueError
"""
if gain_A not in self._valid_gains_for_channel_A:
... |
check if ther is som data is ready to get read.
:return True if there is some date
:rtype bool
def _ready(self):
"""
check if ther is som data is ready to get read.
:return True if there is some date
:rtype bool
"""
# if DOUT pin is low, data is ready for... |
Finish data transmission from HX711 by setting
next required gain and channel
Only called from the _read function.
:param num: how often so do the set (1...3)
:type num: int
:return True on success
:rtype bool
def _set_channel_gain(self, num):
"""
Finish... |
- read the bit stream from HX711 and convert to an int value.
- validates the acquired data
:param max_tries: how often to try to get data
:type max_tries: int
:return raw data
:rtype: int
def _read(self, max_tries=40):
"""
- read the bit stream from HX711 and co... |
do some readings and aggregate them using the defined statistics function
:param times: how many measures to aggregate
:type times: int
:return: the aggregate of the measured values
:rtype float
def get_raw_data(self, times=5):
"""
do some readings and aggregate them us... |
This returns you subtree of ordered objects relative
to the start resource_id (currently only implemented in postgresql)
:param resource_id:
:param limit_depth:
:param db_session:
:return:
def from_resource_deeper(
self, resource_id=None, limit_depth=1000000, db_session... |
This deletes whole branch with children starting from resource_id
:param resource_id:
:param db_session:
:return:
def delete_branch(self, resource_id=None, db_session=None, *args, **kwargs):
"""
This deletes whole branch with children starting from resource_id
:param r... |
This returns you subtree of ordered objects relative
to the start parent_id (currently only implemented in postgresql)
:param resource_id:
:param limit_depth:
:param db_session:
:return:
def from_parent_deeper(
self, parent_id=None, limit_depth=1000000, db_session=None,... |
Returns a dictionary in form of
{node:Resource, children:{node_id: Resource}}
:param result:
:return:
def build_subtree_strut(self, result, *args, **kwargs):
"""
Returns a dictionary in form of
{node:Resource, children:{node_id: Resource}}
:param result:
... |
This returns you path to root node starting from object_id
currently only for postgresql
:param object_id:
:param limit_depth:
:param db_session:
:return:
def path_upper(
self, object_id, limit_depth=1000000, db_session=None, *args, **kwargs
):
"""
... |
Moves node to new location in the tree
:param resource_id: resource to move
:param to_position: new position
:param new_parent_id: new parent id
:param db_session:
:return:
def move_to_position(
self,
resource_id,
to_position,
new_parent_id=noop,... |
Shifts ordering to "close gaps" after node deletion or being moved
to another branch, begins the shift from given position
:param parent_id:
:param position:
:param db_session:
:return:
def shift_ordering_down(
self, parent_id, position, db_session=None, *args, **kwargs... |
Shifts ordering to "open a gap" for node insertion,
begins the shift from given position
:param parent_id:
:param position:
:param db_session:
:return:
def shift_ordering_up(self, parent_id, position, db_session=None, *args, **kwargs):
"""
Shifts ordering to "op... |
Sets node position for new node in the tree
:param resource_id: resource to move
:param to_position: new position
:param db_session:
:return:def count_children(cls, resource_id, db_session=None):
def set_position(self, resource_id, to_position, db_session=None, *args, **kwargs):
... |
Checks if parent destination is valid for node
:param resource_id:
:param new_parent_id:
:param db_session:
:return:
def check_node_parent(
self, resource_id, new_parent_id, db_session=None, *args, **kwargs
):
"""
Checks if parent destination is valid for no... |
Counts children of resource node
:param resource_id:
:param db_session:
:return:
def count_children(self, resource_id, db_session=None, *args, **kwargs):
"""
Counts children of resource node
:param resource_id:
:param db_session:
:return:
"""
... |
Checks if node position for given parent is valid, raises exception if
this is not the case
:param parent_id:
:param position:
:param on_same_branch: indicates that we are checking same branch
:param db_session:
:return:
def check_node_position(
self, parent_id,... |
takes a list of lists, l and returns a flat list
def flatten_list(l: List[list]) -> list:
""" takes a list of lists, l and returns a flat list
"""
return [v for inner_l in l for v in inner_l] |
Read in NEM file and return meter readings named tuple
:param file_path: The NEM file to process
:returns: The file that was created
def read_nem_file(file_path: str) -> NEMFile:
""" Read in NEM file and return meter readings named tuple
:param file_path: The NEM file to process
:returns: The fil... |
Parse NEM file and return meter readings named tuple
def parse_nem_file(nem_file) -> NEMFile:
""" Parse NEM file and return meter readings named tuple """
reader = csv.reader(nem_file, delimiter=',')
return parse_nem_rows(reader, file_name=nem_file) |
Parse NEM row iterator and return meter readings named tuple
def parse_nem_rows(nem_list: Iterable, file_name=None) -> NEMFile:
""" Parse NEM row iterator and return meter readings named tuple """
header = HeaderRecord(None, None, None, None, file_name)
readings = dict() # readings nested by NMI then cha... |
Calculate the interval between two manual readings
def calculate_manual_reading(basic_data: BasicMeterData) -> Reading:
""" Calculate the interval between two manual readings """
t_start = basic_data.previous_register_read_datetime
t_end = basic_data.current_register_read_datetime
read_start = basic_da... |
Parse header record (100)
def parse_100_row(row: list, file_name: str) -> HeaderRecord:
""" Parse header record (100) """
return HeaderRecord(
row[1],
parse_datetime(row[2]),
row[3],
row[4],
file_name,
) |
Parse NMI data details record (200)
def parse_200_row(row: list) -> NmiDetails:
""" Parse NMI data details record (200) """
return NmiDetails(row[1], row[2], row[3], row[4], row[5], row[6],
row[7], int(row[8]), parse_datetime(row[9])) |
Parse basic meter data record (250)
def parse_250_row(row: list) -> BasicMeterData:
""" Parse basic meter data record (250) """
return BasicMeterData(row[1], row[2], row[3], row[4], row[5],
row[6], row[7], float(row[8]),
parse_datetime(row[9]), row[10],... |
Interval data record (300)
def parse_300_row(row: list, interval: int, uom: str) -> IntervalRecord:
""" Interval data record (300) """
num_intervals = int(24 * 60 / interval)
interval_date = parse_datetime(row[1])
last_interval = 2 + num_intervals
quality_method = row[last_interval]
interval_... |
Convert interval values into tuples with datetime
def parse_interval_records(interval_record, interval_date, interval, uom,
quality_method) -> List[Reading]:
""" Convert interval values into tuples with datetime
"""
interval_delta = timedelta(minutes=interval)
return [
... |
Convert reading value to float (if possible)
def parse_reading(val: str) -> Optional[float]:
""" Convert reading value to float (if possible) """
try:
return float(val)
except ValueError:
logging.warning('Reading of "%s" is not a number', val)
return None |
Interval event record (400)
def parse_400_row(row: list) -> tuple:
""" Interval event record (400) """
return EventRecord(int(row[1]), int(row[2]), row[3], row[4], row[5]) |
Updates readings from a 300 row to reflect any events found in a
subsequent 400 row
def update_reading_events(readings, event_record):
""" Updates readings from a 300 row to reflect any events found in a
subsequent 400 row
"""
# event intervals are 1-indexed
for i in range(event_record.... |
Parse a datetime string into a python datetime object
def parse_datetime(record: str) -> Optional[datetime]:
""" Parse a datetime string into a python datetime object """
# NEM defines Date8, DateTime12 and DateTime14
format_strings = {8: '%Y%m%d', 12: '%Y%m%d%H%M', 14: '%Y%m%d%H%M%S'}
if record == '':... |
Called from ``gnotty.server.run`` and parses any CLI args
provided. Also handles loading settings from the Python
module specified with the ``--conf-file`` arg. CLI args
take precedence over any settings defined in the Python
module defined by ``--conf-file``.
def parse_args(self):
... |
Provides a consistent color for a nickname. Uses first 6 chars
of nickname's md5 hash, and then slightly darkens the rgb values
for use on a light background.
def color(nickname):
"""
Provides a consistent color for a nickname. Uses first 6 chars
of nickname's md5 hash, and then slightly darkens th... |
Join the channel once connected to the IRC server.
def on_welcome(self, connection, event):
"""
Join the channel once connected to the IRC server.
"""
connection.join(self.channel, key=settings.IRC_CHANNEL_KEY or "") |
Increment a digit on the nickname if it's in use, and
re-connect.
def on_nicknameinuse(self, connection, event):
"""
Increment a digit on the nickname if it's in use, and
re-connect.
"""
digits = ""
while self.nickname[-1].isdigit():
digits = self.nic... |
Nicer shortcut for sending a message to a channel. Also
irclib doesn't handle unicode so we bypass its
privmsg -> send_raw methods and use its socket directly.
def message_channel(self, message):
"""
Nicer shortcut for sending a message to a channel. Also
irclib doesn't handle u... |
Send a message to the channel. We also emit the message
back to the sender's WebSocket.
def emit_message(self, message):
"""
Send a message to the channel. We also emit the message
back to the sender's WebSocket.
"""
try:
nickname_color = self.nicknames[self.... |
Send the nickname list to the Websocket. Called whenever the
nicknames list changes.
def emit_nicknames(self):
"""
Send the nickname list to the Websocket. Called whenever the
nicknames list changes.
"""
nicknames = [{"nickname": name, "color": color(name)}
... |
Initial list of nicknames received - remove op/voice prefixes,
and send the list to the WebSocket.
def on_namreply(self, connection, event):
"""
Initial list of nicknames received - remove op/voice prefixes,
and send the list to the WebSocket.
"""
for nickname in event.a... |
Someone joined the channel - send the nicknames list to the
WebSocket.
def on_join(self, connection, event):
"""
Someone joined the channel - send the nicknames list to the
WebSocket.
"""
#from time import sleep; sleep(10) # Simulate a slow connection
nickname =... |
Someone changed their nickname - send the nicknames list to the
WebSocket.
def on_nick(self, connection, event):
"""
Someone changed their nickname - send the nicknames list to the
WebSocket.
"""
old_nickname = self.get_nickname(event)
old_color = self.nicknames.... |
Someone left the channel - send the nicknames list to the
WebSocket.
def on_quit(self, connection, event):
"""
Someone left the channel - send the nicknames list to the
WebSocket.
"""
nickname = self.get_nickname(event)
nickname_color = self.nicknames[nickname]
... |
Messages received in the channel - send them to the WebSocket.
def on_pubmsg(self, connection, event):
"""
Messages received in the channel - send them to the WebSocket.
"""
for message in event.arguments():
nickname = self.get_nickname(event)
nickname_color = se... |
Fetch row using primary key -
will use existing object in session if already present
:param resource_id:
:param db_session:
:return:
def get(cls, resource_id, db_session=None):
"""
Fetch row using primary key -
will use existing object in session if already pres... |
returns all permissions that given user has for this resource
from groups and directly set ones too
:param instance:
:param user:
:param db_session:
:return:
def perms_for_user(cls, instance, user, db_session=None):
"""
returns all permissions that given use... |
returns permissions that given user has for this resource
without ones inherited from groups that user belongs to
:param instance:
:param user:
:param db_session:
:return:
def direct_perms_for_user(cls, instance, user, db_session=None):
"""
returns permissio... |
returns permissions that given user has for this resource
that are inherited from groups
:param instance:
:param user:
:param db_session:
:return:
def group_perms_for_user(cls, instance, user, db_session=None):
"""
returns permissions that given user has for... |
return PermissionTuples for users AND groups that have given
permission for the resource, perm_name is __any_permission__ then
users with any permission will be listed
:param instance:
:param perm_name:
:param user_ids: limits the permissions to specific user ids
:param ... |
fetch the resouce by id
:param resource_id:
:param db_session:
:return:
def by_resource_id(cls, resource_id, db_session=None):
"""
fetch the resouce by id
:param resource_id:
:param db_session:
:return:
"""
db_session = get_db_session(db... |
fetch permissions by group and permission name
:param resource_id:
:param group_id:
:param perm_name:
:param db_session:
:return:
def perm_by_group_and_perm_name(
cls, resource_id, group_id, perm_name, db_session=None
):
"""
fetch permissions by grou... |
return PermissionTuples for groups that have given
permission for the resource, perm_name is __any_permission__ then
users with any permission will be listed
:param instance:
:param perm_name:
:param group_ids: limits the permissions to specific group ids
:param limit_gr... |
Selects resource for update - locking access for other transactions
:param resource_id:
:param db_session:
:return:
def lock_resource_for_update(cls, resource_id, db_session):
"""
Selects resource for update - locking access for other transactions
:param resource_id:
... |
Fetch row using primary key -
will use existing object in session if already present
:param user_id:
:param db_session:
:return:
def get(cls, user_id, db_session=None):
"""
Fetch row using primary key -
will use existing object in session if already present
... |
returns all non-resource permissions based on what groups user
belongs and directly set ones for this user
:param instance:
:param db_session:
:return:
def permissions(cls, instance, db_session=None):
"""
returns all non-resource permissions based on what groups use... |
returns all resources that user has perms for
(note that at least one perm needs to be met)
:param instance:
:param perms:
:param resource_ids: restricts the search to specific resources
:param resource_types:
:param db_session:
:return:
def resources_with_p... |
Returns a list of groups users belongs to with eager loaded
resources owned by those groups
:param instance:
:return:
def groups_with_resources(cls, instance):
"""
Returns a list of groups users belongs to with eager loaded
resources owned by those groups
:para... |
returns list of permissions and resources for this user
:param instance:
:param resource_ids: restricts the search to specific resources
:param resource_types: restricts the search to specific resource types
:param db_session:
:return:
def resources_with_possible_perms(
... |
returns user gravatar url
:param instance:
:param default:
:param kwargs:
:return:
def gravatar_url(cls, instance, default="mm", **kwargs):
"""
returns user gravatar url
:param instance:
:param default:
:param kwargs:
:return:
""... |
sets new password on a user using password manager
:param instance:
:param raw_password:
:return:
def set_password(cls, instance, raw_password):
"""
sets new password on a user using password manager
:param instance:
:param raw_password:
:return:
... |
checks string with users password hash using password manager
:param instance:
:param raw_password:
:param enable_hash_migration: if legacy hashes should be migrated
:return:
def check_password(cls, instance, raw_password, enable_hash_migration=True):
"""
checks string ... |
fetch user by user id
:param user_id:
:param db_session:
:return:
def by_id(cls, user_id, db_session=None):
"""
fetch user by user id
:param user_id:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
query =... |
fetch user objects by user name and security code
:param user_name:
:param security_code:
:param db_session:
:return:
def by_user_name_and_security_code(cls, user_name, security_code, db_session=None):
"""
fetch user objects by user name and security code
:para... |
fetch user objects by user names
:param user_names:
:param db_session:
:return:
def by_user_names(cls, user_names, db_session=None):
"""
fetch user objects by user names
:param user_names:
:param db_session:
:return:
"""
user_names = [(n... |
fetch users with similar names using LIKE clause
:param user_name:
:param db_session:
:return:
def user_names_like(cls, user_name, db_session=None):
"""
fetch users with similar names using LIKE clause
:param user_name:
:param db_session:
:return:
... |
fetch user object by email
:param email:
:param db_session:
:return:
def by_email(cls, email, db_session=None):
"""
fetch user object by email
:param email:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
... |
return users hat have one of given permissions
:param perm_names:
:param db_session:
:return:
def users_for_perms(cls, perm_names, db_session=None):
"""
return users hat have one of given permissions
:param perm_names:
:param db_session:
:return:
... |
Store join times for current nicknames when we first join.
def handle_joined(self, connection, event):
"""
Store join times for current nicknames when we first join.
"""
nicknames = [s.lstrip("@+") for s in event.arguments()[-1].split()]
for nickname in nicknames:
se... |
Store join time for a nickname when it joins.
def handle_join(self, connection, event):
"""
Store join time for a nickname when it joins.
"""
nickname = self.get_nickname(event)
self.joined[nickname] = datetime.now() |
Store quit time for a nickname when it quits.
def handle_quit(self, connection, event):
"""
Store quit time for a nickname when it quits.
"""
nickname = self.get_nickname(event)
self.quit[nickname] = datetime.now()
del self.joined[nickname] |
Returns human friendly version of the timespan between now
and the given datetime.
def timesince(self, when):
"""
Returns human friendly version of the timespan between now
and the given datetime.
"""
units = (
("year", 60 * 60 * 24 * 365),
("we... |
Shows version information.
def version(self, event):
"""
Shows version information.
"""
name = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
return "%s [%s]" % (settings.GNOTTY_VERSION_STRING, name) |
Lists all available commands.
def commands(self, event):
"""
Lists all available commands.
"""
commands = sorted(self.commands_dict().keys())
return "Available commands: %s" % " ".join(commands) |
Shows the help message for the bot. Takes an optional command name
which when given, will show help for that command.
def help(self, event, command_name=None):
"""
Shows the help message for the bot. Takes an optional command name
which when given, will show help for that command.
... |
Shows the amount of time since the given nickname has been
in the channel. If no nickname is given, I'll use my own.
def uptime(self, event, nickname=None):
"""
Shows the amount of time since the given nickname has been
in the channel. If no nickname is given, I'll use my own.
"... |
Shows the amount of time since the given nickname was last
seen in the channel.
def seen(self, event, nickname):
"""
Shows the amount of time since the given nickname was last
seen in the channel.
"""
try:
self.joined[nickname]
except KeyError:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.