示例#1
0
    def __init__(self):
        """Конструктор класса"""

        self.cities = Cities()
        logging.basicConfig(
            format='%(asctime)s | %(levelname)-8s | %(message)s',
            level=logging.INFO)
示例#2
0
文件: bot.py 项目: mrbinwin/vk-bot
 def __init__(self, **kwargs):
     self.admin_vk_id = kwargs['admin_vk_id']
     self.antigate_key = kwargs['antigate_key']
     self.rucaptcha_key = kwargs['rucaptcha_key']
     self.vk_username = kwargs['username']
     self.vk_password = kwargs['password']
     self.vk_my_group = kwargs['vk_my_group']
     self._cities = Cities()
     if 'logger' in kwargs:
         self._logger = kwargs['logger']
示例#3
0
 def get(self):
     user = users.get_current_user()
     p_obj = permissions.Permissions()
     userTypes = p_obj.getPermissions(user.email())
     if userTypes[1] == 1:
         self.redirect('/owner-home')
         return
     template = jinja_environment.get_template('register_owner.html')
     cities_obj = Cities()
     my_cities = cities_obj.getCitiesFromDb()
     parameters_for_template = {'user': user, 'cities': my_cities}
     self.response.write(template.render(parameters_for_template))
示例#4
0
def main():
    n = 4
    hyperparameter = 0.1
    c = Cities(n)
    h = Hopfield(c.c, hyperparameter)
    #h.go_to_minimum()
    #h.plot_energy()
    h.show_shortest_route()
示例#5
0
 def get(self):
     user = users.get_current_user()
     p_obj = permissions.Permissions()
     userTypes = p_obj.getPermissions(user.email())
     if userTypes[0] != 1:  #UPDATE TO CHECK IN DB
         parameters_for_template = {
             'message':
             'You don\'t have permissions to this page. Please try again later'
         }
         template = jinja_environment.get_template('error_page.html')
         self.response.write(template.render(parameters_for_template))
     else:
         cities_obj = Cities()
         my_owner_finder = owner_finder.OwnerFinder()
         my_cities = cities_obj.getCitiesFromDb()
         owners = my_owner_finder.getAllOwners('', 0, 0, user.email(), True)
         parameters_for_template = {
             'user': user,
             'cities': my_cities,
             'owners': owners
         }
         template = jinja_environment.get_template('filter_owners.html')
         self.response.write(template.render(parameters_for_template))
示例#6
0
    def get(self):
        user = users.get_current_user()
        p_obj = permissions.Permissions()
        userTypes = p_obj.getPermissions(user.email())
        if userTypes[0] != 1:
            parameters_for_template = {
                'message':
                'You don\'t have permissions to this page. Please try again later'
            }
            template = jinja_environment.get_template('error_page.html')
            self.response.write(template.render(parameters_for_template))
        else:
            city = self.request.get('city')
            minAge = self.request.get('minAge')
            maxAge = self.request.get('maxAge')
            viewAll = True if self.request.get('all') == 'on' else False
            logging.error(viewAll)
            my_owner_finder = owner_finder.OwnerFinder()
            if viewAll:
                owners = my_owner_finder.getAllOwners('', 0, 0, user.email(),
                                                      viewAll)
            else:
                owners = my_owner_finder.getAllOwners(city, minAge, maxAge,
                                                      user.email(), viewAll)

        logging.error(owners)
        cities_obj = Cities()
        my_cities = cities_obj.getCitiesFromDb()
        my_cities.insert(0, 'All Cities')
        parameters_for_template = {
            'cities': my_cities,
            'user': user,
            'owners': owners
        }
        template = jinja_environment.get_template('filter_owners.html')
        self.response.write(template.render(parameters_for_template))
示例#7
0
def main():
    uf_name = input("Digite o estado: ")
    population = input("Digite o limite de população: ")

    cities = Cities(uf_name, population)
    points = cities.list

    if (len(points) > 1):
        d, closest_points = get_closest_points(points)

        print("\nAs cidades mais próximas são: " + closest_points[0].name +
              " e " + closest_points[1].name)

        draw(points, closest_points)
    else:
        print("\nNão há cidades que se encaixam nas especificações!")
示例#8
0
from cities import Cities
ciudades = Cities()

menu = '''\n****************************
*       MENU PAISES        *
****************************
*                          *
*  i) Insertar País        *
*  e) Eliminar País        *
*  m) Modificar País       *
*  p) Imprimir Paises      *
*  x) Salir                *
*                          *
****************************'''


def main():
    opcion = 0
    while opcion != 'X':
        print(menu)
        opcion = input("Que deseas hacer?").upper()

        if opcion == 'I':
            print("******* Insertar Paises******")
            ISO3 = input("Introduce la clave ISO3 del nuevo País:  ")
            CountryName = input("Introduce el nombre del nuevo País:  ")
            Capital = input("Introduce la capital  del nuevo País:  ")
            CurrencyCode = input("Introduce el código de su moneda:  ")
            r = ciudades.inserta_ciudad(ISO3, CountryName, Capital,
                                        CurrencyCode)
            if (r == 0):
示例#9
0
def index():
    from regnews import Regnews
    from mailboxing import Mailboxing
    from cities import Cities
    from province import Province
    from queuemail import Queuemail
    Province(db)
    Cities(db)
    Regnews(db)
    Mailboxing(db)
    Queuemail(db)

    wpoblacion = SQLFORM.widgets.autocomplete(request,
                                              db.cities.poblacion,
                                              limitby=(0, 10),
                                              min_length=2)
    wprovincia = SQLFORM.widgets.autocomplete(request,
                                              db.province.provincia,
                                              limitby=(0, 10),
                                              min_length=2)

    name = Field('name',
                 'string',
                 label="Nombre",
                 length=50,
                 requires=IS_NOT_EMPTY(
                     error_message="Debe identificarse con un nombre"),
                 widget=lambda field, value: SQLFORM.widgets.string.widget(
                     field, value, _placeholder='Nombre y apellidos'))
    email = Field('email',
                  'string',
                  length=128,
                  requires=[
                      IS_NOT_EMPTY(error_message="Un email es requerido"),
                      IS_EMAIL(error_message="email incorrecto")
                  ],
                  widget=lambda field, value: SQLFORM.widgets.string.widget(
                      field, value, _placeholder='ejemplo: [email protected]'))
    phone = Field('phone', 'string', length=18, notnull=False)
    poblacion = Field('city',
                      'string',
                      length=40,
                      notnull=False,
                      widget=wpoblacion)
    provincia = Field('province',
                      'string',
                      length=40,
                      notnull=False,
                      widget=wprovincia)
    rnews = Field('rnews', 'boolean', default=True)
    message = Field(
        'message',
        'text',
        notnull=True,
        requires=IS_NOT_EMPTY(
            error_message=
            "Por favor, díganos por qué quiere contactar con nosotros."))
    form = SQLFORM.factory(name,
                           rnews,
                           email,
                           phone,
                           poblacion,
                           provincia,
                           message,
                           submit_button='contactar',
                           formstyle='bootstrap')

    queuedata = []
    if form.validate(keepvalues=False):
        data = form.vars
        try:

            reg = db(db.regnews.email == data.email).select()
            if len(reg) == 0:
                id = db.regnews.insert(email=data.email,
                                       name=data.name,
                                       news=data.rnews,
                                       phone=data.phone,
                                       city=data.city,
                                       province=data.province)
                db.mailbox.insert(regnews=id, message=data.message)
            else:
                db.mailbox.insert(regnews=reg[0].id, message=data.message)
            db.commit()
        except:
            db.rollback()
            response.flash = 'Su petición de contacto no pudo registrarse. Inténtelo de nuevo.'
        #primero encolamos el mail al usuario que ha hecho la petición de contacto
        queuedata.append({
            'to':
            '%s' % data.email,
            'subject':
            'Confirmación de petición de contacto',
            'message':
            'Estimado %s,\n hemos recibido una petición de contacto por parte suya desde el formulario de contacto de Despacho Cifrado.\n\n Muchas gracias por su interés. Le responderemos en breve.\n\n Reciba un cordial saludo.\n--\nDespacho Cifrado'
            % data.name
        })
        #y ahora notificación a cada uno de los administradores
        mails = db(db.auth_membership.group_id == 1).select(
            db.auth_membership.ALL,
            db.auth_user.ALL,
            left=db.auth_user.on(
                db.auth_membership.user_id == db.auth_user.id))
        for m in mails:
            queuedata.append({
                'to':
                '%s' % m.auth_user.email,
                'subject':
                'Tienes una solicitud de contacto',
                'message':
                '%s con mail: %s y teléfono: %s  te ha enviado el siguiente mensaje: \n %s '
                % (data.name, data.email, data.phone, data.message)
            })
        try:
            logger.debug(queuedata)
            queue.queuemessage(queuedata)
        except Exception, ex:
            logger.debug("error al almacenar la cola de mensajes %s" % ex)
            pass
        session.flash = 'Su petición ha sido registrada'
        redirect(URL(request.application, 'default', 'index'))
