Exemplo n.º 1
0
def import_spreadsheet():
    try:
        spreadsheet_id = Settings.get('sheet_id')
        range_name = Settings.get('sheet_range')

        config = config_sheet()
        result = config.service.spreadsheets().values().get(
            spreadsheetId=spreadsheet_id,
            range=range_name).execute(http=config.http)

        values = result.get('values', [])

        for r in values:
            obj = gdgchapter()

            obj.groupName = r[0]
            obj.groupStatus = r[2]
            obj.groupMembers = int(r[3])
            obj.city = r[1]
            obj.countryMod = r[4]

            obj.put()

        return 'importing process completed'
    except:
        logging.error('error into importing process')
        raise
Exemplo n.º 2
0
		def txn():
			settings = Settings(key_name=config.SETTINGS_KEY, 
								auth_key=d['auth_key'],
								default_subject=d['default_subject'],
								default_sender=d['default_sender'],
								allowed_ips=d['allowed_ips'])
			settings.put()
Exemplo n.º 3
0
    def validate(self, curuser):
        result = True
        if not Form.validate(self):
            return False
        sum = (self.sum_nds18.data + self.sum_no_nds18.data +
              self.sum_nds10.data + self.sum_no_nds10.data)
        if not sum == self.sum_snds.data:
            self.sum_snds.errors.append(u"Неверно указана сумма с НДС. Расчетная сумма "+str(sum))
            result = False
        sum18 = round(self.sum_no_nds18.data*decimal.Decimal(str(0.18)),2)
        fault = math.fabs(sum18-(float(self.sum_nds18.data)))
        if fault>0.05:
            self.sum_nds18.errors.append(u"Неверно указана сумма НДС 18%. Расчетная сумма "+str(sum18))
            result = False
        sum10 = round(self.sum_no_nds10.data*decimal.Decimal(str(0.10)),2)
        fault = math.fabs(sum10-(float(self.sum_nds10.data)))
        if fault>0.05:
            self.sum_nds10.errors.append(u"Неверно указана сумма НДС 10%. Расчетная сумма "+str(sum10))
            result = False

        if self.ninvoice is not None:
            invoice = Invoice.query.filter(Invoice.ninvoice==self.ninvoice.data, Invoice.agent_uid==self.agent_uid.data,
                                       Invoice.org_uid==self.org_uid.data, Invoice.uid!=self.uid.data).first()
            if invoice is not None:
                self.ninvoice.errors.append(u"Счет фактура с указанным номером уже добавлена")
                result = False

        if not curuser.allow_edit:
            if self.dinvoice.data>Settings.dend().date() or self.dinvoice.data<Settings.dbegin().date():
                self.dinvoice.errors.append(u"Закрытый период. Ввод и изменение данных запрещены!")
                result = False

        return result
Exemplo n.º 4
0
def register(request):
    if request.method == 'POST':
        span = {1:False}
        form = NewUserForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            user = auth.authenticate(
                email=request.POST.get('email', ''),
                password=request.POST.get('password1',''))
            if user is not None:
                auth.login(request, user)
                profile = Profile(user=user)
                profile.save()
                settings = Settings(user=user)
                settings.save()
                return HttpResponseRedirect("/create/profile/")
            else:
                span[1] = True
                form = NewUserForm()
    else:
        form = NewUserForm()
        span = {1:False}
    return render(request, "registration/register.html", {
        'form': form,
        'span': span
        })
Exemplo n.º 5
0
def import_chapter_url():
    try:
        spreadsheet_id = Settings.get('sheet_id')
        range_name = Settings.get('sheet_range')

        config = config_sheet()
        result = config.service.spreadsheets().values().get(
            spreadsheetId=spreadsheet_id,
            range=range_name).execute(http=config.http)

        values = result.get('values', [])
        #gdglist = gdgchapterurl.query().fetch()

        for r in values:
            #if r[0] not in gdglist:
            if not gdgchapterurl.query(
                    gdgchapterurl.groupUrlname == r[0]).fetch():
                obj = gdgchapterurl()
                obj.groupUrlname = r[0]
                obj.put()

        return 'importing process completed'
    except:
        logging.error('error into importing process')
        raise
Exemplo n.º 6
0
def add_setting(name, value, type, id=-1):
    setting = Settings(name=name,
                       value=str(value),
                       type=type,
                       user_id=id if id > -1 else current_user.id)
    db.session.add(setting)
    db.session.commit()
    log.info('add : {}'.format(setting.log()))
    return True
Exemplo n.º 7
0
def user():
    app.config['BASIC_AUTH_USERNAME'] = Settings.get('user_access')
    app.config['BASIC_AUTH_PASSWORD'] = Settings.get('pass_access')

    if (Settings.get('user_access')
            == "not set") or (Settings.get('pass_access') == "not set"):
        return 'User Not Confirmed'
    else:
        return 'User Confirmed'
Exemplo n.º 8
0
    def closeEvent(self, event):
        if sys.platform != "darwin" and self.app.show_minimize_message:
            msg = QMessageBox(self)
            msg.setWindowTitle("App Minimized")
            msg.setText("The app will be minimized to your system tray.")
            msg.setIcon(QMessageBox.Icon.Information)
            check = QCheckBox("Don't show again.")
            msg.setCheckBox(check)
            msg.exec_()

            self.app.show_minimize_message = not check.isChecked()
            Settings.set_param("minimize", not self.app.show_minimize_message)
Exemplo n.º 9
0
	def get(self, form=None):
		current_settings = Settings.get_by_key_name(config.SETTINGS_KEY)
		if current_settings:
			current_settings = current_settings.to_dict()
			current_settings['allowed_ips'] = ','.join(current_settings['allowed_ips'])
		else:
			current_settings = Settings.reset_auth(config.SETTINGS_KEY);

		if form is None:
			form = SettingsForm(current_settings)

		self.response.out.write(template.render(os.path.join(config.APP_ROOT_DIR, "templates/index.html"),
								{"no_settings" : (current_settings is None), "form" : form, "title" : "Mail Engine for App Engine"}))
