понедельник, 21 ноября 2016 г.

Код сайта kontrolnaya-rabota.ru

equations/detailed.py:
# -*- coding:  utf-8 -*-
from hideme_proxy import get_good_proxy
from mechanize._response import response_seek_wrapper
from wolfram.utils import get_appid, get_user_agent
import mechanize
import time
import urllib
import random
import re
import xml.etree.ElementTree as ET


def get_inequal_detailed(list_data):
    expressions = []
    for data in list_data:
        solve1 = data['solve1']
        solve2 = data['solve2']
        oper = data['oper']
        expression = '%s%s%s' % (solve1, oper, solve2)
        expressions.append(expression)
    text = ' and '.join(expressions)
    expression_quote = urllib.quote(text)
    appid = get_appid()
    url_pattern = 'http://api.wolframalpha.com/v2/query?input=Solve+{0}&appid={1}&format=plaintext'
    url = url_pattern.format(expression_quote, appid)
    br = mechanize.Browser()
    br.set_handle_robots(False)
    br.set_handle_equiv(False)
    ip = get_good_proxy()
    br.set_proxies({'http': ip})
    ua = get_user_agent()
    br.addheaders = [('User-agent', ua)]
    br.open(url)
    response = br.response()
    response_text = response.read()
    root = ET.fromstring(response_text)
    if root.get('success') == 'true':
        elems = root.findall("./pod[@id='Result']/subpod/plaintext")
        ret = [el.text for el in elems]
        return ret
    raise NotImplementedError(response_text)


def get_equal_detailed(data):
    solve1 = data['solve1']
    solve2 = data['solve2']
    expression = '%s=%s' % (solve1, solve2)
    expression_quote = urllib.quote(expression)
    appid = get_appid()
    url_pattern = 'http://api.wolframalpha.com/v2/query?input=Solve+{0}&appid={1}&format=plaintext&podstate=Result__Step-by-step+solution'
    url = url_pattern.format(expression_quote, appid)
    ip = get_good_proxy()
    br = mechanize.Browser()
    br.set_proxies({'http': ip})
    ua = get_user_agent()
    br.addheaders = [('User-agent', ua)]
    br.set_handle_robots(False)
    br.set_handle_equiv(False)
    br.open(url)
    response = br.response()
    response_text = response.read()
    root = ET.fromstring(response_text)
    if root.get('success') == 'true':
        text = root.find("./pod//subpod[@title='Possible intermediate steps']/plaintext").text
        return text
    raise NotImplementedError(response_text)


def test_appid(appid):
    url = 'http://api.wolframalpha.com/v2/query?input=Solve+x^2-1&appid={0}&format=plaintext&podstate=Result__Step-by-step+solution'.format(appid)
    ip = get_good_proxy()
    br = mechanize.Browser()
    br.set_proxies({'http': ip})
    ua = get_user_agent()
    br.addheaders = [('User-agent', ua)]
    br.set_handle_robots(False)
    br.set_handle_equiv(False)
    br.open(url)
    response = br.response()
    response_text = response.read()
    root = ET.fromstring(response_text)
    if root.get('success') == 'true':
        return 'OK'
    return response_text
buy/views.py:
# encoding:utf-8
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render
from django.utils.translation import ugettext as _
from django.views.decorators.cache import cache_page
from latexmath2png import math2png
from s.buy.forms import FreeForm, FreeFormWithoutCaptha
from s.equal_one.detailed import get_equal_detailed
from settings import at_project_root
from wolfram.base import get_solution_class
import datetime
import hashlib
import re
import time


def free_old(request):
    return redirect('/s/', permanent=True)


def free(request):
    form = FreeForm(request.POST or None)
    redirect_to = None
    if form.is_valid():
        cleaned_data = form.cleaned_data
        key = generate_key()
        base_url = reverse('buy-complete', kwargs={'key': key})
        query_string = form.get_request_string(cleaned_data)
        redirect_to = '%s?%s' % (base_url, query_string)
    context = {'free_form': form, 'redirect_to': redirect_to}
    template_name = 's/buy/free.html'
    return render(request, template_name, context)


