Пример #1
0
    def get_context_data(self, **kwargs):
        c = super().get_context_data(**kwargs)
        c['katex'] = True

        c['year'] = kwargs.get('year', None)
        if not c['year']:
            c['year'] = c.get('now', now()).year

        # c["host"] = self.request.host

        # c['EGE'] = settings.SITE_ID == 2
        c['EGE'] = self.request.host.name == 'ege'
        c['OGE'] = self.request.host.name == 'oge'
        c['exam_type'] = 0 if c['EGE'] else 1
        c['exam_type_str'] = 'ЕГЭ' if c['EGE'] else 'ОГЭ'

        c['menu']['index'] = {
            'title':
            'ЕГЭ' if c['EGE'] else 'ОГЭ',
            'url':
            reverse('index', host=c['host'].name),
            'hint':
            'Единый государственный экзамен'
            if c['EGE'] else 'Основной государственный экзамен'
        }
        c['menu'].current = 'index'
        c['subjects'] = Subject.objects.filter(published=True) \
                                       .order_by('name')
        for subj in c['subjects']:
            c['menu'][subj.slug] = {
                'title':
                subj.name,
                'url':
                reverse('subject:index',
                        host=c['host'].name,
                        kwargs={
                            'subj': subj.slug,
                        }),
            }
        # c['menu'] = Menu(
        #     [
        #         ('index', {
        #             'title': 'Главная',
        #             'url': reverse('index'),
        #         }),
        #         ('articles', {
        #             'title': 'Статьи',
        #             'url': reverse('articles:index'),
        #         } if c['user'].is_superuser else None),
        #         ('faq', {
        #             'title': 'Вопросы',
        #             'url': reverse('faq'),
        #         }),
        #         ('contacts', {
        #             'title': 'Контакты',
        #             'url': reverse('contacts'),
        #         }),
        #     ]
        # )
        return c
Пример #2
0
 def get_url(self, article):
     return reverse("articles:article",
                    kwargs={
                        'id': article.pk,
                        'slug': article.slug
                    },
                    host='pashinin')
Пример #3
0
    def get_context_data(self, **kwargs):
        c = super().get_context_data(**kwargs)
        c['year'] = kwargs.get('year', None)
        if not c['year']:
            c['year'] = c.get('now', now()).year

        subj = kwargs['subj']  # from urls pattern
        try:
            c['subject'] = Subject.objects.get(slug=subj, published=True)
            c['menu'].current = subj
            # дательный падеж:
            c['po_subject'] = " ".join([
                morph.parse(w)[0].inflect({'datv'}).word
                for w in str(c['subject']).split()
            ]).lower()
        except Subject.DoesNotExist:
            c['redirect'] = reverse("index")
            c['ege'] = None
            return c
            # return HttpResponseRedirect(reverse("index"))

        c['tasks'] = []
        try:
            c['exam'] = Exam.objects.get(subject=c['subject'],
                                         year=c['year'],
                                         type=c['exam_type'])
            c['tasks'] = c['exam'].tasks.filter().order_by('order')
        except Exam.DoesNotExist:
            # c['redirect'] = reverse("index")
            # print('EGE.DoesNotExist')
            # c['subject'] = None
            c['exam'] = None
            c['status'] = 404

        return c
Пример #4
0
    def location(self, item):
        if item == '/':
            return reverse('index', host='baumanka')

        F, K, sem = item
        if sem is None:
            return reverse('kafedra', kwargs={
                'F': F,
                'K': K,
            }, host='baumanka')
        else:
            return reverse('sem', kwargs={
                'F': F,
                'K': K,
                'sem': sem,
                'path': ''
            }, host='baumanka')
Пример #5
0
 def get_absolute_url(self):
     # not all sites have "/article/..." in urls
     # if settings.SITE_ID == 1:  # pashinin.com
     return reverse("articles:article",
                    kwargs={
                        'id': self.pk,
                        'slug': self.slug
                    })
Пример #6
0
    def get_context_data(self, **kwargs):
        c = super().get_context_data(**kwargs)
        # c["search"] = True
        c["hljs"] = True
        slug = self.kwargs.get('slug', '')
        id = int(self.kwargs.get('id', 0))
        # user = c["user"]

        # Get article
        article = None
        try:
            article = Article.objects.get(pk=id)
        except Article.DoesNotExist:
            raise Http404

        if not article.published and not c['user'].is_superuser:
            raise Http404

        # Redirect article if wrong slug used
        if article.slug != slug:
            c['redirect'] = reverse("articles:article",
                                    kwargs={
                                        'id': id,
                                        'slug': article.slug
                                    })
            log.debug("redirect: ", c['redirect'])

        c["article"] = article
        # When 'pdf' parameter exists - download article in PDF format
        # if 'pdf' in self.request.GET:
        #     try:
        #         from files.sendfile import send_file
        #         fname = article.title.strip(".")
        #         r = send_file(self.request, article.pdf.filename,
        #                       in_browser=True,
        #                       outFilename=fname+".pdf")
        #         return r
        #     except:
        #         client.captureException()
        #         return HttpResponse("")

        # if user.is_superuser:
        #     drafts = Article.objects.filter(is_draft=True,
        #                            namespace=Article.NS_ARTICLE)
        return c