Exemplo n.º 10
0
 def post(self, request, *args, **kwargs):
     visble_q_types = []
     for key in request.POST:
         if key.startswith('quest-type'):
             visble_q_types.append(int(key[-1]))
     if Settings.objects.filter(user=request.user).exists():
         setting = Settings.objects.get(user=request.user)
         setting.options = {'visible_type': visble_q_types}
     else:
         setting = Settings()
         setting.user = request.user
         setting.options = {'visible_type': visble_q_types}
     setting.save()
     return self.get(request, *args, **kwargs)
Exemplo n.º 11
0
 def setUp(self):
     self.shop_items = (
         {
             'id': 1234,
             'title': 'Wine Glass',
             'price': 9.99,
         },
         {
             'id': 2345,
             'title': 'Frosted Shot Glasses, set of 4',
             'price': 14.99,
         },
     )
     f = open('secret_settings.json')
     self.settings = Settings(**json.load(f))
Exemplo n.º 12
0
def get_current_settings():
    try:
        current_settings = Settings.get(Settings.id == 1)
    except Settings.DoesNotExist:
        current_settings = Settings.create(blog_title="Blog",
                                           initialized=True,
                                           icon_1_link='',
                                           icon_1_icon_type='github',
                                           icon_2_link='',
                                           icon_2_icon_type='linkedin',
                                           posts_per_page=10,
                                           max_synopsis_chars=500,
                                           table_entries_per_page=14)
        current_settings.save()
    return current_settings
Exemplo n.º 13
0
    def get(self, key, ta='', responses=None, success=None, errors=None):
        invite = EvalInvite.get_by_key_name(key)
        if not invite:
            return self.redirect('/')

        settings = Settings.get_by_key_name('settings')
        invite.expired = datetime.datetime.now() > settings.expire_date
        success = success or []
        errors = errors or []

        remaining = invite.remaining_evals()
        if not remaining and not invite.tas:
            if settings.send_completed_email:
                body = const.COMPLETED_EMAIL_TEMPLATE.format(invite.name)
                try:
                    to_email = '{} <{}>'.format(invite.name, invite.email)
                    mail.send_mail(settings.admin_email, to_email,
                                   const.COMPLETED_EMAIL_SUBJECT, body)
                except apiproxy_errors.OverQuotaError as message:
                    logging.error(message)
            completed = Completed(name=invite.name, email=invite.email)
            completed.put()
            invite.delete()
            questions = None
        else:
            if not responses:
                responses = [''] * len(const.QUESTIONS)
            questions = zip(const.QUESTIONS, responses)

        values = {'invite': invite, 'success': success, 'errors': errors,
                  'sel_ta': ta, 'questions': questions, 'remaining': remaining}
        template = jinja_environment.get_template('eval.html')
        self.response.out.write(template.render(values))
Exemplo n.º 14
0
def enrollment_confirm(request):
    remote_addr = request.META['REMOTE_ADDR']
    form = EnrollmentRequestForm(request.REQUEST,
                                 remote_ip=dotted_quad_to_num(remote_addr))

    if form.is_valid():  # raises valid exceptions on errors
        # All validation done, so we need to verificate a session
        dyn_settings = Settings.get_instance()
        enrollment_process = form.cleaned_data['enrollment_process']
        utterance_count = enrollment_process\
                .sample_sessions\
                    .aggregate(count=Count('uploadedutterance')).get('count')
        assert utterance_count > dyn_settings.min_utterance_count_to_enroll,\
                    _("Need at least %(count)d utterance to enroll") % {'count': utterance_count}

        target_speakers = enrollment_process.sample_sessions.values_list(
            'target_speaker').distinct()
        assert target_speakers.count() == 1, _(
            "More than one speaker tagged as target in sample sessions")

        target_speaker = target_speakers[0][0]
        assert request.user.id == target_speaker, _(
            "Enrollment can be confirmed only by original person")
        enrollment_process.transition(LearningProcess.STARTED)
        send_message("django_verispeak.enrollment",
                     enrollment_process_id=enrollment_process.id,
                     target_speaker_id=target_speaker)

        return _("Enrollment in progress")
    else:
        raise NotImplementedError
Exemplo n.º 15
0
    def email_result(self):
        key_name = self.request.get('key')
        obj = Eval.get_by_key_name(key_name)
        if not obj:
            return self.get(errors=['Invalid key: {!r}'.format(key_name)])

        if obj.sent_results:
            return self.get(errors=['Results already emailed.'])

        safe_ta_name = obj.ta.replace(' ', '_')
        ta_result_name = '{}-{}.txt'.format(obj.course, safe_ta_name)
        ta_result = Eval.generate_summary([obj])

        course_list = [x for x in Eval.all().filter('course =', obj.course)]
        course_result = Eval.generate_summary(course_list, True)
        all_result = Eval.generate_summary([x for x in Eval.all()], True)

        settings = Settings.get_by_key_name('settings')
        email_to = '{} <{}>'.format(obj.ta, obj.ta_email)
        email_cc = '{} <{}>'.format(obj.instructor, obj.instructor_email)
        body = const.RESULT_EMAIL_TEMPLATE.format(obj.ta)
        attachments = [(ta_result_name, ta_result),
                       ('{}.txt'.format(obj.course), course_result),
                       ('all.txt', all_result)]

        try:
            mail.send_mail(sender=settings.admin_email, to=email_to,
                           cc=email_cc, subject=const.RESULT_EMAIL_SUBJECT,
                           body=body, attachments=attachments)
            obj.sent_results = True
            obj.put()
            self.get(['Sent result to {} and {}'.format(obj.ta,
                                                        obj.instructor)])
        except Exception, e:
            self.get(errors=[str(e)])