@cache_page(60 * 60)
def buy_complete(request, key):

    user_agent = request.META.get('HTTP_USER_AGENT')

    if 'Mediapartners-Google' in user_agent or \
        'YandexDirect' in user_agent:
        return free(request)

    if key != generate_key():
        return redirect('/s/')
    form = FreeFormWithoutCaptha(request.GET or None)
    if not form.is_valid():
        return redirect(reverse('s-main'))
    module = form.cleaned_data['module']
    data = form.cleaned_data['data']
    if module in ['diff', 'limit']:
        SolutionClass = get_solution_class(module)
        text = SolutionClass(data, with_proxy=False).get_text()
    elif module in ('indefinite', 'definite'):
        SolutionClass = get_solution_class('indefinite')
        text = SolutionClass(data).get_text()
    elif module == 'equal':
        text = get_equal_detailed(data)
    for trans in BLOCK_I18N:
        text = text.replace(trans, _(trans))
    text = text.replace('\\n', '\n')
    text = text.replace('\\/', '/')
    if 'wolfram' in text.lower():
        raise ValidationError(u'wolfram text on solution')
    tex_body = text_to_tex(text)
    prefix = hashlib.md5(tex_body.encode('utf-8')).hexdigest()
    try:
        math2png(
            [tex_body.encode('utf-8')],
            'media/buy',
            prefix=prefix,
        )
    except:
        with_simple_text = True
    else:
        with_simple_text = False

    time.sleep(3)
    template_name = 's/buy/complete.html'
    context = {
        'tex_body': tex_body,
        'prefix': prefix,
        'with_simple_text': with_simple_text,
        'text': text,
    }
    return render(request, template_name, context)


def i18n_blocks():
    fn = at_project_root('kr/wolfram.trans')
    ret = open(fn).read().strip().decode('utf-8').split('\n')
    ret = sorted(ret, key=lambda s: len(s), reverse=True)
    return ret

BLOCK_I18N = i18n_blocks()


def generate_key():
    today_text = datetime.date.today().strftime('%F')
    open_key = '%s-%s' % (settings.SECRET_KEY, today_text)
    key = hashlib.md5(open_key).hexdigest()
    return key


def text_to_tex(text):
    fp = '(?:cos|sin|tan|atan|csc|cot|sec|log|ln|sqrt|sinh|cosh|arccos|arcsin|arccosh|arcsinh|arctg|arcctg|atan)'

    ac = '[_a-zA-Z@^\d.]'

    ac_p = '[_a-zA-Z@^{}\d.]'

    text = text.replace('d/dx', '@@@')
    text = text.replace('tan^(-1)', 'arctg')
    text = text.replace('cos^(-1)', 'arccos')
    text = text.replace('sin^(-1)', 'arcsin')
    text = text.replace('cot^(-1)', 'arcctg')
    text = re.sub(r'\b(sec)\b', '1/sin', text)
    text = re.sub(r'd(sec)\b', 'd 1/sin', text)
    text = re.sub(r'\b(csc)\b', '1/cos', text)
    text = re.sub(r'd(csc)\b', 'd 1/cos', text)
    text = re.sub(r'\b(log)\b', 'ln', text)
    text = re.sub(r'd(log)\b', 'd log', text)
    text = re.sub(r'\b(cot)\b', 'ctg', text)
    text = re.sub(r'd(cot)\b', 'd ctg', text)
    text = re.sub(r'\b(tan)\b', 'tg', text)
    text = re.sub(r'd(tan)\b', 'd tg', text)

    text = re.sub(r'lim_\(([^\)]+)\)', r'lim_{\1}', text)

    text = re.sub(r'(%(fp)s)\^%(b)s\(' % {
        'fp': fp, 'b': get_bucket_pattern_by_level(4)[2:-2]
    }, r'\1^{\2}(', text)

    A = []
    j = 0
    for i in range(5):
        list_expr = set(re.findall(r'(%(fp)s*\([^\(\)]+\))' % {'fp': fp}, text))
        list_expr = sorted(list_expr, key=lambda expr: len(expr))
        list_expr.reverse()
        for bracket in list_expr:
            text = text.replace(bracket, '__III%s__' % j)
            A.append(bracket)
            j += 1

    for j, bucket in enumerate(A):
        in_bucket = bucket
        if bucket.startswith('('):
            in_bucket = in_bucket[1:-1]
        in_bucket = re.sub(r'(%(fp)s*%(ac_p)s+)/(%(fp)s*%(ac_p)s+)' % {
            'fp': fp, 'ac_p': ac_p
        }, r'\\frac{\1}{\2}', in_bucket)

        in_bucket = re.sub(r'(%(ac)s+)\^(%(ac)s+)' % {
            'ac': ac
        }, r'\1^{\2}', in_bucket)
        if bucket.startswith('('):
            A[j] = '(%s)' % in_bucket
        else:
            A[j] = in_bucket

    text = re.sub(r'(%(fp)s*%(ac_p)s+)/(%(fp)s*%(ac_p)s+)' % {
        'fp': fp, 'ac_p': ac_p
    }, r'\\frac{\1}{\2}', text)
    text = re.sub(r'(%(ac)s+)\^(%(ac)s+)' % {'ac': ac}, r'\1^{\2}', text)

    for i in range(5):
        for j, backet in enumerate(A):
            text = text.replace('__III%s__' % j, backet)

    text = text.replace('= | ', '\\\\\\\\ = ').replace(' | ', '\\\\\\\\').replace(' ', '\;').replace('\n', '\\\\\\\\')
    text = text.replace("\\'", "'")

    text = re.sub(r'{\(([^{}]+)\)}', r'{\1}', text)

    text = text.replace('@@@', '\\frac{d}{dx}')
    text = text.replace('integral', '\\int')
    text = text.replace('·', u'*')
    text = text.replace('>infinity', u'>oo')
    text = text.replace('>-infinity', u'>-oo')
    return text


