def __cache():
     if (key not in CACHE or
        cur_time() > CACHE[key]['time']):
         CACHE[key] = {
             'data': fun(),
             'time': cur_time()+duration
         }
     return CACHE[key]['data']
Пример #2
0
 def __init__(self, pd):
     self.pd = pd
     self.nt2vecs = defaultdict(lambda: defaultdict(lambda: (np.random.rand(
         pd['dim']) - 0.5) / pd['dim']))
     self.start_time = cur_time()
     self.product_counts = defaultdict(lambda: 0)
     self.emb_size = pd['dim']
     self.embed_algo = OMBA(self.pd)
Пример #3
0
    def create_backup(self, physical: bool = True, memory: bool = True):
        """
        Back up the current state of the hosts file to another file or to memory.

        :param physical: Whether to back up the file to another backup file.
        :param memory: Whether to back up the file to memory.
        :raises ValueError: If both options are disabled (because then no backup will occur).
        """
        if not physical and not memory:
            raise ValueError(f"create_backup called but both backup methods are disabled")
        if memory:
            self._memory_backup = self.read_raw()
            self._last_memory_backup = cur_time()
        if physical:
            if self._backup_path.exists():
                print(f"Overriding existing backup file at {self._backup_path}")
            copy(str(self.path), str(self._backup_path))
            self._last_physical_backup = cur_time()
Пример #4
0
    def check_alarms(self):
        if 'queue' not in self.alarms:
            return

        queue = self.alarms['queue']
        while queue:
            time, msg, location = queue[0]
            if time <= cur_time():
                self.msg(location, msg)
                queue.pop(0)
            else:
                break

        self.alarms['queue'] = queue
Пример #5
0
    def check_alarms(self):
        if 'queue' not in self.alarms:
            return

        queue = self.alarms['queue']
        while queue:
            time, msg, location = queue[0]
            if time <= cur_time():
                self.msg(location, msg)
                queue.pop(0)
            else:
                break

        self.alarms['queue'] = queue
Пример #6
0
def setstate():
    """ Compute state from all animations instead of just diffs. """
    animations = doc['editor.slide.animations']
    count = doc['editor.slide.count']
    t = cur_time() - animations['start_t']
    print "setting state to t=%s count=%s" % (t, count)
    waits = 0
    # Should probably traverse values that are higher than count in reverse order for.
    reindexed = [
        list(group)
        for k, group in groupby(animations, lambda x: x.name == "anim_wait")
        if not k
    ]
    print "max_count=", len(reindexed)
    for one_set in reindexed[:count]:
        for group in one_set:
            if group.name != "group":
                group = [group]
            for node in group:
                if node['max_t'] is None:
                    continue
                doc[node['target']] = interpolate(node, node['max_t'])

    for one_set in reversed(reindexed[count + 1:]):
        for group in one_set:
            if group.name != "group":
                group = [group]
            for node in group:
                if node['max_t'] is None:
                    continue
                doc[node['target']] = interpolate(node, 0)

    if count >= len(reindexed):
        return
    one_set = reindexed[count]
    for group in one_set:
        if group.name != "group":
            group = [group]
        for node in group:
            _t = min(node['max_t'], t) if node['max_t'] is not None else t
            doc[node['target']] = interpolate(node, _t)
        # Only last element controls ending time in group.
        if t < node['max_t']:
            break
        else:
            t = t - node['max_t']
Пример #7
0
def slide_transition(diff=1):
    diff = int(diff)
    slide = doc['editor.slide']
    if 'count' not in slide:
        slide['count'] = 0
        slide = slide.L
    if diff > 0 and ("animations" not in slide
                     or slide['count'] >= max_count(slide['animations'])):
        change_slide(1)
    elif diff < 0 and ("animations" not in slide or slide['count'] == 0):
        # Should set t to max_t here?
        change_slide(-1)
        slide = doc['editor.slide']
        if 'animations' in slide:
            slide.L['count'] = max_count(slide.L['animations'])
    else:
        slide['count'] = max(0, slide['count'] + diff)
        pause_timer()
        doc['editor.slide.animations.start_t'] = cur_time()
        setstate()
        if diff > 0:
            runanim()
Пример #8
0
def animstep():
    animations = doc['editor.slide.animations']
    count = doc['editor.slide.count']
    t = cur_time() - animations['start_t']
    print "t=%s count=%s" % (t, count)
    waits = 0
    for group in animations:
        if group.name == "anim_wait":
            waits += 1
            continue
        if waits != count:
            continue
        if group.name != "group":
            group = [group]
        for node in group:
            _t = min(node['max_t'], t) if node['max_t'] is not None else t
            doc[node['target']] = interpolate(node, _t)
        # Only last element controls ending time in group.
        if t < node['max_t']:
            break
        else:
            t = t - node['max_t']
    else:
        doc.remove_expr('drawing.transforms.dummy', newval=None, if_expr=True)
Пример #9
0
def runanim():
    doc['editor.slide.animations.start_t'] = cur_time()
    #doc['animations.finished'] = False
    doc['drawing.transforms.dummy'] = exr("animstep()")
    unpause_timer()