Exemplo n.º 16
0
 def __init__(self, id):
     self.id = id
     self.tables = BTree()
     self.messages = BTree()
     self.clients = BTree()
     self.network = Network()
     self.settings = Settings(self.id)
Exemplo n.º 17
0
class TestCheckoutByAmazonIntegration(unittest.TestCase):
    def setUp(self):
        self.shop_items = (
            {
                'id': 1234,
                'title': 'Wine Glass',
                'price': 9.99,
            },
            {
                'id': 2345,
                'title': 'Frosted Shot Glasses, set of 4',
                'price': 14.99,
            },
        )
        f = open('secret_settings.json')
        self.settings = Settings(**json.load(f))

    def fill_cart(self):
        self.cart = [self.shop_items[1], self.shop_items[0]]

    def test_whole_checkout_process(self):
        # While browsing, the customer add stuff to the cart
        self.fill_cart()
        # Page 1: initiate checkout and choose address
        contract = PurchaseContract(settings=self.settings.as_dict())
        for item in self.cart:
            contract.order.add_item(
                Item(id=item['id'], title=item['title'], price=item['price']))
        # Page 2: Choose payment method
        contract.add_destination('#default', 'John Doe', '123 Main St\nApt. B',
                                 'New York', 'NY', 'US', '(123) 456-7890')
        # Page 3: Confirmation
        # Page 4: "Thank You" page
        contract.complete()
Exemplo n.º 18
0
def edit_settings(request):
    settings = Settings(Dbus.get_temperature_settings(),
                        Dbus.get_manual_mode())
    if not request.POST:
        return _get_settings(request, settings)
    else:
        return _edit_settings(request, settings)
Exemplo n.º 19
0
    async def announce_time(self, msg, time: int = None):
        try:
            # Make sure we receive a positive number
            if int(time) < 1:
                raise ValueError

            self.delay = int(time)

            updated = session.query(Settings).filter(Settings.key == "announcement_delay").update({"value": self.delay})

            if not updated:
                # Insert if it wasn't updated, because it didn't exist.
                insert = Settings(key="announcement_delay", value=self.delay)
                session.add(insert)

            session.commit()

            self.restart_task()
            await msg.reply(f"{bot.msg_prefix}New announce time is {time} seconds")
        except ValueError:
            await msg.reply(f"{bot.msg_prefix}Invalid time, please use an integer in seconds")
        except TypeError:
            await msg.reply(f"{bot.msg_prefix} Current announce time is {self.delay} seconds.")
        except Exception as e:
            print(type(e), e)
Exemplo n.º 20
0
def startup():

    # db initializations
    db.create_all()
    settings = Settings(secret_key=pyotp.random_base32())
    db.session.add(settings)
    db.session.commit()
Exemplo n.º 21
0
    def __init__(self):
        self.app = QSingleApplication("BlobBackup", sys.argv)
        self.app.setQuitOnLastWindowClosed(False)
        self.app.setStyle("Fusion")
        self.window = MainWindow(self)
        self.scheduler = Scheduler(self.app)

        self.show_minimize_message = not Settings.get_param("minimize")

        self.app.start_backup.connect(self.window.go_backup)

        if self.app.isRunning():
            QMessageBox.warning(
                None, "BlobBackup already running",
                "An instance of BlobBackup is already running. Check your status bar."
            )
            sys.exit()

        menu = QMenu()
        window_action = menu.addAction("BlobBackup")
        window_action.triggered.connect(self.show_window)
        quit_action = menu.addAction("Exit")

        quit_action.triggered.connect(self.quit_action)

        self.tray = QSystemTrayIcon()
        self.tray.setIcon(QIcon(get_resource_path("images/logo.ico")))
        self.tray.setContextMenu(menu)
        self.tray.show()
        self.tray.setToolTip("BlobBackup")

        self.tray.activated.connect(self.tray_activated)

        self.show_window()
Exemplo n.º 22
0
async def on_raw_message_edit(message_id, data):
    channel = client.get_channel(int(data['channel_id']))
    try:
        m = LogMessage.get(channel.guild.id, message_id)
    except LogMessage.DoesNotExist as e:
        return
    try:
        ts = dateutil.parser.parse(data['edited_timestamp'])
    except KeyError as e:
        ts = dt.datetime.utcnow()
    except TypeError as e:
        ts = dt.datetime.utcnow()
    if 'content' in data:
        rev = LogRevision(content=data['content'],
                          timestamp=ts,
                          pinned=data['pinned'])
    else:
        rev = LogRevision(timestamp=ts, pinned=data['pinned'])
    m.revisions.append(rev)
    m.save()
    # pp = pprint.PrettyPrinter(depth=4)
    # pp.pprint(data)
    s = Settings.get(channel.guild.id)
    logchannel = client.get_channel(s.log_channel)
    if not m.revisions[-2].pinned == m.revisions[-1].pinned:
        state = pin_status[m.revisions[-1].pinned]
        await logchannel.send(f'Message {message_id} has been {state}')
    else:
        await logchannel.send(f'Message {message_id} has been edited')
Exemplo n.º 23
0
def enrollment(enrollment_process_id, target_speaker_id):
    logging.info("Learning, id=%d", enrollment_process_id)
    try:
        enrollment_process = LearningProcess.objects.get(
            id=enrollment_process_id)
    except LearningProcess.DoesNotExist:
        logging.error("No such LearningProcess: %s", enrollment_process_id)
        return

    try:
        target_speaker = Speaker.objects.get(id=target_speaker_id)
    except Speaker.DoesNotExist:
        logging.error("No such speaker in DB: %s", target_speaker_id)
        return

    sample_files = enrollment_process.sample_filepath_iterator()
    try:
        if enrollment_process.retrain_model is None:
            dyn_settings = Settings.get_instance()
            model = enroll(
                sample_files,
                model_classname=settings.SPEAKER_MODEL_CLASSNAME,
                model_parameters=dyn_settings.speaker_model_parameters_dict)
        else:
            model = retrain_model(sample_files,
                                  enrollment_process.retrain_model)
    except NeedMoreDataError:
        logging.info("Need more data")
        enrollment_process.transition(enrollment_process.WAIT_FOR_DATA)
    except BaseException, e:
        log_exception(msg="Exception raised during enrollment:")
        enrollment_process.transition(enrollment_process.FAILED)