def get_bucket_pattern_by_level(level):
    list_res = []
    b0 = '[^\(\)]'
    c = '%s+' % b0
    list_res.append(c)
    for i in range(level):
        b = '\((%s)\)' % '|'.join(list_res)
        c = '(?:(?:\((?:%s)\))|%s)+' % (b[3:-3], b0)
        list_res.append(c)
    return b
buy/urls.py:
from django.conf.urls.defaults import patterns, url

urlpatterns = patterns('s.buy.views',
    url(r'^free/$',  'free_old' , name='free-old'),
    url(r'^besplatno/$',  'free' , name='free'),
    url(r'^complete/(?P[0-9a-f]+)/$',  'buy_complete', name='buy-complete'),
)
buy/forms.py
# -*- coding: utf8 -*-
from s.models import Ads, ExcludeUrl
from captcha.fields import CaptchaField, CaptchaTextInput
from django import forms
import json
import urllib


BUY_VERSION = 2


class FreeFormWithoutCaptha(forms.Form):

    data = forms.CharField(widget=forms.HiddenInput)
    module = forms.CharField(widget=forms.HiddenInput)

    def clean_data(self):
        data = self.cleaned_data['data']
        try:
            data = json.loads(data)
        except:
            raise forms.ValidationError('No load json')
        return data

    def get_request_string(self, cleaned_data):
        data = cleaned_data['data']
        data = json.dumps(data)
        data = urllib.quote(data)
        module = cleaned_data['module']
        req_string = 'module=%(module)s&data=%(data)s' % {
            'module': module, 'data': data,
        }
        return req_string


if BUY_VERSION == 1:


    class FreeForm(FreeFormWithoutCaptha):

        url = forms.URLField(
            help_text=(
                u'URL страницы, где содержится активная ссылка на мой сайт'
            ), label=u'Url страницы',
        )
        captcha = CaptchaField()

        def __init__(self, *args, **kwargs):
            super(FreeForm, self).__init__(*args, **kwargs)
            self.fields['captcha'].widget.attrs = {'autocomplete': "off"}

        def clean_url(self):
            url = self.cleaned_data['url'].lower()
            exclude_urls = ExcludeUrl.objects.all().values_list('url', flat=True)
            for exclude_url in exclude_urls:
                if url.startswith('http://' + exclude_url) or \
                    url.startswith('http://www.' + exclude_url):
                    raise forms.ValidationError(
                        (u'Котэ следит за тобой. Пожалуйста, добавьте ссылку себе на '
                         u'сайт, форум или блог!')
                    )
            return url

        def get_ads(self):
            ads = Ads.objects.random()
            return ads

elif BUY_VERSION == 2:

    class FreeForm(FreeFormWithoutCaptha):

        captcha = CaptchaField()

        def __init__(self, *args, **kwargs):
            super(FreeForm, self).__init__(*args, **kwargs)
            self.fields['captcha'].widget.attrs = {'autocomplete': "off"}

        def get_ads(self):
            ads = Ads.objects.random()
            return ads
wolfram/utils.py
# coding:utf-8
from settings import at_project_root
import random


def get_appid():
    filename = at_project_root('kr/wolfram.keys')
    appid_list = open(filename).read().strip().split()
    random.shuffle(appid_list)
    appid = appid_list[0]
    return appid


def get_user_agent():
    filename = at_project_root('kr/wolfram.ua')
    ua_list = open(filename).read().strip().split('\n')
    assert len(ua_list) > 1
    random.shuffle(ua_list)
    ua = ua_list[0]
    return ua
wolfram/base.py
#encoding:utf-8
from hideme_proxy import get_good_proxy, IpProxyDNotExist
from wolfram.utils import get_user_agent, get_appid
import httplib
import mechanize
import urllib
import urllib2
import xml.etree.ElementTree as ET
import zlib


