Ejemplo n.º 1
0
def edit_contact(request, username, action='block'):
    
    contact = get_object_or_404(request.user.contacts.exclude(contact=request.user), contact__username=username)
    contact_username = contact.contact.username.capitalize()
    
    redirect = request.GET.get(REDIRECT_FIELD_NAME, None)

    if action == 'delete':
        notification(request, _('%(user)s was removed from your contact list%(blocked)s.') % {
                          'user': contact_username,
                          'blocked': contact.is_blocked and _(' and unblocked') or '',
                          }
              )
        contact.delete()
    else:
        if action == 'block':
            contact.is_blocked = True
            notice_message = _('%s cannot contact you anymore.') % contact_username
            link_url = '%s%s' % (reverse('pm_contact_unblock', args=[contact.contact.username]),
                                 redirect and '?%s=%s' % (REDIRECT_FIELD_NAME, redirect) or '')
        else:
            contact.is_blocked = False
            notice_message = _('%s is now allowed to contact you.') % contact_username
            link_url = '%s%s' % (reverse('pm_contact_block', args=[contact.contact.username]),
                                 redirect and '?%s=%s' % (REDIRECT_FIELD_NAME, redirect) or '') 
        contact.save()
        
    notification(request,
           notice_message,
           template = 'notice_link',
           link_url = link_url,
           link_text = _('undo'),
           )

    return HttpResponseRedirect(redirect or reverse('pm_contact'))
Ejemplo n.º 2
0
 def checkboxsignal_udp(self):
     fg = bool(self.checkBox_4.isChecked())
     share.new_change_flag("UDP", fg)
     if fg and self.fnotification:
         notification(['Event Trigger', 'UDP Verbose Start'])
         self.addBottomText('Event Trigger : ' + 'UDP Verbose Start')
     if not fg:
         notification(['Event Trigger', 'UDP Verbose Stop'])
         self.addBottomText('Event Trigger : ' + 'UDP Verbose Stop')
     self.sniff.verbose_udp = fg
Ejemplo n.º 3
0
def send_sms():
    #Defining response
    response = {}

    #Getting variable from the request

    ep_id = request.args.get('ep_id', default=1, type=int)
    channel = request.args.get('channel', default='', type=str)
    whoto = request.args.get('whoto')

    #Requesting EP info and converting into a JSON
    p = json.loads(get_ep_info(ep_id))
    try:
        if p['status']['code'] != 200:
            response['status'] = 'failure'
            response['comment'] = 'review ep id'
            return response
    except:
        pass

    #Setting Body message, same for every channel
    body = '''
    Hello! Here is the result of your consult!
    EP Name: {ep_name}
    EP ID: {ep_id}
    LC: {ep_lc}
    MC: {ep_mc}
    Status: {ep_status}
    '''
    body = body.format(ep_name=p['full_name'],
                       ep_id=p['id'],
                       ep_lc=p['home_lc']['full_name'],
                       ep_mc=p['home_lc']['country'],
                       ep_status=p['status'])

    #send_by_the_channel_requested
    ##set params
    params = {'body': body, 'whoto': whoto, 'channel': channel}
    try:
        notification(params)
        response['ep_id'] = ep_id
        response['ep_name'] = p['first_name']
        response['channel'] = channel
        response['whoto'] = whoto
        response['body_message'] = params['body']
        response['status'] = 'success'
    except:
        response['status'] = 'failure'
        response[
            'comment'] = 'review params on http://127.0.0.1:5000/ or contact support'

    return response
Ejemplo n.º 4
0
def redirect(request, id, contact='', up=False, manager='inbox'):
    "Redirects to a message according to filters or return to messagebox."
    
    mgr = getattr(request.user, manager)
    if contact:
        mgr.filter_username(contact)
    redirect_url, page = mgr.get_redirect_detail(id, contact, up)
    
    if page:
        notice_message = page > 1 and _('No more messages, you are back on the last page.')\
                          or _('No more messages, you are back on the first page.')
        notification(request, notice_message)
      
    return HttpResponseRedirect(redirect_url)