Exemplo n.º 24
0
def add_question(request):
    context = {}

    settings = Settings.get_by_user(request.user)
    initial = {}

    if settings.group:
        initial["groups"] = [settings.group.id]

    if request.method == "POST":
        form = QuestionForm(request.POST)
        if form.is_valid():
            question = form.save(commit=False)
            question.added_by = request.user
            question.save()

            revision = QuestionRevision(question=question,
                                        user=request.user,
                                        text=form.cleaned_data["body"],
                                        active=True)
            revision.save()
            return HttpResponseRedirect("/question/%s" % question.id)
    else:
        form = QuestionForm(initial=initial)

    context["form"] = form

    return r2r(request, "add_question", context)
Exemplo n.º 25
0
def view_tag(request, tagname):
    context = {}

    approved_questions = Question.objects.filter(status__exact="Approved")
    pending_questions = Question.objects.filter(status__exact="Pending")
    banned_questions = Question.objects.filter(status__exact="Banned")

    settings = Settings.get_by_user(request.user)
    if settings.group:
        approved_questions = approved_questions.filter(
            groups__id=settings.group.id)
        pending_questions = pending_questions.filter(
            groups__id=settings.group.id)
        banned_questions = banned_questions.filter(
            groups__id=settings.group.id)

    context["tagname"] = tagname
    tagname = '"%s"' % tagname
    context["approved_questions"] = TaggedItem.objects.get_by_model(
        approved_questions, tagname)
    context["pending_questions"] = TaggedItem.objects.get_by_model(
        pending_questions, tagname)
    context["banned_questions"] = TaggedItem.objects.get_by_model(
        banned_questions, tagname)
    context["settings"] = settings

    return r2r(request, "view_tag", context)
Exemplo n.º 26
0
def create_project():
    if request.method == 'POST':
        newname = request.form.get('projectname', 'New project')
        newkeywords = request.form.get('keywords', None)
        newfollowers = request.form.get('followers', None)
        newtweetslimit = request.form.get('tweetslimit', None)
        newtweetsperyear = request.form.get('tweetsperyear', None)
        newnotweetsfor = request.form.get('notweetsfor', None)
        newlocation = request.form.get('location', None)
        newexclude = request.form.get('exclude', False)

        newproject = Project(name=newname)
        db.session.add(newproject)
        db.session.commit()
        newsettings = Settings(project_id=newproject.id,
                               include_keywords=newkeywords,
                               exclude=newexclude,
                               followers=newfollowers,
                               tweets=newtweetslimit,
                               tweetsperyear=newtweetsperyear,
                               notweetsfor=newnotweetsfor,
                               fromcountries=newlocation)
        db.session.add(newsettings)
        db.session.commit()

        flash('New project created', category='success')

        return redirect(url_for('index'))
    else:
        return render_template('parameters.html', action='new')
Exemplo n.º 27
0
def add_question(request):
    context = {}

    settings = Settings.get_by_user(request.user)
    initial = {}

    if settings.group:
        initial["groups"] = [settings.group.id]

    if request.method == "POST":
        form = QuestionForm(request.POST)
        if form.is_valid():
            question = form.save(commit=False)
            question.added_by = request.user
            question.save()

            revision = QuestionRevision(
                question=question, user=request.user,
                text=form.cleaned_data["body"], active=True)
            revision.save()
            return HttpResponseRedirect("/question/%s" % question.id)
    else:
        form = QuestionForm(initial=initial)

    context["form"] = form


    return r2r(request, "add_question", context)
Exemplo n.º 28
0
 def mutate(self, info, user_data=None):
     # NOTE: Netlify creates the account regardless of this response
     portfolio = Portfolio()
     settings = Settings()
     metrics = UserMetrics()
     try:
         user = User.objects.get(pk=user_data.email)
         # If no query error, then either the user exists or
         # user variable becomes None. In both cases the response fails.
         return CreateUserMutation(user=None, success=False)
     except Exception as e:  # email not taken
         if "matching query does not exist" not in str(e):
             # unexpected error during query
             return CreateUserMutation(user=None, success=False)
         user = User(name=user_data.name,
                     bio=user_data.bio,
                     email=user_data.email,
                     password=user_data.password,
                     profile_pic=user_data.profile_pic,
                     metrics=metrics,
                     achievements=[],
                     personal_portfolio=portfolio,
                     groups=[],
                     settings=settings)
         checkAchievements(user)
         user.save()
         return CreateUserMutation(user=user, success=True)
Exemplo n.º 29
0
def get(session):
    '''
    Uses memcache or the datastore to fetch a single setting by wave_id,
    wavelet_id and email. Ideally this should fetch session only if needed but
    this wouldn't work with the appengine transaction framework.
    @transaction_safe
    @param session: the parent session object

    @return the setting using the most efficient means possible or None if it
    couldn't be found
    '''
    if not session:
        return None
    key = base64.b64encode( memcacheConfig.PREFIX['SETTINGS'] + 
                            session.wave_id + 
                            session.wavelet_id +
                            session.email)
    setting = memcache.get(key)
    if not setting == None:
        return setting
    else:
        query = Settings.all()
        query.ancestor(session)
        setting = query.get()
        memcache.add(key, setting, time=memcacheConfig.DEFAULT_EXPIRE_SECS)
        return setting
