sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _estimateCubicCurveLength(pt0, pt1, pt2, pt3, precision=10): """ Estimate the length of this curve by iterating through it and averaging the length of the flat bits. """ points = [] length = 0 step = 1.0 / precision factors = range(0, precision + 1) for i in factors: poin...
Estimate the length of this curve by iterating through it and averaging the length of the flat bits.
entailment
def _mid(pt1, pt2): """ (Point, Point) -> Point Return the point that lies in between the two input points. """ (x0, y0), (x1, y1) = pt1, pt2 return 0.5 * (x0 + x1), 0.5 * (y0 + y1)
(Point, Point) -> Point Return the point that lies in between the two input points.
entailment
def split(self, tValues): """ Split the segment according the t values """ if self.segmentType == "curve": on1 = self.previousOnCurve off1 = self.points[0].coordinates off2 = self.points[1].coordinates on2 = self.points[2].coordinates ...
Split the segment according the t values
entailment
def tValueForPoint(self, point): """ get a t values for a given point required: the point must be a point on the curve. in an overlap cause the point will be an intersection points wich is alwasy a point on the curve """ if self.segmentType == "curve": ...
get a t values for a given point required: the point must be a point on the curve. in an overlap cause the point will be an intersection points wich is alwasy a point on the curve
entailment
def getData(self): """ Return a list of normalized InputPoint objects for the contour drawn with this pen. """ # organize the points into segments # 1. make sure there is an on curve haveOnCurve = False for point in self._points: if point.segme...
Return a list of normalized InputPoint objects for the contour drawn with this pen.
entailment
def reCurveFromEntireInputContour(self, inputContour): """ Match if entire input contour matches entire output contour, allowing for different start point. """ if self.clockwise: inputFlat = inputContour.clockwiseFlat else: inputFlat = inputContour...
Match if entire input contour matches entire output contour, allowing for different start point.
entailment
def _is_custom_qs_manager(funcdef): """Checks if a function definition is a queryset manager created with the @queryset_manager decorator.""" decors = getattr(funcdef, 'decorators', None) if decors: for dec in decors.get_children(): try: if dec.name == 'queryset_mana...
Checks if a function definition is a queryset manager created with the @queryset_manager decorator.
entailment
def _is_call2custom_manager(node): """Checks if the call is being done to a custom queryset manager.""" called = safe_infer(node.func) funcdef = getattr(called, '_proxied', None) return _is_custom_qs_manager(funcdef)
Checks if the call is being done to a custom queryset manager.
entailment
def _is_custom_manager_attribute(node): """Checks if the attribute is a valid attribute for a queryset manager. """ attrname = node.attrname if not name_is_from_qs(attrname): return False for attr in node.get_children(): inferred = safe_infer(attr) funcdef = getattr(inferre...
Checks if the attribute is a valid attribute for a queryset manager.
entailment
def by_group_and_perm(cls, group_id, perm_name, db_session=None): """ return by by_user_and_perm and permission name :param group_id: :param perm_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.quer...
return by by_user_and_perm and permission name :param group_id: :param perm_name: :param db_session: :return:
entailment
def serve_forever(django=False): """ Starts the gevent-socketio server. """ logger = getLogger("irc.dispatch") logger.setLevel(settings.LOG_LEVEL) logger.addHandler(StreamHandler()) app = IRCApplication(django) server = SocketIOServer((settings.HTTP_HOST, settings.HTTP_PORT), app) pr...
Starts the gevent-socketio server.
entailment
def kill(pid_file): """ Attempts to shut down a previously started daemon. """ try: with open(pid_file) as f: os.kill(int(f.read()), 9) os.remove(pid_file) except (IOError, OSError): return False return True
Attempts to shut down a previously started daemon.
entailment
def run(): """ CLI entry point. Parses args and starts the gevent-socketio server. """ settings.parse_args() pid_name = "gnotty-%s-%s.pid" % (settings.HTTP_HOST, settings.HTTP_PORT) pid_file = settings.PID_FILE or os.path.join(gettempdir(), pid_name) if settings.KILL: if kill(pid_fil...
CLI entry point. Parses args and starts the gevent-socketio server.
entailment
def on_start(self, host, port, channel, nickname, password): """ A WebSocket session has started - create a greenlet to host the IRC client, and start it. """ self.client = WebSocketIRCClient(host, port, channel, nickname, password, self) ...
A WebSocket session has started - create a greenlet to host the IRC client, and start it.
entailment
def disconnect(self, *args, **kwargs): """ WebSocket was disconnected - leave the IRC channel. """ quit_message = "%s %s" % (settings.GNOTTY_VERSION_STRING, settings.GNOTTY_PROJECT_URL) self.client.connection.quit(quit_message) super(IRCN...
WebSocket was disconnected - leave the IRC channel.
entailment
def bot_watcher(self): """ Thread (greenlet) that will try and reconnect the bot if it's not connected. """ default_interval = 5 interval = default_interval while True: if not self.bot.connection.connected: if self.bot.reconnect(): ...
Thread (greenlet) that will try and reconnect the bot if it's not connected.
entailment
def respond_webhook(self, environ): """ Passes the request onto a bot with a webhook if the webhook path is requested. """ request = FieldStorage(fp=environ["wsgi.input"], environ=environ) url = environ["PATH_INFO"] params = dict([(k, request[k].value) for k in re...
Passes the request onto a bot with a webhook if the webhook path is requested.
entailment
def respond_static(self, environ): """ Serves a static file when Django isn't being used. """ path = os.path.normpath(environ["PATH_INFO"]) if path == "/": content = self.index() content_type = "text/html" else: path = os.path.join(os.p...
Serves a static file when Django isn't being used.
entailment
def index(self): """ Loads the chat interface template when Django isn't being used, manually dealing with the Django template bits. """ root_dir = os.path.dirname(__file__) template_dir = os.path.join(root_dir, "templates", "gnotty") with open(os.path.join(templa...
Loads the chat interface template when Django isn't being used, manually dealing with the Django template bits.
entailment
def authorized(self, environ): """ If we're running Django and ``GNOTTY_LOGIN_REQUIRED`` is set to ``True``, pull the session cookie from the environment and validate that the user is authenticated. """ if self.django and settings.LOGIN_REQUIRED: try: ...
If we're running Django and ``GNOTTY_LOGIN_REQUIRED`` is set to ``True``, pull the session cookie from the environment and validate that the user is authenticated.
entailment
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." if not db.dry_run: orm['gnotty.IRCMessage'].objects.filter(message="joins").update(join_or_leave=True) orm['gnotty.IRCMessage...
Write your forwards methods here.
entailment
def resource_permissions_for_users( models_proxy, perm_names, resource_ids=None, user_ids=None, group_ids=None, resource_types=None, limit_group_permissions=False, skip_user_perms=False, skip_group_perms=False, db_session=None, ): """ Returns permission tuples that match ...
Returns permission tuples that match one of passed permission names perm_names - list of permissions that can be matched user_ids - restrict to specific users group_ids - restrict to specific groups resource_ids - restrict to specific resources limit_group_permissions - should be used if we do not w...
entailment
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.append((perm.user.id, perm.perm_name)) elif perm.type == "group": ...
Legacy acl format kept for bw. compatibility :param permissions: :return:
entailment
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: if perm.type == "user": acls.append((Allow, perm.user.id, perm.perm_name)) elif per...
Returns a list of permissions in a format understood by pyramid :param permissions: :return:
entailment
def ChunkBy(self, 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) if is_to_destruct(f): f = destruct_func(f) r...
[ { 'self': [1, 1, 3, 3, 1, 1], 'f': lambda x: x%2, 'assert': lambda ret: ret == [[1, 1], [3, 3], [1, 1]] } ]
entailment
def GroupBy(self: Iterable, 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, f)
[ { 'self': [1, 2, 3], 'f': lambda x: x%2, 'assert': lambda ret: ret[0] == [2] and ret[1] == [1, 3] } ]
entailment
def Take(self: Iterable, n): """ [ { 'self': [1, 2, 3], 'n': 2, 'assert': lambda ret: list(ret) == [1, 2] } ] """ for i, e in enumerate(self): if i == n: break yield e
[ { 'self': [1, 2, 3], 'n': 2, 'assert': lambda ret: list(ret) == [1, 2] } ]
entailment
def TakeIf(self: Iterable, 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 if f(e))
[ { 'self': [1, 2, 3], 'f': lambda e: e%2, 'assert': lambda ret: list(ret) == [1, 3] } ]
entailment
def TakeWhile(self: Iterable, 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: if not f(e): ...
[ { 'self': [1, 2, 3, 4, 5], 'f': lambda x: x < 4, 'assert': lambda ret: list(ret) == [1, 2, 3] } ]
entailment
def Drop(self: Iterable, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [1, 2] } ] """ con = tuple(self) n = len(con) - n if n <= 0: yield from con else: for i, e in enumerate(con): ...
[ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [1, 2] } ]
entailment
def Skip(self: Iterable, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [4, 5] } ] """ con = iter(self) for i, _ in enumerate(con): if i == n: break retur...
[ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [4, 5] } ]
entailment
def Shift(self, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [4, 5, 1, 2, 3] } ] """ headn = tuple(Take(self, n)) yield from self yield from headn
[ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [4, 5, 1, 2, 3] } ]
entailment
def Concat(self: Iterable, *others): """ [ { '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] } ] """ return concat_generator(self, *[unbox_if_flow(other) for other in others])
[ { '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] } ]
entailment
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')""" last_child = node.last_child() if not last_child: return False # the default qs manager is called '...
Checks if an attribute is being accessed throught the default queryset manager, ie: MyClass.objects.filter(some='value')
entailment
def all(cls, klass, db_session=None): """ 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: ...
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:
entailment
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_session.query(cls.model)
returns base query for specific service :param db_session: :return: query
entailment
def on(event, *args, **kwargs): """ 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 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...
entailment
def get_db_session(session=None, obj=None): """ 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...
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...
entailment
def get_dict(self, exclude_keys=None, include_keys=None): """ 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 re...
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...
entailment
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))) return result
return list of tuples keys and values corresponding to this model's data
entailment
def populate_obj(self, appstruct, exclude_keys=None, include_keys=None): """ 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 fro...
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...
entailment
def populate_obj_from_obj(self, instance, exclude_keys=None, include_keys=None): """ 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 fro...
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...
entailment
def delete(self, db_session=None): """ Deletes the object via session, this will permanently delete the object from storage on commit :param db_session: :return: """ db_session = get_db_session(db_session, self) db_session.delete(self)
Deletes the object via session, this will permanently delete the object from storage on commit :param db_session: :return:
entailment
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
turn off the HX711 :return: always True :rtype bool
entailment
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
power up the HX711 :return: always True :rtype bool
entailment
def reset(self): """ reset the HX711 and prepare it for the next reading :return: True on success :rtype bool :raises GenericHX711Exception """ logging.debug("power down") self.power_down() logging.debug("power up") self.power_up() ...
reset the HX711 and prepare it for the next reading :return: True on success :rtype bool :raises GenericHX711Exception
entailment
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( ...
check if "times" is within the borders defined in the class :param times: "times" to check :type times: int
entailment
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))
validate a given value for gain_A :type gain_A: int :raises: ValueError
entailment
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...
check if ther is som data is ready to get read. :return True if there is some date :rtype bool
entailment
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 ...
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
entailment
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...
- 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
entailment
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...
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
entailment
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 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:
entailment
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 deletes whole branch with children starting from resource_id :param resource_id: :param db_session: :return:
entailment
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: ...
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:
entailment
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)
Returns a dictionary in form of {node:Resource, children:{node_id: Resource}} :param result: :return:
entailment
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...
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:
entailment
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 ...
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:
entailment
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 "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:
entailment
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...
Shifts ordering to "open a gap" for node insertion, begins the shift from given position :param parent_id: :param position: :param db_session: :return:
entailment
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...
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):
entailment
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...
Checks if parent destination is valid for node :param resource_id: :param new_parent_id: :param db_session: :return:
entailment
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...
Counts children of resource node :param resource_id: :param db_session: :return:
entailment
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...
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:
entailment
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]
takes a list of lists, l and returns a flat list
entailment
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...
Read in NEM file and return meter readings named tuple :param file_path: The NEM file to process :returns: The file that was created
entailment
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 file and return meter readings named tuple
entailment
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...
Parse NEM row iterator and return meter readings named tuple
entailment
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....
Calculate the interval between two manual readings
entailment
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 header record (100)
entailment
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 NMI data details record (200)
entailment
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], ...
Parse basic meter data record (250)
entailment
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...
Interval data record (300)
entailment
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 interval values into tuples with datetime
entailment
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
Convert reading value to float (if possible)
entailment
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])
Interval event record (400)
entailment
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_...
Updates readings from a 300 row to reflect any events found in a subsequent 400 row
entailment
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...
Parse a datetime string into a python datetime object
entailment
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 ``...
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``.
entailment
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...
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.
entailment
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 "")
Join the channel once connected to the IRC server.
entailment
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...
Increment a digit on the nickname if it's in use, and re-connect.
entailment
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...
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.
entailment
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 a message to the channel. We also emit the message back to the sender's WebSocket.
entailment
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...
Send the nickname list to the Websocket. Called whenever the nicknames list changes.
entailment
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] = ...
Initial list of nicknames received - remove op/voice prefixes, and send the list to the WebSocket.
entailment
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 joined the channel - send the nicknames list to the WebSocket.
entailment
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 changed their nickname - send the nicknames list to the WebSocket.
entailment
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...
Someone left the channel - send the nicknames list to the WebSocket.
entailment
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"...
Messages received in the channel - send them to the WebSocket.
entailment
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...
Fetch row using primary key - will use existing object in session if already present :param resource_id: :param db_session: :return:
entailment
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 all permissions that given user has for this resource from groups and directly set ones too :param instance: :param user: :param db_session: :return:
entailment
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 without ones inherited from groups that user belongs to :param instance: :param user: :param db_session: :return:
entailment
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...
returns permissions that given user has for this resource that are inherited from groups :param instance: :param user: :param db_session: :return:
entailment
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 ...
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 ...
entailment
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 the resouce by id :param resource_id: :param db_session: :return:
entailment
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...
fetch permissions by group and permission name :param resource_id: :param group_id: :param perm_name: :param db_session: :return:
entailment
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...
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...
entailment
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...
Selects resource for update - locking access for other transactions :param resource_id: :param db_session: :return:
entailment
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...
Fetch row using primary key - will use existing object in session if already present :param user_id: :param db_session: :return:
entailment