Ejemplo n.º 5
0
def delete(request, id, manager='inbox', delete_time=datetime.now()):
    "Deletes a single message."
    mgr = getattr(request.user, manager)    
    message = get_object_or_404(mgr.all(), id=id)
    
    if message.set_delete_flag(request.user, delete_time):
        view = '%s/detail/' % manager
        timestamp = mktime(delete_time.timetuple()) + delete_time.microsecond / 1e6
        notification(request,
               _('Message deleted.'),
               template = 'notice_link',
               link_url = reverse('pm_restore', args=['%f' % timestamp, view]),
               link_text = _('undo'),
               )
    else:
        notification(request, _('No messages deleted.'))

    return redirect(request, id, '', manager)
Ejemplo n.º 6
0
def new(request, id=''):
    "Displays a form to compose a new message or edit a draft."

    draft = id and get_object_or_404(request.user.drafts, pk=id) or DraftMessage()

    if request.POST:
        if request.POST.has_key('draft'):
            # Save draft
            form = DraftMessageForm(request.POST)
            if form.is_valid():
                draft.sender = request.user
                draft.recipient_list = form.cleaned_data['recipient_list']
                draft.subject = form.cleaned_data['subject']
                draft.body = form.cleaned_data['body']
                draft.previous_message = form.cleaned_data['previous_message']
                draft.save()

                notification(request, _('Your draft was saved.'))
                return HttpResponseRedirect(draft.get_absolute_url())            
        
        else:
            # Send message
            form = NewMessageForm(request.POST)
            if form.is_valid():
                id and draft.delete()
                message = Message.objects.create(
                                                 subject = form.cleaned_data['subject'],
                                                 body = form.cleaned_data['body'],
                                                 )
                for recipient in form.cleaned_data['recipient_list']:
                    MessageBox.objects.create(
                                              sender = request.user,
                                              recipient = recipient,
                                              message = message,
                                              previous_message = form.cleaned_data['previous_message'],
                                              )
                notification(request, _('Your message was sent to %s.') % \
                    ', '.join([u.username.capitalize() for u in form.cleaned_data['recipient_list']]))
                
                return HttpResponseRedirect(form.cleaned_data['redirect'])
    else:
        initial_data = id and draft.__dict__ or {'recipient_list': request.GET.get(_('recipient'), '')}
        form = DraftMessageForm(initial=initial_data)
    return direct_to_template(request, 'pm/form.html', {'form': form})
Ejemplo n.º 7
0
def list(request, contact='', manager='inbox'):
    "Lists messages for inbox, outbox and drafts"
    
    mgr = getattr(request.user, manager)
    mgr.filter_username(contact)
    qs = mgr.all().select_related()
    
    if request.POST:
        # Handle message deletion
        if request.POST.has_key('delete'):
            delete_time = datetime.now()
            messages = mgr.in_bulk(request.POST.getlist('checkbox')).values()
            for message in messages:
                message.set_delete_flag(request.user, delete_time)
                
            count_deleted = len(messages)
            if count_deleted:
                view = '%s/list%s%s/' % ( manager, contact and '/' or '', contact )
                timestamp = mktime(delete_time.timetuple()) + delete_time.microsecond / 1e6
                notification(request,
                       ungettext('Message deleted.',
                                   '%(count)d messages deleted.', count_deleted) % {'count': count_deleted},
                       template = 'notice_link',
                       link_url = reverse('pm_restore', args=['%f' % timestamp, view]),
                       link_text = _('undo'),
                       )
                return HttpResponseRedirect(mgr.get_redirect_list(message.id, contact))
            else:
                notification(request,_('No messages deleted.'))
        
        # Handle contact filter
        if alnum_re.search(request.POST.get('contact', '')):
            return HttpResponseRedirect(reverse('pm_%s_contact' % manager, args=[request.POST['contact']]))
    
    return object_list(request=request,
                       queryset=qs,
                       template_name='pm/list_%s.html' % manager,
                       allow_empty=True,
                       paginate_by=PAGINATE_BY,
                       extra_context={'contact': contact}
                       )