Exemplo n.º 30
0
class TestCheckoutByAmazonIntegration(unittest.TestCase):
    def setUp(self):
        self.shop_items = (
            {
                'id': 1234,
                'title': 'Wine Glass',
                'price': 9.99,
            },
            {
                'id': 2345,
                'title': 'Frosted Shot Glasses, set of 4',
                'price': 14.99,
            },
        )
        f = open('secret_settings.json')
        self.settings = Settings(**json.load(f))

    def fill_cart(self):
        self.cart = [self.shop_items[1], self.shop_items[0]]

    def test_whole_checkout_process(self):
        # While browsing, the customer add stuff to the cart
        self.fill_cart()
        # Page 1: initiate checkout and choose address
        contract = PurchaseContract(settings=self.settings.as_dict())
        for item in self.cart:
            contract.order.add_item(Item(id=item['id'], title=item['title'], price=item['price']))
        # Page 2: Choose payment method
        contract.add_destination('#default', 'John Doe', '123 Main St\nApt. B', 'New York', 'NY', 'US', '(123) 456-7890')
        # Page 3: Confirmation
        # Page 4: "Thank You" page
        contract.complete()
Exemplo n.º 31
0
def thewarbase():
    db_query = Settings.query.order_by(Settings.WarbaseFaction).first()
    the_id = "No faction stored" if not db_query else db_query.WarbaseFaction
    the_form = FactionIDForm(obj=db_query, WarbaseFaction=the_id)
    get_members = WarBase.query.order_by(WarBase.Level.desc()).all()
    if request.method == "POST":
        if the_form.validate_on_submit():
            try:
                get_input = request.form['WarbaseFaction']
                if not db_query:
                    form = Settings(WarbaseFaction=get_input)
                    db_session.add(form)
                    db_session.commit()
                    flash('Saved successfully, you may now hit update.', 'success')
                if db_query:
                    if str(db_query.WarbaseFaction) != str(get_input):
                        db_query.WarbaseFaction = get_input
                        all_mems = WarBase.query.order_by(WarBase.Level.desc()).all()
                        for person in all_mems:
                            db_session.delete(person)
                        db_session.commit()
                        get_members = WarBase.query.order_by(WarBase.Level.desc()).all()
                        flash('Saved successfully, you may now hit update.', 'success')
                    else:
                        flash(f'{get_input} is already the faction saved, hit update.', 'danger')

            except Exception as e:
                db_session.rollback()
                flash(f'Error updating faction {e}.', 'danger')
                return render_template('warbase.html', members=get_members, form=the_form)
            return render_template('warbase.html', members=get_members, form=the_form)

    if request.method == "GET":
        return render_template('warbase.html', members=get_members, form=the_form)
Exemplo n.º 32
0
    def save_settings(self, username):
        self.linkcolor = self.request.get('linkcolor')
        self.sidebarcolor = self.request.get('sidebarcolor')
        self.headercolor = self.request.get('headercolor')
        self.headerfont = self.request.get('headerfont')
        self.bodyfont = self.request.get('bodyfont')
        self.projects = bool(self.request.get('projects'))
        self.courses = bool(self.request.get('courses'))
        self.books = bool(self.request.get('books'))
        self.online = bool(self.request.get('online'))
        self.opensource = bool(self.request.get('opensource'))
        self.meatspace = bool(self.request.get('meatspace'))

        
        s = Settings.by_username(username)
        s.link_color = self.linkcolor
        s.sidebar_color = self.sidebarcolor
        s.header_color = self.headercolor
        s.header_font = self.headerfont
        s.body_font = self.bodyfont
        s.projects = self.projects
        s.courses = self.courses
        s.books = self.books
        s.online = self.online
        s.open_source = self.opensource
        s.meatspace = self.meatspace
        s.put()
Exemplo n.º 33
0
def send_mail(their_email, their_message):
    ''' Send an email message to me '''
    message = mail.EmailMessage(sender=app_identity.get_application_id() +
                                '@appspot.gserviceaccount.com>')
    message.subject = 'Message from Bagbatch Website'
    message.to = Settings.get('EMAIL')
    message.body = """From: {}\n\n<<BEGINS>>\n\n{}\n\n<<ENDS>>""".format(their_email, their_message)
    message.send()
Exemplo n.º 34
0
def override_settings(f, *args, **kwargs):
    arg_index = f.__code__.co_varnames.index('settings')

    new_settings = Settings().to_dict()
    if 'settings' in kwargs:
        new_settings.update(kwargs['settings'])
        del kwargs['settings']

    if len(args) < arg_index + 1:
        kwargs['settings'] = new_settings
    else: # need to place it in args
        args = list(args)
        args[arg_index] = new_settings
        args = tuple(args)

  # print args, kwargs
    return f(*args, **kwargs)    
Exemplo n.º 35
0
def send_text(to, subject, text):
    message = mail.EmailMessage()
    message.sender = Settings.all().get().bot
    message.to = to
    message.subject = subject
    message.body = '\n'.join(text)
    message.html = u"<html><body>%s</body></html>" % ('<br>'.join(text),)
    message.send()
