code
stringlengths
1
1.72M
language
stringclasses
1 value
# coding=utf-8 from django import forms from django.db import models from django.contrib.auth.models import User from registration.forms import RegistrationForm from datetime import date conceitos = (('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D'), ('FF', 'FF')) anos = range(1985, date.today().year + 1) cla...
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll ha...
Python
from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin from forca.models import Professor, Disciplina, RegistroII admin.autodiscover() prof = {'queryset': Professor.objects.all(), 'template_name': "listaprof.html", 'template_object_name': "lista_prof"} di...
Python
from hashlib import sha1 from base64 import b64encode def tripcode(nome): return b64encode(sha1(nome + ". NOT!").digest())
Python
# coding = utf-8 from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponseRedirect from django.template import RequestContext as RC from django.contrib.auth.decorators import login_required from forca.models import * from forca.tripcode import tripcode def discipl...
Python
from forca.models import * from django.contrib import admin admin.site.register(Disciplina) admin.site.register(Professor) admin.site.register(Avaliacao)
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll ha...
Python
# find_missing_files_and_cleanup.py # # author: xtraeme # date: 2014/09/18 # # In addition to finding missing and misnamed files (typically "Page 1.jpg," often misnamed # "age1.jpg", because of how the system code navigates to a new directory -- # https://code.google.com/p/footnotereap/issues/detail?id=6#c8 )....
Python
# create_sym_links_with_padded_zeros.py (CSLPZ) # # author: xtraeme # date: 2014/09/20 # # The Blue Book NARA pages adhere to the following naming convention and increment like so: # Page 1, Page 2, ... Page 10, ..., Page 20, etc. # # Since the filenames don't have padded zeroes, navigating through the files ...
Python
#!/usr/bin/python import sys import os import string import subprocess import time """ Usage: rpcexec -n n_to_start -f [hostsfile] [program] [options] To start local only: rpcexec [program] [options] """ def escape(s): s = string.replace(s, '"', '\\"') s = string.replace(s, "'", "\\'") return s #enddef # gui: ...
Python
#!/usr/bin/python import os import sys def update_source(filename, oldcopyright, copyright): fdata = file(filename,"r+").read() # If there was a previous copyright remove it if (oldcopyright != None): if (fdata.startswith(oldcopyright)): fdata = fdata[len(oldcopyright):] # If the...
Python
#!/usr/bin/python import sys import string import subprocess def left_child(index) : return 2 * index + 1 def right_child(index) : return 2 * index + 2 def escape_str(text) : return text.replace('\\', '\\\\').replace('"', '\\"') def do_send(src, dest, path ) : return ' ( rsync -avz ' + \ pat...
Python
for v in graph.getVertices(): print(v.value.rank)
Python
import math # Python implementation of pagerank damping = 0.85 def update(scope, scheduler): pvertex = scope.getVertex().value sumval = pvertex.rank * pvertex.selfedge + sum([e.value * scope.getNeighbor(e.from).value.rank for e in scope.getInboundEdges()]) newval = (1-damping)/scope.getNumOfVertices() + ...
Python
class pagerank_vertex: def __init__(self, value, selfedge): self.rank = value self.selfedge = selfedge f = open(filename, "r") lines = f.readlines() # First line is header header = lines[0] lines = lines[1:] nvertices = int(header.split(",")[1]) for i in range(0,nvertices): # format: first v...
Python
import math lamb = 0.5 # Python implementation of Lasso Shooting algorithm. # min ||Ax-y||_2^2 + lambda ||x||_1 def update(scope, scheduler): # Of class lasso_variable_vertex or lasso_estimate_vertex lassov = scope.getVertex().value if (lassov.vtype == 0): if lassov.initialized == False: ...
Python
graphlab.setScheduler("round_robin") graphlab.setIterations(100) graphlab.setScopeType("vertex")
Python
import math # Python implementation of pagerank def update(scope, scheduler): vertex = scope.getVertex() oldval = vertex.value newval = vertex.value * vertex.selfEdgeWeight newval = newval + sum([e.weight*e.value for e in scope.getInboundEdges()]) vertex.setValue(newval) if (abs(newval-oldval)...
Python
leastsqr_err = 0.0 penalty = 0.0 lamb = 0.5 for v in graph.getVertices(): lassov = v.value if lassov.vtype == 0: penalty += lamb * abs(lassov.value) else: leastsqr_err += pow(lassov.observed - lassov.curval,2) print("Objective:", penalty + leastsqr_err)
Python
# # Solve Lasso: min ||Ax-y||_2^2 + \lambda ||x||_1 # # We present Lasso as a bipartite graph. On the left side, we have # variables x_i (predictors) and on the right side the current estimates # for y_i = (Ax)_i. Sides are connected by edges weighted by A_ij # # # Rights side of the graph. Estimate for y_i. We st...
Python
# module pyparsing.py # # Copyright (c) 2003-2010 Paul T. McGuire # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to u...
Python
# module pyparsing.py # # Copyright (c) 2003-2010 Paul T. McGuire # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to u...
Python
#!/usr/bin/python '''Usage: %s [OPTIONS] <input file(s)> Generate test source file for CxxTest. -v, --version Write CxxTest version -o, --output=NAME Write output to file NAME --runner=CLASS Create a main() function that runs CxxTest::CLASS --gui=CLASS Like --runner, with GUI c...
Python
#!/opt/ActivePython-3.2/bin/python3 #This program is the master GUI for the Manta Ray project. #version 1.14 #########################COPYRIGHT INFORMATION############################ #Copyright (C) 2013 Kevin.Murphy@ManTech.com # #This program is free software: you can redistribute it and/or modify...
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for ...
Python
#! /usr/bin/python import glob import shutil import sys import subprocess import os if 'linux' in sys.platform: platform = 'linux' else: platform = 'darwin' toolchain = "%s/android-toolchain" % os.getenv("HOME") openssl_version = "1.0.0n" encfs_version = "1.7.5" def cpfile(src, target): sys.stdout.write...
Python
#! /usr/bin/python import glob import shutil import sys import subprocess import os def cpfile(src, target): sys.stdout.write("Copying %s to %s\n" % (src, target)) shutil.copy(src, target) # We only copy the armeabi version of the binary archs = ["armeabi"] for arch in archs: try: os.makedirs("....
Python
#! /usr/bin/python import glob import shutil import sys import subprocess import os def cpfile(src, target): sys.stdout.write("Copying %s to %s\n" % (src, target)) shutil.copy(src, target) # We only copy the armeabi version of the binary archs = ["armeabi"] for arch in archs: try: os.makedirs("....
Python
#! /usr/bin/python import glob import shutil import sys import subprocess import os def cpfile(src, target): sys.stdout.write("Copying %s to %s\n" % (src, target)) shutil.copy(src, target) # We only copy the armeabi version of the binary archs = ["armeabi"] for arch in archs: try: os.makedirs("....
Python
# YOU NEED TO INSERT YOUR APP KEY AND SECRET BELOW! # Go to dropbox.com/developers/apps to create an app. app_key = '' app_secret = '' # access_type can be 'app_folder' or 'dropbox', depending on # how you registered your app. access_type = 'app_folder' from dropbox import client, rest, session from getpass import ...
Python
# YOU NEED TO INSERT YOUR APP KEY AND SECRET BELOW! # Go to dropbox.com/developers/apps to create an app. app_key = '' app_secret = '' # access_type can be 'app_folder' or 'dropbox', depending on # how you registered your app. access_type = 'app_folder' from dropbox import client, rest, session from getpass import ...
Python
from ._Sonars import *
Python
#!/usr/bin/python import sys import os import string import subprocess import time """ Usage: rpcexec -n n_to_start -f [hostsfile] [program] [options] To start local only: rpcexec [program] [options] """ def escape(s): s = string.replace(s, '"', '\\"') s = string.replace(s, "'", "\\'") return s #enddef # gui: ...
Python
#!/usr/bin/python import os import sys def update_source(filename, oldcopyright, copyright): fdata = file(filename,"r+").read() # If there was a previous copyright remove it if (oldcopyright != None): if (fdata.startswith(oldcopyright)): fdata = fdata[len(oldcopyright):] # If the...
Python
#!/usr/bin/python import sys import string import subprocess def left_child(index) : return 2 * index + 1 def right_child(index) : return 2 * index + 2 def escape_str(text) : return text.replace('\\', '\\\\').replace('"', '\\"') def do_send(src, dest, path ) : return ' ( rsync -avz ' + \ pat...
Python
for v in graph.getVertices(): print(v.value.rank)
Python
import math # Python implementation of pagerank damping = 0.85 def update(scope, scheduler): pvertex = scope.getVertex().value sumval = pvertex.rank * pvertex.selfedge + sum([e.value * scope.getNeighbor(e.from).value.rank for e in scope.getInboundEdges()]) newval = (1-damping)/scope.getNumOfVertices() + ...
Python
class pagerank_vertex: def __init__(self, value, selfedge): self.rank = value self.selfedge = selfedge f = open(filename, "r") lines = f.readlines() # First line is header header = lines[0] lines = lines[1:] nvertices = int(header.split(",")[1]) for i in range(0,nvertices): # format: first v...
Python
import math lamb = 0.5 # Python implementation of Lasso Shooting algorithm. # min ||Ax-y||_2^2 + lambda ||x||_1 def update(scope, scheduler): # Of class lasso_variable_vertex or lasso_estimate_vertex lassov = scope.getVertex().value if (lassov.vtype == 0): if lassov.initialized == False: ...
Python
graphlab.setScheduler("round_robin") graphlab.setIterations(100) graphlab.setScopeType("vertex")
Python
import math # Python implementation of pagerank def update(scope, scheduler): vertex = scope.getVertex() oldval = vertex.value newval = vertex.value * vertex.selfEdgeWeight newval = newval + sum([e.weight*e.value for e in scope.getInboundEdges()]) vertex.setValue(newval) if (abs(newval-oldval)...
Python
leastsqr_err = 0.0 penalty = 0.0 lamb = 0.5 for v in graph.getVertices(): lassov = v.value if lassov.vtype == 0: penalty += lamb * abs(lassov.value) else: leastsqr_err += pow(lassov.observed - lassov.curval,2) print("Objective:", penalty + leastsqr_err)
Python
# # Solve Lasso: min ||Ax-y||_2^2 + \lambda ||x||_1 # # We present Lasso as a bipartite graph. On the left side, we have # variables x_i (predictors) and on the right side the current estimates # for y_i = (Ax)_i. Sides are connected by edges weighted by A_ij # # # Rights side of the graph. Estimate for y_i. We st...
Python
# module pyparsing.py # # Copyright (c) 2003-2010 Paul T. McGuire # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to u...
Python
# module pyparsing.py # # Copyright (c) 2003-2010 Paul T. McGuire # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to u...
Python
#!/usr/bin/python '''Usage: %s [OPTIONS] <input file(s)> Generate test source file for CxxTest. -v, --version Write CxxTest version -o, --output=NAME Write output to file NAME --runner=CLASS Create a main() function that runs CxxTest::CLASS --gui=CLASS Like --runner, with GUI c...
Python
#!/home/cheshire/install/bin/python -i # depth first web crawler import sys, os, re import urllib import urlparse from lxml import etree import StringIO import hashlib from foresite import * from foresite import conneg from rdflib import URIRef, Literal parser = etree.HTMLParser() nonHttpRe = re.compile("^(mailto|...
Python
#!/usr/bin/env python from setuptools import setup, find_packages version = '0.9' setup(name='foresite', version=version, description='Library for constructing, parsing, manipulating and serializing OAI-ORE Resource Maps', long_description="""\ """, classifiers=[], author='Rob Sanderson'...
Python
#!/home/cheshire/install/bin/python -i from foresite import * import urllib2 import os, sys import getopt # given an initial starting point, crawl nested and linked ORE aggregations # download aggregated resources # content negotiation for prefered ReM format def usage(): print """Usage: %s [-r] [-d DEPTH] [-f R...
Python
#!/usr/bin/env python from setuptools import setup, find_packages version = '0.9' setup(name='foresite', version=version, description='Library for constructing, parsing, manipulating and serializing OAI-ORE Resource Maps', long_description="""\ """, classifiers=[], author='Rob Sanderson'...
Python
#!/home/cheshire/install/bin/python -i # depth first web crawler import sys, os, re import urllib import urlparse from lxml import etree import StringIO import hashlib from foresite import * from foresite import conneg from rdflib import URIRef, Literal parser = etree.HTMLParser() nonHttpRe = re.compile("^(mailto|...
Python
#!/home/cheshire/install/bin/python -i from foresite import * import urllib2 import os, sys import getopt # given an initial starting point, crawl nested and linked ORE aggregations # download aggregated resources # content negotiation for prefered ReM format def usage(): print """Usage: %s [-r] [-d DEPTH] [-f R...
Python
import os import urllib, urllib2 from rdflib import ConjunctiveGraph, URIRef, BNode, Literal from utils import * from StringIO import StringIO from utils import unconnectedAction from foresite import libraryName, libraryUri, libraryEmail from foresite import conneg # --- Object Class Definitions --- class Graph(Conj...
Python
import doctest import unittest import glob import os optionflags = (doctest.REPORT_ONLY_FIRST_FAILURE | doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS) def open_file(filename, mode='r'): """Helper function to open files from within the tests package.""" return open(os.path.join...
Python
import re from ore import * from ore import foresiteAgent from foresite import libraryName, libraryUri, libraryVersion from utils import namespaces, OreException, unconnectedAction, pageSize from utils import gen_uuid, build_html_atom_content from rdflib import URIRef, BNode, Literal, plugin, syntax, RDF from rdflib.u...
Python
try: import json except ImportError: import simplejson as json from rdflib.syntax.parsers import Parser from rdflib import URIRef, BNode, Literal class JsonParser(Parser): def __init__(self): pass def parse(self, source, sink, **args): data = source.getByteStream().read() ...
Python
def skipws(next): skip = 1 if not skip: return next else: def foo(*args): tok = next(*args) if tok.isspace(): tok = next(*args) return tok return foo class ParseError(Exception): pass class MiniLex(object): def __init__(...
Python
import urllib import time import re from rdflib import Namespace ### Configuration Options ### Assign a UUID URI or Blank Node for autogenerating agent URIs ### if not present in data assignAgentUri = False #assignAgentUri = True ### Use UUID or oreproxy.org for autogenerating proxy URIs if ### not present in data p...
Python
# Dependencies: rdflib # lxml libraryName= "Foresite Toolkit (Python)" libraryUri = "http://foresite-toolkit.googlecode.com/#pythonAgent" libraryVersion = "1.1" libraryEmail = "foresite@googlegroups.com" __all__ = ['ore', 'utils','parser', 'serializer', 'tripleStore', 'Aggregation', 'ResourceMap', 'A...
Python
from __future__ import generators from rdflib.syntax.serializers import Serializer from rdflib.URIRef import URIRef from rdflib.Literal import Literal from rdflib.BNode import BNode from rdflib.util import uniq from rdflib.exceptions import Error from rdflib.syntax.xml_names import split_uri from xml.sax.saxutils i...
Python
from __future__ import generators from rdflib.syntax.serializers import Serializer from rdflib.URIRef import URIRef from rdflib.Literal import Literal from rdflib.BNode import BNode from rdflib.util import uniq from rdflib.exceptions import Error from rdflib.syntax.xml_names import split_uri from xml.sax.saxutils i...
Python
from ore import * from utils import namespaces, OreException, unconnectedAction, protocolUriRe from lxml import etree from xml.dom import minidom from rdflib import StringInputSource, URIRef, plugin, syntax plugin.register('json', syntax.parsers.Parser, 'foresite.JsonParser', 'JsonParser') class OREParser(object):...
Python
from ore import * from utils import namespaces from rdflib import URIRef, plugin, store # Store raw triples into a TripleStore somewhere class TripleStore(object): def __init__(self, configuration, db, create): self.configuration = configuration self.create = create self.db = db ...
Python
# # Simple Mod_Python handler for validating and transforming # ORE Resource Maps # # apache config: # <Directory /home/cheshire/install/htdocs/txr> # SetHandler mod_python # PythonDebug On # PythonPath "['/path/to/validateHandler.py/']+sys.path" # PythonHandler validateHandler # </Directory> impor...
Python
#!/home/cheshire/install/bin/python -i # depth first web crawler import sys, os, re import urllib import urlparse from lxml import etree import StringIO import hashlib from foresite import * from foresite import conneg from rdflib import URIRef, Literal parser = etree.HTMLParser() nonHttpRe = re.compile("^(mailto|...
Python
#!/usr/bin/env python from setuptools import setup, find_packages version = '1.1' setup(name='foresite', version=version, description='Library for constructing, parsing, manipulating and serializing OAI-ORE Resource Maps', long_description="""\ """, classifiers=[], author='Rob Sanderson'...
Python
#!/home/cheshire/install/bin/python -i from foresite import * import urllib2 import os, sys import getopt # given an initial starting point, crawl nested and linked ORE aggregations # download aggregated resources # content negotiation for prefered ReM format def usage(): print """Usage: %s [-r] [-d DEPTH] [-f R...
Python
#!/usr/bin/env python from setuptools import setup, find_packages version = '1.1' setup(name='foresite', version=version, description='Library for constructing, parsing, manipulating and serializing OAI-ORE Resource Maps', long_description="""\ """, classifiers=[], author='Rob Sanderson'...
Python
#!/home/cheshire/install/bin/python -i # depth first web crawler import sys, os, re import urllib import urlparse from lxml import etree import StringIO import hashlib from foresite import * from foresite import conneg from rdflib import URIRef, Literal parser = etree.HTMLParser() nonHttpRe = re.compile("^(mailto|...
Python
#!/home/cheshire/install/bin/python -i from foresite import * import urllib2 import os, sys import getopt # given an initial starting point, crawl nested and linked ORE aggregations # download aggregated resources # content negotiation for prefered ReM format def usage(): print """Usage: %s [-r] [-d DEPTH] [-f R...
Python
import os import urllib, urllib2 from rdflib import ConjunctiveGraph, URIRef, BNode, Literal from utils import * from StringIO import StringIO from utils import unconnectedAction from foresite import libraryName, libraryUri, libraryEmail from foresite import conneg # --- Object Class Definitions --- class Graph(Conj...
Python
import doctest import unittest import glob import os optionflags = (doctest.REPORT_ONLY_FIRST_FAILURE | doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS) def open_file(filename, mode='r'): """Helper function to open files from within the tests package.""" return open(os.path.join...
Python
import re from ore import * from ore import foresiteAgent from foresite import libraryName, libraryUri, libraryVersion from utils import namespaces, OreException, unconnectedAction, pageSize from utils import gen_uuid, build_html_atom_content from rdflib import URIRef, BNode, Literal, plugin, RDF #syntax, RDF from rdf...
Python
try: import json except ImportError: import simplejson as json from rdflib.parser import Parser from rdflib import URIRef, BNode, Literal class JsonParser(Parser): def __init__(self): pass def parse(self, source, sink, **args): data = source.getByteStream().read() objs ...
Python
def skipws(next): skip = 1 if not skip: return next else: def foo(*args): tok = next(*args) if tok.isspace(): tok = next(*args) return tok return foo class ParseError(Exception): pass class MiniLex(object): def __init__(...
Python
import urllib import time import re from rdflib import Namespace ### Configuration Options ### Assign a UUID URI or Blank Node for autogenerating agent URIs ### if not present in data assignAgentUri = False #assignAgentUri = True ### Use UUID or oreproxy.org for autogenerating proxy URIs if ### not present in data p...
Python
# Dependencies: rdflib # lxml libraryName= "Foresite Toolkit (Python)" libraryUri = "http://foresite-toolkit.googlecode.com/#pythonAgent" libraryVersion = "1.1" libraryEmail = "foresite@googlegroups.com" __all__ = ['ore', 'utils','parser', 'serializer', 'tripleStore', 'Aggregation', 'ResourceMap', 'A...
Python
from __future__ import generators from rdflib.serializer import Serializer from rdflib.term import URIRef from rdflib.term import Literal from rdflib.term import BNode from rdflib.util import uniq from rdflib.exceptions import Error #from rdflib.syntax.xml_names import split_uri from xml.sax.saxutils import quoteat...
Python
from __future__ import generators from rdflib.serializer import Serializer from rdflib import URIRef from rdflib import Literal from rdflib import BNode from rdflib.util import uniq from rdflib.exceptions import Error from rdflib.namespace import split_uri from xml.sax.saxutils import quoteattr, escape try: im...
Python
from ore import * from utils import namespaces, OreException, unconnectedAction, protocolUriRe from lxml import etree from xml.dom import minidom from rdflib.parser import StringInputSource from rdflib import URIRef, plugin, query #, syntax from rdflib.parser import Parser plugin.register('sparql', query.Processor, ...
Python
from ore import * from utils import namespaces from rdflib import URIRef, plugin, store # Store raw triples into a TripleStore somewhere class TripleStore(object): def __init__(self, configuration, db, create): self.configuration = configuration self.create = create self.db = db ...
Python
# # Simple Mod_Python handler for validating and transforming # ORE Resource Maps # # apache config: # <Directory /home/cheshire/install/htdocs/txr> # SetHandler mod_python # PythonDebug On # PythonPath "['/path/to/validateHandler.py/']+sys.path" # PythonHandler validateHandler # </Directory> impor...
Python
# -*- coding: utf-8 -*- import urllib2 import re from foreignsites.parse.parsehtml import parsehtml, HtmlTag from foreignsites.browser import Browser, BrowserError SITE = 'ru.wikipedia.org' #SITE = 'test.tfolder.ru' WIKI_PAGES = '/wiki/' RESULT_DIR = 'ru_wikipedia/' def main(): page = 'А._А._Зализняк' ...
Python
import re SITE_URL = 'http://pass.rzd.ru' START_PATH = '/wps/portal/pass/express?STRUCTURE_ID=735' TICKETS_PAGE_URL_REGEX = re.compile('<a href=[\'"]([^\'"]*)[\'"]>Наличие билетов от станции до станции</a>') class Agent(type): def __init__(self, session_id): self._session_id = session_id ...
Python
from loggers import * from random import randint from datetime import datetime lj_host = 'www.livejournal.com' PORT = 80 TIMEOUT_SECONDS = 20 MAX_ATTEMPTS = 5 class LjClient(type): def __init__(self, user, password, logger_class=None): self.user, self.password, self.debug_mode = user, password...
Python
class FakeLogger(object): def request(self, str): pass def response(self, str): pass def ScreenLogger(FakeLogger): def request(self, str): print ' --> %s' % str def response(self, str): print ' <-- %s' % str
Python
# -*- coding: utf-8 -*- import re from helpers import EntityProcessor, OpenedTagsStat process_entities = EntityProcessor({ 'amp': '&', 'mdash': u'—', 'ndash': u'–', 'minus': u'−', 'hellip': u'…', 'copy': u'©', 'trade': u'™', }) class HtmlElem(object): """ ...
Python
import re class EntityProcessor(object): """ # Replace all &...; enities. # &#number; replace automatically, for replacing &keyword; # need dictionary at constructor. >>> replacer = EntityProcessor({'amp': '&', 'apos': '`'}) >>> print replacer('A&amp;B') A&B """ _entity_re = re....
Python
import unittest from parse.htmlchunks import htmlchunks, parsehtml, HtmlTag, HtmlText, HtmlComment #class TestSkiptagcontent(unittest.TestCase): # def test001(self): # html = """<style>h1 {color: green}</style> <h1>HELLO!</h1>""" # chunks = tuple(skiptagcontent(['style'], htmlchunks(html))) #...
Python
import urllib2 class BrowserError(Exception): pass class Browser(object): """ Create 'browser' """ def __init__(self, user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3', proxy = None ): handlers = [] if proxy...
Python
#!/usr/bin/python import os from dcinstall import setup_py, debian, AbstractPackageInfo from dcinstall.version import get_revisions, get_changelog_core, save_last_revision class build(AbstractPackageInfo.build): sources_dir = os.path.realpath(os.path.dirname(__file__)) build_dir = sources_dir result_dir = ...
Python
BYR = 974 USD = 840 EUR = 978 UAH = 980 GBP = 826 CHF = 756 JPY = 392 RUR = 810 # before denomination RUB = 643 # after denomination. 1 RUB = 1000 * RUR _strcodes = dict((v, k) for k, v in locals().items() if len(k) == 3) def currency2str(intcode): try: return _strcodes[intcode] except KeyErro...
Python
# -*- coding: utf-8 -*- import datetime import os import re import sys import urllib2 from codes import * from errors import CurrencyConvertError from db import CurrenciesDb import banks import conf def equals(a, b): "Compare two float or ints by 2 digits" return round(a - b, 2) == 0 cdb = None def convert(v...
Python
import datetime import unittest from core import convert, equals, CurrencyConvertError from codes import * class TestConvert(unittest.TestCase): def testEquals(self): self.assertTrue(equals(1.00, 1)) self.assertTrue(equals(1.001, 1)) self.assertTrue(equals(0.331, 0.33)) self.assertT...
Python
CBR_RU = 1 def loader(bank): if bank == CBR_RU: from loaders import CbrRateLoader return CbrRateLoader()
Python
import datetime try: import pysqlite2.dbapi2 as sqlite3 except ImportError: import sqlite3 import banks class DbError(Exception): pass class CurrenciesDb(object): def __init__(self, db_name): try: self.conn = sqlite3.connect(db_name) except sqlite3.OperationalError: ...
Python
# -*- coding: utf-8 -*- from codes import * _ru = { BYR: (u'белорусский рубль', u'белорусских рубля', u'белорусских рублей'), USD: (u'доллар США', u'доллара США', u'долларов США'), EUR: (u'евро', u'евро', u'евро'), UAH: (u'украинская гривна', u'украинских гривны', u'украинских гривен'), GBR: (u'фу...
Python
import re import urllib2 from codes import * import conf class CbrRateLoader(object): #<tr bgcolor="#ffffff"><td align="right" >36</td> #<td align="left" >&nbsp;&nbsp;AUD<td align="right" >1</td> #<td>&nbsp;&nbsp;Австралийский доллар</td> #<td align="right">14,8100</td></tr> _re_currency = re.comp...
Python
class CurrencyConvertError(Exception): pass
Python
FIRST_DENOMINATION_YEAR = 1998
Python