Пример #7
0
    def get_context_data(self, **kwargs):
        c = super().get_context_data(**kwargs)
        utcnow = localtime(now())
        c["momentjs"] = True
        c['timeago'] = True
        c['dragula'] = True

        c['menu'] = Menu([
            # ('index', {
            #     'title': 'Главная',
            #     # 'img': staticfiles_storage.url('favicon.png'),
            #     'url': reverse('index'),
            # }),
            # ('articles', {
            #     'title': 'Статьи',
            #     'url': reverse('articles:index'),
            # } if c['user'].is_superuser else None),
            # ('faq', {
            #     'title': 'Вопросы',
            #     'url': reverse('faq'),
            # }),
            # ('pay', {
            #     'title': 'Оплата',
            #     'url': reverse('pay'),
            # }),
            # # ('agreement', {
            # #     'title': 'Правила',
            # #     'url': reverse('agreement'),
            # # }),
            # ('contacts', {
            #     'title': 'Контакты',
            #     'url': reverse('contacts'),
            # }),
            ('prepare', {
                'title': 'Подготовка',
                'url': reverse('students'),
            }),
        ])

        c['students'] = {
            'active':
            User.objects.filter(
                lessons__start__gt=utcnow - self.last_lesson_period
                # start__year=self.date.year,
                # start__month=self.date.month,
                # start__day=self.date.day,
            ),
            'inactive':
            User.objects.filter(lessons__start__lte=utcnow -
                                self.last_lesson_period)
        }

        from ege.models import Exam
        c['ege_exams'] = Exam.objects.all()
        c['exam'] = Exam.objects.filter()[0]

        c['pause_mins'] = Day.pause.seconds // 60
        c["menu"].current = 'prepare'
        # utcnow = datetime.datetime.utcnow()

        # django.utils.timezone.now()
        c['monday'] = next_weekday(utcnow, 0)
        c['today'] = Day(utcnow)
        c['days'] = []
        c['days'] += [
            # {
            #     'weekday': datetime.date(2001, 1, i+1).weekday(),
            #     'datetime': utcnow + datetime.timedelta(days=7),
            # }
            Day(c['monday'] + datetime.timedelta(days=i))
            # datetime.date(2001, 1, i).strftime('%A'),
            # c['monday'] + datetime.timedelta(days=i),
            # datetime.date(2001, 1, i+1).weekday(),
            for i in range(0, utcnow.weekday())
        ]
        if c['days']:
            c['days'][-1].next_week_last_day = True

        c['days'] += [
            Day(utcnow + datetime.timedelta(days=i))
            for i in range(0, 7 - utcnow.weekday())
        ]
        c['times'] = [item for item in times()]
        return c
Пример #8
0
    def get_context_data(self, **kwargs):
        c = super().get_context_data(**kwargs)
        c["phone"] = '+7 (977) 801-25-41'
        c["email"] = '*****@*****.**'
        c["price"] = 1000
        c["price45"] = 800
        c["menu_id"] = "services"

        h = self.request.META.get('HTTP_HOST', '')  # hostname
        c['city_host'] = h.split('.')[0] if len(h.split('.')) >= 3 else h
        c['remote_only'] = h != settings.DOMAIN and \
            c['city_host'] != 'moskva'

        city = cities.get(c['city_host'], None)
        c['city_specific'] = city is not None
        city = cities.get(c['city_host'], 'Россия')

        c['city'] = city
        c['in_city'] = restore_capitalization(
            morph.parse(city)[0].inflect({'loct'}).word, city)
        c['cities'] = ({
            'name': 'Москва',
            'url': 'moskva.{}'.format(settings.DOMAIN),
        }, {
            'name': 'Санкт-Петербург',
            'url': 'spb.{}'.format(settings.DOMAIN),
        })

        c['menu'] = Menu([
            (
                'index',
                {
                    'title': 'Главная',
                    # 'img': staticfiles_storage.url('favicon.png'),
                    'url': reverse('index'),
                }),
            ('articles', {
                'title': 'Статьи',
                'url': reverse('articles:index'),
            } if c['user'].is_superuser else None),
            ('faq', {
                'title': 'Вопросы',
                'url': reverse('faq'),
            }),
            ('pay', {
                'title': 'Оплата',
                'url': reverse('pay'),
            }),
            # ('agreement', {
            #     'title': 'Правила',
            #     'url': reverse('agreement'),
            # }),
            ('contacts', {
                'title': 'Контакты',
                'url': reverse('contacts'),
            }),
            ('students', {
                'title': 'Ученики',
                'url': reverse('students'),
            } if c['user'].is_superuser else None),
        ])
        return c