Пример #10
0
def pause_timer():
    if not doc['timer.paused']:
        doc['timer.total'] = cur_time()
        doc['timer.paused'] = True
Пример #11
0
def test_setstate():
    doc['slide1.count'] = 0
    doc['slide1.animations.start_t'] = cur_time()
    setstate()
Пример #12
0
 def __init__(self, pd):
     self.pd = pd
     self.nt2vecs = None
     self.nt2cvecs = None
     self.start_time = cur_time()
Пример #13
0
 def __init__(self, pd):
     self.pd = pd
     self.lClus = pd['lClus'](pd)
     self.nt2vecs = None
     self.start_time = cur_time()
     self.embed_algo = self.pd['embed_algo'](self.pd)
Пример #14
0
def media(update: Update, context: CallbackContext) -> None:
    """Sends a reaction to media messages (pictures, videos, documents, voice notes)"""

    global last_reacted_at

    if cur_time() - last_reacted_at < 60:  # If a reaction was sent less than a minute ago
        return  # Don't send a reaction

    last_reacted_at = cur_time()

    chat_id = update.effective_chat.id
    msg_id = update.message.message_id
    name = get_nick(update, context)
    query = f"SELECT MEDIA_PROB FROM CHAT_SETTINGS WHERE CHAT_ID={chat_id};"

    true = connection(query, update)
    logger(message=f"The query executed on the database was:\n{query}\nand the result was:\n{true=}")

    false = 1 - true

    prob = r.choices([0, 1], weights=[false, true])[0]  # Probabilities are 0.7 - False, 0.3 - True by default

    if not prob:
        return

    if hasattr(update.message.audio, 'performer'):
        if update.message.audio.performer == 'Shani Sir':  # Don't send reaction to its own inline clips.
            return

    try:
        doc = update.message.document.file_name.split('.')[-1]
    except Exception as e:  # When there is no document sent (most likely AttributeError)
        logger(message=f"File extension was not assigned. The warning is: \n{e}", warning=True)
        doc = ''

    img_reactions = ("😂", "🤣", "�", f"Not funny {name} okay?", "This is not fine like you say", "*giggles*",
                     f"This is embarrassing to me {name}", "What your doing?! Go for the worksheet",
                     "I don't like this now", "This is beneficial to me like", f"I don't understand this {name}",
                     f"See {name}, I want you to delete this")

    vid_reactions = ("😂", "🤣", "�", f"I've never seen anything like this {name}", "What is this",
                     f"Tell me the physics behind it {name}", "This is like you say boring", "Now I feel very bad like",
                     f"Are you fine {name}?", f"See {name}, I want you to delete this")

    voice_reactions = ("What is this", f"I can't hear you {name}", f"Are you fine {name}?",
                       "Now your on the track like", "Your voice is funny like you say",
                       f"See I can't tolerate this {name}", "What your saying??",
                       f"See {name}, I want you to delete this")

    app_reactions = ("Is this a virus", "I'm just suggesting like, don't open this", "We just don't mind that okay?")

    doc_reactions = (f"Did you read this {name}", "I'm not in agreement like", "I don't like this okay",
                     "This is very good like you say", "Now your on the track like", "Nice for reading okay",
                     "This is fake news delete this like", "This is like you say cut and paste from somewhere")

    context.bot.send_chat_action(chat_id=chat_id, action='typing')
    sleep(2)

    if update.message.photo or doc in ('jpg', 'jpeg', 'png'):
        context.bot.send_message(chat_id=chat_id, text=r.choice(img_reactions), reply_to_message_id=msg_id)
        logger(message=f"Bot sent a reaction to a photo to {name}.")

    elif update.message.voice or update.message.audio:
        context.bot.send_message(chat_id=chat_id, text=r.choice(voice_reactions), reply_to_message_id=msg_id)
        logger(message=f"Bot sent a reaction to a voice message/audio to {name}.")

    elif update.message.video or doc in ('mp4', 'gif'):
        context.bot.send_message(chat_id=chat_id, text=r.choice(vid_reactions), reply_to_message_id=msg_id)
        logger(message=f"Bot sent a reaction to a video to {name}.")

    elif doc in ('apk', 'exe'):
        context.bot.send_message(chat_id=chat_id, text=r.choice(app_reactions), reply_to_message_id=msg_id)
        logger(message=f"Bot sent a reaction to a executable to {name}.")

    elif doc in ('pdf', 'doc', 'docx', 'txt'):
        context.bot.send_message(chat_id=chat_id, text=r.choice(doc_reactions), reply_to_message_id=msg_id)
        logger(message=f"Bot sent a reaction to a text document to {name}.")

    else:
        logger(message=f"This shouldn't be happening, bot needs to respond to at least one of the media."
                       f"The file extension was {doc=}.", warning=True)

    del chat_id, name, msg_id, query, true, false, prob, app_reactions, img_reactions, vid_reactions, voice_reactions, \
        doc_reactions