Example #1
0
def exit_ok(msg=""):
    if not msg == "":
        feed_utils.ok(msg)
    if feed_utils.NOTIFY:
        mail_utils.send_mail(feed_utils.NOTIFY_TO, "TC app ok",
                             feed_utils.COLLECTED_FEED, feed_utils.NOTIFY_FROM)
    sys.exit(0)
Example #2
0
def exit_fail(msg=""):
    if not msg == "":
        feed_utils.failed(msg)
    if feed_utils.NOTIFY:
        mail_utils.send_mail(feed_utils.NOTIFY_TO, "app failure",
                             feed_utils.COLLECTED_FEED, feed_utils.NOTIFY_FROM)
    sys.exit(-1)
Example #3
0
def update_active(_id):
    """
    Публікація опитування, розсилання смс та email з паролями для проходження опитування. В групу Poll
    :param _id: id опитування
    """
    k = 0
    session = Session()
    res = request.json
    all_records = session.query(Poll).filter_by(id=_id).all()
    converter = PollSchema(many=True,
                           only=[
                               'id', 'name', 'created', 'count_of_complete',
                               'total_count', 'status', 'description'
                           ])
    result = converter.dump(all_records).data
    for arg in res['email']:
        for step in range(0, arg['copy']):
            k += 1
            password = id_generator()
            dep = from_dep(arg['email'])
            if dep == []:
                data = []
                qw = {}
                qw.setdefault('departmentUa', '')
                qw.setdefault('cityUa', '')
                data.append(qw)
                dep = data
            list_count_poll = session.query(Statistics) \
                .filter(Statistics.department == dep[0]['departmentUa']) \
                .filter(Statistics.city == dep[0]['cityUa']) \
                .filter(Statistics.fk_poll == _id).all()
            if list_count_poll == []:
                statistick = Statistics(total_count=1,
                                        fk_poll=_id,
                                        department=dep[0]['departmentUa'],
                                        city=dep[0]['cityUa'])
                session.add(statistick)
            else:
                session.query(Statistics) \
                    .filter(Statistics.department == dep[0]['departmentUa']) \
                    .filter(Statistics.city == dep[0]['cityUa']) \
                    .filter_by(fk_poll=_id).update({"total_count": Statistics.total_count + 1})

            passrords = Password(password=password,
                                 department=dep[0]['departmentUa'],
                                 city=dep[0]['cityUa'],
                                 fk_poll=_id)
            session.add(passrords)
            send_mail(arg['email'], password)
    send_sms(res['mobile'], _id)
    for arg in res['mobile']:
        k += 1
    if int(_id) > 2:
        session.query(Poll).filter_by(id=_id).update({"status": 'active'})
    session.query(Poll).filter_by(id=_id).update(
        {"total_count": k + int(result[0]['total_count'])})
    session.commit()
    session.close()
    return "ok"
Example #4
0
def receive_form():
    if request.method == 'POST':
        # retrieves data from form
        email = request.form['email']
        attendees = request.form['attendees']

        # should send mail here
        mail_utils.send_mail(email, attendees)

        return render_template("done.html")

    return render_template("error.html")  # in case of a problem
Example #5
0
                print('epoch:{} iterations:{}, train_loss:{}'.format(
                    epoch, total_step % len(users), loss))

        # perform evaluation
        fpr, tpr, threshold = metrics.roc_curve(np.ravel(np.array(labels)),
                                                predictions,
                                                pos_label=1)
        auc = metrics.auc(fpr, tpr)
        evaluations.append(auc)
        print(predictions)
        print(labels)
        print('AUC %.3f' % auc)
        # record allocation for resources with timeline
        fetched_timeline = timeline.Timeline(run_metadata.step_stats)
        chrome_trace = fetched_timeline.generate_chrome_trace_format()
        with open(config.timeline_path, "w") as f:
            f.write(chrome_trace)

    print('train complete')

    pd.DataFrame(evaluations).to_csv(config.score_path, index=False)
    #save model
    saver.save(sess, config.model_path)
    tf.contrib.tfprof.model_analyzer.print_model_analysis(
        tf.get_default_graph(),
        run_meta=run_metadata,
        tfprof_options=tf.contrib.tfprof.model_analyzer.PRINT_ALL_TIMING_MEMORY
    )