_open_url_error_classes = (
    urllib2.HTTPError,
    urllib2.URLError,
    IOError,
    httplib.BadStatusLine,
    httplib.IncompleteRead,
    zlib.error,  # for gzip compressed responses
    IpProxyDNotExist,
)


class InternetError(Exception):

    pass


def get_solution_class(class_name):
    return SOLUTION_CLASSES[class_name]


SOLUTION_CLASSES = {}
def register_solution_class(class_name):
    def wrapper(cls):
        SOLUTION_CLASSES[class_name] = cls
        return cls
    return wrapper


class _InternetObject(object):

    def _initial_browser(self):
        br = mechanize.Browser()
        ua = get_user_agent()
        br.addheaders = [('User-agent', ua)]
        br.set_handle_robots(False)
        br.set_handle_equiv(False)
        return br

    def _get_rawurlencode(self, params):
        items = []
        for key, val in params.items():
            new_val = urllib.quote(val)
            item = '{0}={1}'.format(key, new_val)
            items.append(item)
        ret = '&'.join(items)
        return ret

    def get_params(self):
        raise NotImplementedError


class DetailedSolution(_InternetObject):

    base_url = 'http://api.wolframalpha.com/v2/query'

    def __init__(self, data, with_proxy=True):
        self.data = data
        self.with_proxy = with_proxy
        self.br = self._initial_browser()
        self.appid = get_appid()

    def __str__(self):
        super_str = super(DetailedSolution, self).__str__()
        ret = '{0} with appid={1}'.format(super_str, self.appid)
        return ret

    def get_text(self):
        response_text = self.get_response_text()
        root = ET.fromstring(response_text)
        if root.get('success') == 'true':
            xpath = "./pod//subpod[@title='Possible intermediate steps']/plaintext"
            text = root.find(xpath).text
            return text
        raise NotImplementedError(response_text)

    def get_response_text(self):
        if self.with_proxy:
            try:
                ip = get_good_proxy()
            except _open_url_error_classes, exc:
                raise InternetError(exc)
            self.br.set_proxies({'http': ip})
        params = self.get_params()
        params.update({
            'format': 'plaintext',
            'appid': self.appid,
        })
        url = self.base_url + '?' + \
            self._get_rawurlencode(params)
        try:
            self.br.open(url)
            response = self.br.response()
            response_text = response.read()
        except _open_url_error_classes, exc:
            raise InternetError(exc)
        return response_text


@register_solution_class('limit')
class LimitSolution(DetailedSolution):

    def get_params(self):
        data = self.data
        x0 = data['x0']
        function = data['function']
        expression = 'lim %s x->%s' % (function, x0)
        ret = {
            'input': expression,
            'podstate': 'Limit__Step-by-step solution',
        }
        return ret


@register_solution_class('indefinite')
class IndefiniteSolution(DetailedSolution):

    def get_params(self):
        data = self.data
        function = data['function']
        expression = 'integrate %s' % function
        ret = {
            'input': expression,
            'podstate': 'IndefiniteIntegral__Step-by-step solution',
        }
        return ret


@register_solution_class('diff')
class DiffSolution(DetailedSolution):

    def get_params(self):
        data = self.data
        function = data['function']
        expression = 'derivative of %s' % function
        ret = {
            'input': expression,
            'podstate': 'Input__Step-by-step solution',
        }
        return ret


@register_solution_class('series-number')
class SeriesNumberSolution(DetailedSolution):

    def get_result(self):
        ret = {}
        response_text = self.get_response_text()
        root = ET.fromstring(response_text)
        if root.get('success') == 'true':
            nods = root.findall('./pod[@id="ConvergenceTests"]/subpod/plaintext')
            tests = map(lambda n: n.text, nods)
            ret['tests'] = tests
            return ret
        raise NotImplementedError(response_text)

    def get_params(self):
        data = self.data
        function = data['function']
        n = data['n']
        n0 = data['n0']
        nm = data['nm']
        infinity = data['infinity']
        if infinity:
            nm = 'oo'
        expression = 'Sum[{0}, {1}, {2}, {3}]'.format(function, n, n0, nm)
        ret = {
            'input': expression,
        }
        return ret


