INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
check if times is within the borders defined in the class | 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
"""
if not self.min_measures <= times <= self.max_measures:
raise ParameterValidationError(
... |
validate a given value for gain_A | 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:
raise ParameterValidationError("{gain_A} is not a valid gain".format(gain_A=gain_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 reading
_is_ready = GPIO.input(self._dout) == 0
logging.debug("check data ready for reading: {r... |
Finish data transmission from HX711 by setting next required gain and channel | def _set_channel_gain(self, num):
"""
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
... |
- 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 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
"""
# start by setting t... |
do some readings and aggregate them using the defined statistics function | def get_raw_data(self, times=5):
"""
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
"""
self._validate_mea... |
This returns you subtree of ordered objects relative to the start resource_id ( currently only implemented in postgresql ) | def from_resource_deeper(
self, resource_id=None, limit_depth=1000000, db_session=None, *args, **kwargs
):
"""
This returns you subtree of ordered objects relative
to the start resource_id (currently only implemented in postgresql)
:param resource_id:
:param limit_de... |
This deletes whole branch with children starting from resource_id | def delete_branch(self, resource_id=None, db_session=None, *args, **kwargs):
"""
This deletes whole branch with children starting from resource_id
:param resource_id:
:param db_session:
:return:
"""
return self.service.delete_branch(
resource_id=resou... |
This returns you subtree of ordered objects relative to the start parent_id ( currently only implemented in postgresql ) | def from_parent_deeper(
self, parent_id=None, limit_depth=1000000, db_session=None, *args, **kwargs
):
"""
This returns you subtree of ordered objects relative
to the start parent_id (currently only implemented in postgresql)
:param resource_id:
:param limit_depth:
... |
Returns a dictionary in form of { node: Resource children: { node_id: Resource }} | def build_subtree_strut(self, result, *args, **kwargs):
"""
Returns a dictionary in form of
{node:Resource, children:{node_id: Resource}}
:param result:
:return:
"""
return self.service.build_subtree_strut(result=result, *args, **kwargs) |
This returns you path to root node starting from object_id currently only for postgresql | def path_upper(
self, object_id, limit_depth=1000000, db_session=None, *args, **kwargs
):
"""
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... |
Moves node to new location in the tree | def move_to_position(
self,
resource_id,
to_position,
new_parent_id=noop,
db_session=None,
*args,
**kwargs
):
"""
Moves node to new location in the tree
:param resource_id: resource to move
:param to_position: new position
... |
Shifts ordering to close gaps after node deletion or being moved to another branch begins the shift from given position | def shift_ordering_down(
self, parent_id, position, db_session=None, *args, **kwargs
):
"""
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... |
Shifts ordering to open a gap for node insertion begins the shift from given position | def shift_ordering_up(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:
"""
ret... |
Sets node position for new node in the tree | def set_position(self, resource_id, to_position, db_session=None, *args, **kwargs):
"""
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_se... |
Checks if parent destination is valid for node | def check_node_parent(
self, resource_id, new_parent_id, db_session=None, *args, **kwargs
):
"""
Checks if parent destination is valid for node
:param resource_id:
:param new_parent_id:
:param db_session:
:return:
"""
return self.service.check... |
Counts children of resource node | def count_children(self, resource_id, db_session=None, *args, **kwargs):
"""
Counts children of resource node
:param resource_id:
:param db_session:
:return:
"""
return self.service.count_children(
resource_id=resource_id, db_session=db_session, *args... |
Checks if node position for given parent is valid raises exception if this is not the case | def check_node_position(
self, parent_id, position, on_same_branch, db_session=None, *args, **kwargs
):
"""
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: i... |
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 | 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 file that was created
"""
_, file_extension = os.path.splitext(file_path)
if file_extension.lower() == '.zip':
with zipfile.Z... |
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 channel
trans = dict() # transactions 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_data.previous_register_read
read_end = basic_data.... |
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], row[11], row[12],
... |
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_values = parse_interval_reco... |
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 [
Reading(
t_start=interval_date + (i *... |
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.start_interval - 1, event_record.end_interval):
readings[i] = Reading(
t_... |
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 == '':
return None
return datetime.strptime(recor... |
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):
"""
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 ``... |
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 the rgb values
for use on a light background.
"""
_hex = md5(nickname).hexdigest()[:6]
darken = lambda s: str(int(round(int(s, 16) * .7)))
return "rgb... |
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.nickname[-1] + digits
self.nickname = self.nickname[:-1]
d... |
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 unicode so we bypass its
privmsg -> send_raw methods and use its socket directly.
"""
data = "PRIVMSG %s :%s\r\n" % (self.channel, message)
self.c... |
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.nickname]
except KeyError:
# Only accept messages if we've joined.
... |
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)}
for name in sorted(self.nicknames.keys())]
self.namespace.emit("nicknames", ni... |
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.arguments()[-1].split():
nickname = nickname.lstrip("@+")
self.nicknames[nickname] = ... |
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 = self.get_nickname(event)
nickname_color = color(nickname)
self.... |
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.pop(old_nickname)
new_nickname = event.target()
message = "is now kn... |
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]
del self.nicknames[nickname]
self.namespace.emit("message", nic... |
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 = self.nicknames[nickname]
self.namespace.emit("message"... |
Fetch row using primary key - will use existing object in session if already present | def get(cls, resource_id, db_session=None):
"""
Fetch row using primary key -
will use existing object in session if already present
:param resource_id:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
return db_session.quer... |
returns all permissions that given user has for this resource from groups and directly set ones too | def perms_for_user(cls, instance, user, db_session=None):
"""
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:
"""
db_session = get_db... |
returns permissions that given user has for this resource without ones inherited from groups that user belongs to | def direct_perms_for_user(cls, instance, user, db_session=None):
"""
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:
"""
... |
returns permissions that given user has for this resource that are inherited from groups | def group_perms_for_user(cls, instance, user, db_session=None):
"""
returns permissions that given user has for this resource
that are inherited from groups
:param instance:
:param user:
:param db_session:
:return:
"""
db_session = get_db_sess... |
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 | def users_for_perm(
cls,
instance,
perm_name,
user_ids=None,
group_ids=None,
limit_group_permissions=False,
skip_group_perms=False,
db_session=None,
):
"""
return PermissionTuples for users AND groups that have given
permission ... |
fetch the resouce by id | 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_session)
query = db_session.query(cls.model).filter(
cls.model.resource_id ==... |
fetch permissions by group and permission name | def perm_by_group_and_perm_name(
cls, resource_id, group_id, perm_name, db_session=None
):
"""
fetch permissions by group and permission name
:param resource_id:
:param group_id:
:param perm_name:
:param db_session:
:return:
"""
db_ses... |
return PermissionTuples for groups that have given permission for the resource perm_name is __any_permission__ then users with any permission will be listed | def groups_for_perm(
cls,
instance,
perm_name,
group_ids=None,
limit_group_permissions=False,
db_session=None,
):
"""
return PermissionTuples for groups that have given
permission for the resource, perm_name is __any_permission__ then
u... |
Selects resource for update - locking access for other transactions | def lock_resource_for_update(cls, resource_id, db_session):
"""
Selects resource for update - locking access for other transactions
:param resource_id:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
query = db_session.query(cls.mo... |
Fetch row using primary key - will use existing object in session if already present | def get(cls, user_id, db_session=None):
"""
Fetch row using primary key -
will use existing object in session if already present
:param user_id:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
return db_session.query(cls.mo... |
returns all non - resource permissions based on what groups user belongs and directly set ones for this user | def permissions(cls, instance, db_session=None):
"""
returns all non-resource permissions based on what groups user
belongs and directly set ones for this user
:param instance:
:param db_session:
:return:
"""
db_session = get_db_session(db_session, in... |
returns all resources that user has perms for ( note that at least one perm needs to be met ) | def resources_with_perms(
cls, instance, perms, resource_ids=None, resource_types=None, db_session=None
):
"""
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: ... |
Returns a list of groups users belongs to with eager loaded resources owned by those groups | def groups_with_resources(cls, instance):
"""
Returns a list of groups users belongs to with eager loaded
resources owned by those groups
:param instance:
:return:
"""
return instance.groups_dynamic.options(
sa.orm.eagerload(cls.models_proxy.Group.res... |
returns list of permissions and resources for this user | def resources_with_possible_perms(
cls, instance, resource_ids=None, resource_types=None, db_session=None
):
"""
returns list of permissions and resources for this user
:param instance:
:param resource_ids: restricts the search to specific resources
:param resource_t... |
returns user gravatar url | def gravatar_url(cls, instance, default="mm", **kwargs):
"""
returns user gravatar url
:param instance:
:param default:
:param kwargs:
:return:
"""
# construct the url
hash = hashlib.md5(instance.email.encode("utf8").lower()).hexdigest()
i... |
sets new password on a user using password manager | def set_password(cls, instance, raw_password):
"""
sets new password on a user using password manager
:param instance:
:param raw_password:
:return:
"""
# support API for both passlib 1.x and 2.x
hash_callable = getattr(
instance.passwordmanag... |
checks string with users password hash using password manager | def check_password(cls, instance, raw_password, enable_hash_migration=True):
"""
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:
"""
... |
fetch user by user id | 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 = db_session.query(cls.model)
query = query.filter(cls.model.id == user_id)
q... |
fetch user objects by user name and security code | def by_user_name_and_security_code(cls, user_name, security_code, db_session=None):
"""
fetch user objects by user name and security code
:param user_name:
:param security_code:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
... |
fetch user objects by user names | 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 = [(name or "").lower() for name in user_names]
db_session = get_db_session(db_session)
query =... |
fetch users with similar names using LIKE clause | 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:
"""
db_session = get_db_session(db_session)
query = db_session.query(cls.model)
query = query.... |
fetch user object by email | 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)
query = db_session.query(cls.model).filter(
sa.func.lower(cls.model.email) == (emai... |
return users hat have one of given permissions | 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:
"""
db_session = get_db_session(db_session)
query = db_session.query(cls.model)
query = query.... |
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:
self.joined[nickname] = datetime.now() |
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),
("week", 60 * 60 * 24 * 7),
("day", 60 * 60 * 24),
("hour", 60 * ... |
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.
"""
if command_name is None:
return ("Type !commands for a list of all commands. Type "
... |
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.
"""
if nickname and nickname != self.nickname:
try:
uptime = self.timesince(self.joined[nic... |
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:
pass
else:
if nickname == self.get_nickname(event):
... |
Unique identifier of user object | def id(self):
""" Unique identifier of user object"""
return sa.Column(sa.Integer, primary_key=True, autoincrement=True) |
Date of user s last login | def last_login_date(self):
""" Date of user's last login """
return sa.Column(
sa.TIMESTAMP(timezone=False),
default=lambda x: datetime.utcnow(),
server_default=sa.func.now(),
) |
Date of user s security code update | def security_code_date(self):
""" Date of user's security code update """
return sa.Column(
sa.TIMESTAMP(timezone=False),
default=datetime(2000, 1, 1),
server_default="2000-01-01 01:01",
) |
returns dynamic relationship for groups - allowing for filtering of data | def groups_dynamic(self):
""" returns dynamic relationship for groups - allowing for
filtering of data """
return sa.orm.relationship(
"Group",
secondary="users_groups",
lazy="dynamic",
passive_deletes=True,
passive_updates=True,
... |
Returns all resources directly owned by user can be used to assign ownership of new resources:: | def resources(self):
""" Returns all resources directly owned by user, can be used to assign
ownership of new resources::
user.resources.append(resource) """
return sa.orm.relationship(
"Resource",
cascade="all",
passive_deletes=True,
... |
Returns all resources directly owned by group can be used to assign ownership of new resources:: | def resources_dynamic(self):
""" Returns all resources directly owned by group, can be used to assign
ownership of new resources::
user.resources.append(resource) """
return sa.orm.relationship(
"Resource",
cascade="all",
passive_deletes=True,
... |
validates if group can get assigned with permission | def validate_permission(self, key, permission):
""" validates if group can get assigned with permission"""
if permission.perm_name not in self.__possible_permissions__:
raise AssertionError(
"perm_name is not one of {}".format(self.__possible_permissions__)
)
... |
Iterates through each of the feed URLs parses their items and sends any items to the channel that have not been previously been parsed. | def parse_feeds(self, message_channel=True):
"""
Iterates through each of the feed URLs, parses their items, and
sends any items to the channel that have not been previously
been parsed.
"""
if parse:
for feed_url in self.feeds:
feed = parse(fe... |
[ { 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: dict, f=None):
"""
[
{
'self': [1, 1, 3, 3, 1, 1],
'f': lambda x: x%2,
'assert': lambda ret: ret == [[1, 1], [3, 3], [1, 1]]
}
]
"""
if f is None:
return _chunk(self.items())
if is_to_destruct(f):
f = destruct... |
[ { self: [ 1 2 3 ] f: lambda x: x%2 assert: lambda ret: ret [ 0 ] == [ 2 ] and ret [ 1 ] == [ 1 3 ] } ] | def GroupBy(self: dict, f=None):
"""
[
{
'self': [1, 2, 3],
'f': lambda x: x%2,
'assert': lambda ret: ret[0] == [2] and ret[1] == [1, 3]
}
]
"""
if f and is_to_destruct(f):
f = destruct_func(f)
return _group_by(self.items(), f) |
[ { self: [ 1 2 3 ] n: 2 assert: lambda ret: list ( ret ) == [ 1 2 ] } ] | def Take(self: dict, n):
"""
[
{
'self': [1, 2, 3],
'n': 2,
'assert': lambda ret: list(ret) == [1, 2]
}
]
"""
for i, e in enumerate(self.items()):
if i == n:
break
yield e |
[ { self: [ 1 2 3 ] f: lambda e: e%2 assert: lambda ret: list ( ret ) == [ 1 3 ] } ] | def TakeIf(self: dict, f):
"""
[
{
'self': [1, 2, 3],
'f': lambda e: e%2,
'assert': lambda ret: list(ret) == [1, 3]
}
]
"""
if is_to_destruct(f):
f = destruct_func(f)
return (e for e in self.items() if f(e)) |
[ { self: [ 1 2 3 4 5 ] f: lambda x: x < 4 assert: lambda ret: list ( ret ) == [ 1 2 3 ] } ] | def TakeWhile(self: dict, f):
"""
[
{
'self': [1, 2, 3, 4, 5],
'f': lambda x: x < 4,
'assert': lambda ret: list(ret) == [1, 2, 3]
}
]
"""
if is_to_destruct(f):
f = destruct_func(f)
for e in self.items():
if not f(e):
... |
[ { self: [ 1 2 3 4 5 ] n: 3 assert: lambda ret: list ( ret ) == [ 1 2 ] } ] | def Drop(self: dict, n):
"""
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [1, 2]
}
]
"""
n = len(self) - n
if n <= 0:
yield from self.items()
else:
for i, e in enumerate(self.items()):
... |
[ { self: [ 1 2 3 4 5 ] n: 3 assert: lambda ret: list ( ret ) == [ 4 5 ] } ] | def Skip(self: dict, n):
"""
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [4, 5]
}
]
"""
con = self.items()
for i, _ in enumerate(con):
if i == n:
break
return... |
Output readings for specified number of rows to console | def print_meter_record(file_path, rows=5):
""" Output readings for specified number of rows to console """
m = nr.read_nem_file(file_path)
print('Header:', m.header)
print('Transactions:', m.transactions)
for nmi in m.readings:
for channel in m.readings[nmi]:
print(nmi, 'Channel'... |
returns all users that have permissions for this resource | def users(self):
""" returns all users that have permissions for this resource"""
return sa.orm.relationship(
"User",
secondary="users_resources_permissions",
passive_deletes=True,
passive_updates=True,
) |
This returns you subtree of ordered objects relative to the start resource_id ( currently only implemented in postgresql ) | def from_resource_deeper(
cls, resource_id=None, limit_depth=1000000, db_session=None, *args, **kwargs
):
"""
This returns you subtree of ordered objects relative
to the start resource_id (currently only implemented in postgresql)
:param resource_id:
:param limit_dep... |
This deletes whole branch with children starting from resource_id | def delete_branch(cls, resource_id=None, db_session=None, *args, **kwargs):
"""
This deletes whole branch with children starting from resource_id
:param resource_id:
:param db_session:
:return:
"""
tablename = cls.model.__table__.name
# lets lock rows to... |
This returns you subtree of ordered objects relative to the start parent_id ( currently only implemented in postgresql ) | def from_parent_deeper(
cls, parent_id=None, limit_depth=1000000, db_session=None, *args, **kwargs
):
"""
This returns you subtree of ordered objects relative
to the start parent_id (currently only implemented in postgresql)
:param resource_id:
:param limit_depth:
... |
Returns a dictionary in form of { node: Resource children: { node_id: Resource }} | def build_subtree_strut(self, result, *args, **kwargs):
"""
Returns a dictionary in form of
{node:Resource, children:{node_id: Resource}}
:param result:
:return:
"""
items = list(result)
root_elem = {"node": None, "children": OrderedDict()}
if len... |
This returns you path to root node starting from object_id currently only for postgresql | def path_upper(
cls, object_id, limit_depth=1000000, db_session=None, *args, **kwargs
):
"""
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:... |
Moves node to new location in the tree | def move_to_position(
cls,
resource_id,
to_position,
new_parent_id=noop,
db_session=None,
*args,
**kwargs
):
"""
Moves node to new location in the tree
:param resource_id: resource to move
:param to_position: new position
... |
Shifts ordering to open a gap for node insertion begins the shift from given position | def shift_ordering_up(cls, 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:
"""
db_s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.