mail_utils.send_mail("ripple network trained completed", "train complete")
Example #6
0
def send_message(request, text='', to_addr='', cc_addr='', bcc_addr = '', subject='',
    attachments=''):
    '''Generic send message view
    '''
    if request.method == 'POST':
        new_data = request.POST.copy()
        other_action = False

        old_files = []
        if new_data.has_key('saved_files'):
            if new_data['saved_files']:
                old_files = new_data['saved_files'].split(',')

        uploaded_files = UploadFiles( request.user,
            old_files = old_files,
            new_files = request.FILES.getlist('attachment[]'))

        # Check if there is a request to delete files
        for key in new_data:
            match = delete_re.match(key)
            if match:
                id = int(match.groups()[0])
                uploaded_files.delete_id(id)
                other_action = True

        # Check if the cancel button was pressed
        if  new_data.has_key('cancel'):
            # Delete the files
            uploaded_files.delete()
            # return
            return HttpResponseRedirect('/')

        # create an hidden field with the file list.
        # In case the form does not validate, the user doesn't have
        # to upload it again
        new_data['saved_files'] = ','.join([ '%d' % Xi
            for Xi in uploaded_files.id_list()])

        user_profile = request.user.get_profile()

        form = ComposeMailForm(new_data, request = request)

        if new_data.has_key('upload'):
            other_action = True

        if form.is_valid() and not other_action:
            # get the data:
            form_data = form.cleaned_data

            subject = form_data['subject']
            from_addr  = form_data['from_addr']

            to_addr    = join_address_list( form_data['to_addr'] )
            cc_addr    = join_address_list( form_data['cc_addr'] )
            bcc_addr   = join_address_list( form_data['bcc_addr'] )

            text_format = form_data['text_format']
            message_text = form_data['message_text'].encode('utf-8')

            config = WebpymailConfig( request )

            if text_format == MARKDOWN and HAS_MARKDOWN:
                md = markdown.Markdown(output_format='HTML')
                message_html = md.convert(smart_unicode(message_text))
                css = config.get('message', 'css')
                # TODO: use a template to get the html and insert the css
                message_html = '<html>\n<style>%s</style><body>\n%s\n</body>\n</html>' % (css, message_html)
            else:
                message_html = None

            message = compose_rfc822( from_addr, to_addr, cc_addr, bcc_addr,
                subject, message_text, message_html, uploaded_files )

            try:
                host = config.get('smtp', 'host')
                port = config.getint('smtp', 'port')
                user = config.get('smtp', 'user')
                passwd = config.get('smtp', 'passwd')
                security = config.get('smtp', 'security').upper()
                use_imap_auth = config.getboolean('smtp', 'use_imap_auth')

                if use_imap_auth:
                    user = request.session['username']
                    passwd = request.session['password']

                send_mail( message,  host, port, user, passwd, security)
            except SMTPRecipientsRefused, detail:
                error_message = ''.join(
                    ['<p>%s' % escape(detail.recipients[Xi][1])
                     for Xi in detail.recipients ] )
                return render_to_response('mail/send_message.html', {'form':form,
                    'server_error': error_message,
                    'uploaded_files': uploaded_files},
                    context_instance=RequestContext(request))
            except SMTPException, detail:
                return render_to_response('mail/send_message.html', {'form':form,
                    'server_error': '<p>%s' % detail,
                    'uploaded_files': uploaded_files},
                    context_instance=RequestContext(request))
            except Exception, detail:
                error_message = '<p>%s' % detail
                return render_to_response('mail/send_message.html', {'form':form,
                    'server_error': error_message,
                    'uploaded_files': uploaded_files},
                    context_instance=RequestContext(request))