Exemplo n.º 36
0
def report():
    form = ReportForm()
    if current_user.is_admin:
        form.user.choices = [(g.uid, g.login) for g in User.query.order_by('name')]
    else:
        form.user.choices = [(g.uid, g.login) for g in current_user.subusers]
        form.user.choices.append((current_user.uid, current_user.login))
    form.user.choices.insert(0,(-1, u"Все пользователи"))
    if request.method == "POST":
        if form.validate():
            title = CONST.INVOICE_NAME[form.inv_type.data]
            rpt_filter = [Invoice.inv_type==form.inv_type.data]
            filter_text = u''
            if form.org_uid.data != u'':
                filter_text = filter_text + u'Организация: ' + form.org.data + ' '
                rpt_filter.append(Invoice.org_uid==form.org_uid.data)
            if form.agent_uid.data !=u'':
                filter_text = filter_text + u'Контрагент: ' + form.agent.data + ' '
                rpt_filter.append(Invoice.agent_uid==form.agent_uid.data)
            if form.user.data !=-1:
                filter_text = filter_text + u"Пользователь: " + User.query.get(form.user.data).login + ' '
                rpt_filter.append(Invoice.user_uid==form.user.data)
            if form.dbegin.data is not None:
                filter_text = filter_text + u'с ' + datetime.strftime(form.dbegin.data, '%d.%m.%Y') + ' '
                rpt_filter.append(Invoice.dinvoice>=datetime.combine(form.dbegin.data, datetime.min.time()))
            if form.dend.data is not None:
                filter_text = filter_text + u'по ' + datetime.strftime(form.dend.data, '%d.%m.%Y') + ' '
                rpt_filter.append(Invoice.dinvoice<=datetime.combine(form.dend.data, datetime.max.time()))
            invoices = current_user.available_invoices(inv_type=form.inv_type.data, rpt_filter=rpt_filter)
            if form.agent_inn.data != u'':
                filer_text = filer_text + u'ИНН Контрагента: ' + form.agent_inn.data + ' '
                invoices.join(Agent).filter(Agent.inn.contains(form.agent_inn.data))
            sums = invoices.with_entities(func.sum(Invoice.sum_snds),
                                  func.sum(Invoice.sum_no_nds18),
                                  func.sum(Invoice.sum_nds18),
                                  func.sum(Invoice.sum_no_nds10),
                                  func.sum(Invoice.sum_nds10),
                                  func.sum(Invoice.commission)).first()
            if request.form['submit']==u'excel':
                return export_xls(title, filter_text, invoices)
            else:
                return render_template("report.html", invoices=invoices.all(),
                                        dbegin=Settings.dbegin(),
                                        dend=Settings.dend(),
                                        sums=sums, title=title, filter_text=filter_text)
    return render_template("frmReport.html", form=form)
Exemplo n.º 37
0
def runProcess():
    jar = cookielib.CookieJar()
    u = get("https://www.rbi.org.in/Scripts/bs_viewcontent.aspx?Id=2009", cookies=jar)
    pattern = re.compile(r'<th>.*as on\s(.*)</th>')
    dateString = pattern.findall(u.content)[0]
    rbiLastModifiedDate = datetime.strptime(dateString.strip(), '%B %d, %Y')

    if(Settings.objects(settingsID="datesettings").first()):
        settings = Settings.objects.get(settingsID="datesettings")
        if rbiLastModifiedDate > settings.lastUpdated:
            print ("Data modified in rbi website.\nDownloading new data..")
            settings.lastUpdated = rbiLastModifiedDate
            settings.save()

            #Download files from rbi and save to xls/
            downloadFiles()

            #Parse details from xls files and insert into mongodb
            parseFiles()
        else:
            print ("Data is up to date.\n")
    else:
        print ("Running for the first time.")
        settings = Settings()
        settings.lastUpdated = rbiLastModifiedDate
        settings.yomLastFetched = rbiLastModifiedDate
        settings.save()

        downloadFiles()
        parseFiles()

    return True
Exemplo n.º 38
0
def register(request):
    if request.GET.get('username'):
        username = request.GET['username']
        password = request.GET['password1']
        email = request.GET['email']
        data = {}
        if User.objects.filter(username=username):
            data['invalid_user'] = True
        if User.objects.filter(email=email):
            data['invalid_email'] = True
        if (not data.get('invalid_user') and (not data.get('invalid_email'))):
            user = User.objects.create_user(username, request.GET['email'],
                                            password)
            user.save()

            sett = Settings()
            sett.usuario = user
            sett.clave = "tooltips"
            sett.valor = "true"
            sett.save()

            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    djlogin(request, user)
                    data['user'] = username
        return js(data)

    return render_to_response('registrar.html',
                              context_instance=RequestContext(request))
Exemplo n.º 39
0
    def post(self):
        try:
            delete = str(self.request.get('delete'))
            if delete == "I wish to delete all records":
                all_keys = StudentGradesModel.get_all_keys()
                for a in all_keys:
                    a.key.delete()
                return self.redirect('/admin?message=' + 'RECORDS DELETED')
            quarter = int(self.request.get('quarter'))
            year = int(self.request.get('year'))
            course = str(self.request.get('course'))

            current_settings = SettingsModel.get_current_settings()
            if current_settings == None:
                new_settings = Settings()
                new_settings.quarter = quarter
                new_settings.year = year
                new_settings.course = course
                new_settings.put()
            else:
                current_settings.quarter = quarter
                current_settings.year = year
                current_settings.course = course
                current_settings.put()

            return self.redirect('/admin?message=' +
                                 'Successfully changed settings')
        except Exception, e:
            return self.redirect(
                '/admin/settings?message=' +
                'There was a problem changing the settings: ' + str(e))
Exemplo n.º 40
0
def send_mail(their_email, their_message):
    ''' Send an email message to me '''
    message = mail.EmailMessage(sender=app_identity.get_application_id() +
                                '@appspot.gserviceaccount.com>')
    message.subject = 'Message from Bagbatch Website'
    message.to = Settings.get('EMAIL')
    message.body = """From: {}\n\n<<BEGINS>>\n\n{}\n\n<<ENDS>>""".format(
        their_email, their_message)
    message.send()
Exemplo n.º 41
0
def _edit_settings(request, settings):
    settings_form = SettingsForm(request.POST)
    if not settings_form.is_valid():
        raise Exception('SettingsForm validation fails')
    new_settings = Settings.from_form(settings_form)
    Dbus.set_manual_mode(new_settings.manual_mode)
    if new_settings.temperature != settings.temperature:
        Dbus.set_temperature_settings(new_settings.temperature)
    return redirect('stat_module:edit_settings')
Exemplo n.º 42
0
def index_get(request):
    status = Status(Dbus.get_temperature_status(), Dbus.get_manual_mode())
    settings = Settings(Dbus.get_temperature_settings(),
                        Dbus.get_manual_mode())

    return render(request, 'stat/index.html', {
        'status': status,
        'settings': settings
    })