@register_solution_class('power-series')
class PowerSeriesSolution(DetailedSolution):

    def get_result(self):
        ret = {}
        response_text = self.get_response_text()
        root = ET.fromstring(response_text)
        if root.get('success') == 'true':
            nods = root.findall('./pod[@id="ConvergenceTests"]/subpod/plaintext')
            tests = map(lambda n: n.text, nods)
            ret['tests'] = tests
            return ret
        raise NotImplementedError(response_text)

    def get_params(self):
        expression = 'Sum of {function}'.format(**self.data)
        ret = {
            'input': expression,
        }
        return ret


@register_solution_class('system-diff')
class SystemDiffSolution(DetailedSolution):

    def get_result(self):
        ret = {}
        response_text = self.get_response_text()
        root = ET.fromstring(response_text)
        if root.get('success') == 'true':
            nods = root.findall('./pod[@id="DifferentialEquationSolution"]/subpod/plaintext')
            solves = map(lambda n: n.text, nods)
            solves = map(lambda s: s.replace('_', ''), solves)
            ret['solves'] = solves
            return ret
        raise NotImplementedError(response_text)

    def get_params(self):
        expression = ' and '.join('='.join(i) for i in self.data['equations'])
        ret = {
            'input': expression,
        }
        return ret
widgetes/jscalendar.py
from django import forms
from django.template.loader import render_to_string

class JSCalendarWidget(forms.DateTimeInput):
    class Media:
        css = {
            'all': ('javascript/jscalendar-1.0/calendar-system.css',)
        }
        js = ('javascript/jscalendar-1.0/calendar.js',
              'javascript/jscalendar-1.0/calendar-setup.js',
              'javascript/jscalendar-1.0/lang/calendar-ru-UTF.js',)

    def render(self, name, value, lang='ru', attrs=None):
        value = value or ''
        return render_to_string("widgets/jscalendar.html", locals())
buy/complete.html
{% extends "s/sbase.html" %}
{% block title %}Подробное решение бесплатно!{% endblock %}
{% block head %}
    
{% endblock %}
{% block crumbs %}Больше решений!{% endblock %}
{% block base_table %}
    

Подробное решение: ответ

{% include "partner_block.html" %} {% if with_simple_text %}
{{ text }}
{% else %} {{ text }} {% endif %} {% include "other-social.html" %} {% include "partner_block.html" %}
{% endblock %}
buy/definite.tex
\documentclass[a4paper, 12pt]{article}
\usepackage[unicode]{hyperref}
\usepackage{mathtext}
\usepackage[T1, T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english, russian]{babel}
\vskip 0.5 cm

\begin{document}

${{ tex_body }}$

\end{document}
buy/diff.tex
\documentclass[a4paper, 12pt]{article}
\usepackage[unicode]{hyperref}
\usepackage{mathtext}
\usepackage[T1, T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english, russian]{babel}
\vskip 0.5 cm

\begin{document}

${{ tex_body }}$

\end{document}
buy/free_form.html

Для того, чтобы получить подробное решение бесплатно, пожалуйста, проделайте следующие действия:

    {% if not request.COOKIES.ilikeit %}
  1. Скопируйте ссылку и
    разместите вконтакте или др. сайте:
  2. {% endif %}
  3. Введите цифры на рисунке
{% csrf_token %} {{ free_form }}
buy/free.html
{% extends "s/sbase.html" %}
{% load i18n %}
{% block head %}
 {% if redirect_to %}
 
 
 {% endif %}
{% endblock %}
{% block title %}Подробное решение бесплатно!{% endblock %}

{% block content %}
  

Подробное решение

{% include "partner_block.html" %} {% if redirect_to %}

Производится проверка размещения ссылки, пожалуйста подождите чуть больше 1 мин...

Если ссылка на наш сайт будет найдена, то Вам будет предложено решение.
Если программа не найдет ссылку вида http://kontrolnaya-rabota.ru, то Вы не получите файла, но можно попробовать разместить ссылку на сайт http://kontrolnaya-rabota.ru/s/ снова.
Назад.
{% else %}

Хотите получить подробное решение с описанием действий?

{% include "s/buy/free_form.html" %} {% endif %} {% include "partner_block.html" %} {% endblock %}
buy/indefinite.tex
\documentclass[a4paper, 12pt]{article}
\usepackage[unicode]{hyperref}
\usepackage{mathtext}
\usepackage[T1, T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english, russian]{babel}
\vskip 0.5 cm

\begin{document}

${{ tex_body }}$

\end{document}
buy/limit.html
\documentclass[a4paper, 12pt]{article}
\usepackage[unicode]{hyperref}
\usepackage{mathtext}
\usepackage[T1, T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english, russian]{babel}
\vskip 0.5 cm

\begin{document}

${{ tex_body|safe }}$

\end{document}

Комментариев нет:

Отправить комментарий