from cities import Cities
from population import Population
from distance import DistanceResolver
import matplotlib.pyplot as plt
import matplotlib

cities_location = Cities()
population = Population(cities_location)

for _ in range(10000):
    population.next_generation()    

# resultado final
final_population = population.get_population()
best_solution = final_population[0]
best_chromosome = best_solution[0]
best_distance = best_solution[1]

print("Tamanho da população: {}".format(len(final_population)))
print("Taxa de mutação: 5%")
print("Número de cidades: {}".format(cities_location.get_cities_count()))
print("Melhor solução: {}".format(best_distance))

plt.plot(cities_location.get_cities()[0], cities_location.get_cities()[1], 'ro')

best_chromosome_cities = best_chromosome.get_cities()
best_path_x = []
best_path_y = []
for i in range(len(best_chromosome_cities)):
    city = cities_location.get_city(best_chromosome_cities[i])
    best_path_x.append(city.x)
示例#11
0
def fiscal():
    from invoices import Fiscal
    from cities import Cities
    from province import Province
    Fiscal(db), Province(db), Cities(db)

    fiscal = db(db.fiscals.user == auth.user_id).select().first()
    logger.debug(fiscal)
    wpoblacion = SQLFORM.widgets.autocomplete(request,
                                              db.cities.poblacion,
                                              limitby=(0, 10),
                                              min_length=2)
    wprovincia = SQLFORM.widgets.autocomplete(request,
                                              db.province.provincia,
                                              limitby=(0, 10),
                                              min_length=2)
    if request.vars.wizard:
        wizard = request.vars.wizard
    else:
        wizard = False
    if fiscal:
        tax_identification = Field(
            'tax_identification',
            'string',
            label=XML(
                "<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"
            ),
            default=fiscal.tax_identification,
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
        fiscalname = Field('fiscalname',
                           'string',
                           label=XML("<strong>Nombre empresa</strong>"),
                           default=fiscal.fiscalname,
                           length=128,
                           notnull=False)
        address = Field(
            'address',
            'string',
            label=XML("<strong>Dirección</strong>"),
            default=fiscal.address,
            length=250,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        city = Field(
            'city',
            'string',
            label=XML("<strong>Ciudad/Población</strong>"),
            default=fiscal.city,
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"),
            widget=wpoblacion)
        province = Field('province',
                         'string',
                         label=XML("<strong>Provincia</strong>"),
                         default=fiscal.province,
                         notnull=False,
                         widget=wprovincia)
        country = Field(
            'country',
            'string',
            label=XML("<strong>Pais</strong>"),
            length=45,
            default=fiscal.country,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        postalcode = Field(
            'postal_code',
            'string',
            label=XML("<strong>Código postal</strong>"),
            default=fiscal.postal_code,
            length=10,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        phone = Field('phone',
                      'string',
                      label=XML("<strong>Teléfono de contacto</strong>"),
                      length=20,
                      default=fiscal.phone,
                      notnull=False)
    else:
        tax_identification = Field(
            'tax_identification',
            'string',
            label=XML(
                "<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"
            ),
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
        fiscalname = Field('fiscalname',
                           'string',
                           label=XML("<strong>Nombre empresa</strong>"),
                           length=128,
                           notnull=False)
        address = Field(
            'address',
            'string',
            label=XML("<strong>Dirección</strong>"),
            length=196,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        city = Field(
            'city',
            'string',
            label=XML("<strong>Ciudad/Población</strong>"),
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"),
            widget=wpoblacion)
        province = Field('province',
                         'string',
                         label=XML("<strong>Provincia</strong>"),
                         length=45,
                         notnull=False,
                         widget=wprovincia)
        country = Field(
            'country',
            'string',
            label=XML("<strong>Pais</strong>"),
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        postalcode = Field(
            'postal_code',
            'string',
            label=XML("<strong>Código postal</strong>"),
            length=10,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        phone = Field('phone',
                      'string',
                      label=XML("<strong>Teléfono de contacto</strong>"),
                      length=20,
                      notnull=False)

    form = SQLFORM.factory(tax_identification,
                           fiscalname,
                           address,
                           city,
                           province,
                           country,
                           postalcode,
                           phone,
                           submit_button=('enviar datos',
                                          'siguiente')[wizard == True],
                           formstyle='bootstrap3_inline')

    if form.validate(keepvalues=True):
        if fiscal:  #update
            db(db.fiscals.id == fiscal.id).update(
                tax_identification=form.vars.tax_identification,
                fiscalname=form.vars.fiscalname,
                address=form.vars.address,
                city=form.vars.city,
                province=form.vars.province,
                country=form.vars.country,
                postal_code=form.vars.postal_code,
                phone=form.vars.phone)
        else:  #insert
            db.fiscals.insert(user=auth.user_id,
                              tax_identification=form.vars.tax_identification,
                              fiscalname=form.vars.fiscalname,
                              address=form.vars.address,
                              city=form.vars.city,
                              province=form.vars.province,
                              country=form.vars.country,
                              postal_code=form.vars.postal_code,
                              phone=form.vars.phone)
        session.flash = "Datos enviados correctamente"
        if wizard:
            redirect(URL(request.application, 'payment', 'index'))
        else:
            redirect(URL('account'))

    elif form.errors:
        response.flash = 'Hay errores'

    form.element('input[name=city]')['_class'] = 'form-control'
    form.element('input[name=province]')['_class'] = 'form-control'
    form.element('div#no_table_tax_identification__row div.col-sm-9'
                 )['_class'] = 'col-sm-3'
    form.element(
        'div#no_table_fiscalname__row div.col-sm-9')['_class'] = 'col-sm-4'
    form.element('div#no_table_city__row div.col-sm-9')['_class'] = 'col-sm-4'
    form.element(
        'div#no_table_province__row div.col-sm-9')['_class'] = 'col-sm-3'
    form.element(
        'div#no_table_country__row div.col-sm-9')['_class'] = 'col-sm-2'
    form.element(
        'div#no_table_postal_code__row div.col-sm-9')['_class'] = 'col-sm-2'
    form.element('div#no_table_phone__row div.col-sm-9')['_class'] = 'col-sm-4'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'

    return dict(form=form)
示例#12
0
# -*- coding: latin1 -*-
'''
Created on May 28, 2018

@author: Jesús Molina
'''

import time

from cities import Cities
from convoy_control import ConvoyControl

if __name__ == '__main__':

    game_time = 12
    main_city = Cities("Nuka Town", 20, 20, 20,
                       100)  #wood, oil, water, discontent.
    my_convoy_control = ConvoyControl()
    my_convoy_control.create_convoy("Slipknot", 100,
                                    10)  #name, health, number of escorts.
    my_convoy_control.create_convoy("Slayer", 100, 5)
    my_convoy_control.set_convoy_times("Slipknot", 13, 12)

    while True:

        print "\n"
        print "Time: " + str(game_time) + ":00"
        print "\n"

        my_convoy_control.time_control(game_time)

        print main_city
示例#13
0
def myaccount():
    from invoices import Fiscal
    from cities import Cities
    from province import Province
    Fiscal(db), Province(db), Cities(db),

    customer = db(db.auth_user.id == auth.user_id).select(
        db.auth_user.id,
        db.auth_user.first_name,
        db.auth_user.last_name,
        db.auth_user.email,
        db.fiscals.ALL,
        left=[db.fiscals.on(db.fiscals.user == db.auth_user.id)]).first()

    wpoblacion = SQLFORM.widgets.autocomplete(request,
                                              db.cities.poblacion,
                                              limitby=(0, 10),
                                              min_length=2)
    wprovincia = SQLFORM.widgets.autocomplete(request,
                                              db.province.provincia,
                                              limitby=(0, 10),
                                              min_length=2)

    if customer != None:

        first_name = Field(
            'first_name',
            'string',
            label=XML("<strong>Nombre</strong>"),
            length=128,
            notnull=True,
            default=customer.auth_user.first_name,
            requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
        last_name = Field(
            'last_name',
            'string',
            label=XML("<strong>Apellidos</strong>"),
            length=128,
            notnull=True,
            default=customer.auth_user.last_name,
            requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
        email = Field('email',
                      label=XML('<strong>Email</strong>'),
                      length=128,
                      writable=False,
                      notnull=True,
                      default=customer.auth_user.email,
                      requires=[
                          IS_NOT_EMPTY(),
                          IS_EMAIL(error_message='No puede estar vacío.')
                      ])
        tax_identification = Field(
            'tax_identification',
            'string',
            label=XML(
                "<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"
            ),
            length=45,
            notnull=True,
            default=customer.fiscals.tax_identification,
            requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
        fiscalname = Field('fiscalname',
                           'string',
                           label=XML("<strong>Nombre empresa</strong>"),
                           length=128,
                           notnull=False,
                           default=customer.fiscals.fiscalname)
        address = Field(
            'address',
            'string',
            label=XML("<strong>Dirección</strong>"),
            length=196,
            notnull=True,
            default=customer.fiscals.address,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        city = Field(
            'city',
            'string',
            label=XML("<strong>Ciudad/Población</strong>"),
            length=45,
            notnull=True,
            default=customer.fiscals.city,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"),
            widget=wpoblacion)
        province = Field(
            'province',
            'string',
            label=XML("<strong>Provincia</strong>"),
            length=45,
            notnull=True,
            default=customer.fiscals.province,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"),
            widget=wprovincia)
        country = Field(
            'country',
            'string',
            label=XML("<strong>Pais</strong>"),
            length=45,
            notnull=True,
            default=customer.fiscals.country,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        postalcode = Field('postal_code',
                           'string',
                           label=XML("<strong>Código postal</strong>"),
                           length=10,
                           notnull=False,
                           default=customer.fiscals.postal_code)
        phone = Field('phone',
                      'string',
                      label=XML("<strong>Teléfono</strong>"),
                      length=20,
                      notnull=False,
                      default=customer.fiscals.phone)

        form = SQLFORM.factory(first_name,
                               last_name,
                               email,
                               tax_identification,
                               fiscalname,
                               address,
                               city,
                               province,
                               country,
                               postalcode,
                               phone,
                               submit_button='modificar datos',
                               formstyle='bootstrap3_inline')

        if form.validate(keepvalues=True):

            try:
                db(db.auth_user.id == customer.auth_user.id).update(
                    first_name=form.vars.first_name,
                    last_name=form.vars.last_name)
                db(db.fiscals.id == customer.fiscals.id).update(
                    tax_identification=form.vars.tax_identification,
                    fiscalname=form.vars.fiscalname,
                    address=form.vars.address,
                    city=form.vars.city,
                    province=form.vars.province,
                    country=form.vars.country,
                    postal_code=form.vars.postal_code,
                    phone=form.vars.phone)
                db.commit()
            except Exception, ex:
                logger.debug(
                    "No se pudo modificar los datos del usuario/fiscal: %s" %
                    ex)
                db.rollback()
                response.flash = 'Hubo un error: %s' % ex
            response.flash = "Datos modificados correctamente"
        elif form.errors:
            response.flash = 'Hay errores'
        else:
            response.flash = 'Por favor completa los campos'

        form.element('input[name=city]')['_class'] = 'form-control'
        form.element('input[name=province]')['_class'] = 'form-control'

        form.element('input[name=city]')['_class'] = 'form-control'
        form.element('input[name=province]')['_class'] = 'form-control'
        form.element(
            'div#no_table_first_name__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element(
            'div#no_table_last_name__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element('div#no_table_tax_identification__row div.col-sm-9'
                     )['_class'] = 'col-sm-3'
        form.element(
            'div#no_table_fiscalname__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element(
            'div#no_table_city__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element(
            'div#no_table_province__row div.col-sm-9')['_class'] = 'col-sm-3'
        form.element(
            'div#no_table_country__row div.col-sm-9')['_class'] = 'col-sm-2'
        form.element('div#no_table_postal_code__row div.col-sm-9'
                     )['_class'] = 'col-sm-2'
        form.element(
            'div#no_table_phone__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element('label#no_table_first_name__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_last_name__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element(
            'label#no_table_email__label')['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_fiscalname__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_tax_identification__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_address__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element(
            'label#no_table_city__label')['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_province__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_country__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_postal_code__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element(
            'label#no_table_phone__label')['_class'] = 'col-sm-2 control-label'
        form.element('div#submit_record__row div.col-sm-9'
                     )['_class'] = 'col-sm-9 col-sm-offset-2'
        return dict(form=form, userid=customer.auth_user.id)
示例#14
0
import os
import socket
import datetime
import copy
import gluon.contenttype
import gluon.fileutils

from blog import Blog, Draft, Images
from shops import Shop, DomainShop, PricePlan, Product, ContractedProduct, ProfilePlan, PricePlan, CustomerAgreement, Agreement
from invoices import Invoice, Order, Orderlist, Fiscal, CreditAccount, AccountingEntry, Budget, Budgetlist
from regnews import Regnews
from province import Province
from cities import Cities
Images(db), Blog(db, ckeditor), Draft(
    db, ckeditor), Regnews(db), Province(db), Cities(db)
Shop(db), PricePlan(db), DomainShop(db), Product(db)
ProfilePlan(db), PricePlan(db), CustomerAgreement(db), Agreement(db)
Invoice(db), Order(db), Orderlist(db), Budget(db), Budgetlist(db), Fiscal(
    db), ContractedProduct(db), CreditAccount(db), AccountingEntry(db)

try:
    import pygraphviz as pgv
except ImportError:
    pgv = None

# ## critical --- make a copy of the environment

global_env = copy.copy(globals())
global_env['datetime'] = datetime
示例#15
0
def newcustomer():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):

		from invoices import Fiscal
		from cities import Cities
		from province import Province
		Fiscal(db),	Province(db), Cities(db)

		wpoblacion = SQLFORM.widgets.autocomplete(request, db.cities.poblacion, limitby=(0,10), min_length=2)
		wprovincia = SQLFORM.widgets.autocomplete(request, db.province.provincia, limitby=(0,10), min_length=2)
		first_name = Field('first_name', 'string', label=XML("<strong>Nombre</strong>"), length=128, notnull=True, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
		last_name = Field('last_name', 'string', label=XML("<strong>Apellidos</strong>"), length=128, notnull=True, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
		password = Field('password', label = XML("<strong>Contraseña</strong>"), requires=[IS_NOT_EMPTY(error_message="No olvide esta dato")])
		email = Field('email',  label=XML('<strong>Email</strong>'), length=128,  notnull=True, requires=[IS_NOT_EMPTY(), IS_EMAIL(error_message='No puede estar vacío.'), IS_NOT_IN_DB(db,'auth_user.email')])
		tax_identification = Field('tax_identification', 'string', label=XML("<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"),length=45, notnull=False)
		fiscalname = Field('fiscalname', 'string', label=XML("<strong>Nombre empresa</strong>") ,length =128, notnull=False)
		address = Field('address', 'string', label=XML("<strong>Dirección</strong>"), length =196, notnull=False)
		city = Field('city', 'string',   label=XML("<strong>Ciudad/Población</strong>"), length=45, notnull=False, widget=wpoblacion)
		province = Field('province', 'string',   label=XML("<strong>Provincia</strong>"), length=45, notnull=False, widget=wprovincia)
		country = Field('country', 'string', label=XML("<strong>Pais</strong>"), length =45, notnull=False)
		postalcode = Field('postal_code', 'string', label=XML("<strong>Código postal</strong>"), length=10, notnull=False)
		phone = Field('phone', 'string', label=XML("<strong>Teléfono</strong>"), length=20, notnull=False)

		form = SQLFORM.factory(first_name, last_name, password, email, tax_identification, fiscalname, address, city, province, country, postalcode, phone, submit_button = 'enviar datos', formstyle='bootstrap3_inline')



		if form.validate(keepvalues=True):

			try:
				userid=db.auth_user.insert(first_name=form.vars.first_name,
									last_name=form.vars.last_name,
									password=CRYPT(key=Auth.get_or_create_key(), digest_alg='pbkdf2(1000,20,sha512)', salt=True)(form.vars.password)[0],
									email=form.vars.email)
				if userid:
					db.fiscals.insert(	user=userid, 
										tax_identification=form.vars.tax_identification, 
										fiscalname=form.vars.fiscalname,
										address=form.vars.address, 
										city=form.vars.city,
										province=form.vars.province,
										country=form.vars.country, 
										postal_code=form.vars.postal_code,
										phone=form.vars.phone)
					auth.add_membership(db(db.auth_group.role=="clientes").select().first()["id"], userid)
					db.commit()
				else:
					response.flash="no se ha creado al usario"

			except Exception, ex:
				logger.debug("No se pudo crear al nuevo cliente: %s" % ex)
				db.rollback()
				response.flash = 'Hubo un error: %s' % ex
			redirect(URL('administrator','editcustomer', args=userid))
		elif form.errors:
			response.flash = 'Hay errores'
		else:
			response.flash = 'Por favor completa los campos'
		
		form.element('input[name=city]')['_class']='form-control'
		form.element('input[name=province]')['_class']='form-control'
		
		return dict(form=form)
示例#16
0
from cities import Cities

city = Cities()

#city.elimina_ciudad(8)

#city.inserta_ciudad('HHH', 'CytiName', 'capitale', 'MMN')

#city.modifica_ciudad(7, 'IN', 'Pais India', 'Capital de India', 'DDG')

print(city)
示例#17
0
文件: paths.py 项目: sw561/map_path
#!/usr/bin/env python

from cities import Cities, Equirectangular, Lambert, Mollweide, distance

# Example of using the cities module without plotting (much faster)
# Distance are by default in km unless use_miles is set to True
m = Cities(plot=False, use_miles=1)
print m.distance("London", "Los Angeles")
print m.distance("London", "Beijing")

# Use of miles / km can be switched after initialisation
# m.use_miles = True
# m.use_miles = False

# Cities instances initialised like this can't be used to plot
try:
    m.plot_path("London", "Beijing")
except TypeError as e:
    print e
else:
    print "Didn't catch exception here"

# Exceptions due to cities not being in the database can be caught
from cities import DatabaseKeyError
try:
    print m.distance("London", "Fake")
except DatabaseKeyError as e:
    print e
else:
    print "Didn't catch exception here"
示例#18
0
class Bot:
    """LPVSBot"""
    def __init__(self):
        """Конструктор класса"""

        self.cities = Cities()
        logging.basicConfig(
            format='%(asctime)s | %(levelname)-8s | %(message)s',
            level=logging.INFO)

    def start_bot(self):
        """Запуск бота"""

        my_bot = Updater(API_KEY, use_context=True)

        dp = my_bot.dispatcher
        dp.add_handler(CommandHandler('start', self.greet_user))
        dp.add_handler(CommandHandler('quess', self.quess_number))
        dp.add_handler(CommandHandler('cat', self.send_cat))
        dp.add_handler(CommandHandler('planet', self.check_planet))
        dp.add_handler(CommandHandler('wordcount', self.check_word_count))
        dp.add_handler(CommandHandler('fullmoon', self.check_full_moon))
        dp.add_handler(CommandHandler('cities', self.check_city))
        dp.add_handler(CommandHandler('calc', self.calc_numbers))
        dp.add_handler(
            MessageHandler(Filters.regex('^(Команда /cat)$'), self.send_cat))
        dp.add_handler(MessageHandler(Filters.location, self.get_coordanites))

        logging.info('Запуск бота.')

        my_bot.start_polling()
        my_bot.idle()

    def keyboard(self):
        """Клавиатура"""

        return ReplyKeyboardMarkup([[
            'Команда /cat',
            KeyboardButton('Отправить координаты', request_location=True)
        ]])

    def greet_user(self, update, context):
        """Приветствие пользователя"""

        first_name = update.message.chat.first_name
        last_name = update.message.chat.last_name
        context.user_data['emoji'] = get_emoji(context.user_data)

        update.message.reply_text(
            f'Привет {first_name} {last_name}! {context.user_data["emoji"]}\n'
            'Поддерживаемые команды:\n'
            '1. /quess [целое число] - придумай и напиши целое число, если оно будет больше моего - ты выиграл!\n'
            '2. /cat - любишь собак? Тогда тебе не повезло! Эта команда покажет тебе котиков!\n'
            '3. /planet [название планеты] - напиши название планеты и узнай в каком созвездии она сейчас находится:\n'
            '- Mercury\n- Venus\n- Mars\n- Jupiter\n- Saturn\n- Uranus\n- Neptune\n'
            '4. /wordcount [текст] - напиши мне что-нибудь, а я подсчитаю сколько в этом слов!\n'
            '5. /fullmoon [ГГГГ-ММ-ДД] - укажи дату и узнай когда будет следующее полнолуние!\n'
            '6. /cities [название города] - уже прошёл GTA 5 и Call of duty: Black ops 4? Тогда попробуй сыграть в '
            'Города!\n'
            '7. /calc [a+b-c*d/e] - выполняй арифметические операции с несколькими числами!',
            reply_markup=self.keyboard())

    def get_coordanites(self, update, context):
        """Получение координат"""

        coords = update.message.location
        message = f'Твои координаты: долгота {coords["longitude"]} и широта {coords["latitude"]}.'
        update.message.reply_text(message)

    def quess_number(self, update, context):
        """Угадывание числа"""

        if context.args:
            try:
                user_number = context.args[0]
                message = get_random_numbers(user_number)
            except (TypeError, ValueError):
                message = 'Введите целое число!'
        else:
            message = 'Введите число!'

        update.message.reply_text(message)

    def send_cat(self, update, context):
        """Отправка картинки с котиками"""

        photo_list = glob('images/cat*.jpg')
        photo_name = choice(photo_list)
        chat_id = update.effective_chat.id
        context.bot.send_photo(chat_id=chat_id, photo=open(photo_name, 'rb'))

    def check_planet(self, update, context):
        """Проверка планеты"""

        if len(context.args) == 1:
            planet = context.args[0]
            date = time.strftime('%Y/%m/%d')

            data = getattr(ephem, planet, None)

            if data:
                constellation = ephem.constellation(data(date))
                update.message.reply_text(
                    f'Планета {planet} находится в созвездии {constellation[1]}.'
                )
            else:
                update.message.reply_text(f'Нет такой планеты в списке.')

    def check_word_count(self, update, context):
        """Проверка количества слов"""

        if len(context.args) != []:
            update.message.reply_text(
                f'В вашем сообщении {len(context.args)} слов(-а).')
        else:
            update.message.reply_text(f'Введите текст.')

    def check_full_moon(self, update, context):
        """Проверка полнолуния"""

        if len(context.args) == 1:
            date = context.args[0]

            try:
                time.strptime(date, '%Y-%m-%d')
            except ValueError:
                update.message.reply_text(
                    f'Дата не соответствует формату "ГГГГ-ММ-ДД"')
            else:
                moon_date = ephem.next_full_moon(date)
                moon_date = moon_date.datetime().strftime('%H:%M %Y-%m-%d')
                update.message.reply_text(
                    f'Следующее полнолуние будет в {moon_date}.')
        else:
            update.message.reply_text(
                f'Дата не соответствует формату "ГГГГ-ММ-ДД"')

    def check_city(self, update, context):
        """Проверка города"""

        user_city = update.message.text
        user_city = user_city.replace('/cities ', '').strip()

        if user_city != '':
            self.cities.load_cities(context.user_data)
            message = self.cities.check_city(context.user_data, user_city)
            update.message.reply_text(message)

    def calc_numbers(self, update, context):
        """Подсчёт результата арифметических действий"""

        if context.args != []:
            data = ''.join(context.args)

            try:
                result = eval(data)
                update.message.reply_text(result)
            except NameError:
                update.message.reply_text('Одно из чисел указано неккоректно!')
            except SyntaxError:
                update.message.reply_text(
                    'Одно из арифметических действий указано неккоректно!')
            except ZeroDivisionError:
                update.message.reply_text('Деление на ноль недопустимо!')
        else:
            update.message.reply_text(
                'Не соответствует формату! Пример: a+b-c*d/e.')
示例#19
0
def restart():
    global cities
    cities = Cities()
    return "Browser restart"
示例#20
0
def editcustomer():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		if request.args(0):
			from invoices import Fiscal, Order, Orderlist, Invoice, Budget, AccountingEntry, CreditAccount
			from shops import ContractedProduct, Product, Shop
			from cities import Cities
			from province import Province
			Fiscal(db),	Province(db), Cities(db), ContractedProduct(db), Product(db), Shop(db), Order(db), Orderlist(db), AccountingEntry(db), CreditAccount(db),  Invoice(db), Budget(db)
			
			customer=db(db.auth_user.id==request.args(0)).select(	db.auth_user.id,
																	db.auth_user.first_name,
																	db.auth_user.last_name,
																	db.auth_user.email,
																	db.fiscals.ALL,
																	left=[db.fiscals.on(db.fiscals.user==db.auth_user.id)]).first()
			
			wpoblacion = SQLFORM.widgets.autocomplete(request, db.cities.poblacion, limitby=(0,10), min_length=2)
			wprovincia = SQLFORM.widgets.autocomplete(request, db.province.provincia, limitby=(0,10), min_length=2)


			inc=datetime.timedelta(days=30)
			
			contractedproducts = db((db.contractedproducts.user==request.args(0)) & 
									(	(db.contractedproducts.expiration+inc>=datetime.datetime.now()) | 
										(db.contractedproducts.expiration==None)	)).select(	db.contractedproducts.ALL,
																							db.products.ALL,
																							db.shop.ALL,
																							db.auth_user.ALL,
																							db.fiscals.ALL,
																							left=[	db.products.on(db.products.id==db.contractedproducts.product),
																									db.shop.on(db.shop.id==db.contractedproducts.shop),
																									db.auth_user.on(db.auth_user.id==db.contractedproducts.user),
																									db.fiscals.on(db.fiscals.user==db.auth_user.id)],
																							orderby=~db.contractedproducts.expiration)

			invoices = db( db.invoices.user==request.args(0)).select(db.invoices.ALL,
																	db.orders.id,
																	db.orders.status,
																	left=[  db.orders.on(db.orders.invoice==db.invoices.id)],
																	orderby=~db.invoices.id,
																	groupby=db.orders.id
																	)
			

			budgets = db((db.budgets.user==request.args(0)) & (db.budgets.status!="Creando")).select(db.budgets.ALL, orderby=~db.budgets.id)

			orders= db((db.orders.invoice==None) & (db.orders.user==request.args(0))).select(orderby=~db.orders.id)

			if customer!=None:

				first_name= Field('first_name', 'string', label=XML("<strong>Nombre</strong>"), length=128, notnull=True, default=customer.auth_user.first_name, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
				last_name= Field('last_name', 'string', label=XML("<strong>Apellidos</strong>"), length=128, notnull=True, default=customer.auth_user.last_name, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
				email=Field('email',  label=XML('<strong>Email</strong>'), length=128,  writable=False, notnull=True, default=customer.auth_user.email, requires=[IS_NOT_EMPTY(), IS_EMAIL(error_message='No puede estar vacío.')])
				tax_identification = Field('tax_identification', 'string', label=XML("<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"),length=45, notnull=True, default=customer.fiscals.tax_identification, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
				fiscalname=Field('fiscalname', 'string', label=XML("<strong>Nombre empresa</strong>") ,length =128, notnull=False, default=customer.fiscals.fiscalname)
				address=Field('address', 'string', label=XML("<strong>Dirección</strong>"), length =196, notnull=True, default=customer.fiscals.address, requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
				city= Field('city', 'string',   label=XML("<strong>Ciudad/Población</strong>"), length=45, notnull=True, default=customer.fiscals.city, requires=IS_NOT_EMPTY(error_message="no olvide este dato"), widget=wpoblacion)
				province = Field('province', 'string',   label=XML("<strong>Provincia</strong>"), length=45, notnull=True, default=customer.fiscals.province, requires=IS_NOT_EMPTY(error_message="no olvide este dato"), widget=wprovincia)
				country=Field('country', 'string', label=XML("<strong>Pais</strong>"), length =45, notnull=True, default=customer.fiscals.country, requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
				postalcode=Field('postal_code', 'string', label=XML("<strong>Código postal</strong>"), length=10, notnull=False, default=customer.fiscals.postal_code)
				phone=Field('phone', 'string', label=XML("<strong>Teléfono</strong>"), length=20, notnull=False, default=customer.fiscals.phone)

				form = SQLFORM.factory(first_name, last_name, email, tax_identification, fiscalname, address, city, province, country, postalcode, phone, submit_button = 'enviar datos', formstyle='bootstrap3_inline')



				if form.validate(keepvalues=True):

					try:
						db(db.auth_user.id==customer.auth_user.id).update(first_name=form.vars.first_name,
																		  last_name=form.vars.last_name)
						db(db.fiscals.id==customer.fiscals.id).update(tax_identification=form.vars.tax_identification, 
															fiscalname=form.vars.fiscalname,
															address=form.vars.address, 
															city=form.vars.city,
															province=form.vars.province,
															country=form.vars.country, 
															postal_code=form.vars.postal_code,
															phone=form.vars.phone)
						db.commit()
					except Exception, ex:
						logger.debug("No se pudo modificar los datos del usuario/fiscal: %s" % ex)
						db.rollback()
						response.flash = 'Hubo un error: %s' % ex				
					response.flash="Datos enviados correctamente"
				elif form.errors:
					response.flash = 'Hay errores'

				
				form.element('input[name=city]')['_class']='form-control'
				form.element('input[name=province]')['_class']='form-control'


				creditaccount=db(db.creditaccounts.user==customer.auth_user.id).select().first()
				accountingentries=None

				if creditaccount:
					accountingentries = db(	(db.accountingentries.creditaccount==creditaccount.id) &
											(db.accountingentries.active==True) ).select(	db.accountingentries.ALL, 
																							db.orders.ALL,
																							db.invoices.ALL,
																							db.products.name,
																							join=[	db.orderlist.on(db.accountingentries.orderlist==db.orderlist.id),
																									db.products.on(db.products.id==db.orderlist.product),
																									db.orders.on(db.orders.id==db.orderlist.g_order),
																									db.invoices.on(db.invoices.id==db.orders.invoice)],
																							orderby=~db.accountingentries.id)




				return dict(form=form, contractedproducts=contractedproducts, invoices=invoices, budgets=budgets, orders=orders, userid=customer.auth_user.id, accountingentries=accountingentries, creditaccount=creditaccount)

			else:
				redirect(URL('administrator','newcustomer'))
		else:
			redirect(URL('administrator','users'))
示例#21
0
文件: bot.py 项目: mrbinwin/vk-bot
class SkynetBot:

    ACTION_ONLINE = 'online'
    ACTION_ADD_FRIEND = 'add_friend'
    ACTION_CHECK_FRIENDS = 'check_friends'
    ACTION_SEND_STAT = 'send_stat'
    ACTION_VISIT_GROUP = 'visit_group'
    ACTION_REPOST_OUR = 'repost_our'
    ACTION_REPOST_RANDOM = 'repost_random'

    admin_vk_id = None
    antigate_key = None
    rucaptcha_key = None

    vk_id = None
    vk_username = None
    vk_password = None
    vk_my_group = None

    _actions_periods = {
        ACTION_ONLINE: 60 * 7,
        ACTION_ADD_FRIEND: 60 * 45,
        ACTION_CHECK_FRIENDS: 60 * 25,
        ACTION_SEND_STAT: 60 * 60 * 20,
        ACTION_VISIT_GROUP: 60 * 60 * 7,
        ACTION_REPOST_OUR: 60 * 60 * 10,
        ACTION_REPOST_RANDOM: 60 * 60 * 12,
    }

    _reposts_min_periods = {
        'our_post': 60 * 60 * 20,
        'random_post': 60 * 60 * 65
    }

    _actions_timestamps = {
        ACTION_ONLINE: 0,
        ACTION_ADD_FRIEND: 0,
        ACTION_CHECK_FRIENDS: 0,
        ACTION_SEND_STAT: 0,
        ACTION_VISIT_GROUP: 0,
        ACTION_REPOST_OUR: 0,
        ACTION_REPOST_RANDOM: 0,
    }
    _cities = None
    _logger = None
    _session = None

    def __init__(self, **kwargs):
        self.admin_vk_id = kwargs['admin_vk_id']
        self.antigate_key = kwargs['antigate_key']
        self.rucaptcha_key = kwargs['rucaptcha_key']
        self.vk_username = kwargs['username']
        self.vk_password = kwargs['password']
        self.vk_my_group = kwargs['vk_my_group']
        self._cities = Cities()
        if 'logger' in kwargs:
            self._logger = kwargs['logger']

    def add_friend(self):
        """
        Find a friend and send him a request
        :return: bool

        """
        self._log('run add_friend')
        if self._open_main_page():
            friend_id, friend_hash = self._search_friend()
            if not friend_id or not friend_hash:
                self._log('error: not friend_id or not friend_hash')
                return False

            def send_friend_request(fr_id, fr_hash, captcha_res=None):
                params = {
                    'act': 'subscr',
                    'al': 1,
                    'from': 'search',
                    'hash': fr_hash,
                    'oid': fr_id,
                    'ref': 'friends'
                }
                if captcha_res:
                    params['recaptcha'] = captcha_res
                time.sleep(3)
                response = self._post('https://vk.com/al_feed.php', data=params)
                return response

            r = send_friend_request(friend_id, friend_hash)

            if re.match('(.*)Вы подписались', r.text):
                self._save_session()
                self._log('a friend ' + str(friend_id) + ' added successfully')
                return True
            if re.match('(.*)<!>ru', r.text):
                try:
                    captcha_key = re.search('(.+)<!>2<!>(.+)<!>2<!>ru', r.text).group(2)
                except AttributeError:
                    self._log('error: AttributeError captcha_key regex')
                    return False

                captcha_response = self._solve_captcha(captcha_key)
                if not captcha_response:
                    self._log('error: not captcha_response')
                    return False

                r = send_friend_request(friend_id, friend_hash, captcha_response)
                if re.match('(.*)Вы подписались', r.text):
                    self._save_session()
                    self._log('a friend ' + str(friend_id) + ' added successfully')
                    return True
                self._log('error: add_friend regex')
                return False

            self._log('error: send_friend_request regex')
            return False

        self._log('error: add_friend')
        return False

    def check_action_timestamp(self, action_name):
        """
        Check if action_timestamp is older than timeout

        example of usage:
        if bot.check_action_timestamp(bot.ACTION_ADD_FRIEND):
            action = bot.add_friend()

        :param action_name: str
        :return: bool

        """
        now = time.time()
        timeout = self._actions_periods[action_name]
        return now - self._actions_timestamps[action_name] >= timeout

    def check_friends(self):
        """
        Check the income friendship quotes and accept one
        :return: bool

        """
        self._log('run check_friends')
        if self._open_main_page():
            time.sleep(3)
            r = self._get('https://vk.com/friends?section=requests')
            buttons = re.findall(
                '<button([^>]*)accept_request_([0-9]+)([^>]*)Friends.acceptRequest\(([0-9]+), \'([^>]*)\', this\)">Добавить в друзья</button>',
                r.text)
            if not len(buttons):
                self._log('check_friends completed successfully, accepted %d' % 0)
                return True
            html_trash, friend_id, html_trash, html_trash, friend_hash = buttons[0]

            params = {
                'act': 'add',
                'al': 1,
                'hash': friend_hash,
                'mid': int(friend_id),
                'request': 1,
                'select_list': 1
            }

            time.sleep(3)
            r = self._post('https://vk.com/al_friends.php', data=params)

            if re.match('(.*)у Вас в друзьях(.*)', r.text):
                self._save_session()
                self._log('check_friends completed successfully, accepted %d' % 1)
                return True

        self._log('error: check_friends')
        return False

    def get_online(self):
        """
        Open the profile page to refresh online status
        :return: bool

        """
        self._log('run get_online')
        if self._open_main_page():
            time.sleep(3)
            r = self._get('https://vk.com/id'+self.vk_id)
            if r.status_code == 200:
                self._save_session()
                self._log('status online updated sucessfully')
                return True

        self._log('error: get_online')
        return False

    def repost_our_post(self):
        """
        Check if there is a new post in our group post it
        with 1 random post interval and _reposts_min_periods['our_post'] interval
        :return: bool

        """
        self._log('run repost_our_post')
        if not self._open_main_page():
            return False

        time.sleep(3)
        r = self._get('https://vk.com/id' + self.vk_id)
        if r.status_code != 200:
            return False

        last_bot_post_age = self._get_bot_last_post_age(r)
        now = time.time()
        if now - last_bot_post_age < self._reposts_min_periods['our_post']:
            return False

        last_my_group_post = self._get_last_my_group_post()
        already_reposted = self._check_post_already_reposted_by_bot(last_my_group_post)
        if already_reposted:
            return True

        last_bot_post = self._get_last_bot_post()
        if last_bot_post and last_bot_post['copy_author_link'] == '/buzovaofficial':
            self.repost_random_post(self._reposts_min_periods['our_post'])
        else:
            self._repost_post(last_my_group_post)
        return False

    def repost_random_post(self, interval=_reposts_min_periods['random_post']):
        """
        Repost a new post from _groups_list it with interval
        :return: bool

        """
        self._log('run repost_random_post')
        if not self._open_main_page():
            return False

        time.sleep(3)
        r = self._get('https://vk.com/id' + self.vk_id)
        if r.status_code != 200:
            return False

        last_bot_post_age = self._get_bot_last_post_age(r)
        now = time.time()
        if now - last_bot_post_age < interval:
            return False

        best_post = self._find_best_random_post()
        result = self._repost_post(best_post)
        return result

    def get_session(self):
        """
        The current Requests.session() getter
        :rtype: Session

        """
        if self._session is None:
            self._session = self._init_session()
        return self._session

    def send_stat(self):
        """
        Send a message with the current account parameters
        :return: bool

        """
        self._log('run send_stat')
        if self._open_main_page():
            time.sleep(3)
            r = self._get('https://vk.com/id' + self.admin_vk_id)
            if r.status_code == 200:
                try:
                    admin_hash = re.search('\\\\n    hash: \'([^\']+)\',\\\\n', r.text).group(1)
                    stat = self._collect_stat()
                    params = {
                        'act': 'a_send_box',
                        'al': 1,
                        'chas': admin_hash,
                        'entrypoint': 'writebox',
                        'from': 'box',
                        'media': '',
                        'message': 'Привет! ' + '/'.join(stat),
                        'title': '',
                        'to_ids': self.admin_vk_id
                    }
                    r = self._post('https://vk.com/al_im.php', data=params, allow_redirects=True)
                    if r.status_code == 200:
                        self._log('success: send_stat')
                        return True
                    return False
                except AttributeError:
                    self._log('error: send_stat')
                    return False

        self._log('error: send_stat _open_main_page')
        return False

    def update_action_timestamp(self, action_name):
        """
        Update action_timestamp to the current timestamp

        example of usage:
        bot.add_friend()
        bot.update_action_timestamp(bot.ACTION_ADD_FRIEND)

        :param action_name: str
        :return: bool

        """
        self._actions_timestamps[action_name] = time.time()
        return True

    def visit_group(self):
        """
        Just visit a group
        :return: bool

        """
        self._log('run visit_group')
        if self._open_main_page():
            r = self._get(self.vk_my_group)
            if r.status_code == 200:
                self._log('success: visit_group')
                return True
        self._log('error: visit_group')
        return False

    """
    Private functions

    """

    def _collect_stat(self):
        stat = []
        if self._open_main_page():
            time.sleep(3)
            r = self._get('https://vk.com/id'+self.vk_id)
            if r.status_code == 200:
                try:
                    soup = BeautifulSoup(r.text, "html.parser")

                    friends_count = '0'
                    friends_wrapper = soup.select_one('#profile_friends .header_count')
                    if friends_wrapper:
                        friends_count = friends_wrapper.getText()
                    stat.append(friends_count)

                    incoming_requests_count = '0'
                    incoming_wrapper = soup.select_one('#l_fr .left_count')
                    if incoming_wrapper:
                        incoming_requests_count = incoming_wrapper.getText()
                    stat.append(incoming_requests_count)

                    messages_count = '0'
                    messages_wrapper = soup.select_one('#l_msg .left_count')
                    if messages_wrapper:
                        messages_count = messages_wrapper.getText()
                    stat.append(messages_count)
                except:
                    pass

        return stat

    def _change_language(self, response):
        try:
            my_hash = re.search('lang_id: 0, hash: \'([^\']+)\'}', response.text).group(1)
            params = {
                'act': 'change_lang',
                'al': 1,
                'hash': my_hash,
                'lang_id': 0
            }
            r = self._post('https://vk.com/al_index.php', data=params, allow_redirects=True)
            if r.status_code == 200:
                return True
        except:
            pass
        return False

    def _check_post_already_reposted_by_bot(self, post):
        self._log('run _check_post_already_reposted_by_bot')

        try:
            time.sleep(3)
            r = self._get('https://vk.com/id' + self.vk_id)
            soup = BeautifulSoup(r.text, "html.parser")
            my_posts = soup.select('.wall_posts .post.own')
        except Exception as e:
            return False

        group_post_id = post['id'].replace('post', '').replace('-', '')
        for my_post in my_posts:
            my_post = self._parse_wall_post(my_post)
            if my_post['original_id'] is None:
                continue
            my_post_id = my_post['original_id'].replace('post', '').replace('-', '')
            if my_post_id == group_post_id:
                return True

        return False

    def _find_best_random_post(self):
        self._log('run _find_best_random_post')
        all_random_posts = self._get_all_random_posts()
        all_skynet_bots_posts = self._get_all_skynet_bots_posts()

        new_random_posts = []
        for random_post in all_random_posts:
            random_post_id = random_post['id'].replace('post', '').replace('-', '')
            already_reposted = False
            for skynet_bot_post in all_skynet_bots_posts:
                if not skynet_bot_post['original_id']:
                    continue
                bot_post_id = skynet_bot_post['original_id'].replace('post', '').replace('-', '')
                if bot_post_id == random_post_id:
                    already_reposted = True
            if not already_reposted:
                new_random_posts.append(random_post)

        result = sorted(new_random_posts, key=lambda k: k['rating'], reverse=True)
        result = result[:30]
        result = random.choice(result)
        return result

    def _get(self, *args, **kwargs):
        try:
            result = self.get_session().get(*args, **kwargs)
        except BrokenPipeError:
            self._log('BrokenPipeError, reinit session')
            self._init_session()
            result = self.get_session().get(*args, **kwargs)
        return result

    def _get_all_random_posts(self):
        self._log('run _get_all_random_posts')
        all_random_posts = []
        for group in groups:
            try:
                time.sleep(3)
                r = self._get(group)
                soup = BeautifulSoup(r.text, "html.parser")
                posts = soup.select('.post.own')
                for post in posts:
                    if not 'post_copy' in post.get('class') and not post.select_one('.wall_marked_as_ads'):
                        all_random_posts.append(post)
            except Exception as e:
                continue

        result = []
        for post in all_random_posts:
            result.append(self._parse_wall_post(post))
        return result

    def _get_all_skynet_bots_posts(self):
        self._log('run _get_all_skynet_bots_posts')
        all_skynet_bots_posts = []
        for bot_page in bots:
            try:
                time.sleep(3)
                r = self._get(bot_page)
                soup = BeautifulSoup(r.text, "html.parser")
                posts = soup.select('.wall_posts .post.own')
                for post in posts:
                    all_skynet_bots_posts.append(post)
            except Exception as e:
                continue

        result = []
        for post in all_skynet_bots_posts:
            result.append(self._parse_wall_post(post))
        return result

    def _get_bot_last_post_age(self, response):
        try:
            soup = BeautifulSoup(response.text, "html.parser")
            last_post = soup.select_one('.post.own.post_copy')

            if not last_post:
                return 0

            post_data = self._parse_wall_post_date(last_post)
            return post_data
        except:
            pass
        return 0

    def _get_last_bot_post(self):
        try:
            time.sleep(3)
            r = self._get('https://vk.com/id' + self.vk_id)
            soup = BeautifulSoup(r.text, "html.parser")
            my_post = soup.select_one('.wall_posts .post.own')
        except Exception as e:
            return None

        my_post = self._parse_wall_post(my_post)
        return my_post

    def _get_last_my_group_post(self):
        r = self._get(self.vk_my_group)
        soup = BeautifulSoup(r.text, "html.parser")
        post = soup.select_one('.wall_posts .post.own')
        post = self._parse_wall_post(post)
        return post

    def _init_session(self):
        self._session = None
        headers = {
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'content-type': 'application/x-www-form-urlencoded',
        }
        os.makedirs(os.path.dirname('tmp/vk_user_agent.out'), exist_ok=True)
        try:
            with open('tmp/vk_user_agent.out', 'r') as f:
                user_agent = f.read()
        except IOError:
            user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%d.0.3309.6 Safari/537.36' % random.randint(52, 65)
            with open('tmp/vk_user_agent.out', 'w') as f:
                f.write(user_agent)
        headers['user-agent'] = user_agent

        self._session = requests.session()
        self._session.headers.update(headers)
        os.makedirs(os.path.dirname('tmp/vk_cookies.out'), exist_ok=True)
        try:
            with open('tmp/vk_cookies.out', 'rb') as f:
                cookies = pickle.load(f)
                cookies = requests.utils.cookiejar_from_dict(cookies)
                self._session.cookies = cookies
        except IOError:
            pass

        return self._session

    def _log(self, msg):
        if self._logger:
            self._logger.log(msg)
            return True
        return False

    def _login(self, response):
        try:
            soup = BeautifulSoup(response.text, "html.parser")
            ip_h = soup.find('input', {'name': 'ip_h'}).get('value')
            lg_h = soup.find('input', {'name': 'lg_h'}).get('value')

            params = {
                'act': 'login',
                'role': 'al_frame',
                '_origin': 'https://vk.com',
                'ip_h': ip_h,
                'lg_h': lg_h,
                'email': self.vk_username,
                'pass': self.vk_password
            }

            time.sleep(3)
            r = self._post('https://login.vk.com/', data=params, allow_redirects=False)
            location = r.headers['location']

            parsed_location = urllib.parse.urlparse(location)
            parsed_location = urllib.parse.parse_qs(parsed_location.query)

            if 'sid' in parsed_location:
                captcha_response = self._solve_captcha(parsed_location['sid'])
                if not captcha_response:
                    return False
                params['recaptcha'] = captcha_response

                time.sleep(3)
                r = self._post('https://login.vk.com/', data=params, allow_redirects=False)
                location = r.headers['location']
                parsed_location = urllib.parse.urlparse(location)
                parsed_location = urllib.parse.parse_qs(parsed_location.query)

            if '__q_hash' in parsed_location:
                time.sleep(3)
                r = self._get(location)

                try:
                    self.vk_id = re.search('"uid":"([0-9]+)"', r.text).group(1)
                except AttributeError:
                    pass
                self._save_session()
                return True
            else:
                return False

        except Exception as e:
            pass
        return False

    def _needs_change_language(self, response):
        try:
            soup = BeautifulSoup(response.text, "html.parser")
            html = soup.find(name="html", attrs={'lang': 'ru'})
            if html:
                return False
            return True
        except Exception as e:
            return True

    def _needs_login(self, response):
        try:
            soup = BeautifulSoup(response.text, "html.parser")
            ip_h = soup.find('input', {'name': 'ip_h'}).get('value')
            lg_h = soup.find('input', {'name': 'lg_h'}).get('value')
            return True
        except:
            return False

    def _open_main_page(self):
        self._log('run _open_main_page')
        time.sleep(3)
        r = self._get('https://vk.com/')
        if self._needs_login(r):
            if self._needs_change_language(r):
                self._change_language(r)
                r = self._get('https://vk.com/')
            if not self._login(r):
                return False
            time.sleep(3)
            r = self._get('https://vk.com/')

        if r.status_code == 200:
            try:
                self.vk_id = re.search(r',\n  id: ([0-9]+)', r.text, re.M).group(1)
                return True
            except AttributeError:
                pass

        return False

    def _parse_int_from_human_number(self, number):
        if number == '':
            return 0
        result = float(re.search(r'[\d\.]+', number).group())
        if 'K' in number:
            result = result * 1000
        if 'M' in number:
            result = result * 1000000
        if 'B' in number:
            result = result * 1000000000
        return result

    def _parse_wall_post(self, post):
        result = {
            'rating': 0
        }
        try:
            result['id'] = post.get('id')
            result['original_id'] = post.get('data-copy')
            result['view_hash'] = post.get('post_view_hash'),
            result['author_name'] = post.select_one('.post_author > a.author').getText()
            result['author_link'] = post.select_one('.post_author > a.author').get('href')
            try:
                result['copy_author_name'] = post.select_one('.copy_post_author > a.copy_author').getText()
                result['copy_author_link'] = post.select_one('.copy_post_author > a.copy_author').get('href')
            except Exception:
                result['copy_author_name'] = None
                result['copy_author_link'] = None
            result['date'] = self._parse_wall_post_date(post)
            result['likes'] = post.select_one('.post_like_count._count').getText()
            result['reposts'] = post.select_one('.post_share_count._count').getText()
            result['views'] = post.select_one('.post_views_count._count').getText()

            result['likes'] = self._parse_int_from_human_number(result['likes'])
            result['reposts'] = self._parse_int_from_human_number(result['reposts'])
            result['views'] = self._parse_int_from_human_number(result['views'])

            result['rating'] = (result['likes'] + result['reposts']) / result['views'] * 100
        except Exception as e:
            pass
        return result

    def _parse_wall_post_date(self, post):
        try:
            post_date = post.select_one('.post_header .post_date').getText()
            if "год" in post_date or "года" in post_date or "лет" in post_date:
                return 0

            if "назад" in post_date:
                return time.time()

            post_date = post_date.split(' в ')
            post_date = {
                'date': post_date[0],
                'time': post_date[1]
            }
            if post_date['date'] == 'сегодня':
                post_date['date'] = datetime.datetime.now().strftime("%d-%m-%Y")
            elif post_date['date'] == 'вчера':
                post_date['date'] = datetime.datetime.now() - datetime.timedelta(days=1)
                post_date['date'] = post_date['date'].strftime("%d-%m-%Y")
            else:
                post_date['date'] = post_date['date'].split(' ')
                post_date['date'][1] = months[post_date['date'][1]]
                if len(post_date['date']) == 2:
                    post_date['date'].append(str(datetime.datetime.now().year))
                post_date['date'] = '-'.join(str(v) for v in post_date['date'])

            post_date_string = post_date['date'] + ' ' + post_date['time']
            post_date = datetime.datetime.strptime(post_date_string, '%d-%m-%Y %H:%M')
            return post_date.timestamp()
        except Exception as e:
            self._log('exception in _parse_wall_post_date. post_date=' + str(post_date) + ' ' + str(e).encode().decode("utf-8"))
            return 0

    def _post(self, *args, **kwargs):
        try:
            result = self.get_session().post(*args, **kwargs)
        except BrokenPipeError:
            self._log('BrokenPipeError, reinit session')
            self._init_session()
            result = self.get_session().post(*args, **kwargs)
        return result

    def _repost_post(self, post):
        post_id = 'wall'+post['id'].replace('post', '')
        params = {
            'act': 'publish_box',
            'al': 1,
            'object': post_id
        }
        time.sleep(3)
        r = self._post('https://vk.com/like.php', data=params)

        try:
            share_hash = re.search('shHash: \'([^\']+)\'', r.text).group(1)
        except AttributeError:
            return False

        params = {
            'act': 'a_do_publish',
            'al': '1',
            'from': 'box',
            'hash': share_hash,
            'list': '',
            'object': post_id,
            'to': 0
        }
        time.sleep(3)
        r = self._post('https://vk.com/like.php', data=params)

        if re.match('(.*)Запись отправлена', r.text):
            self._save_session()
            self._log('a post ' + str(post['id']) + ' reposted successfully')
            return True

        return False

    def _save_session(self):
        os.makedirs(os.path.dirname('tmp/vk_cookies.out'), exist_ok=True)
        with open('tmp/vk_cookies.out', 'wb+') as f:
            f.truncate()
            cookies = requests.utils.dict_from_cookiejar(self.get_session().cookies)
            pickle.dump(cookies, f)
        return True

    def _search_friend(self):
        time.sleep(3)
        r = self._get('https://vk.com/friends?act=find')
        city = self._cities.get_rand_city()
        status = random.choice([1, 5, 6])

        def recursive_search_friends(offset=0):
            # 'c[sex]': 2,
            params = {
                'al': '1',
                'c[age_from]': 18,
                'c[age_to]': 45,
                'c[city]': city,
                'c[country]': 1,
                'c[online]': 1,
                'c[photo]': 1,
                'c[section]': 'people',
                'c[status]': status,
                'change': 1,
                'search_loc': 'friends?act=find',
            }
            if offset > 0:
                params['al_ad'] = 0
                params['offset'] = offset

            time.sleep(3)
            r = self._post('https://vk.com/al_search.php', data=params)

            try:
                result = re.search('"has_more":true', r.text).group(0)
                new_offset = re.search('"offset":([0-9]+)', r.text).group(1)
                new_offset = int(new_offset)
                has_more = True
            except AttributeError:
                new_offset = None
                has_more = False

            buttons = re.findall('<button id="search_sub([0-9]+)"([^>]*)this, ([0-9]+), \'([^>]*)\', true([^>]*)>Добавить в друзья</button>', r.text)
            ids = []
            for friend_id, trash, same_id, friend_hash, button_end in buttons:
                if not re.match('(.*)display: none;(.*)', button_end):
                    ids.append((friend_id, friend_hash))

            if not len(ids) and has_more and new_offset and new_offset > offset:
                ids = recursive_search_friends(new_offset)
            return ids

        people_ids = recursive_search_friends()

        if not len(people_ids):
            return False, False
        if len(people_ids) > 1:
            friend_id, friend_hash = people_ids[1]
        else:
            friend_id, friend_hash = people_ids[0]

        return friend_id, friend_hash

    def _solve_captcha(self, captcha_key):
        result = self._solve_antigate_captcha(captcha_key)
        if not result:
            result = self._solve_rucaptcha_captcha(captcha_key)
        return result

    def _solve_antigate_captcha(self, captcha_key):
        self._log('Resolving captcha in Antigate')
        task = NoCaptchaTaskProxyless.NoCaptchaTaskProxyless(anticaptcha_key=self.antigate_key)
        result = task.captcha_handler(websiteURL='https://vk.com', websiteKey=captcha_key)
        if result['errorId'] == 0 and 'solution' in result:
            solution = result['solution']
            if 'gRecaptchaResponse' in solution:
                return solution['gRecaptchaResponse']
        return False

    def _solve_rucaptcha_captcha(self, captcha_key):
        self._log('Resolving captcha in RuCaptcha')
        url = 'http://rucaptcha.com/in.php?key=' + self.rucaptcha_key + '&method=userrecaptcha&googlekey=' + captcha_key + '&pageurl=https://vk.com'
        r = requests.get(url)
        if r.status_code != 200:
            self._log('Rucaptcha returns error ' + str(r.status_code) + ' for url: ' + url)
            return False

        captcha_id = r.text[3:]

        while True:
            time.sleep(10)
            url = 'http://rucaptcha.com/res.php?key=' + self.rucaptcha_key + '&action=get&id=' + captcha_id
            r = requests.get(url)
            if r.status_code != 200:
                self._log('Rucaptcha returns error ' + str(r.status_code) + ' for url: ' + url)
                return False

            if r.text != 'CAPCHA_NOT_READY':
                if r.text[:3] != 'OK|':
                    return False
                return r.text[3:]
示例#22
0
def handler(event, context):
    body_cities = None
    body_distances = None
    population_size = 20
    mutation_rate = 1  # 1% - taxa de mutação
    generations = 1000  # critério de parada
    time_distances = []

    if event:
        event = json.loads(event['body'])
        population_size = int(event['populationSize'])
        mutation_rate = int(event["mutationRate"])
        generations = int(event["generations"])
        body_cities = event['cities']
        body_distances = event["distances"]

    try:
        c = Cities()
        if body_cities and body_distances:
            c.set_cities(body_cities, body_distances)
        else:
            c.test()  # carrega cidades para testes

        cities_list = c.get_cities()

        for city in cities_list:
            print("Distâncias da cidade: %s\n******" % city.name)
            time_distances.append(city.distances)
            print(city.distances)
            for index, distance in enumerate(city.distances):
                print("De %s --> %s = %s" %
                      (city.name, cities_list[index].name, distance))

        ga = GeneticAlgorithm(population_size)
        result = ga.resolve(mutation_rate, generations, time_distances,
                            cities_list)

        print({
            'generation': result[0],
            'travelled_distance': result[1],
            'chromosome': result[2],
            'cities': c.chromose_to_cities(result[2])
        })

        return {
            'statusCode':
            200,
            'headers': {
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'application/json'
            },
            'body':
            json.dumps({
                'generation': result[0],
                'travelled_distance': result[1],
                'chromosome': result[2],
                'cities': c.chromose_to_cities(result[2])
            })
        }

    except ImportError:
        print(ImportError)
        return {
            'statusCode': 500,
            'body': json.dumps({'message': "Erro ao executar"})
        }
示例#23
0
from celery import Celery
from cities import Cities
from selenium.common.exceptions import SessionNotCreatedException

MAX_TRIES = 2

app = Celery('tasks', backend='rpc://', broker='pyamqp://guest@localhost//')
cities = Cities()


@app.task
def add(x, y):
    return x + y


@app.task
def nyc_zone(address, zip, retry=0):
    try:
        return cities.nyc.get_zone(address, zip)
    except SessionNotCreatedException:
        if retry < MAX_TRIES:
            restart()
            return nyc_zone(address, zip, retry + 1)
        else:
            return "NYC lookup failed"


@app.task
def dc_zone(address, zip):
    try:
        return cities.dc.get_zone(address, zip)