Exemplo n.º 43
0
 def post(self):
     settings = Settings.all().get()
     form = SettingsForm(self.request.POST, obj=settings)
     if form.validate():
         if settings:
             settings.auth_code = form.auth_code.data
             settings.account_sid = form.account_sid.data
             settings.twilio_number = form.twilio_number.data
             settings.tz = form.tz.data
             settings.sms_timeout = form.sms_timeout.data
         else:
             settings = Settings(auth_code=form.auth_code.data, account_sid=form.account_sid.data,
                                 twilio_number=form.twilio_number.data, tz=form.tz.data,
                                 sms_timeout=form.sms_timeout.data)
         settings.put()
         self.redirect('/settings')
     else:
         self.render_response('settings.html', form=form, settings=settings)
Exemplo n.º 44
0
def post_list(request, page=0, paginate_by=20, **kwargs):

    page_size = Settings.get_current().page_size

    return list_detail.object_list(
        request,
        queryset = Post.objects.published(),
        paginate_by = page_size,
        page = page,
        **kwargs
    )
Exemplo n.º 45
0
def send_pdf(pdf, name, email):
    logging.info(u"Отправляем детализацию абонента %s на адрес %s" % (pdf.name, email))
    message = mail.EmailMessage()
    message.sender = Settings.all().get().bot
    if name:
        message.to = u"%s <%s>" % (name, email)
    else:
        message.to = email
    message.subject = u"Детализация Beeline абонента %s %s %s" % (pdf.name, gen_date(pdf), pdf.num)
    message.attachments = [(u"Beeline %s %s %s.pdf" % (pdf.name, gen_date(pdf), pdf.num), pdf.blob)]
    message.body = u"Детализация во вложении"
    message.send()
Exemplo n.º 46
0
    def get(self, successes=None, warnings=None, errors=None):
        courses = {}

        # Remaining Evaluations
        for invite in EvalInvite.all():
            if invite.course not in courses:
                courses[invite.course] = {}

            for ta in invite.tas:
                if ta in courses[invite.course]:
                    courses[invite.course][ta].remaining += 1
                else:
                    courses[invite.course][ta] = helpers.Dummy(
                        remaining=1, completed=0, sent_results=None)

        # Completed Evaluations
        for evaluation in Eval.all():
            completed = sum(evaluation.get_responses()[0])
            tas = courses[evaluation.course]
            if evaluation.ta in tas:
                tas[evaluation.ta].completed = completed
                tas[evaluation.ta].sent_results = evaluation.sent_results
            else:
                tas[evaluation.ta] = helpers.Dummy(
                    completed=completed, remaining=0,
                    sent_results=evaluation.sent_results)

        form_token, cookie = helpers.generate_validation_token()
        self.response.headers.add_header('Set-Cookie', cookie)

        successes = helpers.nsorted(successes) if successes else []
        warnings = helpers.nsorted(warnings) if warnings else []
        errors = helpers.nsorted(errors) if errors else []
        courses = [(x, sorted(courses[x].items())) for x in
                   helpers.nsorted(courses)]

        # Initialize settings if not already set
        user = users.get_current_user()
        admin_email = 'Computer Science Lead TA <{}>'.format(user.email())
        now = datetime.datetime.now()
        expire_date = now + datetime.timedelta(days=5)
        settings = Settings.get_or_insert('settings', admin_email=admin_email,
                                          expire_date=expire_date)
        if settings.expire_date < now:
            remaining_time = str(datetime.timedelta())
        else:
            remaining_time = str(settings.expire_date - now)

        values = {'successes': successes, 'warnings': warnings,
                  'errors': errors, 'courses': courses,
                  'form_token': form_token, 'eval_time': remaining_time}
        template = jinja_environment.get_template('admin.html')
        self.response.out.write(template.render(values))
Exemplo n.º 47
0
def notify_task(queue_id):
    try:
        settings = Settings.all().get()
        client = TwilioRestClient(settings.account_sid, settings.auth_code)
        call_queue = CallQueue.get_by_id(queue_id)
        next_entry = call_queue.entries.filter('status =', 'P').order('sequence').get()

        if next_entry and call_queue.status == 'P':

            if next_entry.entry_type == 'phone':
                next_entry.status = 'C'
                next_entry.put()
                client.calls.create(to=next_entry.recipient.phone_number, from_=settings.twilio_number,
                                    url='http://%s.appspot.com/call?call_queue_id=%s&queue_entry_id=%s' % (
                                        app_identity.get_application_id(), queue_id, next_entry.key().id()),
                                    status_callback='http://%s.appspot.com/callStatus?call_queue_id=%s&queue_entry_id=%s' % (
                                        app_identity.get_application_id(), queue_id, next_entry.key().id()),
                                    method='GET', timeout=15)
                event_log = 'Called %s (%s)' % (next_entry.recipient.name, next_entry.recipient.phone_number)
                alert_trace = AlertTrace(event_log=event_log, call_queue=call_queue)
                alert_trace.put()

            if next_entry.entry_type == 'sms':
                next_entry.status = 'C'
                next_entry.put()
                sms_message = '%s Send 1 to accept' % call_queue.notifier.sms_message
                client.sms.messages.create(to=next_entry.recipient.phone_number,
                                           from_=settings.twilio_number,
                                           body=sms_message)
                deferred.defer(notify_task, queue_id, _countdown=settings.sms_timeout)
                event_log = 'SMS %s (%s)' % (next_entry.recipient.name, next_entry.recipient.phone_number)
                alert_trace = AlertTrace(event_log=event_log, call_queue=call_queue)
                alert_trace.put()

        elif next_entry == None and call_queue.status == 'P' and call_queue.loop_count <= 5:
            call_queue.loop_count = call_queue.loop_count + 1
            call_queue.put()
            event_log = 'Alert not accepted yet. Restarting. Loop count:%s' % call_queue.loop_count
            alert_trace = AlertTrace(event_log=event_log, call_queue=call_queue)
            alert_trace.put()
            # re start the alert propagation
            entries = []
            for entry in call_queue.entries:
                new_entry = clone_entity(entry, status='P')
                entries.append(new_entry)
            if len(entries) != 0:
                db.put(entries)
                deferred.defer(notify_task, queue_id, _countdown=5 * 60)

    except:
        # raise
        logging.error("notify_task failed for  queue_id : %s" % queue_id)
        logging.error(traceback.format_exc())