Example #7
0
def send_message(request,
                 text='',
                 to_addr='',
                 cc_addr='',
                 bcc_addr='',
                 subject='',
                 attachments=''):
    '''Generic send message view
    '''
    if request.method == 'POST':
        new_data = request.POST.copy()
        other_action = False

        old_files = []
        if new_data.has_key('saved_files'):
            if new_data['saved_files']:
                old_files = new_data['saved_files'].split(',')

        uploaded_files = UploadFiles(
            request.user,
            old_files=old_files,
            new_files=request.FILES.getlist('attachment[]'))

        # Check if there is a request to delete files
        for key in new_data:
            match = delete_re.match(key)
            if match:
                id = int(match.groups()[0])
                uploaded_files.delete_id(id)
                other_action = True

        # Check if the cancel button was pressed
        if new_data.has_key('cancel'):
            # Delete the files
            uploaded_files.delete()
            # return
            return HttpResponseRedirect('/')

        # create an hidden field with the file list.
        # In case the form does not validate, the user doesn't have
        # to upload it again
        new_data['saved_files'] = ','.join(
            ['%d' % Xi for Xi in uploaded_files.id_list()])

        user_profile = request.user.get_profile()

        form = ComposeMailForm(new_data, request=request)

        if new_data.has_key('upload'):
            other_action = True

        if form.is_valid() and not other_action:
            # get the data:
            form_data = form.cleaned_data

            subject = form_data['subject']
            from_addr = form_data['from_addr']

            to_addr = join_address_list(form_data['to_addr'])
            cc_addr = join_address_list(form_data['cc_addr'])
            bcc_addr = join_address_list(form_data['bcc_addr'])

            text_format = form_data['text_format']
            message_text = form_data['message_text'].encode('utf-8')

            config = WebpymailConfig(request)

            if text_format == MARKDOWN and HAS_MARKDOWN:
                md = markdown.Markdown(output_format='HTML')
                message_html = md.convert(smart_unicode(message_text))
                css = config.get('message', 'css')
                # TODO: use a template to get the html and insert the css
                message_html = '<html>\n<style>%s</style><body>\n%s\n</body>\n</html>' % (
                    css, message_html)
            else:
                message_html = None

            message = compose_rfc822(from_addr, to_addr, cc_addr, bcc_addr,
                                     subject, message_text, message_html,
                                     uploaded_files)

            try:
                host = config.get('smtp', 'host')
                port = config.getint('smtp', 'port')
                user = config.get('smtp', 'user')
                passwd = config.get('smtp', 'passwd')
                security = config.get('smtp', 'security').upper()
                use_imap_auth = config.getboolean('smtp', 'use_imap_auth')

                if use_imap_auth:
                    user = request.session['username']
                    passwd = request.session['password']

                send_mail(message, host, port, user, passwd, security)
            except SMTPRecipientsRefused, detail:
                error_message = ''.join([
                    '<p>%s' % escape(detail.recipients[Xi][1])
                    for Xi in detail.recipients
                ])
                return render_to_response(
                    'mail/send_message.html', {
                        'form': form,
                        'server_error': error_message,
                        'uploaded_files': uploaded_files
                    },
                    context_instance=RequestContext(request))
            except SMTPException, detail:
                return render_to_response(
                    'mail/send_message.html', {
                        'form': form,
                        'server_error': '<p>%s' % detail,
                        'uploaded_files': uploaded_files
                    },
                    context_instance=RequestContext(request))
            except Exception, detail:
                error_message = '<p>%s' % detail
                return render_to_response(
                    'mail/send_message.html', {
                        'form': form,
                        'server_error': error_message,
                        'uploaded_files': uploaded_files
                    },
                    context_instance=RequestContext(request))