def intersects(self, aabb): """Return True if this AABB intersects with the argument AABB.""" check_type(aabb, AABB) return not (self.xmin > aabb.xmax or self.xmax < aabb.xmin or self.ymin > aabb.ymax or self.ymax < aabb.ymin)
def _multistream_call(self, method, streams): """Call 'method' (a string, should be the name of a log stream method) on each of the argument 'streams'.""" for stream in streams: if isinstance(stream, basestring): stream = getattr(self, stream) check_type(stream, LogStream) bound_method = getattr(stream, method) bound_method()
def append(self, data): check_type(data, basestring) if self.payload_size is None: self.header += data self.parse_header() else: self.payload += data if self.payload_size is not None and len(self.payload) > self.payload_size: raise Exception("current payload size exceeds size declared in header")
def name(self, name): check_type(name, basestring) sep = type(self).NAME_SEPARATOR if sep in name: raise NameError("name cannot contain {!r}".format(sep)) if self._parent is not None: self._parent._rename_child(self, name) self._name = name self._update_fullname()
def add(self, plugin): """Add a plugin to the plugin manager. The argument can be a plugin object or a callable taking no arguments that returns a plugin object.""" if not isinstance(plugin, Plugin) and callable(plugin): plugin = plugin() check_type(plugin, Plugin) if plugin.name in self.namespace: raise NameError("duplicate plugin name {!r}".format(plugin.name)) self.namespace[plugin.name] = plugin plugin.install(self.solver)
def draw_object(self, widget): check_type(widget, EditorObject) if widget.id is None: widget.id = self.editor.id_generator(widget) if isinstance(widget, Origin): if self.origin is not None: raise ValueError("surface already has an origin") self.origin = widget self.origin.bind(pos=self.update_plane_status) self.plane.add_widget(widget)
def register_class(cls): """Class decorator used to add an editor object class to the class registry.""" try: key = cls.__dict__["registry_key"] except KeyError: raise KeyError("editor object type must define a registry key") check_type(key, str) if key in EditorObject.registry: raise KeyError("conflicting registry key %r" % (key,)) EditorObject.registry[key] = cls return cls
def set_enabled(self, **state): """Allows setting the state of multiple log streams in a single call. Example: log = Logger() log.set_enabled(debug=False, info=True, warning=False, error=True) If called without arguments, this is equivalent to enable().""" if len(state) == 0: self.enable() else: for name, enabled in state.iteritems(): stream = getattr(self, name) check_type(stream, LogStream) stream.enabled = enabled
def intersection(self, other): """Line intersection algorithm using Cramer's Rule. We put the two lines in parametric form and solve the system for the parameters 't' and 's' (the parameter in each line's parametric equation). This system of two equations is solved using Cramer's Rule. NOTE: this method will break when any of the values involved in the computation is too large (close to float/double overflow) and the internal computations result in an infinite determinant (i.e. float("inf")) for the original coefficient matrix ((a b) (c d)). If this determinant is infinite, the values of the parameters t and s will both be zero or NaN, leading to incorrect results.""" check_type(other, Segment) # both the x and y ranges must overlap for an intersection to be possible if (self.x_min > other.x_max or self.x_max < other.x_min or self.y_min > other.y_max or self.y_max < other.y_min): return None # a, b, c and d are the coefficients of the matrix a = self.dx b = -other.dx c = self.dy d = -other.dy ad_bc = a*d - b*c # if the determinant is 0, the system is either incompatible or indeterminate if ad_bc == 0.0: return _parallel_intersection(self, other) # e and f are the rhs values of the system e = other.x0 - self.x0 f = other.y0 - self.y0 # compute the parameter t in this line's equation and check if it is within bounds t = float(e*d - b*f) / ad_bc cls = type(self) if not (cls.t_min <= t <= cls.t_max): return None # compute the parameter s in the other line's equation and check if it is within bounds s = float(a*f - e*c) / ad_bc cls = type(other) if not (cls.t_min <= s <= cls.t_max): return None # finally, we find the point of intersection by applying parameter t to this line x = self.x0 + self.dx * t y = self.y0 + self.dy * t _x = other.x0 + other.dx * s _y = other.y0 + other.dy * s assert x == Approx(_x) and y == Approx(_y) return (x, y)
def __init__(self, name, parent=None, type_validation=True, register_types=None, callback_mode=CALLBACK_TAKES_LISTENER, log_fnc=None): check_type(name, basestring) sep = type(self).NAME_SEPARATOR if sep in name: raise NameError("name cannot contain {!r}".format(sep)) self._name = name self._fullname = name self._parent = None self._children = {} self.type_validation = type_validation self.registered_types = MultiSet() self.listeners = {} self.callback_mode = callback_mode self.log_fnc = log_fnc self.stack = [] if parent is not None: self.parent = parent if register_types is not None: self._register_propagate(register_types)
async def main(): packages = await get_packages_to_update() print(f"Total packages: {len(packages)}") packages = list(filter(lambda p: should_update(p), packages)) packages = list(filter(lambda p: check_type(p["code"]) is correios, packages)) batches = group_packages(packages, BATCH_SIZE) print(f"Number of batches: {len(batches)}, batch_size={BATCH_SIZE}") with ProgressBar("Packages", total=len(packages)) as progress: semaphore = asyncio.BoundedSemaphore(SEMAPHORE_SIZE) tasks = [update_package_group(batch, semaphore, progress) for batch in batches] await asyncio.gather(*tasks)
async def async_main(): cursor1 = db.rastreiobot.find() start = time() if check_system(): pass else: print("exit") return # await bot.send_message(str(-340600919), "oi", parse_mode='HTML', # disable_web_page_preview=True) tasks = [] n = 0 async for elem in cursor1: api_type = check_type(elem['code']) if api_type is correios: n += 1 tasks.append(up_package(elem)) await asyncio.gather(*tasks)
def cmd_magic(message): ''' Entry point for adding a tracking number ''' bot.send_chat_action(message.chat.id, 'typing') if str(message.from_user.id) in BANNED: log_text(message.chat.id, message.message_id, '--- BANIDO --- ' + message.text) bot.send_message(message.chat.id, msgs.banned) return 0 log_text(message.chat.id, message.message_id, message.text) user = str(message.chat.id) message_text = (message.text.replace('/start ', '').replace( '/', '').replace('📮', '').strip().split()) code = code_type = None for word in message_text: if word.lower() == '@rastreiobot': message_text.remove(word) code_type = check_type(word) if code_type: code = word.upper() message_text.remove(word) break message_text = ' '.join(message_text) try: desc = message_text.split('Data:')[0].replace(' ', '') if desc == '': desc = code except Exception: desc = code if code_type: try: subscriber = webhook.select_user('chatid', user)[1] except TypeError: subscriber = '' if code_type != correios and user not in PATREON and user not in subscriber: bot.reply_to(message, msgs.premium, parse_mode='HTML', disable_web_page_preview=True) log_text(message.chat.id, message.message_id, 'Pacote chines. Usuario nao assinante.') return 0 exists = check_package(code) if exists: if not db.package_has_user(code, user): db.add_user_to_package(code, user) stats = db.package_status(code) message = '' system = check_system_correios() for stat in stats: message = message + '\n\n' + stat if not system: message = (message + msgs.error_sys) if int(user) > 0: bot.send_message(user, message, parse_mode='HTML', reply_markup=markup_btn, disable_web_page_preview=True) else: send_clean_msg(bot, user, message) if desc != code: db.set_package_description(code, user, desc) else: stat = add_package(str(code), str(user)) share_button = types.InlineKeyboardMarkup() share_button.row( types.InlineKeyboardButton( "Compartilhar", url="https://rastreiobot.xyz/?codigo=" + code)) if stat == status.OFFLINE: bot.reply_to(message, 'Sistema fora do ar') elif stat == status.TYPO: bot.reply_to(message, msgs.typo) bot.delete_message(message.from_user.id, message.message_id) elif stat == status.NOT_FOUND: bot.reply_to(message, msgs.not_found) elif stat == status.NOT_FOUND_TM: bot.reply_to(message, msgs.not_found_tm) elif stat == status.OK: db.set_package_description(code, user, desc) if int(message.chat.id) > 0: bot.reply_to( message, 'Pacote cadastrado.\n\nCompartilhe usando o link abaixo:', reply_markup=share_button) print('share') if desc == code: send_clean_msg(bot, user, msgs.desc) else: bot.reply_to(message, 'Pacote cadastrado.', reply_markup=markup_clean) sttus = db.package_status(code) last = len(sttus) - 1 if int(user) > 0: bot.send_message(user, db.package_status(code)[last], parse_mode='HTML', reply_markup=markup_btn, disable_web_page_preview=True) else: send_clean_msg(bot, user, db.package_status(code)[last]) elif message.text.upper() == '/START': if int(message.chat.id) > 0: send_clean_msg(bot, message.chat.id, msgs.user) # bot.send_document(message.chat.id, 'CgADAQADhgAD45bBRvd9d-3ACM-cAg') # bot.send_document(message.chat.id, 'CgADAQADTAAD9-zRRl9s8doDwrMmAg') # bot.send_document(message.chat.id, 'CgADAQADPgADBm7QRkzGU7UpR3JzAg') try: bot.send_document(message.chat.id, 'CgADAQADWQADGu_QRlzGc4VIGIYaAg') except telebot.apihelper.ApiException: pass else: send_clean_msg(bot, message.chat.id, msgs.group) else: if int(user) > 0: bot.reply_to(message, msgs.typo) bot.delete_message(message.from_user.id, message.message_id) if int(user) > 0 and len(message.text) > 25: send_clean_msg(bot, message.from_user.id, msgs.invalid.format(message.from_user.id))
def type_check(obj, val): check_type(val, cls, none_allowed)
def dispatch(self, req): """Put a Request in the dispatcher's message queue.""" check_type(req, Request) self.messages.put(req)
def test_get_carrier_by_code(code, carrier): assert check_type(code) == carrier
def remove(self, plugin): check_type(plugin, Plugin) if self.namespace[plugin.name] is not plugin: raise ValueError("argument does not match plugin registered with the same name") del self.namespace[plugin.name] plugin.uninstall()
def children(self, child): check_type(child, Channel) if child._name in self._children: raise NameError("name {!r} already in use".format(child._name))