Exemplo n.º 48
0
 def post(self):
     enable_desable = self.request.get('enable_desable')
     settings = Settings.all().get()
     if not settings:
         self.redirect('/settings')
     else:
         if 'enable' == enable_desable:
             settings.alert_enabled = True
         else:
             settings.alert_enabled = False
         settings.put()
     self.redirect('/')
Exemplo n.º 49
0
def register(request):
	if request.GET.get('username'):
		username = request.GET['username']
		password = request.GET['password1']
		email = request.GET['email']
		data = {}
		if User.objects.filter(username=username):
			data['invalid_user']=True
		if User.objects.filter(email=email):
			data['invalid_email']=True
		if (not data.get('invalid_user') and (not data.get('invalid_email'))):
			user = User.objects.create_user(username, request.GET['email'], password)
			user.save()
			
			sett = Settings()
			sett.usuario = user;
			sett.clave = "tooltips"
			sett.valor = "true"
			sett.save()
			
			user = authenticate(username=username, password=password)
			if user is not None:
				if user.is_active:
					djlogin(request, user)
					data['user']=username
		return js(data)

	return render_to_response('registrar.html',
								context_instance=RequestContext(request))
Exemplo n.º 50
0
 def render_response(self, _template, **context):
     settings = Settings.all().get()
     # Renders a template and writes the result to the response.
     logout = '/logout'
     email = users.get_current_user().email()
     context['admin'] = users.is_current_user_admin()
     context['session'] = self.session
     context['request'] = self.request
     context['logout'] = logout
     context['email'] = email
     context['settings'] = settings
     rv = self.jinja2.render_template(_template, **context)
     self.response.write(rv)
Exemplo n.º 51
0
 def update_expire_date(self):
     expire_date = self.request.get('expire_date')
     try:
         expire_date = datetime.datetime.strptime(expire_date,
                                                  '%Y:%m:%d %H:%M')
     except ValueError:
         expire_date = None
     if not expire_date:
         return self.get(errors=['Invalid expire date'])
     settings = Settings.get_by_key_name('settings')
     settings.expire_date = expire_date
     settings.put()
     return self.get(['Expire date updated.'])
Exemplo n.º 52
0
def edit_settings(request):
    context = {}
    settings = Settings.get_by_user(request.user)

    if request.method == "POST":
        form = SettingsForm(request.POST, instance=settings)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/settings")
    else:
        form = SettingsForm(instance=settings)

    context["form"] = form
    return r2r(request, "edit_settings", context)
Exemplo n.º 53
0
def check(token, public, remote_addr):
	authorized = False
	
	settings = Settings.get_by_key_name(config.SETTINGS_KEY)

	if settings is not None:
		compare_token = hashlib.sha1(public + settings.auth_key).hexdigest()
		if compare_token == token:
			authorized = True
		
		if settings.allowed_ips and remote_addr not in settings.allowed_ips:
			authorized = False

	return authorized
Exemplo n.º 54
0
 def add_settings(self, params, username):
     s = Settings.by_username(username)
     if s:
         params['linkcolor'] = s.link_color
         params['sidebarcolor'] = s.sidebar_color
         params['headercolor'] = s.header_color
         params['headerfont'] = s.header_font
         params['bodyfont'] = s.body_font
         params['projects'] = s.projects
         params['courses'] = s.courses
         params['books'] = s.books
         params['online'] = s.online
         params['opensource'] = s.open_source
         params['meatspace'] = s.meatspace
Exemplo n.º 55
0
 def setUp(self):
     self.shop_items = (
         {
             'id': 1234,
             'title': 'Wine Glass',
             'price': 9.99,
         },
         {
             'id': 2345,
             'title': 'Frosted Shot Glasses, set of 4',
             'price': 14.99,
         },
     )
     f = open('secret_settings.json')
     self.settings = Settings(**json.load(f))
Exemplo n.º 56
0
def sms_task(queue_id):
    try:
        settings = Settings.all().get()
        client = TwilioRestClient(settings.account_sid, settings.auth_code)
        sms_queue = CallQueue.get_by_id(queue_id)
        next_entry = sms_queue.entries.filter('status =', 'P').filter('entry_type =', 'sms').order('sequence').get()
        if next_entry and sms_queue.status == 'P':
            next_entry.status = 'C'
            next_entry.put()
            sms_message = '%s Send 1 to accept' % sms_queue.notifier.sms_message
            client.sms.messages.create(to=next_entry.phone_number,
                                       from_=settings.twilio_number,
                                       body=sms_message)
            deferred.defer(sms_task, queue_id, _countdown=settings.sms_timeout)
    except:
        logging.error("sms_task failed for  queue_id : %s" % queue_id)
Exemplo n.º 57
0
 def post(self):
     settings = Settings.get_by_key_name('settings')
     for invites, output in helpers.invite_iterator():
         name = invites[0].name
         to_email = '{} <{}>'.format(name, invites[0].email)
         body = const.EMAIL_TEMPLATE.format(student=name, body=output)
         try:
             mail.send_mail(settings.admin_email, to_email,
                            const.EMAIL_SUBJECT, body)
             now = datetime.datetime.now()
             for invite in invites:
                 invite.email_sent = now
                 invite.put()
         except apiproxy_errors.OverQuotaError:
             taskqueue.add(url='/admin/email', countdown=60)
             return self.response.set_status(200)