Ejemplo n.º 8
0
def restore(request, timestamp, view):
    "Restores freshly deleted messages."
    MAX_RESTORE_TIME = 15 # minutes
    
    # Parse deletion time
    time_delete = datetime.fromtimestamp(float(timestamp))
    
    # Parse manager info
    manager, view, contact = view.split('/')[:3]
    
    # Allow restoration
    if datetime.now() - time_delete < timedelta(0, 60 * MAX_RESTORE_TIME):
        
        mgr = getattr(request.user, manager)
        message, count_restored = mgr.restore_deleted_messages(time_delete, request.user)
        
        if count_restored:
            notice_message = ungettext('Message restored.',
                               '%(count)d messages restored.', count_restored) % {'count': count_restored}
        else:
            notice_message = _('No messages restored.')      
    else:
        count_restored = 0
        notice_message = _('You cannot restore messages deleted more than %d minutes ago.') % MAX_RESTORE_TIME
    
    notification(request, notice_message)
    
    if count_restored == 0:
        return HttpResponseRedirect(reverse('pm_%s' % manager))
    
    # Construct redirect url with the correct page if we have a list
    if view == 'detail':
        return HttpResponseRedirect(reverse('pm_%s_read' % manager, args=[message.id]))
    else:
        if contact:
            mgr.filter_username(contact)
        return HttpResponseRedirect(mgr.get_redirect_list(message.id, contact))
Ejemplo n.º 9
0
 def write_final_stat(self):
     ''' Function writes statistics to log after job
         and if set than send email notification to job owner
     '''
     msg = "Job {0} finished OK. Compressed files {1}, error {2} \n".format(
         self.conf["job_name"], str(self.ok), str(self.err))
     print(msg)
     self.write_to_log(msg)
     if (self.conf["inform_owner"]):
         notification1 = notification.notification(
             self.conf["sender_email"], self.conf["receiver_email"],
             self.conf["email_passwd"], self.conf["smtp_server"],
             self.conf["ssl_port"])
         notification1.prepare_message(msg)
         notification1.sent()
Ejemplo n.º 10
0
    def decrementTime(self):
        currentTime = self.currentTime.get()

        if self.timerRunning and currentTime != "00:00":
            minutes, seconds = currentTime.split(":")

            if int(seconds) > 0:
                seconds = int(seconds) - 1
                minutes = int(minutes)
            else:
                seconds = 59
                minutes = int(minutes) - 1

            self.currentTime.set(f"{minutes:02d}:{seconds:02d}")
            self._timerDecrementJob = self.after(1000, self.decrementTime)

        elif self.timerRunning and currentTime == "00:00":
            self.controller.timerSchedule.rotate(-1)
            nextUp = self.controller.timerSchedule[0]
            self.currentTimerLabel.set(nextUp)

            if nextUp == "Pomodoro":
                notification("Break has ended. Get back to work!")
                pomodoroTime = int(self.controller.pomodoro.get())
                self.currentTime.set(f"{pomodoroTime:02d}:00")
            elif nextUp == "Short Break":
                notification(
                    "Focus session has ended. Let's take a Short Break!")
                shortBreakTime = int(self.controller.shortBreak.get())
                self.currentTime.set(f"{shortBreakTime:02d}:00")
            elif nextUp == "Long Break":
                notification(
                    "4th Focus session has ended. Time for a Long Break")
                longBreakTime = int(self.controller.longBreak.get())
                self.currentTime.set(f"{longBreakTime:02d}:00")

            sound.Beep(500, 1000)
            self._timerDecrementJob = self.after(1000, self.decrementTime)
Ejemplo n.º 11
0
 def push_notification(self, text):
     if self.verbose_notification:
         notification(text)
Ejemplo n.º 12
0
    img_urls = []
    source = path['remoteReadPath'].split('/')[-3]
    if source == "reddit-Search" or source == "reddit-Post" \
            or source == "crimson-Hexagon" or source == "reddit-Historical-Post"\
            and 'url' in list(df.columns):
        img_urls = df['url'].dropna().tolist()

    elif source == "twitter-Tweet" or source == "twitter-Timeline" \
            and 'entities.media.media_url' in list(df.columns):
        img_urls = df['entities.media.media_url'].dropna().tolist()

    elif source == 'flickr-Photo' and 'size.source' in list(df.columns):
        img_urls = df['size.source'].dropna().tolist()

    else:
        raise ValueError("This data source does not support image collection!")

    urls = {}
    for img_url in img_urls:
        if ic.is_image(img_url):
            filename, binary = ic.crawler(img_url)
            dataset.save_local_output(path['localSavePath'], filename, binary)
    urls['images.zip'] = dataset.save_remote_output(
        path['localSavePath'], path['remoteSavePath'], 'images.zip')

    # push notification email
    notification(toaddr=params['email'], case=3,
                 filename=path['remoteSavePath'],
                 links=urls, sessionURL=params['sessionURL'])
