# -*- 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 %}
{% endif %}
{% include "other-social.html" %}
{% include "partner_block.html" %}
Для того, чтобы получить подробное решение бесплатно, пожалуйста, проделайте следующие действия:
{% if not request.COOKIES.ilikeit %}
Скопируйте ссылку и разместите вконтакте или др. сайте:
{% endif %}
Введите цифры на рисунке
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 %}
Комментариев нет:
Отправить комментарий