Пример #9
0
def train():
    model = Sequential()
    if trainingMode:
        opt = keras.optimizers.Adam(lr=0.0001)
        model.add(Dense(13, input_dim=13, kernel_initializer='normal'))
        model.add(ReLU(max_value=1.))
        model.add(Dense(200, kernel_initializer='normal'))
        model.add(LeakyReLU())
        model.add(Dense(70, kernel_initializer='normal'))
        model.add(LeakyReLU())
        model.add(Dense(40, kernel_initializer='normal'))
        model.add(LeakyReLU())
        model.add(Dense(1, kernel_initializer='normal', activation='sigmoid'))
        model.compile(loss='mean_squared_error', optimizer=opt)
        model.summary()

        history = model.fit(Xtrain,
                            Ytrain,
                            epochs=2000,
                            validation_data=(Xtest, Ytest),
                            verbose=2,
                            shuffle=True)
        # serialize model to JSON
        model_json = model.to_json()
        with open("model.json", "w") as json_file:
            json_file.write(model_json)
        # serialize weights to HDF5
        model.save_weights("model.h5")
        print("Saved model to disk")
        # "Loss"
        plt.plot(history.history['loss'])
        plt.plot(history.history['val_loss'])
        plt.title('model loss')
        plt.ylabel('loss')
        plt.xlabel('epoch')
        plt.legend(['train', 'validation'], loc='upper left')
        plt.show()
    else:
        json_file = open('model.json', 'r')
        loaded_model_json = json_file.read()
        json_file.close()
        model = model_from_json(loaded_model_json)
        # load weights into new model
        model.load_weights("model.h5")
        opt = keras.optimizers.Adam(lr=0.00003)
        model.compile(loss='mean_squared_error', optimizer=opt)
        print("Loaded model from disk")

    for i in range(0, len(Xtest)):
        results = model.predict(Xtest[i:i + 1])
        print(Xtest[i:i + 1], "->", (results[0, 0]), (Ytest[i:i + 1]))

    scores = model.evaluate(Xtest, Ytest, verbose=1)
    print(scores)

    newPatient = np.array([[
        0.26826923, 0.16643159, 0.17498192, 0.08873505, 0.58562555, 0.37325349,
        0.76, 0.59472422, 0.57688113, 0.85923218, 0.41318477, 0.27671914,
        0.58829365
    ]])
    print("-------------")
    print(K.mean(model.layers[-1].output))
    print("-------------")
    print(newPatient)
    print(stretch(model.predict(newPatient)[0, 0]))

    diff = reverse(
        np.array([[
            0.26826923, 0.16643159, 0.17498192, 0.08873505, 0.58562555,
            0.37325349, 0.76, 0.59472422, 0.57688113, 0.85923218, 0.41318477,
            0.27671914, 0.58829365
        ]]), model.input)
    print(diff)
    newPatient[0, np.argmax(diff[0])] += np.max(diff[0]) * 0.2
    print(newPatient)
    print((model.predict(newPatient)[0, 0]))
Пример #10
0
import core