Ejemplo n.º 13
0
    def count(self, timer):
        if timer <= -1:

            # toggle is break
            self.is_break = not self.is_break

            # prompt and start new session
            if self.is_break and self.session_counter % 4 != 0:
                if self.user:
                    success_text, scored_task = self.score_to_habitica()
                notification(0, task=scored_task if self.user is True else "")
                prompt_answer = messagebox.askquestion(
                    "Session Ended!",
                    success_text if self.user is True else "" +
                    "Are you ready for a break?",
                    icon='question')
            elif self.is_break and self.session_counter % 4 == 0:
                if self.user:
                    success_text, scored_task = self.score_to_habitica()
                notification(0, task=scored_task if self.user is True else "")
                prompt_answer = messagebox.askquestion(
                    "4 POMODORI!",
                    success_text if self.user is True else "" +
                    "\nDo you think you deserve a very long break?",
                    icon='question')
            else:
                notification(1)
                prompt_answer = messagebox.askquestion(
                    "Time's up!", "Ready for a new session?", icon='question')

            # prompts and restart cycle
            if prompt_answer == 'yes' and self.session_counter % 4 != 0 and self.is_break:
                self.after_cancel(self.job)
                self.count(self.short_rest_scs)
                self.status_label.config(text="Break", fg="orange")
                if self.user:
                    self.switch_task_label.grid()
                    self.switch_task_menu.grid()
            elif prompt_answer == 'yes' and self.session_counter % 4 == 0 and self.is_break:
                self.after_cancel(self.job)
                self.count(self.long_rest_scs)
                self.status_label.config(text="Long Break", fg="orange")
                if self.user:
                    self.switch_task_label.grid()
                    self.switch_task_menu.grid()
            elif prompt_answer == 'no':
                self.stop_count()
            else:
                self.status_label.config(text="Pomodoro", fg="green")
                if self.user:
                    self.set_radio_from_optionlist()
                self.update_current_task_labels()
                self.session_counter += 1
                self.count(self.session_scs)
                if self.user:
                    self.switch_task_label.grid_remove()
                    self.switch_task_menu.grid_remove()
            return

        m, s = divmod(timer, 60)
        self.time_label.configure(text='{:02d}:{:02d}'.format(m, s))
        if self.is_break:
            self.streak_label.configure(text='BREAK!')
        else:
            self.streak_label.configure(
                text='Streak: {}'.format(self.session_counter))
        self.job = self.after(1000, self.count, timer - 1)
Ejemplo n.º 14
0
    try:
        s3.downloadToDisk(screen_name + '_tweets.txt', localPath, awsPath)
    except:
        raise ValueError('Cannot find the timeline in the remote storage!')

    # calculate brand personality
    model = MultiLabelClassificationModel('roberta',
                                          'checkpoint-17315-epoch-5',
                                          num_labels=5,
                                          args={
                                              "reprocess_input_data": True,
                                              'use_cached_eval_features': False
                                          },
                                          use_cuda=False)
    df = pd.read_csv(os.path.join(localPath, screen_name + '_tweets.txt'))
    new_df = multiple_sentences(df, model)
    fname_sentences = screen_name + '_utku_personality_sentences.csv'
    new_df.to_csv(os.path.join(localPath, fname_sentences), index=False)
    s3.upload(localPath, awsPath, fname_sentences)

    # get the average score
    mean_metrics = average(new_df)
    fname_average = screen_name + '_utku_personality_average.json'
    with open(os.path.join(localPath, fname_average), 'w') as f:
        json.dump(mean_metrics, f)
    s3.upload(localPath, awsPath, fname_average)

    # push notification email
    notification(toaddr=params['email'], sessionURL=params['sessionURL'])
Ejemplo n.º 15
0
	def push_notification(self,notification):
		if self.verbose_notification:
			notification(notification)