text = raw_input('Type a text, please:')
print "the reverse text is: ",core.reverse(text)
Пример #11
0
    def get_context_data(self, **kwargs):
        c = super().get_context_data(**kwargs)

        c['org'], new = Organization.objects.get_or_create(
            title='МГТУ им. Баумана')
        # if not c['org'].location_str:
        #     c['org'].location_str = 'Россия, Москва'
        #     c['org'].save()

        for code in ['IU', 'RL', 'RK', 'BMT']:
            f, new = Faculty.objects.get_or_create(
                code=faculties[code]['code'],
                title=faculties[code]['title'],
                university=c['org'],
            )
            # add departments
            for K in faculties[code].get('kafs', []):
                # print(
                #     faculties[code]['code']+str(K),
                #     faculties[code][K]['title']
                # )
                dep_code = faculties[code]['code'] + str(K)
                name = faculties[code][K]['title']
                d, new = Department.objects.get_or_create(
                    code=dep_code,
                    title=name,
                    university=c['org'],
                    faculty=f,
                )
                if not d.code_slug:
                    d.save()

        c['menu'] = Menu([(
            'faculties',
            {
                'title': 'Факультеты',
                # 'img': reverse(
                #     'core:files:file',
                #     host=c['host'].name,
                #     kwargs={
                #         'sha1': 'cb5766f0333ebeb9f3cdb0efad36e141566fa67f'
                #     },
                # ),
                'url': reverse('index', host=c['host'].name),
            })])
        c['menu']['iu2'] = {
            'title':
            'ИУ-2',
            'url':
            reverse(
                'kafedra',
                host=c['host'].name,
                # kwargs={'faculty': 'IU', 'kafedra': 2}
                kwargs={'dpt_code': 'iu2'}),
        }
        c['menu']['bmt1'] = {
            'title':
            'БМТ-1',
            'url':
            reverse('kafedra',
                    host=c['host'].name,
                    kwargs={'dpt_code': 'bmt1'}),
        }
        c['menu']['iu4'] = {
            'title':
            'ИУ-4',
            'url':
            reverse('kafedra', host=c['host'].name, kwargs={'dpt_code':
                                                            'iu4'}),
        }
        return c
Пример #12
0
    def get_context_data(self, **kwargs):
        # self.dir is a path for DirView
        period_code = kwargs.get('period_code', 'semestr-1')
        self.dir = os.path.join(
            self.d,
            kwargs.get('dpt_code').upper(),
            # 'sem'+kwargs.get('period_code','').split('-')[1]
            period_code,
        )
        try:
            if not os.path.isdir(self.dir):
                self.dir = os.path.join(
                    self.d,
                    kwargs.get('dpt_code').upper(),
                    'sem' + period_code.split('-')[-1],
                )
        except Exception:
            pass

        c = super().get_context_data(**kwargs)

        try:
            c['period'] = Period.objects.get(
                slug=kwargs.get('period_code'),
                department=c['department'],
            )
        except Period.DoesNotExist:
            c['status'] = 404

        c['dropzone'] = True
        c['menu'] = Menu([
            # (c['kafurl'].lower(), {
            (
                c['dpt_code'],
                {
                    'title':
                    c["department"].code,
                    'url':
                    reverse(
                        'kafedra',
                        host=c['host'].name,
                        kwargs={
                            # 'faculty': kwargs.get('faculty'),
                            # 'kafedra': kwargs.get('kafedra')
                            'dpt_code': kwargs.get('dpt_code'),
                        }),
                })
        ] if c["department"] else [])
        c['menu'] = Menu([])
        c['menu'] = Menu([(
            'baumanka',
            {
                'title':
                c["org"].title,  # МГТУ им. Баумана
                'img':
                reverse(
                    'files:file',
                    host=c['host'].name,
                    kwargs={
                        'sha1': 'cb5766f0333ebeb9f3cdb0efad36e141566fa67f'
                    },
                ),
                'url':
                reverse(
                    'kafedra',
                    host=c['host'].name,
                    kwargs={
                        # 'faculty': kwargs.get('faculty'),
                        # 'kafedra': kwargs.get('kafedra'),
                        'dpt_code': kwargs.get('dpt_code'),
                    }),
            })])
        for i in range(1, 13):
            c["menu"]['sem' + str(i)] = {
                'title':
                str(i),
                'url':
                reverse(
                    'sem',
                    host=c['host'].name,
                    kwargs={
                        'dpt_code': kwargs.get('dpt_code'),
                        'period_code': 'semestr-' + str(i),
                        # 'sem': i,
                        'path': '/'
                    }),
            }
        c['menu'].current = 'sem' + str(kwargs.get('sem'))
        # c['subjects'] = EduMaterial.objects.all()
        return c
Пример #13
0
 def get_absolute_url(self):
     return ''
     return reverse('subject:index', kwargs={'subj': self.slug})
Пример #14
0
 def get(self, request, **kwargs):
     c = self.get_context_data(**kwargs)
     logout(request)
     return HttpResponseRedirect(reverse("index", host=c['host'].name))
Пример #15
0
 def get(self, request, **kwargs):
     c = self.get_context_data(**kwargs)
     if request.user.is_authenticated:  # and not request.user.is_lazy:
         return HttpResponseRedirect(reverse("index", host=c['host'].name))
     else:
         return self.render_to_response(c, status=c['status'])
Пример #16
0
 def test_reverse(self):
     self.assertEqual(core.reverse('123'),'321')