Beispiel #1
0
def scrape(symbol):
    myDB = DBHelper()
    url = "https://www.google.com/finance/getprices?q=%s&x=NSE&i=60&p=1d&f=d,c,o,h,l,v&df=cpct&auto=1" %symbol
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0')
    try:
        f = urllib2.urlopen(req)
        rawdata = f.read()
        f.close()
    except Exception as e:
        logging.error("Error fetching URL")
        f.close()
    base_timestamp = 0
    priceTuple = namedtuple('priceTuple', ['close', 'high', 'low', 'open', 'volume'])
    for idx, line in enumerate(rawdata.splitlines()):
        if (idx == 3):
            interval = int(line.strip().split('=')[1])
        if (idx >= 7):
            content = line.strip().split(',')
            if (content[0].startswith('a')):
                timestamp = datetime.datetime.fromtimestamp(int(content[0][1:]))
                base_timestamp = timestamp
                p = priceTuple._make(tuple(content[1:]))
            else:
                timestamp = base_timestamp + datetime.timedelta(seconds=int(content[0]) * interval)
                p = priceTuple._make(tuple(content[1:]))
            try:
                myDB.insertPrice(timestamp=timestamp, symbol=symbol, pricetuple=p)
            except Exception as e:
                logging.error(e.message)

    conn = myDB.getConn()
    conn.commit()
    conn.close()
Beispiel #2
0
def fetch_user(openid):
    access_token = get_access_token(putao_config.access_token_url) 
    user_dic = user_by_openid(openid, access_token,putao_config.service_id)
    args = {'putao_token_uid': openid, 'putao_name': user_dic['data']['nick_name']}
    DB = DBHelper()
    newuserid = DB.add_user(args)
    print('newuserid=',newuserid)
    return newuserid
Beispiel #3
0
def save_child_data(name,sex,birthday,imgurl,userid):
    print('get_child_picture')
    data=requests.get(imgurl)
    photo=data.content
    # newstring = photo.decode(encoding='UTF-8')
    args = {'name': name, 'sex': sex, 'birthday': birthday,'picture':''}

    args['picture'] = photo

    DB = DBHelper()
    lastid = DB.add_children(args)
    DB.add_patientuser({'patientid':lastid,'userid':userid})
    print('lastid=',lastid)
Beispiel #4
0
def run():
    financeapi = GoogleFinanceAPI()
    while 1:
        myDB = DBHelper()
        scripsData = myDB.getAll(tbname='scrips')
        conn = myDB.getConn()
        conn.close()
        scripList = [scrip[0] for scrip in scripsData]
        chunkList = list(chunks(scripList,99))      #since URL can only be 2000 characters long and google finance returns only 100 symbols at a time
        for chunk in chunkList:
            time.sleep(1)
            quotelist = financeapi.get(chunk)
            myDB.updatelivedata(quotelist)
        time.sleep(2)
Beispiel #5
0
def run():
    logging.basicConfig(filename='scyther.log', level= logging.DEBUG, format= '%(asctime)s %(message)s')
    logging.info('Backfill Started for %s at %s' %(datetime.datetime.now().date(),datetime.datetime.now()))
    myDB = DBHelper()
    scripsData = myDB.getAll(tbname = 'scrips')
    conn = myDB.getConn()
    conn.close()
    scripList = [scrip[0] for scrip in scripsData]
    idx = 0
    for scrip in scripList:
        scrape(scrip)
        print idx, scrip
        time.sleep(1)
        idx += 1
        logging.info('%s Scraped Successfully' %scrip)
    logging.info('Scraping completed successfully for %s' %datetime.datetime.now().date())
Beispiel #6
0
import json

from dbhelper import DBHelper
from flask import Flask
from flask import render_template
from flask import request

app = Flask(__name__)
DB = DBHelper()

categories = ['mugging', 'break-in']

@app.route('/')

def home():
    crimes = DB.get_all_crimes()
    crimes = json.dumps(crimes)
    return render_template("home.html", crimes=crimes, categories=categories)

@app.route('/add', methods=['POST'])
def add():
    try:
        data = request.form.get('userinput')
        DB.add_input(data)
    except Exception as e:
        print e
    return home()

@app.route('/clear')
def clear():
    try:
Beispiel #7
0
    def __init__(self):

        self.db = DBHelper()
        # Load GUI
        self.load_login_window()
 def __init__(self):
     """Init function of class BaremetalStatus
     """
     self.db_client = DBHelper()
Beispiel #9
0
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
from messages import emojidb as emo
from messages import info
from messages import buttons as btn

from nearest import get_nearest_location

import telegram
from dbhelper import DBHelper

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
					level=logging.INFO)
logger = logging.getLogger(__name__)

# DB settings
db = DBHelper()
db.setup()

def str_to_keyboard(lst):
	return [[KeyboardButton(j) for j in i] for i in lst]

def create_main_keyboard():
	keyboard_main = str_to_keyboard(btn.keyboard_main_layout)
	reply_markup_main = ReplyKeyboardMarkup(keyboard_main, resize_keyboard=1)
	return reply_markup_main


def start(bot, update):
	update.message.reply_text(info.helping_info, reply_markup=create_main_keyboard(), parse_mode='HTML')

# Create main keyboard
Beispiel #10
0
#!/usr/bin/env python
#-*-coding: utf-8-*-

# Version: 0.1
# Author: Don Li <*****@*****.**>
# License: Copyright(c) 2013 Don.Li
# Summary: 

import setting
from dbhelper import DBHelper

try:
    POOL
except NameError:
    print "db conf:", setting.DB_CONF
    user_db_conf = dict(
                      host     = setting.DB_CONF['host'],
                      port     = setting.DB_CONF['port'],
                      user     = setting.DB_CONF['user'],
                      passwd   = setting.DB_CONF['pass'],
                      db       = setting.DB_CONF['userdb'],
                      #charaset = 'utf8',
                      cp_noisy = setting.DEBUG,
                      cp_min   = 5,
                      cp_max   = setting.DB_CONF['pool_size'],
                      cp_reconnect = True)

    print "final db conf:", user_db_conf
    POOL = DBHelper(**user_db_conf)
    print "POOL: ", POOL
Beispiel #11
0
class SpiderStart(object):
    def __init__(self):

        self.db = DBHelper()

        self.list = self.db.selectcommuity()
        self.spider5i5j = Spider5a5j()
        self.spiderlianjia = Spiderlianjia()
        self.spiderke = SpiderKe()
        self.spider365 = Spider365()

    def start_spider(self):

        for info in self.list:

            pricelis5i5jtall = []
            pricelistlianjia = []
            pricelistbeike = []
            isgo5i5j = True
            isolianjia = True
            isgoke = True

            for i in range(1, 10):
                pass

                if info[2] != None and isgo5i5j:

                    response = self.spider5i5j.start_url(
                        str(info[2], encoding="utf-8"), i)
                    if response == False:
                        isgo5i5j = False
                    else:
                        isgo5i5j, pricelist1 = self.spider5i5j.parse(response)
                        pricelis5i5jtall.extend(pricelist1)

                if info[4] != None and isolianjia:
                    response = self.spiderlianjia.start_url(
                        str(info[4], encoding='utf-8'), i)
                    if response == False:
                        isolianjia = False
                    else:
                        isolianjia, pricelist2 = self.spiderlianjia.parse(
                            response)
                        pricelistlianjia.extend(pricelist2)
            #
                if info[4] != None and isgoke:
                    response = self.spiderke.start_url(
                        str(info[4], encoding='utf-8'), i)
                    if response == False:
                        isgoke = False
                    else:
                        isgoke, pricelist3 = self.spiderke.parse(response)

                        pricelistbeike.extend(pricelist3)
            response = self.spider365.start_url(str(info[1], encoding="utf-8"))
            isgo, pricelist365 = self.spider365.parse(
                response, str(info[1], encoding="utf-8"))

            result1 = []
            result = []
            result2 = []
            result3 = []
            if len(pricelis5i5jtall) != 0:

                result1 = self.productResult(pricelis5i5jtall,
                                             str(info[1], encoding="utf-8"),
                                             True)

            if len(pricelistlianjia) != 0:
                result2 = self.productResult(pricelistlianjia,
                                             str(info[1], encoding="utf-8"))

            if len(pricelistbeike) != 0:
                result = self.productResult(pricelistbeike,
                                            str(info[1], encoding="utf-8"))

            if len(pricelist365) != 0:
                result3 = self.productResult(pricelist365,
                                             str(info[1], encoding="utf-8"),
                                             False)

            result.extend(result1)
            result.extend(result2)
            result.extend(result3)

            if len(result) != 0:

                self.db.insert(result, str(info[1], encoding="utf-8"))

    def productResult(self, pricelist2, communityName, type=True):

        pricelist = self.optionmin(pricelist2, type)

        ave = float('%.2f' % self.optionAve(pricelist2))
        pricelist = self.optionrate(pricelist, ave)

        resultlist = []
        for i in pricelist:
            list = []
            list.append(communityName)
            list.append(i['sourceName'])
            list.append(i['priceall'])
            list.append(i['price'])
            list.append(ave)
            list.append(i['floor'])
            list.append(i['apartment'])
            list.append(i['area'])
            list.append(i['orientation'])
            list.append(i['isIncludeTop'])
            list.append(i['rate'])
            resultlist.append(list)

        return resultlist

    def optionrate(self, pricelist, avg):
        for i in pricelist:
            rate = float(i['price']) / float(avg)

            i['rate'] = float('%.4f' % rate)

        return pricelist

    def optionmin(self, pricelist, type=True):
        pricelist = list(pricelist)

        pricelist.sort(key=lambda x: float(x['price']))
        if len(pricelist) > 3:

            pricelistmin = pricelist[:3]
        else:
            pricelistmin = pricelist

        if type:

            for item in pricelist:

                if '顶层' not in item['floor']:
                    global otherprice
                    otherprice = copy.deepcopy(item)
                    otherprice['isIncludeTop'] = False
                    pricelistmin.append(otherprice)
                    break

        else:

            for item in pricelist:

                if item['istop'] == False:

                    otherprice = copy.deepcopy(item)
                    otherprice['isIncludeTop'] = False

                    pricelistmin.append(otherprice)
                    break

        return pricelistmin

    def optionAve(self, pricelist):
        #求均值
        sum = 0
        for item in pricelist:
            item = float(item['price'])
            sum += item
        return sum / len(pricelist)
Beispiel #12
0
 def __init__(self):
     coll_name = "inventory"
     self.yaml_file = config_file("/cloudmesh_mac.yaml")
     self.db_client = DBHelper(coll_name)
     self.bm_status = BaremetalStatus()
Beispiel #13
0
class BaremetalComputer:
    """Baremetal computer class.
    First, this class also provide a easy API to initialize the cobbler baremetal computers in mongodb, e.g., mac and power info,
    Second, this class have an API through which user can get the detail information to provision a cobbler baremetal computer
    """

    def __init__(self):
        coll_name = "inventory"
        self.yaml_file = config_file("/cloudmesh_mac.yaml")
        self.db_client = DBHelper(coll_name)
        self.bm_status = BaremetalStatus()

    def get_default_query(self):
        """
        query helper function.
        :return: the default query field.
        """
        return {"cm_type": "inventory",
                "cm_kind": "server",
                "cm_attribute": "network",
                "cm_key": "server",
                }

    def get_full_query(self, query_elem=None):
        """
        merge the default query and user defined query.
        :return: the full query dict
        """
        result = self.get_default_query()
        if query_elem:
            result.update(query_elem)
        return result

    def read_data_from_yaml(self):
        """
        read mac address and bmc configuration information from **mac.yaml** file.
        """
        data = read_yaml_config(self.yaml_file)
        result = None
        if data:
            result = {}
            data = data["inventory"]
            for cluster in data:
                cluster_data = data[cluster]
                if "bmc" in cluster_data and "common" in cluster_data["bmc"]:
                    # process the common bmc data in cluster
                    common_bmc_data = cluster_data["bmc"]["common"]
                    host_range = common_bmc_data.pop("range", None)
                    hosts = expand_hostlist(host_range)
                mac_data = cluster_data["macaddr"]
                for host in mac_data:
                    if host in hosts:
                        temp_common_bmc_data = deepcopy(common_bmc_data)
                        if "bmc" in mac_data[host]:
                            # bmc config in individual host have a high
                            # priority than common config
                            temp_common_bmc_data.update(mac_data[host]["bmc"])
                        mac_data[host]["bmc"] = temp_common_bmc_data
                result[cluster] = mac_data
        return result

    def insert_mac_data_to_inventory(self):
        """
        Insert the mac address information including power config into inventory.
        This API should be called **BEFORE** baremetal provision.
        Currently, this API is called by **fab mongo.inventory**
        """
        # insert a document of baremetal computers list
        self.insert_blank_baremetal_list()
        # insert mac data
        data = self.read_data_from_yaml()
        result = False
        if data and len(data) > 0:
            result = self.update_mac_address(data)
        return result

    def update_mac_address(self, mac_dict):
        """
        update *inventory* db with mac address information.
        :param dict mac_dict: a dict with the following formation. *label_name* is the *cm_id* defined in inventory.
        *internal* or *public* is the type defined in inventory.
        {"cluster_name":{
          "label_name": {"internal": {"name":"eth0", "macaddr": "aa:aa:aa:aa:aa:aa"},
                         "public": {"name":"eth1", "macaddr": "aa:aa:aa:aa:aa:ab"},
                         "bmc": {"user": "******", "pass": "******", "type": "type",},}
        }
        :return: True means all the mac address in mac_dict updated successfully; False means failed.
        """
        result = True
        if mac_dict:
            for cluster in mac_dict:  # cluster
                cluster_data = mac_dict[cluster]
                for host_id in cluster_data:  # host
                    host_data = cluster_data[host_id]
                    for network_type in host_data:  # network
                        network_data = host_data[network_type]
                        query_elem = {
                            "cm_id": host_id, "type": network_type, "cm_cluster": cluster, }
                        if network_type in ["bmc"]:  # power config information
                            update_elem = network_data
                        else:
                            update_elem = {"ifname": network_data["name"],
                                           "macaddr": network_data["macaddr"],
                                           }
                        update_result = self.db_client.atom_update(self.get_full_query(query_elem),
                                                                   {"$set": update_elem}, False)
                        if not update_result["result"]:
                            result = False
                            break
                    if not result:
                        break
                if not result:
                    break
        return result

    def get_host_info(self, host_id, info_format="cobbler"):
        """
        get the required host info for baremetal computer.
        :param string host_id: the unique name/id of a node in cloudmesh
        :param string info_format: the dest info format of general host info. To support a new formation, such as *xtest*, the API get_host_info_xtest MUST be provided.
        :return: a dict with the following formation if info_format is None, otherwise return the use specified formation conerted from the default one.
        {
          "id": "unique ID",
          "power": {"ipaddr": ipaddr, "power_user": user, "power_pass": pass, "power_type": type,},
          "interfaces": [{"name": "eth0", "ipaddr": ipaddr, "macaddr": macaddr,}],
        }
        """
        query_elem = {"cm_id": host_id}
        full_query_elem = self.get_full_query(query_elem)
        find_result = self.db_client.find(full_query_elem)
        result = None
        if find_result["result"]:
            result = {"id": host_id, "power": {}}
            data = find_result["data"]
            interface_list = []
            cluster_id = None
            for record in data:
                if "macaddr" in record:  # general network interface
                    interface_list.append({"name": record["ifname"],
                                           "ipaddr": record["ipaddr"],
                                           "macaddr": record["macaddr"],
                                           })
                    if record["type"] == "public":
                        result["hostname"] = record["label"]
                        cluster_id = record["cm_cluster"]
                elif "power_user" in record:  # ipmi network interface
                    power_key_list = [
                        "ipaddr", "power_user", "power_pass", "power_type", ]
                    for key in power_key_list:
                        result["power"][key] = record[key]
            # sort the inteface with ascending order
            result["interfaces"] = sorted(
                interface_list, key=lambda k: k["name"])
            if cluster_id:
                # try to find name server for the servers in this cluster
                name_servers = self.get_cluster_name_server(cluster_id)
                if name_servers:
                    result["name_servers"] = name_servers
            if info_format:
                getattr(self, "get_host_info_{0}".format(info_format))(result)
        return result

    def get_cluster_name_server(self, cluster_id):
        """find the name servers for a cluster
        :param string cluster_id: the unique ID of a cluster
        :return: None if not exist a name server for the cluster, otherwise a string represents the one or more name servers
        """
        query_elem = {
            "cm_id": cluster_id, "cm_key": "nameserver", "cm_attribute": "variable"}
        full_query_elem = self.get_full_query(query_elem)
        find_result = self.db_client.find(full_query_elem)
        result = []
        if find_result["result"]:
            data = find_result["data"]
            for record in data:
                result.append(record["cm_value"])
        return None if len(result) < 1 else " ".join(result)

    def change_dict_key(self, data_dict, fields):
        """
        change the key in dict from old_key to new_key.
        :param dict fields: the projection from old_key to new_key. {"old_key": "new_key"}
        """
        for key in fields:
            if key in data_dict:
                data_dict[fields[key]] = data_dict.pop(key)

    def fill_dict_default_key(self, data_dict, fields):
        """
        fill the dict with default key-value pair.
        :param dict fields: the default key-value pair. {"key": "default"}
        """
        for key in fields:
            if key not in data_dict:
                data_dict[key] = fields[key]

    def get_host_info_cobbler(self, host_dict):
        """
        convert general host info dict to the formation of cobbler host formation
        """
        # section 1, general fields
        general_fields = {"id": "name", "name_servers": "name-servers", }
        self.change_dict_key(host_dict, general_fields)
        # section 2, power fields
        power_fields = {"ipaddr": "power-address",
                        "power_user": "******",
                        "power_pass": "******",
                        "power_type": "power-type",
                        }
        power_default = {"power-id": 2,
                         }
        self.change_dict_key(host_dict["power"], power_fields)
        self.fill_dict_default_key(host_dict["power"], power_default)
        # section 3, interface fields
        interface_fields = {"ipaddr": "ip-address",
                            "macaddr": "mac-address",
                            }
        interface_default = {"netmask": "255.255.255.0",
                             "static": True,
                             }
        for one_interface in host_dict["interfaces"]:
            self.change_dict_key(one_interface, interface_fields)
            self.fill_dict_default_key(one_interface, interface_default)

    def insert_blank_baremetal_list(self):
        """insert a blank document of baremetal computers list into mongodb
        ONLY called ONCE by **fab mongo.inventory**
        """
        elem = {"cm_kind": "baremetal", "cm_type": "bm_list_inventory", }
        result = self.db_client.find_one(elem)
        flag_insert = True
        if result["result"] and result["data"]:
            flag_insert = False
        if not flag_insert:
            return True
        result = self.db_client.insert(elem)
        return result["result"]

    def enable_baremetal_computers(self, hosts):
        """add the list of *hosts* to be baremetal computers
        :param list hosts: the list of hosts with the formation ["host1", "host2",]
        :return: True means enabled successfully, otherwise False
        """
        if hosts:
            query_elem = {
                "cm_kind": "baremetal", "cm_type": "bm_list_inventory", }
            update_elem = {"$addToSet": {"data": {"$each": hosts}}}
            result = self.db_client.atom_update(query_elem, update_elem)
            return result["result"]
        return True

    def disable_baremetal_computers(self, hosts):
        """remove the list of *hosts* from baremetal computers
        :param list hosts: the list of hosts with the formation ["host1", "host2",]
        :return: True means disabled successfully, otherwise False
        """
        if hosts:
            query_elem = {
                "cm_kind": "baremetal", "cm_type": "bm_list_inventory", }
            update_elem = {"$pull": {"data": {"$in": hosts}}}
            result = self.db_client.atom_update(query_elem, update_elem)
            return result["result"]
        return True

    def get_baremetal_computers(self):
        """get the list of baremetal computers
        :return: the list of hosts with the formation ["host1", "host2",] or None if failed
        """
        query_elem = {"cm_kind": "baremetal", "cm_type": "bm_list_inventory", }
        result = self.db_client.find_one(query_elem)
        if result["result"]:
            return result["data"]["data"] if "data" in result["data"] else []
        return None
Beispiel #14
0
import psycopg2
from dbhelper import DBHelper

mydb = DBHelper()
scrips = mydb.getAll(tbname="scrips")
conn = mydb.getConn()
conn.close()
scripList = [scrip[0] for scrip in scrips]

mydb.insertlivedata(scripList)

Beispiel #15
0
humiditySensorType = 3

if len(sys.argv) == 3:
    serialPort = sys.argv[1]
    baudRate = sys.argv[2]
    deviceAddress = sys.argv[3]
    logEnabled = sys.argv[4]
elif len(sys.argv) == 1:
    print ('Command line: getweather.py serial_port serial_speed')
    print ('Trying with serial_port = ' + serialPort + ' and serial_speed = ' + str(baudRate))
else:
    print ('Command line: getweather.py serial_port serial_speed')
    sys.exit(1)

currenttime = time.time()
db = DBHelper(dbFileName)

device = Protocol(serialPort, baudRate, logEnabled)
if device.ping(deviceAddress):
    pressure, sernumP = device.getPressure(deviceAddress)
    if 10 < pressure < 1000:
        print ('Pressure - ' + str(pressure) + ' mmHg')
        pressureSensorId = db.getSensorId(pressureSensorType, sernumP)
        db.storeValue(currenttime, pressure, pressureSensorId)
    humidity, sernumH = device.getHumidity(deviceAddress)
    if not math.isnan(humidity):
        print ('Humidity - ' + str(humidity) + '%')
        humiditySensorID = db.getSensorId(humiditySensorType, sernumH)
        db.storeValue(currenttime, humidity, humiditySensorID)
    values = device.getTemp(deviceAddress)
    i = 1
Beispiel #16
0
def main():
    db = DBHelper()
    #db.setup(user, passwd) ##<<run to setup for 1st time
    #db.setupdepts(depts)    ##<<run to modify/add dept
    db.clearhistory(date)  ##<<run to clearhistory
    db.close()
Beispiel #17
0
def db_add_group(group_id, group_name):
    """Add a group to the table Telegram_Group."""
    try:
        DBHelper().sql_add_group(group_id, group_name)
    except DB_Error as db_error:
        raise ValueError(db_error)
Beispiel #18
0
import config
import telebot
from telebot import types
import requests
import smtplib
import os
import sys
import logging
import time
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from dbhelper import DBHelper

db = DBHelper()
bot = telebot.TeleBot(config.token)
logging.basicConfig(filename="logbot.log", level=logging.INFO, filemode='w')

texts = [[] for i in range(8)]
texts[0] = ['Главное меню']
texts[1] = ['HR', 'IT-специалист', 'Контакты']
texts[2] = [
    'Москва', 'Санкт-Петербург', 'Казань', 'Новосибирск', 'Красноярск',
    'Екатеринбург', 'Воронеж', 'Уфа', 'Нижний Новгород', 'Томск', 'Самара',
    'Рязань', u'\U00002B05' + 'Назад'
]
texts[3] = [
    'Python', 'C++', 'PHP', 'C#', 'Java', 'iOS', 'Android', 'Javascript', 'Go',
    'Ruby', 'Разработчик БД SQL', 'Oracle', 'Postgres',
    u'\U00002B05' + 'Назад к выбору города'
]
Beispiel #19
0
# License: Copyright(c) 2013 Don.Li
# Summary:

from dbhelper import DBHelper
from config import DB


def db_config():

    _host = DB['host']
    _port = DB['port']
    _user = DB['user']
    _pass = DB['pass']
    _db = DB['db_userdb']

    return {
        'host': _host,
        'port': _port,
        'user': _user,
        'passwd': _pass,
        'db': _db,
        'charset': 'utf8',
        'use_unicode': True
    }


try:
    db
except NameError:
    db = DBHelper(**db_config())
Beispiel #20
0
def handle_start_help(message):
    try:
        chat = message.chat.id
        logging.info('Start, user: %s %s %s' %
                     (chat, message.chat.first_name, message.chat.last_name))
        db = DBHelper()
        if not str(db.get_state(chat)).isdigit():
            db.add_user(chat)
            state = db.get_state(chat)
        else:
            db.update_state(chat, 1)
            delete_user_info(chat, 1)
            delete_user_info(chat, 2)
            delete_user_info(chat, 3)
            delete_user_info(chat, 4)
            state = db.get_state(chat)
        db.close()
        markup = get_markup(state)
        text = get_text(state)
        bot.send_message(message.chat.id,
                         text,
                         reply_markup=markup,
                         parse_mode="Markdown")
    except:
        print('Важная ошибка!\n Команда start.')
        logging.info('Важная ошибка, команда старт time: %s ' %
                     (time.asctime()))
Beispiel #21
0
class BaremetalPolicy:

    """Baremetal Policy. Get/Add/Delete user/group policy
    FIXME/TODO: It will add **permission access** that only admin can operate on poilicy later
    the formation of policy is
    {"_id" : "53727f1c93f9d73e90520090",
    "name" : "user1,user2,user3",
    "policy_type" : "user", # or "group"
    "policy" : "i[101-103]",
    "cm_kind" : "baremetal",
    "cm_type" : "policy_inventory"
    }
    """

    def __init__(self):
        """Construction fucntion
        """
        self.db_client = DBHelper()

    def add_user_policy(self, user, policy):
        """add a policy for an user.
        :param string user: a username
        :param string policy: one piece of policy, means user can access which baremetal servers, e.g. "i[001-004]"
        :return: UUID means add policy success, otherwise None for failed
        """
        return self.add_ug_policy("user", user, policy)

    def add_group_policy(self, group, policy):
        """add a policy for a group.
        :param string group: a group/project name
        :param string policy: one piece of policy, means this group/project can access which baremetal servers, e.g. "i[001-004]"
        :return: UUID means add policy success, otherwise None for failed
        """
        return self.add_ug_policy("group", group, policy)

    def add_ug_policy(self, type, name, policy):
        """add a policy for a specify *type*
        :param string type: the type of policy, currently supports **user** and **group**
        :param string name: the name in each type
        :param string policy: one piece of policy
        :return: UUID means add policy success, otherwise None for failed
        :rtype: string
        """
        add_elem = {"policy_type": type, "name": name, "policy": policy, }
        full_elem = self.get_full_query(add_elem)
        result = self.db_client.insert(full_elem)
        return None if not result["result"] else self.db_client.convert_objectid_to_str(result["data"])

    def remove_policy(self, uuid):
        """remove a policy based on uuid.
        :param string uuid: an uuid of the removed policy
        :return: True means remove policy success, otherwise False
        """
        object_uuid = self.db_client.convert_str_to_objectid(uuid)
        elem = {"_id": object_uuid, }
        result = self.db_client.remove(elem)
        return result["result"]

    def get_policy_based_user_or_its_projects(self, user, projects):
        """get the merged policy based on the username and his/her related projects
        :param string user: only one valid username
        :param list projects: a list of project
        :return: a policy with hostlist string, or None if non-exist policy for user and its projects
        """
        user_policy = self.get_policy_based_user(user)
        group_policy = self.get_policy_based_group(collect_hostlist(projects))
        if user_policy or group_policy:
            if user_policy:
                valid_policy = user_policy
                if group_policy:
                    valid_policy.update(group_policy)
            else:
                valid_policy = group_policy
        else:
            return None
        all_policys = []
        for name in valid_policy:
            all_policys.extend(expand_hostlist(valid_policy[name]))
        return collect_hostlist(list(set(all_policys)))

    def get_policy_based_user(self, user):
        """get all the policies for a user
        :param string user: a username with hostlist formation
        :return: a dict of user and policy with the formation {"name1": "hostlist", "name2": "hostlist2"}
        """
        policys = self.get_all_user_policy()
        return self.merge_policy_based_ug(policys) if user == "all" else self.merge_policy_based_ug(policys, True, user)

    def get_policy_based_group(self, group):
        """get all the policies for a group/project
        :param string group: a group/project with hostlist formation
        :return: a dict of group and policy with the formation {"name1": "hostlist", "name2": "hostlist2"}
        """
        policys = self.get_all_group_policy()
        return self.merge_policy_based_ug(policys, False) if group == "all" else self.merge_policy_based_ug(policys, False, group)

    def merge_policy_based_ug(self, policys, flag_user=True, name=None):
        """merge policy based the name of user/group
        :param dict policys: all the possible policys for users/groups
        :param boolean flag_user: True means user, False means group
        :param string name: the name of one or more user/group, None means all user/groups
        :return: a dict of user/group and policy with the formation {"name1": "hostlist", "name2": "hostlist2"}
        """
        if policys:
            data = {}
            names = expand_hostlist(name) if name else None
            for puser in policys:
                users = expand_hostlist(puser)
                common_users = [
                    u for u in users if u in names] if names else users
                hosts = []
                for policy in policys[puser]:
                    hosts.extend(expand_hostlist(policy["policy"]))
                for user in common_users:
                    if user in data:
                        data[user].extend(hosts)
                    else:
                        data[user] = deepcopy(hosts)
            for user in data:
                data[user] = collect_hostlist(data[user])
            # flip data, combine duplicate values
            flipped_data = {}
            for user in data:
                if data[user] in flipped_data:
                    flipped_data[data[user]].append(user)
                else:
                    flipped_data[data[user]] = [user]
            # try to merge user with same hosts
            data = {}
            for value in flipped_data:
                data[collect_hostlist(flipped_data[value])] = value
            return data if data else None
        return None

    def get_all_user_policy(self, flag_merge=False):
        """get all the policies for all user
        :param boolean flag_merge: True meanse merge all possible user and policy into string
        :return: flag_merge is False, result is a dict of user and policy with the formation {"user1":['policy1', 'policy2'], "user2": [],}
        flag_merge is True, result is a dict of user/group and policy with the formation {"name1": "hostlist", "name2": "hostlist2"}
        """
        all_policys = self.get_all_policy()
        if all_policys:
            policys = all_policys.get("users", None)
            return policys if not flag_merge else self.merge_policy_based_ug(policys)
        return None

    def get_all_group_policy(self, flag_merge=False):
        """get all the policies for all group/project
        :param boolean flag_merge: True meanse merge all possible user and policy into string
        :return: flag_merge is False, result is a dict of group/project and policy with the formation {"group1":['policy1', 'policy2'], "group2": [],}
        flag_merge is True, result is a dict of user/group and policy with the formation {"name1": "hostlist", "name2": "hostlist2"}
        """
        all_policys = self.get_all_policy()
        if all_policys:
            policys = all_policys.get("groups", None)
            return policys if not flag_merge else self.merge_policy_based_ug(policys, False)
        return None

    def get_all_policy(self):
        """get all the policies for all users and group/project
        :return: a dict of group/project and policy with the formation {"users": {"user1": [], "user2": []}, "groups":{"group1":['policy1', 'policy2'], "group2": [],}}
        """
        policys = self._get_policy()
        if not policys:
            return None
        data = {"users": {}, "groups": {}}
        for policy in policys:
            name = policy["name"]
            type = policy["policy_type"]
            if type == "user":
                if name in data["users"]:
                    data["users"][name].append(policy)
                else:
                    data["users"][name] = [policy]
            elif type == "group":
                if name in data["groups"]:
                    data["groups"][name].append(policy)
                else:
                    data["groups"][name] = [policy]
        return data

    def _get_policy(self):
        """get all the records of policy
        :return: an ordered list of policy or None if failed
        """
        result = self.db_client.find(self.get_full_query())
        if result["result"]:
            records = result["data"]
            for record in records:
                record["_id"] = self.db_client.convert_objectid_to_str(
                    record["_id"])
            return sorted(records, key=lambda x: x["_id"])
        return None

    def get_default_query(self):
        return {"cm_kind": "baremetal", "cm_type": "policy_inventory", }

    def get_full_query(self, query_elem=None):
        elem = self.get_default_query()
        if query_elem:
            elem.update(query_elem)
        return elem
Beispiel #22
0
def repeat_all_messages(message):
    try:
        db = DBHelper()
        chat = message.chat.id
        state = db.get_state(chat)
        db.close()
        information_text = ''
        if not str(state).isdigit():
            bot.send_message(chat, 'Начините работу с ботом командой /start.')
            return 0
        logging.info(
            'new message: %s %s %s name: %s %s time:  %s' %
            (message.chat.id, state, message.text, message.chat.first_name,
             message.chat.last_name, time.asctime()))
        if message.text in texts[0] and state == 0:  # 0 - контакты
            db = DBHelper()
            db.update_state(chat, 1)
            db.close()
        elif message.text in texts[1] and state == 1:  # 1 - главное меню
            if message.text == 'Контакты':
                db = DBHelper()
                db.update_state(chat, 0)
                db.close()
            else:
                db = DBHelper()
                db.update_state(chat, 2)
                db.close()
                add_user_info(chat, state, message.text)
        elif message.text in texts[2] and state == 2:  # 2 - город
            if message.text == u'\U00002B05' + 'Назад':
                db = DBHelper()
                db.update_state(chat, 1)
                db.close()
                delete_user_info(chat, 1)
            else:
                add_user_info(chat, state, message.text)
                db = DBHelper()
                db.update_state(chat, 3)
                db.close()
        elif message.text in texts[3] and state == 3:  # 3 - специализация
            if message.text == u'\U00002B05' + 'Назад к выбору города':
                delete_user_info(chat, 2)
                db = DBHelper()
                db.update_state(chat, 2)
                db.close()
            else:
                mes_text = message.text
                mes_text = check_text3(message.text)
                add_user_info(chat, state, mes_text)
                db = DBHelper()
                db.update_state(chat, 4)
                db.close()
        elif message.text in texts[4] and state == 4:  # 4 - уровень
            if message.text == u'\U00002B05' + 'Назад к выбору специализации':
                delete_user_info(chat, 3)
                db = DBHelper()
                db.update_state(chat, 3)
                db.close()
            else:
                add_user_info(chat, state, message.text)
                db = DBHelper()
                user_info = get_user_info(chat)
                db.close()
                low, high = get_prediction(user_info['City'],
                                           user_info['Ability'],
                                           user_info['Level'].lower())
                information_text = text_on_predicition(low, high,
                                                       user_info['Ability'],
                                                       user_info['Level'],
                                                       user_info['Target'])
                target = get_user_info(chat)['Target']
                if target:
                    db = DBHelper()
                    if target == 'HR':
                        db.update_state(chat, 7)
                    else:
                        db.update_state(chat, 5)
                    db.close()
        elif message.text in texts[5] and state == 5:  # 5 -
            if message.text == 'Отправить резюме':
                db = DBHelper()
                db.update_state(chat, 6)
                db.close()
            else:
                db = DBHelper()
                db.update_state(chat, 1)
                db.close()
                delete_user_info(chat, 1)
                delete_user_info(chat, 2)
                delete_user_info(chat, 3)
                delete_user_info(chat, 4)
        elif message.text in texts[6] and (state == 6 or state == 7):
            db = DBHelper()
            db.update_state(chat, 1)
            db.close()
            delete_user_info(chat, 1)
            delete_user_info(chat, 2)
            delete_user_info(chat, 3)
            delete_user_info(chat, 4)
        else:
            if message.text.upper() == 'SVD':
                bot.send_message(chat, 'https://vk.com/pitpen')
            markup = get_markup(state)
            text = 'Для отправки текстовых сообщений, пожалуйста, воспользуйтесь предложенной клавиатурой.\n\n' + get_text(
                state)
            bot.send_message(chat,
                             text,
                             reply_markup=markup,
                             parse_mode="Markdown")
            return 0
        db = DBHelper()
        state = db.get_state(chat)
        db.close()
        markup = get_markup(state)
        if state == 6:
            text = get_text(state)
            bot.send_message(chat,
                             text,
                             reply_markup=markup,
                             parse_mode="Markdown")
            return 0
        data_info = get_user_info(chat)
        text = information_text + text_user_info(data_info)
        text += get_text(state)
        bot.send_message(chat,
                         text,
                         reply_markup=markup,
                         parse_mode="Markdown")
    except:
        print('Важная ошибка! Отправка и получение сообщений!')
        logging.info(
            'Важная ошибка! Отправка и получение сообщений! %s, time%s' %
            (sys.exc_info()[0], time.asctime()))
        sys.exc_info()[0]
        delete_user_info(chat, 1)
        delete_user_info(chat, 2)
        delete_user_info(chat, 3)
        delete_user_info(chat, 4)
        db = DBHelper()
        db.update_state(chat, 1)
        db.close()
        db = DBHelper()
        state = db.get_state(chat)
        db.close()
        markup = get_markup(state)
        bot.send_message(chat,
                         'Ошбика ввода данных, пожалуйста, начните сначала',
                         reply_markup=markup)
#!/usr/bin/python

# import required classes
from review_sentiment import ReviewSentiment
from dbhelper import DBHelper

# Create instance of DBHelper class
dbHelper = DBHelper();

# Create instance of ReviewSentiment class
sentiment = ReviewSentiment();

# Populate ReviewSentiment object
sentiment.business_id = "123"
sentiment.user_id = "434"
sentiment.text = "something is something"

# Connect DBHelper object
dbHelper.connect();

# Save ReviewSentiment object
dbHelper.save(sentiment);

# Close DBHelper object
dbHelper.close();

Beispiel #24
0
def add_user_info(chat, param=None, value=None):
    keys = {2: 'City', 3: 'Ability', 4: 'Level', 1: 'Target'}
    db = DBHelper()
    db.add_user_info(chat, keys[param], value)
    db.close()
class BaremetalStatus:
    """Baremetal computer Status. 
    """
    def __init__(self):
        """Init function of class BaremetalStatus
        """
        self.db_client = DBHelper()
        
    def get_default_query(self):
        return {"cm_kind": "baremetal", "cm_type": "status_inventory"}
    
    def get_full_query(self, query_elem):
        elem = self.get_default_query()
        if query_elem:
            elem.update(query_elem)
        return elem
    
    def init_deploy_status(self, host):
        """Init the deploy status of host
        :param string host: the host name of baremetal computer
        """
        return self.init_status(host, "deploy")
    
    def init_power_status(self, host, flag_on=True):
        """Init the Power ON/OFF status of the host
        :param string host: the host name of baremetal computer
        """
        return self.init_status(host, "on" if flag_on else "off")
    
    def init_status(self, host, action):
        """init the status of baremetal computer
        :param string action: one of values in ["on", "off", "deploy"]
        :return: True means init status successfully, otherwise failed.
        """
        query_elem = self.get_full_query({"cm_id": host})
        # status cycle for deploy, OFF --> ON --> OFF
        # status cycle for power on, ON
        # status cycle for power off, OFF
        update_elem = {"transient": {"action": "{0}...".format(action), # deploy, on, off
                                     "status_1": "unknown", # status phase 1
                                     "status_2": "unknown", # status phase 2
                                     "status_3": "unknown", # status phase 3
                                     },
                       }
        if action == "deploy":
            update_elem["status"] = "unknown"    # unknown, deploying, deployed, failed
        result = self.db_client.atom_update(query_elem, {"$set": update_elem})
        return result["result"]
    
    def update_deploy_command_result(self, host, result):
        """update the deploy result
        :param string host: the unique name of host
        :param boolean result: True means deploy command success, False means failed
        :return: a flag, True means update mongodb success, otherwise failed. 
        """
        query_elem = self.get_full_query({"cm_id": host})
        update_elem = {"status": "deploying" if result else "failed", }
        result = self.db_client.atom_update(query_elem, {"$set": update_elem})
        return result["result"]
    
    def update_power_status(self, host, status, flag_on):
        """update the status of power ON/OFF
        :param string host: the unique name of host
        :param string status: status of "ON" or "OFF"
        :param boolean flag_on: True means power on, False means power off
        :return: True means udpate successfully, otherwise failed
        """
        query_elem = self.get_full_query({"cm_id": host})
        hosts_status = self.get_status(host)
        result = False
        if hosts_status and hosts_status[0]["status"] == "deployed":
            host_status = hosts_status[0]
            trans_status = {}
            flag_update = False
            if flag_on and host_status["transient"]["action"] == "on...":
                result = True
                if status == "ON":
                    trans_status["transient.action"] = "on"
                    trans_status["transient.status_1"] = "ON"
                    flag_update = True
            elif not flag_on and host_status["transient"]["action"] == "off...":
                result = True
                if status == "OFF":
                    trans_status["transient.action"] = "off"
                    trans_status["transient.status_1"] = "OFF"
                    flag_update = True
            if flag_update:
                update_result = self.db_client.atom_update(query_elem, {"$set": trans_status})
                result = update_result["result"]
        return result
    
    def update_deploy_status(self, host, status):
        """update the status of deploy based on the cycle OFF --> ON --> OFF
        :param string host: the unique name of host
        :param string status: status of "ON" or "OFF"
        :return: True means udpate successfully, otherwise failed
        """
        query_elem = self.get_full_query({"cm_id": host})
        hosts_status = self.get_status(host)
        result = False
        if hosts_status and hosts_status[0]["status"] == "deploying":
            host_status = hosts_status[0]
            if host_status["transient"]["action"] == "deploy...":
                result = True
                trans_status = {}
                flag_update = False
                # phase 1, unknown --> OFF
                if host_status["transient"]["status_1"] == "unknown":
                    if status == "OFF":
                        log.debug("host {0} deploy monitor, step 1 ".format(host))
                        trans_status["transient.status_1"] = "OFF"
                        flag_update = True
                elif host_status["transient"]["status_1"] == "OFF":
                    # phase 2, unknown --> ON
                    if host_status["transient"]["status_2"] == "unknown":
                        if status == "ON":
                            log.debug("host {0} deploy monitor, step 2 ".format(host))
                            trans_status["transient.status_2"] = "ON"
                            flag_update = True
                    elif host_status["transient"]["status_2"] == "ON":
                        # phase 3, unknown --> OFF
                        if host_status["transient"]["status_3"] == "unknown":
                            if status == "OFF":
                                log.debug("host {0} deploy monitor, step 3 ".format(host))
                                trans_status["transient.status_3"] = "OFF"
                                trans_status["transient.action"] = "deploy"
                                trans_status["status"] = "deployed"
                                flag_update = True
                if flag_update:
                    update_result = self.db_client.atom_update(query_elem, {"$set": trans_status})
                    result = update_result["result"]
        return result
    
    def get_deploy_progress(self, host, host_status=None):
        """get the progress of deploy of host baremetal computer.
        :param string host: the unique ID of host
        :param dict host_status: the status document of host in mongodb
        :return: an integer number. -1 means error. 10 means before phase 1, 25, 50, 100 means the end of phase 1, 2, 3.
        """
        result = -1
        if not host_status:
            status_list = self.get_status(host)
            if status_list:
                host_status = status_list[0]
        if host_status:
            if host_status["status"] == "deploying":
                if host_status["transient"]["status_1"] == "unknown":
                    result = 10
                elif host_status["transient"]["status_1"] == "OFF":
                    result = 25
                    if host_status["transient"]["status_2"] == "ON":
                        result = 50
            elif host_status["status"] == "deployed":
                result = 100
        return result 
    
    def get_power_progress(self, host, flag_on, host_status=None):
        """get the progress of power ON/OFF of host baremetal computer.
        :param string host: the unique ID of host
        :param boolean flag_on: True means power ON, False means OFF
        :param dict host_status: the status document of host in mongodb
        :return: an integer number. -1 means error. 10 means before phase 1, 100 means phase 1.
        """
        result = -1
        if not host_status:
            status_list = self.get_status(host)
            if status_list:
                host_status = status_list[0]
        if host_status:
            if host_status["status"] == "deployed":
                if host_status["transient"]["status_1"] == "unknown":
                    result = 10
                elif host_status["transient"]["status_1"] == "ON" if flag_on else "OFF":
                    result = 100
        return result 
    
    def get_host_progress(self, host):
        """get the progress of host baremetal computer.
        :param string host: the unique ID of host
        :return: a dict of {"status": "deploy", "progress": 25, }, there are 5 status of host, namely deploy, poweron, poweroff, failed, unknown  
        """
        result = {"status": "unknown", "progress": -1, }
        status_list = self.get_status(host)
        if status_list:
            host_status = status_list[0]
            if host_status["status"] == "deployed":
                # maybe any status in deploy, poweron, poweroff
                action = host_status["transient"]["action"]
                if action.startswith("on"):
                    result["status"] = "poweron"
                    result["progress"] = self.get_power_progress(host, True, host_status)
                elif action.startswith("off"):
                    result["status"] = "poweroff"
                    result["progress"] = self.get_power_progress(host, False, host_status)
                elif action.startswith("deploy"):
                    result["status"] = "deploy"
                    result["progress"] = self.get_deploy_progress(host, host_status)
            elif host_status["status"] == "deploying":
                result["status"] = "deploy"
                result["progress"] = self.get_deploy_progress(host, host_status)
            elif host_status["status"] == "failed":
                result["status"] = "failed"
        return result 
    
    def get_status(self, host=None):
        """get the status of single or all baremetal computer(s)
        :param string host: the unique ID of host, None means get status of all hosts
        :return: a list of dict with the following formation [{"cm_id": "cm_id", "status":"status", "transient":{"action": "action", "status_1":"status_1", "status_2":"status_2", "status_3":"status_3"}}]
         
        """
        query_elem = self.get_full_query({"cm_id": host} if host else {})
        result = self.db_client.find(query_elem)
        return result["data"] if result["result"] else None
    
    def get_status_short(self, hosts=None):
        """get the short status of baremetal for hosts
        :param list hosts: a list of host or None means all hosts
        :return: a dict with the formation {"host1":"deployed", "host2": "deploying", "host3": "failed", "host4": "unknown", }
        """
        status_list = self.get_status()
        valid_hosts_status = [status for status in status_list if status["cm_id"] in hosts] if hosts is not None else status_list
        result = {}
        for host in valid_hosts_status:
            result[host["cm_id"]] = host["status"]
        return result
    
    def get_status_summary(self, hosts=None):
        """get the summary status of baremetal for hosts
        :param list hosts: a list of host or None means all hosts
        :return: a dict with the formation {"deployed": 1, "deploying":2, "failed":2, "total": 5}
        """
        status_list = self.get_status()
        valid_hosts_status = [status for status in status_list if status["cm_id"] in hosts] if hosts is not None else status_list
        result = {"deployed": 0, "deploying": 0, "failed": 0, "total": 0}
        for host in valid_hosts_status:
            result["total"] += 1
            result[host["status"]] += 1
        return result
Beispiel #26
0
def delete_user_info(chat, param=None):
    keys = {2: 'City', 3: 'Ability', 4: 'Level', 1: 'Target'}
    db = DBHelper()
    db.delete_user_info(chat, keys[param])
    db.close()
Beispiel #27
0
class Tinder:
    def __init__(self):

        self.db = DBHelper()
        # Load GUI
        self.load_login_window()

    def load_login_window(self):
        self._root = Tk()
        self._root.iconbitmap(
            r'C:\Users\WIN8\PycharmProjects\Tinder\tinder.ico')
        self._root.title("Finderr | Find. Propose. Match")
        self._root.minsize(400, 650)
        self._root.maxsize(400, 650)
        self._root.config(background="#FE3C72")

        self._image = PhotoImage(file='logo.png')
        self._label1 = Label(self._root,
                             fg="#fff",
                             bg="#FE3C72",
                             image=self._image,
                             compound=LEFT)
        self._label1.config(font=("Monsterrat", 30))
        self._label1.pack(pady=(10, 0))

        self._label2 = Label(self._root,
                             text="finderr",
                             fg="#fff",
                             bg="#FE3C72")
        self._label2.config(font=("Monsterrat", 40))
        self._label2.pack(pady=(10, 0))

        self._label4 = Label(self._root,
                             text="One step destination to find LOVED ONES",
                             fg="#fff",
                             bg="#FE3C72")
        self._label4.pack(pady=(0, 20))

        self._email = Label(self._root, text="Email", fg="#fff", bg="#FE3C72")
        self._email.config(font=("Monsterrat", 16))
        self._email.pack(pady=(5, 5))

        self._emailInput = Entry(self._root)
        self._emailInput.pack(pady=(5, 10), ipady=5, ipadx=15)

        self._password = Label(self._root,
                               text="Password",
                               fg="#fff",
                               bg="#FE3C72")
        self._password.config(font=("Monsterrat", 16))
        self._password.pack(pady=(5, 5))

        self._passwordInput = Entry(self._root, show="*")
        self._passwordInput.pack(pady=(5, 20), ipady=5, ipadx=15)

        self._img = PhotoImage(file='login.png')
        self._img = self._img.subsample(2, 2)
        self._login = Button(self._root,
                             text="Login",
                             bg="#fff",
                             fg="#FE3C72",
                             font=('Monsterrat', 10, 'bold'),
                             image=self._img,
                             compound=LEFT,
                             relief=RIDGE,
                             width=150,
                             height=35,
                             command=lambda: self.check_login())
        self._login.pack(pady=(10, 5))

        self._lab = Label(self._root,
                          text="---------------OR----------------",
                          fg="#fff",
                          bg="#FE3C72")
        self._lab.pack()

        self._img1 = PhotoImage(file='signup.png')
        self._img1 = self._img1.subsample(2, 2)
        self._reg = Button(self._root,
                           text="Sign Up",
                           bg="#fff",
                           fg="#FE3C72",
                           font=('Monsterrat', 10, 'bold'),
                           image=self._img1,
                           compound=LEFT,
                           relief=RIDGE,
                           width=150,
                           height=35,
                           command=lambda: self.regWindow())
        self._reg.pack(pady=(5, 10))
        self._label3 = Label(
            self._root,
            text="""By clicking Sign Up, you agree to our Terms. Learn how we 
    process your data in our Privacy Policy and Cookie Policy.""",
            fg="#fff",
            bg="#FE3C72")
        self._label3.pack(pady=(10, 10))

        self._root.mainloop()

    def check_login(self):
        email = self._emailInput.get()
        password = self._passwordInput.get()

        data = self.db.check_login(email, password)

        # print(data)
        if len(data) == 0:
            # print("Invalid Credentials")
            messagebox.showerror("Error", "Invalid Credentials")
        else:
            self.user_id = data[0][0]
            self.gender = data[0][5]
            self.is_logged_in = 1
            self.login_handler()

    def regWindow(self):
        self.clear()
        self._name = Label(self._root, text="Name", fg="#fff", bg="#FE3C72")
        self._name.config(font=("Monsterrat", 16))
        self._name.pack(pady=(5, 5))
        self._nameInput = Entry(self._root)
        self._nameInput.pack(pady=(5, 5), ipady=5, ipadx=20)

        self._email = Label(self._root, text="Email", fg="#fff", bg="#FE3C72")
        self._email.config(font=("Monsterrat", 16))
        self._email.pack(pady=(5, 5))
        self._emailInput = Entry(self._root)
        self._emailInput.pack(pady=(5, 5), ipady=5, ipadx=20)

        self._password = Label(self._root,
                               text="Password",
                               fg="#fff",
                               bg="#FE3C72")
        self._password.config(font=("Monsterrat", 16))
        self._password.pack(pady=(5, 5))

        self._passwordInput = Entry(self._root, show='*')
        self._passwordInput.pack(pady=(5, 5), ipady=5, ipadx=20)

        self._age = Label(self._root, text="Age", fg="#fff", bg="#FE3C72")
        self._age.config(font=("Monsterrat", 16))
        self._age.pack(pady=(5, 5))
        self._ageInput = Entry(self._root)
        self._ageInput.pack(pady=(5, 5), ipady=5, ipadx=20)

        self._gender = Label(self._root,
                             text="Gender",
                             fg="#fff",
                             bg="#FE3C72")
        self._gender.config(font=("Monsterrat", 16))
        self._gender.pack(pady=(5, 5))
        self._genderInput = Entry(self._root)
        self._genderInput.pack(pady=(5, 5), ipady=5, ipadx=20)

        self._city = Label(self._root, text="City", fg="#fff", bg="#FE3C72")
        self._city.config(font=("Monsterrat", 16))
        self._city.pack(pady=(5, 5))
        self._cityInput = Entry(self._root)
        self._cityInput.pack(pady=(5, 5), ipady=5, ipadx=20)

        self._dp = Button(self._root,
                          fg="#fff",
                          bg="#FE3C72",
                          text="Selct a Profile Picture",
                          font=('Monsterrat', 10, 'bold'),
                          relief=RIDGE,
                          command=lambda: self._selct_dp())
        self._dp.pack(pady=(10, 5), ipady=5, ipadx=10)

        self.dp_filename = Label(self._root, bg="#FE3C72")
        self.dp_filename.pack()

        self._img2 = PhotoImage(file='back.png')

        self._back = Button(self._root,
                            text="  Back",
                            bg="#fff",
                            fg="#FE3C72",
                            font=('Monsterrat', 10, 'bold'),
                            image=self._img2,
                            compound=LEFT,
                            relief=RIDGE,
                            width=150,
                            height=35,
                            command=lambda: self.back())
        self._back.pack(padx=20, pady=10, side=LEFT)

        self._signup = Button(self._root,
                              text="Sign Up",
                              bg="#fff",
                              fg="#FE3C72",
                              font=('Monsterrat', 10, 'bold'),
                              image=self._img1,
                              compound=LEFT,
                              relief=RIDGE,
                              width=150,
                              height=35,
                              command=lambda: self.reg_handler())
        self._signup.pack(padx=10, pady=10, side=LEFT)

    def _selct_dp(self):

        self.filename = filedialog.askopenfilename(initialdir="/images",
                                                   title="something")
        self.dp_filename.config(text=self.filename)

    def back(self):
        self._root.destroy()
        self.load_login_window()

    def reg_handler(self):
        self.actual_filename = self.filename.split("/")[-1]
        flag = self.db.register(self._nameInput.get(), self._emailInput.get(),
                                self._passwordInput.get(),
                                self._ageInput.get(), self._genderInput.get(),
                                self._cityInput.get(), self.actual_filename)
        if flag == 1:

            self.destination = "C:\\Users\\WIN8\\PycharmProjects\\Tinder\\Images\\" + self.actual_filename
            shutil.copyfile(self.filename, self.destination)
            messagebox.showinfo("Sucess!",
                                "Registered Sucessfully! Login Now.")
            self._root.destroy()
            self.load_login_window()
        else:
            messagebox.showerror("Error", "Try Again")

    def mainWindow(self, data, flag=0, index=0):

        name = "Name: " + str(data[index][1])
        email = "Email: " + str(data[index][2])
        age = "Age: " + str(data[index][4])
        gender = "Gender: " + str(data[index][5])
        city = "City: " + str(data[index][6])
        dp = data[index][7]

        try:
            imageUrl = "images/{}".format(data[index][7])

            load = Image.open(imageUrl)
            load = load.resize((300, 300), Image.ANTIALIAS)
            render = ImageTk.PhotoImage(load)

            img = Label(image=render)
            img.image = render
            img.pack()
        except:
            image_label = Label(self._root,
                                text="No Image found",
                                fg="#fff",
                                bg="#FE3C72")
            image_label.config(font=("Arial", 16))
            image_label.pack(pady=(20, 10))

        # Display remaining info about the user

        name_label = Label(self._root, text=name, fg="#fff", bg="#FE3C72")
        name_label.config(font=("Arial", 16))
        name_label.pack(pady=(20, 10))

        age_label = Label(self._root, text=age, fg="#fff", bg="#FE3C72")
        age_label.config(font=("Arial", 12))
        age_label.pack(pady=(5, 10))

        gender_label = Label(self._root, text=gender, fg="#fff", bg="#FE3C72")
        gender_label.config(font=("Arial", 12))
        gender_label.pack(pady=(5, 10))

        city_label = Label(self._root, text=city, fg="#fff", bg="#FE3C72")
        city_label.config(font=("Arial", 12))
        city_label.pack(pady=(5, 10))

        if flag == 1:
            frame = Frame(self._root, bg="#FE3C72")
            frame.pack()

            previous = Button(frame,
                              text="Previous",
                              command=lambda: self.view_others(index - 1))
            previous.pack(side=LEFT, padx=5, ipadx=10)
            propose = Button(
                frame,
                text="Propose",
                command=lambda: self.propose(self.user_id, data[index][0]))
            propose.pack(side=LEFT, padx=5, ipadx=10)
            next = Button(frame,
                          text="Next",
                          command=lambda: self.view_others(index + 1))
            next.pack(side=LEFT, padx=5, ipadx=20)
        elif flag == 2:
            frame = Frame(self._root, bg="#FE3C72")
            frame.pack()

            previous = Button(frame,
                              text="Previous",
                              command=lambda: self.view_proposals(index - 1))
            previous.pack(side=LEFT, padx=5, ipadx=10)
            propose = Button(
                frame,
                text="Propose",
                command=lambda: self.propose(self.user_id, data[index][0]))
            propose.pack(side=LEFT, padx=5, ipadx=10)
            next = Button(frame,
                          text="Next",
                          command=lambda: self.view_proposals(index + 1))
            next.pack(side=LEFT, padx=5, ipadx=20)
        elif flag == 3:
            frame = Frame(self._root, bg="#FE3C72")
            frame.pack()

            previous = Button(frame,
                              text="Previous",
                              command=lambda: self.view_requests(index - 1))
            previous.pack(side=LEFT, padx=5, ipadx=10)
            next = Button(frame,
                          text="Next",
                          command=lambda: self.view_requests(index + 1))
            next.pack(side=LEFT, padx=5, ipadx=20)
        elif flag == 4:
            frame = Frame(self._root, bg="#FE3C72")
            frame.pack()

            previous = Button(frame,
                              text="Previous",
                              command=lambda: self.view_matches(index - 1))
            previous.pack(side=LEFT, padx=5, ipadx=10)
            next = Button(frame,
                          text="Next",
                          command=lambda: self.view_matches(index + 1))
            next.pack(side=LEFT, padx=5, ipadx=20)

    def propose(self, romeo, juliet):
        flag = self.db.insert_proposal(romeo, juliet)
        if flag == 1:
            messagebox.showinfo("Congrats", "Proposal Sent. Fingers Crossed!")
        elif flag == 2:
            messagebox.showerror("Sorry!", "Proposal already sent!")
        else:
            messagebox.showerror("Sorry!", "Unable to sent Request!")

    def login_handler(self):
        # To load user's profile
        # clear screen
        self.clear()
        self.headerMenu()
        data = self.db.fetch_userdata(self.user_id)
        self.mainWindow(data, flag=0)

    def clear(self):
        for i in self._root.pack_slaves():
            i.destroy()

    def view_others(self, index=0):

        # fetch data of all other users from db
        data = self.db.fetch_otheruserdata(self.user_id, self.gender)
        if index == 0:
            self.clear()
            self.mainWindow(data, flag=1, index=0)
        else:
            if index < 0:
                messagebox.showerror("No User Found", "Click on Next")
            elif index == len(data):
                messagebox.showerror("No User Left", "Click on Previous")
            else:
                self.clear()
                self.mainWindow(data, flag=1, index=index)

    def logout(self):
        self.is_logged_in = 0
        self._root.destroy()
        self.load_login_window()

    def headerMenu(self):
        menu = Menu(self._root)
        self._root.config(menu=menu)
        filemenu = Menu(menu)
        menu.add_cascade(label="Home", menu=filemenu)
        filemenu.add_command(label="My Profile",
                             command=lambda: self.login_handler())
        filemenu.add_command(label="Edit Profile",
                             command=lambda: self.edit_profile())
        filemenu.add_command(label="View Profile",
                             command=lambda: self.view_others())
        filemenu.add_command(label="LogOut", command=lambda: self.logout())

        helpmenu = Menu(menu)
        menu.add_cascade(label="Proposals", menu=helpmenu)
        helpmenu.add_command(label="My Proposals",
                             command=lambda: self.view_proposals())
        helpmenu.add_command(label="My Requests",
                             command=lambda: self.view_requests())
        helpmenu.add_command(label="My Matches",
                             command=lambda: self.view_matches())

    def edit_profile(self):

        data = self.db.fetch_userdata(self.user_id)

        self.clear()
        self._password = Label(self._root,
                               text="Password",
                               fg="#fff",
                               bg="#FE3C72")
        self._password.config(font=("Monsterrat", 16))
        self._password.pack(pady=(5, 5))

        self._passwordInput = Entry(self._root, show='*')
        self._passwordInput.insert(0, data[0][3])
        self._passwordInput.pack(pady=(5, 5), ipady=5, ipadx=20)
        self._age = Label(self._root, text="Age", fg="#fff", bg="#FE3C72")
        self._age.config(font=("Monsterrat", 16))
        self._age.pack(pady=(5, 5))
        self._ageInput = Entry(self._root)
        self._ageInput.insert(0, data[0][4])
        self._ageInput.pack(pady=(5, 5), ipady=5, ipadx=20)
        self._city = Label(self._root, text="City", fg="#fff", bg="#FE3C72")
        self._city.config(font=("Monsterrat", 16))
        self._city.pack(pady=(5, 5))
        self._cityInput = Entry(self._root)
        self._cityInput.insert(0, data[0][6])
        self._cityInput.pack(pady=(5, 5), ipady=5, ipadx=20)

        self._update = Button(self._root,
                              fg="#fff",
                              bg="#FE3C72",
                              text="Update Info",
                              font=('Monsterrat', 10, 'bold'),
                              relief=RIDGE,
                              command=lambda: self.update_info())
        self._update.pack(pady=(10, 5), ipady=5, ipadx=10)

    def update_info(self):

        flag = self.db.update_info(self._passwordInput.get(),
                                   self._ageInput.get(), self._cityInput.get(),
                                   self.user_id)
        if flag == 1:
            messagebox.showinfo("Success", "Profile Updated")
        else:
            messagebox.showerror("Error", "Some Error Occured. Try Again")

    def view_proposals(self, index=0):
        try:
            data = self.db.fetch_proposals(self.user_id)

            new_data = []
            for i in data:
                new_data.append(i[3:])

            if index == 0:
                self.clear()
                self.mainWindow(new_data, flag=2, index=0)
            else:
                if index < 0:
                    messagebox.showerror("No User Found", "Click on Next")
                elif index == len(new_data):
                    messagebox.showerror("No User Left", "Click on Previous")
                else:
                    self.clear()
                    self.mainWindow(new_data, flag=2, index=index)
        except:
            messagebox.showerror("Sorry!", "No Proposals Found")

    def view_requests(self, index=0):
        try:
            data = self.db.fetch_requests(self.user_id)

            new_data = []
            for i in data:
                new_data.append(i[3:])

            if index == 0:
                self.clear()
                self.mainWindow(new_data, flag=3, index=0)
            else:
                if index < 0:
                    messagebox.showerror("No User Found", "Click on Next")
                elif index == len(new_data):
                    messagebox.showerror("No User Left", "Click on Previous")
                else:
                    self.clear()
                    self.mainWindow(new_data, flag=3, index=index)
        except:
            messagebox.showerror("Sorry!", "No Requests Sent")

    def view_matches(self, index=0):
        try:
            data = self.db.fetch_matches(self.user_id)

            new_data = []
            for i in data:
                new_data.append(i[3:])

            if index == 0:
                self.clear()
                self.mainWindow(new_data, flag=4, index=0)
            else:
                if index < 0:
                    messagebox.showerror("No User Found", "Click on Next")
                elif index == len(new_data):
                    messagebox.showerror("No User Left", "Click on Previous")
                else:
                    self.clear()
                    self.mainWindow(new_data, flag=4, index=index)
        except:
            messagebox.showerror("Sorry!", "No Matches Found")
Beispiel #28
0
def handle_docs(message):
    try:
        chat = message.chat.id
        db = DBHelper()
        state = db.get_state(chat)
        if not db.get_state(chat):
            bot.send_message(chat, 'Начините работу с ботом командой /start.')
            return 0
        db.close()
        if state == 6:
            if message.document:
                if message.document.file_id:
                    extension = message.document.file_name.split('.')[-1]
                    if extension not in [
                            'pdf', 'docx', 'doc', 'zip', 'txt', 'rtf'
                    ]:
                        bot.send_message(
                            chat,
                            'Неправильный формат файла. Пожалуйста, отправьте резюме в формате *pdf*, *zip*, *rtf*, *txt* или *docx*!',
                            parse_mode="Markdown")
                        return 0
                    if message.document.file_size > 15000000:
                        bot.send_message(
                            chat,
                            'Ваше резюме слишком большое по объёму.\nПожалуйста, напишите нам на почту: [email protected]'
                        )
                        return 0
                    file_info = bot.get_file(message.document.file_id)
                    text = 'Резюме отправляется.'
                    bot.send_message(chat, text)
                    mail_text = get_mail_text(chat, message.chat)
                    with open(
                            'resumes/' + message.document.file_id + '.' +
                            extension, "wb") as file:
                        response = requests.get(
                            'https://api.telegram.org/file/bot{0}/{1}'.format(
                                config.token, file_info.file_path))
                        file.write(response.content)
                        print('Got it')
                        delete_user_info(chat, 1)
                        delete_user_info(chat, 2)
                        delete_user_info(chat, 3)
                        delete_user_info(chat, 4)
                    text = send_mail(
                        chat, 'resumes/' + message.document.file_id + '.' +
                        extension, mail_text, extension)
                    bot.send_message(chat, text)
            else:
                bot.send_message(
                    chat,
                    'Неправильный формат файла. Пожалуйста, отправьте резюме в формате  *pdf*, *zip*, *rtf*, *txt* или *docx*!',
                    parse_mode="Markdown")
        else:
            if message.document:
                if message.document.file_id:
                    logging.info('Chat, file: %s %s ' %
                                 (chat, message.document.file_id))
            information_text = ''
            markup = get_markup(state)
            data_info = get_user_info(chat)
            text = information_text + text_user_info(data_info)
            text += get_text(state)
            bot.send_message(chat,
                             text,
                             reply_markup=markup,
                             parse_mode="Markdown")
    except:
        print('Фатальная ошибка отправки резюме.')
        logging.info('Фатальная ошибка отправки резюме. %s,\n time: %s' %
                     (sys.exc_info()[0], time.asctime()))
Beispiel #29
0
if len(sys.argv) == 3:
    serialPort = sys.argv[1]
    baudRate = sys.argv[2]
    deviceAddress = sys.argv[3]
    logEnabled = sys.argv[4]
elif len(sys.argv) == 1:
    print('Command line: getweather.py serial_port serial_speed')
    print('Trying with serial_port = ' + serialPort + ' and serial_speed = ' +
          str(baudRate))
else:
    print('Command line: getweather.py serial_port serial_speed')
    sys.exit(1)

currenttime = time.time()
db = DBHelper(dbFileName)

device = Protocol(serialPort, baudRate, logEnabled)
if device.ping(deviceAddress):
    pressure, sernumP = device.getPressure(deviceAddress)
    if 10 < pressure < 1000:
        print('Pressure - ' + str(pressure) + ' mmHg')
        pressureSensorId = db.getSensorId(pressureSensorType, sernumP)
        db.storeValue(currenttime, pressure, pressureSensorId)
    humidity, sernumH = device.getHumidity(deviceAddress)
    if not math.isnan(humidity):
        print('Humidity - ' + str(humidity) + '%')
        humiditySensorID = db.getSensorId(humiditySensorType, sernumH)
        db.storeValue(currenttime, humidity, humiditySensorID)
    values = device.getTemp(deviceAddress)
    i = 1
Beispiel #30
0
def get_user_info(chat):
    db = DBHelper()
    info = db.get_user_info(chat)
    db.close()
    return info
Beispiel #31
0
# Instantiating the resource
class StudentsApi(Resource):
    @marshal_with(resource_fields)
    def get(self):
        return Students.query.all()


# Assigning a route for the api, to access enter in the URL... "http://doc.gold.ac.uk/usr/395/api"
# Will return all student records in the datbase in a JSON format
api.add_resource(StudentsApi, '/api')

# Initalise Bootstrap for application
Bootstrap(app)
# Initialise pymysql database connection
sqldb = DBHelper()
# Initialise SQLAlchemy database connection
db.init_app(app)
# Initialise flask-login
login_manager = LoginManager()
login_manager.init_app(app)


# Callback function for flask-login
@login_manager.user_loader
def load_user(user_id):
    # User object provided by SQLAlchemy
    return Users.query.get(int(user_id))


# Index route
class BaremetalStatus:

    """Baremetal computer Status.
    """

    def __init__(self):
        """Init function of class BaremetalStatus
        """
        self.db_client = DBHelper()

    def get_default_query(self):
        return {"cm_kind": "baremetal", "cm_type": "status_inventory"}

    def get_full_query(self, query_elem):
        elem = self.get_default_query()
        if query_elem:
            elem.update(query_elem)
        return elem

    def init_deploy_status(self, host):
        """Init the deploy status of host
        :param string host: the host name of baremetal computer
        """
        return self.init_status(host, "deploy")

    def init_power_status(self, host, flag_on=True):
        """Init the Power ON/OFF status of the host
        :param string host: the host name of baremetal computer
        """
        return self.init_status(host, "on" if flag_on else "off")

    def init_status(self, host, action):
        """init the status of baremetal computer
        :param string action: one of values in ["on", "off", "deploy"]
        :return: True means init status successfully, otherwise failed.
        """
        query_elem = self.get_full_query({"cm_id": host})
        # status cycle for deploy, OFF --> ON --> OFF
        # status cycle for power on, ON
        # status cycle for power off, OFF
        update_elem = {"transient": {"action": "{0}...".format(action),  # deploy, on, off
                                     "status_1": "unknown",  # status phase 1
                                     "status_2": "unknown",  # status phase 2
                                     "status_3": "unknown",  # status phase 3
                                     },
                       }
        if action == "deploy":
            # unknown, deploying, deployed, failed
            update_elem["status"] = "unknown"
        result = self.db_client.atom_update(query_elem, {"$set": update_elem})
        return result["result"]

    def update_deploy_command_result(self, host, result):
        """update the deploy result
        :param string host: the unique name of host
        :param boolean result: True means deploy command success, False means failed
        :return: a flag, True means update mongodb success, otherwise failed.
        """
        query_elem = self.get_full_query({"cm_id": host})
        update_elem = {"status": "deploying" if result else "failed", }
        result = self.db_client.atom_update(query_elem, {"$set": update_elem})
        return result["result"]

    def update_power_status(self, host, status, flag_on):
        """update the status of power ON/OFF
        :param string host: the unique name of host
        :param string status: status of "ON" or "OFF"
        :param boolean flag_on: True means power on, False means power off
        :return: True means udpate successfully, otherwise failed
        """
        query_elem = self.get_full_query({"cm_id": host})
        hosts_status = self.get_status(host)
        result = False
        if hosts_status and hosts_status[0]["status"] == "deployed":
            host_status = hosts_status[0]
            trans_status = {}
            flag_update = False
            if flag_on and host_status["transient"]["action"] == "on...":
                result = True
                if status == "ON":
                    trans_status["transient.action"] = "on"
                    trans_status["transient.status_1"] = "ON"
                    flag_update = True
            elif not flag_on and host_status["transient"]["action"] == "off...":
                result = True
                if status == "OFF":
                    trans_status["transient.action"] = "off"
                    trans_status["transient.status_1"] = "OFF"
                    flag_update = True
            if flag_update:
                update_result = self.db_client.atom_update(
                    query_elem, {"$set": trans_status})
                result = update_result["result"]
        return result

    def update_deploy_status(self, host, status):
        """update the status of deploy based on the cycle OFF --> ON --> OFF
        :param string host: the unique name of host
        :param string status: status of "ON" or "OFF"
        :return: True means udpate successfully, otherwise failed
        """
        query_elem = self.get_full_query({"cm_id": host})
        hosts_status = self.get_status(host)
        result = False
        if hosts_status and hosts_status[0]["status"] == "deploying":
            host_status = hosts_status[0]
            if host_status["transient"]["action"] == "deploy...":
                result = True
                trans_status = {}
                flag_update = False
                # phase 1, unknown --> OFF
                if host_status["transient"]["status_1"] == "unknown":
                    if status == "OFF":
                        log.debug(
                            "host {0} deploy monitor, step 1 ".format(host))
                        trans_status["transient.status_1"] = "OFF"
                        flag_update = True
                elif host_status["transient"]["status_1"] == "OFF":
                    # phase 2, unknown --> ON
                    if host_status["transient"]["status_2"] == "unknown":
                        if status == "ON":
                            log.debug(
                                "host {0} deploy monitor, step 2 ".format(host))
                            trans_status["transient.status_2"] = "ON"
                            flag_update = True
                    elif host_status["transient"]["status_2"] == "ON":
                        # phase 3, unknown --> OFF
                        if host_status["transient"]["status_3"] == "unknown":
                            if status == "OFF":
                                log.debug(
                                    "host {0} deploy monitor, step 3 ".format(host))
                                trans_status["transient.status_3"] = "OFF"
                                trans_status["transient.action"] = "deploy"
                                trans_status["status"] = "deployed"
                                flag_update = True
                if flag_update:
                    update_result = self.db_client.atom_update(
                        query_elem, {"$set": trans_status})
                    result = update_result["result"]
        return result

    def get_deploy_progress(self, host, host_status=None):
        """get the progress of deploy of host baremetal computer.
        :param string host: the unique ID of host
        :param dict host_status: the status document of host in mongodb
        :return: an integer number. -1 means error. 10 means before phase 1, 25, 50, 100 means the end of phase 1, 2, 3.
        """
        result = -1
        if not host_status:
            status_list = self.get_status(host)
            if status_list:
                host_status = status_list[0]
        if host_status:
            if host_status["status"] == "deploying":
                if host_status["transient"]["status_1"] == "unknown":
                    result = 10
                elif host_status["transient"]["status_1"] == "OFF":
                    result = 25
                    if host_status["transient"]["status_2"] == "ON":
                        result = 50
            elif host_status["status"] == "deployed":
                result = 100
        return result

    def get_power_progress(self, host, flag_on, host_status=None):
        """get the progress of power ON/OFF of host baremetal computer.
        :param string host: the unique ID of host
        :param boolean flag_on: True means power ON, False means OFF
        :param dict host_status: the status document of host in mongodb
        :return: an integer number. -1 means error. 10 means before phase 1, 100 means phase 1.
        """
        result = -1
        if not host_status:
            status_list = self.get_status(host)
            if status_list:
                host_status = status_list[0]
        if host_status:
            if host_status["status"] == "deployed":
                if host_status["transient"]["status_1"] == "unknown":
                    result = 10
                elif host_status["transient"]["status_1"] == "ON" if flag_on else "OFF":
                    result = 100
        return result

    def get_host_progress(self, host):
        """get the progress of host baremetal computer.
        :param string host: the unique ID of host
        :return: a dict of {"status": "deploy", "progress": 25, }, there are 5 status of host, namely deploy, poweron, poweroff, failed, unknown
        """
        result = {"status": "unknown", "progress": -1, }
        status_list = self.get_status(host)
        if status_list:
            host_status = status_list[0]
            if host_status["status"] == "deployed":
                # maybe any status in deploy, poweron, poweroff
                action = host_status["transient"]["action"]
                if action.startswith("on"):
                    result["status"] = "poweron"
                    result["progress"] = self.get_power_progress(
                        host, True, host_status)
                elif action.startswith("off"):
                    result["status"] = "poweroff"
                    result["progress"] = self.get_power_progress(
                        host, False, host_status)
                elif action.startswith("deploy"):
                    result["status"] = "deploy"
                    result["progress"] = self.get_deploy_progress(
                        host, host_status)
            elif host_status["status"] == "deploying":
                result["status"] = "deploy"
                result["progress"] = self.get_deploy_progress(
                    host, host_status)
            elif host_status["status"] == "failed":
                result["status"] = "failed"
        return result

    def get_status(self, host=None):
        """get the status of single or all baremetal computer(s)
        :param string host: the unique ID of host, None means get status of all hosts
        :return: a list of dict with the following formation [{"cm_id": "cm_id", "status":"status", "transient":{"action": "action", "status_1":"status_1", "status_2":"status_2", "status_3":"status_3"}}]

        """
        query_elem = self.get_full_query({"cm_id": host} if host else {})
        result = self.db_client.find(query_elem)
        return result["data"] if result["result"] else None

    def get_status_short(self, hosts=None):
        """get the short status of baremetal for hosts
        :param list hosts: a list of host or None means all hosts
        :return: a dict with the formation {"host1":"deployed", "host2": "deploying", "host3": "failed", "host4": "unknown", }
        """
        status_list = self.get_status()
        valid_hosts_status = [status for status in status_list if status[
            "cm_id"] in hosts] if hosts is not None else status_list
        result = {}
        for host in valid_hosts_status:
            result[host["cm_id"]] = host["status"]
        return result

    def get_status_summary(self, hosts=None):
        """get the summary status of baremetal for hosts
        :param list hosts: a list of host or None means all hosts
        :return: a dict with the formation {"deployed": 1, "deploying":2, "failed":2, "total": 5}
        """
        status_list = self.get_status()
        valid_hosts_status = [status for status in status_list if status[
            "cm_id"] in hosts] if hosts is not None else status_list
        result = {"deployed": 0, "deploying": 0, "failed": 0, "total": 0}
        for host in valid_hosts_status:
            result["total"] += 1
            result[host["status"]] += 1
        return result
Beispiel #33
0
    host = GetConfig(db_config, 'host')
    port = int(GetConfig(db_config, 'port'))
    user = GetConfig(db_config, 'user')
    password = GetConfig(db_config, 'password')
    db = GetConfig('yunying', 'db')

    in_type = 1
    if in_type == 1:
        dt = datetime.today().strftime('%Y%m%d')
    elif in_type == 2:
        dt = 'manual'
    file_name = file_name.replace('yymmdd', dt)
    table_name = "%s_%s" % (table_name, dt)

    # 连接数据库
    dbhelper = DBHelper(host, port, user, password, db)
    cur = dbhelper.conn_db()

    # 打开excel,获取数据
    excelhelper = ExcelHelper(file_dir, file_name)
    file = excelhelper.file_abspath()
    data = excelhelper.get_excel_data(sheet_index=0, column_index=3)

    # >>>>> 数据库
    # 判断表是否存在,不存在则创建,存在则清空表数据
    import_table_exists = dbhelper.table_exists(table_name)
    if import_table_exists == 0:
        with open("%s/%s" % (work_dir, create_sql), 'r',
                  encoding='utf-8') as ct:
            create_table_sql = ct.read()
            create_table_sql = create_table_sql % table_name
 def __init__(self):
     """Init function of class BaremetalStatus
     """
     self.db_client = DBHelper()
Beispiel #35
0
def db_add_user(user_id_hash, user_name):
    """Add a Telegram user to the database."""
    try:
        DBHelper().sql_add_user(user_id_hash, user_name)
    except DB_Error as db_error:
        raise ValueError(db_error)
Beispiel #36
0
class BaremetalPolicy:
    """Baremetal Policy. Get/Add/Delete user/group policy
    FIXME/TODO: It will add **permission access** that only admin can operate on poilicy later
    the formation of policy is
    {"_id" : "53727f1c93f9d73e90520090",
    "name" : "user1,user2,user3",
    "policy_type" : "user", # or "group"
    "policy" : "i[101-103]",
    "cm_kind" : "baremetal",
    "cm_type" : "policy_inventory"
    }
    """
    def __init__(self):
        """Construction fucntion
        """
        self.db_client = DBHelper()

    def add_user_policy(self, user, policy):
        """add a policy for an user.
        :param string user: a username
        :param string policy: one piece of policy, means user can access which baremetal servers, e.g. "i[001-004]"
        :return: UUID means add policy success, otherwise None for failed
        """
        return self.add_ug_policy("user", user, policy)

    def add_group_policy(self, group, policy):
        """add a policy for a group.
        :param string group: a group/project name
        :param string policy: one piece of policy, means this group/project can access which baremetal servers, e.g. "i[001-004]"
        :return: UUID means add policy success, otherwise None for failed
        """
        return self.add_ug_policy("group", group, policy)

    def add_ug_policy(self, type, name, policy):
        """add a policy for a specify *type*
        :param string type: the type of policy, currently supports **user** and **group**
        :param string name: the name in each type
        :param string policy: one piece of policy
        :return: UUID means add policy success, otherwise None for failed
        :rtype: string
        """
        add_elem = {
            "policy_type": type,
            "name": name,
            "policy": policy,
        }
        full_elem = self.get_full_query(add_elem)
        result = self.db_client.insert(full_elem)
        return None if not result[
            "result"] else self.db_client.convert_objectid_to_str(
                result["data"])

    def remove_policy(self, uuid):
        """remove a policy based on uuid.
        :param string uuid: an uuid of the removed policy
        :return: True means remove policy success, otherwise False
        """
        object_uuid = self.db_client.convert_str_to_objectid(uuid)
        elem = {
            "_id": object_uuid,
        }
        result = self.db_client.remove(elem)
        return result["result"]

    def get_policy_based_user_or_its_projects(self, user, projects):
        """get the merged policy based on the username and his/her related projects
        :param string user: only one valid username
        :param list projects: a list of project
        :return: a policy with hostlist string, or None if non-exist policy for user and its projects
        """
        user_policy = self.get_policy_based_user(user)
        group_policy = self.get_policy_based_group(collect_hostlist(projects))
        if user_policy or group_policy:
            if user_policy:
                valid_policy = user_policy
                if group_policy:
                    valid_policy.update(group_policy)
            else:
                valid_policy = group_policy
        else:
            return None
        all_policys = []
        for name in valid_policy:
            all_policys.extend(expand_hostlist(valid_policy[name]))
        return collect_hostlist(list(set(all_policys)))

    def get_policy_based_user(self, user):
        """get all the policies for a user
        :param string user: a username with hostlist formation
        :return: a dict of user and policy with the formation {"name1": "hostlist", "name2": "hostlist2"}
        """
        policys = self.get_all_user_policy()
        return self.merge_policy_based_ug(
            policys) if user == "all" else self.merge_policy_based_ug(
                policys, True, user)

    def get_policy_based_group(self, group):
        """get all the policies for a group/project
        :param string group: a group/project with hostlist formation
        :return: a dict of group and policy with the formation {"name1": "hostlist", "name2": "hostlist2"}
        """
        policys = self.get_all_group_policy()
        return self.merge_policy_based_ug(
            policys, False) if group == "all" else self.merge_policy_based_ug(
                policys, False, group)

    def merge_policy_based_ug(self, policys, flag_user=True, name=None):
        """merge policy based the name of user/group
        :param dict policys: all the possible policys for users/groups
        :param boolean flag_user: True means user, False means group
        :param string name: the name of one or more user/group, None means all user/groups
        :return: a dict of user/group and policy with the formation {"name1": "hostlist", "name2": "hostlist2"}
        """
        if policys:
            data = {}
            names = expand_hostlist(name) if name else None
            for puser in policys:
                users = expand_hostlist(puser)
                common_users = [u for u in users
                                if u in names] if names else users
                hosts = []
                for policy in policys[puser]:
                    hosts.extend(expand_hostlist(policy["policy"]))
                for user in common_users:
                    if user in data:
                        data[user].extend(hosts)
                    else:
                        data[user] = deepcopy(hosts)
            for user in data:
                data[user] = collect_hostlist(data[user])
            # flip data, combine duplicate values
            flipped_data = {}
            for user in data:
                if data[user] in flipped_data:
                    flipped_data[data[user]].append(user)
                else:
                    flipped_data[data[user]] = [user]
            # try to merge user with same hosts
            data = {}
            for value in flipped_data:
                data[collect_hostlist(flipped_data[value])] = value
            return data if data else None
        return None

    def get_all_user_policy(self, flag_merge=False):
        """get all the policies for all user
        :param boolean flag_merge: True meanse merge all possible user and policy into string
        :return: flag_merge is False, result is a dict of user and policy with the formation {"user1":['policy1', 'policy2'], "user2": [],}
        flag_merge is True, result is a dict of user/group and policy with the formation {"name1": "hostlist", "name2": "hostlist2"}
        """
        all_policys = self.get_all_policy()
        if all_policys:
            policys = all_policys.get("users", None)
            return policys if not flag_merge else self.merge_policy_based_ug(
                policys)
        return None

    def get_all_group_policy(self, flag_merge=False):
        """get all the policies for all group/project
        :param boolean flag_merge: True meanse merge all possible user and policy into string
        :return: flag_merge is False, result is a dict of group/project and policy with the formation {"group1":['policy1', 'policy2'], "group2": [],}
        flag_merge is True, result is a dict of user/group and policy with the formation {"name1": "hostlist", "name2": "hostlist2"}
        """
        all_policys = self.get_all_policy()
        if all_policys:
            policys = all_policys.get("groups", None)
            return policys if not flag_merge else self.merge_policy_based_ug(
                policys, False)
        return None

    def get_all_policy(self):
        """get all the policies for all users and group/project
        :return: a dict of group/project and policy with the formation {"users": {"user1": [], "user2": []}, "groups":{"group1":['policy1', 'policy2'], "group2": [],}}
        """
        policys = self._get_policy()
        if not policys:
            return None
        data = {"users": {}, "groups": {}}
        for policy in policys:
            name = policy["name"]
            type = policy["policy_type"]
            if type == "user":
                if name in data["users"]:
                    data["users"][name].append(policy)
                else:
                    data["users"][name] = [policy]
            elif type == "group":
                if name in data["groups"]:
                    data["groups"][name].append(policy)
                else:
                    data["groups"][name] = [policy]
        return data

    def _get_policy(self):
        """get all the records of policy
        :return: an ordered list of policy or None if failed
        """
        result = self.db_client.find(self.get_full_query())
        if result["result"]:
            records = result["data"]
            for record in records:
                record["_id"] = self.db_client.convert_objectid_to_str(
                    record["_id"])
            return sorted(records, key=lambda x: x["_id"])
        return None

    def get_default_query(self):
        return {
            "cm_kind": "baremetal",
            "cm_type": "policy_inventory",
        }

    def get_full_query(self, query_elem=None):
        elem = self.get_default_query()
        if query_elem:
            elem.update(query_elem)
        return elem
Beispiel #37
0
import uuid

import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

from flask import Flask
from flask import render_template
from flask import session
from flask import jsonify

from dbhelper import DBHelper
import dbconfig

DB = DBHelper(dbconfig.IP_ADDR)

plt.rcParams["figure.figsize"] = (8, 4)

app = Flask(__name__)
app.secret_key = 'qmOdTeca0nM2sq01JEN53DTTHoTlWStk'

GETPRICE_URL = "http://127.0.0.1:5008/rpistatus/{}"


@app.route("/")
def home():
    return render_template("home.html")


@app.route("/statusplot/<num>")
Beispiel #38
0
 def __init__(self):
     """Construction fucntion
     """
     self.db_client = DBHelper()
from telegram.ext import Updater, CommandHandler
from dbhelper import DBHelper
import json

# init the database helper
db = DBHelper()

TOKEN = '892132794:AAFkaq95dewuN-mLfTFYWSzWwfhalNz-ez4'
updater = Updater(TOKEN, use_context=True)


def hello(update, context):
    update.message.reply_text('Hello {}'.format(
        update.message.from_user.first_name))


#api message. text.
#remove /add
#just had an idea: when clicking inventory,
#a new temporary keyboard is passed that lists all the items


def add(update, context):
    text = update.message.text
    chat = update.message.from_user.id

    print(text, chat)
    # update.message.reply_text(
    #     'Hello {} and {}'.format(text, chat)
    # )
    db.add_item(text, chat)
Beispiel #40
0
from dbhelper import DBHelper
import dbconfig

DB = DBHelper(dbconfig.IP_ADDR)
try:
  conn = DB.connect()
  print("DB Connect Successful")
except Exception as e:
  print("DB Error in Connect DB", e)
finally:
  conn.close()

drawDF = DB.buildStatusDFFromDB(10)

print(drawDF)

Beispiel #41
0
# - *- coding: utf- 8 - *-
import sys
import os
import cgi

modulePath = os.path.dirname(__file__) + '/../../'
# modulePath = os.path.abspath('/home/weather') + '/'
sys.path.append(modulePath)
from dbhelper import DBHelper

method = 'mtd'
sensorNumber = 'sensornumber'

dbFileName = modulePath + 'weatherstation.db'
# dbFileName = modulePath + 'genweather.db'
db = DBHelper(dbFileName)
args = cgi.FieldStorage()
if len(args) == 0:
    sensors = db.getSensors()
    print 'Content-Type: text/html; charset=utf-8'
    print
    sensorshtml = """
    <title>Метеостанция</title>
    <h1>Датчики</h1>
    <hr>
    <table border=0>
    <tr>
        <td> № </td>
        <td>Тип</td>
        <td> s/n </td>
        <td>Описание</td>
Beispiel #42
0
class RadixEnschedeBot:
    db = None
    TOKEN = ""
    URL = "https://api.telegram.org/bot{}/".format(TOKEN)
    ADMIN = 0

    help_text = """
    === Basic commands ===
    (commands marked with "*" will be answered privately)
    /help * --- shows all commands.
    
    /info * --- some info about Tally
    /nick henk  --- change your nickname in this group to "henk" (max 12 letters).
    /nicks  --- overview of all nicknames 
    /products  --- overview of all added products
    /all_tallies  --- overview of all tallies
    /tallies * --- overview of your tallies
    /debtors --- list of people with a positive amount of (normal) tallies.
    /add grolschbier  --- add a product named "grolschbier" (max 12 letters)
    /all_history 10  --- show last 10 transactions (default 5, max. 99)
    /history 5 * --- show last 5 transactions by you (default 10, max. 99)
    /thanks henk  --- give henk a tally to thank him for something. (-1 for henk +1 for you)
    
    === Tally-ing ===
    You can Tally positivly and negatively between 1 and 99 
    Examples:
    +1  --- add one tally 
    16  --- add 16 tallies 
    -4  --- remove 4 tallies
    
    You can also tally some specific product
    Example:
    +1 coke  --- add one coke
    
    You can also tally some for someone else
    Example:
    sjaak 5  --- add 5 tallies for sjaak
    
    You can also tally some specific product for someone else
    Example:
    sjaak -3 beer  --- remove 3 beers for sjaak
    
    === STFU Tally ===
    If you start your sentence with a dot, Tally will ignore it.
    Example
    . hey Tally! Tally! hey Tally! TALLY!!!"""

    info_text = """Tally is a simple Telegram-bot He is created because someone was to lazy to stand up and tally his 
    beer. This someone rather preferred program a complete Telegram-bot. You're free to use Tally for your own 
    purposes, however Tally is confronted with alcoholic beverages on a regular basis. Therefore Tally, 
    nor it's maker can guarantee that Tally is and will stay functioning at a socially acceptable level. Honestly, 
    we wouldn't be surprised if Tally would get Korsakoff, or have some troubles with (temporary) black-outs. Let 
    alone that he stays alive. 
    
    - Wouter ([email protected])"""

    NOT_WHITESPACE = re.compile(r'[^s]')

    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/home/wouter/tally_out'
        self.stderr_path = '/home/wouter/tally_err'
        self.pidfile_path = '/tmp/tally.pid'
        self.pidfile_timeout = 5
        self.db = DBHelper()
        with open("config.json", "r") as data_file:
            data = json.load(data_file)
        self.ADMIN = data['ADMIN']
        self.TOKEN = data['TOKEN']
        self.URL = "https://api.telegram.org/bot{}/".format(self.TOKEN)

    def get_url(self, url):
        response = requests.get(url)
        content = response.content.decode("utf8")
        return content

    def get_json_from_url(self, url):
        content = self.get_url(url)
        js = json.loads(content)
        return js

    def get_updates(self, offset=None):
        url = self.URL + "getUpdates?timeout=1000"
        if offset:
            url += "&offset={}".format(offset)
        js = self.get_json_from_url(url)
        return js

    def get_last_chat_id_and_text(self, updates):
        num_updates = len(updates["result"])
        last_update = num_updates - 1
        text = updates["result"][last_update]["message"]["text"]
        chat_id = updates["result"][last_update]["message"]["chat"]["id"]
        return (text, chat_id)

    def get_last_update_id(self, updates):
        update_ids = []
        for update in updates["result"]:
            update_ids.append(int(update["update_id"]))
        return max(update_ids)

    def send_message(self, text, chat_id, reply_markup=None):
        text = urllib.parse.quote_plus(text)
        url = self.URL + "sendMessage?text={}&chat_id={}".format(text, chat_id)
        if reply_markup:
            url += "&reply_markup={}".format(reply_markup)
        self.get_url(url)

    def run(self):
        last_update_id = None
        while True:
            try:
                updates = self.get_updates(last_update_id)
                if "result" in updates:
                    if len(updates["result"]) > 0:
                        last_update_id = self.get_last_update_id(updates) + 1
                        self.extract_messages(updates)
            except ConnectionError as e:
                continue
            json_path = os.path.dirname(
                os.path.abspath(__file__)) + '/post.json'
            jsonFile = Path(json_path)
            print(jsonFile.is_file())
            if jsonFile.is_file():
                with open(json_path, 'r') as f:
                    data = f.read().replace('\n', '')
                    for tallyPost in self.decode_stacked(data):
                        x = tallyPost["amount"] + " " + tallyPost["product"]
                        self.handle_message(tallyPost["group"], x,
                                            tallyPost["user"], "", 'group')
                    f.close()
                os.remove(json_path)

    def decode_stacked(self, document, pos=0, decoder=json.JSONDecoder()):
        while True:
            match = self.NOT_WHITESPACE.search(document, pos)
            if not match:
                return
            pos = match.start()

            try:
                obj, pos = decoder.raw_decode(document, pos)
            except json.JSONDecodeError:
                # do something sensible if there's some error
                raise
            yield obj

    def extract_messages(self, updates):
        for update in updates["result"]:
            try:
                text = update["message"]["text"]
                chat = update["message"]["chat"]["id"]
                telegram_id = update["message"]["from"]["id"]
                name = update["message"]["from"]["first_name"]
                type = update["message"]["chat"]["type"]
                self.handle_message(chat, text, telegram_id, name, type)

            except Exception as e:
                print(e)
                traceback.print_stack()
                print(update)
                print("")

    def personal_message(self, chat, text, telegram_id, name):
        if str(telegram_id) != str(self.ADMIN):
            self.send_message("Add me to a group :)", telegram_id)
            return

        split_text = text.split()
        switcher = {'/add_chat': self.add_chat}
        fun = switcher.get(split_text[0], self.command_not_found)
        fun(chat, split_text, telegram_id)

    def add_chat(self, chat, split_text, telegram_id):
        self.db.add_chat(int(split_text[1]))
        self.send_message("Added " + str(split_text[1]), self.ADMIN)

    def handle_message(self, chat, text, telegram_id, name, type):
        text = text.lower()

        # Check if in group
        if type != 'group' and type != 'supergroup':
            self.personal_message(chat, text, telegram_id, name)
            return
        # Check if chat allowed
        if not self.db.check_chat(chat):
            self.send_message(
                "Ask Wouter van Harten (+31)6 833 24 277 to whitelist <" +
                str(chat) + ">", chat)
            self.send_message(
                "Activity from unknown chat <" + str(chat) +
                ">, maybe you can whitelist it with '/add_chat " + str(chat) +
                "' ?", self.ADMIN)
            return

        # Check for STFU
        if text[0] == ".":
            return
        # Check for command
        if text[0] == '/':
            self.handle_command(chat, text, telegram_id)
            return

        split_text = text.split()

        nsp = NumericStringParser()
        try:
            int(nsp.eval(split_text[0]).real)
            self.tally(split_text, chat, telegram_id, name)
            return
        except Exception as e:
            print(e)

        # Try for username
        user = self.db.get_user_by_name(chat, split_text[0])
        if user != False:
            del split_text[0]
            try:
                int(nsp.eval(split_text[0]).real)
                self.tally(split_text, chat, user.telegram_id, split_text[0],
                           False)
                return
            except Exception:
                self.send_message("unknown amount: " + split_text[0], chat)
                pass
            return
        self.send_message("Que? (" + text + ")", chat)

    def tally(self, split_text, chat, telegram_id, name, make_new_user=True):
        nsp = NumericStringParser()
        # We only drink an integer amount of real beer
        amount = int(nsp.eval(split_text[0]).real)
        if abs(amount) > 99:
            self.send_message(
                "Tally between -100 and 100, " + str(amount) + " given", chat)
            return
        if abs(amount) < 0.5:
            self.send_message("That's a bunch of nothing you have there", chat)
            return
        user = self.db.get_user_by_telegram_id(telegram_id)
        if (not make_new_user) & (user == False):
            self.send_message("Unknown user: "******"Unknown product: " + split_text[1], chat)
                return
        purchase = Purchase(user, product, amount, self.db.get_chat(chat))
        # Get old score and new score
        all_tallies = self.db.get_all_tallies(chat, user)
        if product.name in all_tallies.keys():
            new_score = copy.copy(all_tallies[product.name])
            old_score = new_score - amount
        else:
            old_score = 0
            new_score = amount
        # Tallied and balance message:
        message = "Tallied {1!s} {3!s} for {0!s} (current balance is {2!s} {3!s}).".format(
            user.name, amount, new_score, product.name)
        # Attach some additional message if called for If user remains on the wrong end with a positive tally,
        # add a simple notification & sometimes a personal message:
        if (old_score >= 0) and (new_score > 0) and (amount > 0):
            message += "\n{0!s} has run out of {3!s} and is consuming another person's {3!s}!".format(
                user.name, amount, new_score, product.name)
            # Every fourth product or tally of at least 4 products, remind the user personally
            if new_score % 4 == 0:
                self.snark(user, new_score, product)
            elif amount >= 4:
                self.snark(user, new_score, product)
        # If a user remains on the wrong end with a negative tally, a more encouraging message:
        elif (old_score >= 0) and (new_score > 0) and (amount < 0):
            message += "\n{0!s}, thank you for adding some {3!s} to your stock. You did not add enough to return to " \
                       "Tally's good graces, though!".format(
                user.name, amount, new_score, product.name)
        # Notify those who add exactly enough:
        elif (old_score >= 0) and (new_score == 0) and (amount < 0):
            message += "\n{0!s}, thank you for adding some {3!s} to your stock. Tally likes those who do their " \
                       "bookkeeping to the letter!".format(
                user.name, amount, new_score, product.name)
        # Warn a user if their last item is tallied:
        elif (old_score < 0) and (new_score >= 0):
            message += "\nBetter enjoy that {3!s}, {0!s}! You've depleted your stock!".format(
                user.name, amount, new_score, product.name)
            self.send_message(
                "{0!s}, your last {3!s} was just tallied!".format(
                    user.name, amount, new_score, product.name), telegram_id)
        # Send message & commit purchase to database
        self.send_message(message, chat)
        self.db.add_purchase(purchase)
        return

    def snark(self, user, new_score, product):
        # Unpack input
        productname = product.name
        telegram_id, username = user.telegram_id, user.name
        # Messages
        messages = [
            "Beste {0!s}, ter ere van deze speciale gelegenheid wil ik graag iets van de wijsheid van onze voormalige "
            "koningin met je delen:\n'Hee majesteit, ga eens {1!s} halen!'".
            format(username, productname),
            "Beste {0!s}, wat advies: {1!s} {2!s} schuld is {1!s} {2!s} schuld teveel!"
            .format(username, new_score, productname),
            "Beste {0!s}, wist je dat Albert Heijn XL tot 22:00 open is en ze daar {2!s} hebben?"
            .format(username, new_score, productname),
            "Beste {0!s}, voor jou is het geen {2!s}tijd, maar supermarkttijd!"
            .format(username, new_score, productname),
            "Je creëert nu een {2!s}probleem, en nee dat is geen poar neem".
            format(username, new_score, productname),
            "2 woorden, {3!s} letters: {2!s} halen!".format(
                username, new_score, productname,
                len(productname) + 5)
        ]
        # Random integer
        i = randint(0, len(messages))
        message = messages[i]
        # Alexcheck
        if (new_score > 19):
            extra_message = "\n\nOverweeg alsjeblieft het volgende zelfhulp nummer te bellen: Alex bierservice " \
                            "053-4338460 "
            message += extra_message
        else:
            extra_message = "\n\nRaadpleeg je agenda en https://www.biernet.nl/bier/aanbiedingen om dit probleem op " \
                            "te lossen. "
            message += extra_message
        # Send random message
        self.send_message(message, telegram_id)
        return

    def handle_command(self, chat, text, telegram_id):
        switcher = {
            '/help': self.show_help,
            '/info': self.show_info,
            '/nick': self.set_nick,
            '/nicks': self.show_nicks,
            '/products': self.show_products,
            '/debtors': self.show_debtors,
            '/all_tallies': self.show_all_tallies,
            '/tallies': self.show_tallies,
            '/add': self.add_product,
            '/all_history': self.show_all_history,
            '/history': self.show_history,
            '/thanks': self.thank_user,
            '/update': self.update_tally
        }
        split_text = text.split()
        command = split_text[0].split("@")[0]
        fun = switcher.get(command, self.command_not_found)
        fun(chat, split_text, telegram_id)
        return

    def command_not_found(self, chat, split_text, telegram_id):
        self.send_message("Command not found: " + split_text[0], chat)

    def show_help(self, chat, split_text, telegram_id):
        self.send_message(self.help_text, telegram_id)
        self.send_message(
            "Message answered privately. \nIf you didn't get my message, send me a private message and try again.",
            chat)

    def show_info(self, chat, split_text, telegram_id):
        self.send_message(self.info_text, telegram_id)
        self.send_message(
            "Message answered privately. \nIf you didn't get my message, send me a private message and try again.",
            chat)

    def set_nick(self, chat, split_text, telegram_id):
        if len(split_text) < 2:
            self.send_message("Provide new nick", chat)
            return
        if len(split_text[1]) > 12:
            self.send_message("Nick too long", chat)
            return
        if len(split_text[1]) < 2:
            self.send_message("Nick too short", chat)
            return
        user = self.db.get_user_by_telegram_id(telegram_id)
        old_nick = user.name
        user.name = split_text[1]
        self.db.add_user(user)
        self.send_message("Nick changed from " + old_nick + " to " + user.name,
                          chat)

    def show_nicks(self, chat, split_text, telegram_id):
        users = self.db.get_all_users(chat)
        message = "=== NICKS === \n"
        for user in users:
            message += str(user.telegram_id) + ": " + user.name + "\n"
        self.send_message(message, chat)

    def show_products(self, chat, split_text, telegram_id):
        products = self.db.get_all_products(chat)
        message = "=== PRODUCTS ===\n"
        for product in products:
            message += product.name + "\n"
        self.send_message(message, chat)

    def show_debtors(self, chat, split_text, telegram_id):
        users = self.db.get_all_users(chat)
        message = "=== DEBTORS ===\n"
        for user in users:
            shown_name = False
            totals = self.db.get_all_tallies(chat, user)
            for key, value in totals.items():
                if value > 0:
                    if not shown_name:
                        message += user.name + ":\n"
                        shown_name = True
                    message += key + ": " + str(value) + "\n"
            if shown_name:
                message += "\n"
        self.send_message(message, chat)

    def show_all_tallies(self, chat, split_text, telegram_id):
        users = self.db.get_all_users(chat)
        message = "=== All tallies ===\n"
        for user in users:
            shown_name = False
            totals = self.db.get_all_tallies(chat, user)
            for key, value in totals.items():
                if value != 0:
                    if not shown_name:
                        message += user.name + ":\n"
                        shown_name = True
                    message += key + ": " + str(value) + "\n"
            if shown_name:
                message += "\n"
        message += "Total:\n"
        allTallies = self.db.get_total_tallies(chat)
        for key, value in allTallies.items():
            message += key + ": " + str(value) + "\n"
        self.send_message(message, chat)

    def show_tallies(self, chat, split_text, telegram_id):
        message = "=== Tallies ===\n"
        user = self.db.get_user_by_telegram_id(telegram_id)
        totals = self.db.get_all_tallies(chat, user)
        for key, value in totals.items():
            message += key + ": " + str(value) + "\n"
        self.send_message(message, telegram_id)
        self.send_message(
            "Message answered privately. \nIf you didn't get my message, send me a private message and try again.",
            chat)

    def add_product(self, chat, split_text, telegram_id):
        if telegram_id != self.ADMIN:
            self.send_message(
                "🖕🖕🖕🖕🖕🖕🖕🖕🖕🖕🖕🖕🖕erw",
                chat)
            return
        self.db.add_product(Product(split_text[1], self.db.get_chat(chat)))
        self.show_products(chat, split_text, telegram_id)
        return

    def show_all_history(self, chat, split_text, telegram_id):
        if len(split_text) > 1:
            try:
                amount = int(split_text[1])
            except ValueError:
                self.send_message(
                    "Enter integer amount smaller than 99, " +
                    str(split_text[1]) + " given.", chat)
                return
        else:
            amount = 10
        purchases = self.db.get_last_purchases(chat, amount)
        message = "=== All history ===\n"
        for purchase in purchases:
            message += "(" + parse(purchase.date).strftime("%m/%d %H:%M") + ") " + str(purchase.amount) + " " + \
                       purchase.product.name + " by " + purchase.user.name + "\n"
        self.send_message(message, chat)

    def show_history(self, chat, split_text, telegram_id):
        if len(split_text) > 1:
            try:
                amount = int(split_text[1])
            except ValueError:
                self.send_message(
                    "Enter integer amount, " + split_text[1] + " given.", chat)
                return
        else:
            amount = 10
        user = self.db.get_user_by_telegram_id(telegram_id)
        if not user:
            self.send_message("User not found", chat)
            return
        purchases = self.db.get_last_purchases(chat, amount, user)
        message = "=== History ===\n"
        for purchase in purchases:
            message += "(" + parse(purchase.date).strftime("%m/%d %H:%M") + ") " + str(purchase.amount) + " " + \
                       purchase.product.name + " by " + purchase.user.name + "\n"
        self.send_message(message, telegram_id)
        self.send_message(
            "Message answered privately. \nIf you didn't get my message, send me a private message and try again.",
            chat)

    def thank_user(self, chat, split_text, telegram_id):
        if len(split_text) < 2:
            self.send_message("No receiver given", chat)
            return
        receiver = self.db.get_user_by_name(chat, split_text[1])
        if receiver == False:
            self.send_message("Unknown user: "******"Thanks " + receiver.name + "! \nI don't know what you did " + receiver.name + ", but " + user.name + \
                  " would like to thank you! \n" + user.name + \
                  " has granted you a tally from his/her own pocket \nEnjoy, Tally"
        self.send_message(message, chat)

    def update_tally(self, chat, split_text, telegram_id):
        if telegram_id != self.ADMIN:
            self.send_message("🖕🖕🖕🖕🖕🖕", chat)
            return
        f = open(
            os.path.dirname(os.path.abspath(__file__)) + "/" + "update_tally",
            "w+")
        self.send_message("I will update shortly..", chat)
        f.close()

    def test(self):
        jsonFile = Path('post.json')
        if jsonFile.is_file():
            with open('post.json', 'r') as f:
                data = f.read().replace('\n', '')
                for tallyPost in self.decode_stacked(data):
                    x = tallyPost["amount"] + " " + tallyPost["product"]
                    self.handle_message(tallyPost["group"], x,
                                        tallyPost["user"], "", 'group')
                f.close()
            os.remove('post.json')
Beispiel #43
0
 def __init__(self):
     """Construction fucntion
     """
     self.db_client = DBHelper()
Beispiel #44
0
from dbhelper import DBHelper

db = DBHelper()
hosts = ['Dragon', 'Honor']
hDragon = [('2016-08-23 00:05:00', 150), ('2016-08-23 00:10:00', 157),
           ('2016-08-23 00:15:00', 183), ('2016-08-23 00:20:00', 32),
           ('2016-08-23 00:25:00', 123), ('2016-08-23 00:30:00', 2),
           ('2016-08-23 00:35:00', 312), ('2016-08-23 00:40:00', 41),
           ('2016-08-23 00:45:00', 21), ('2016-08-23 00:50:00', 342),
           ('2016-08-23 00:55:00', 12), ('2016-08-23 01:00:00', 21),
           ('2016-08-23 01:05:00', 31), ('2016-08-23 01:10:00', 31),
           ('2016-08-23 01:15:00', 34), ('2016-08-23 01:20:00', 51),
           ('2016-08-23 01:25:00', 66)]
hHonor = [('2016-08-23 00:05:00', 150), ('2016-08-23 00:10:00', 157),
          ('2016-08-23 00:15:00', 183), ('2016-08-23 00:20:00', 157),
          ('2016-08-23 00:25:00', 157), ('2016-08-23 00:30:00', 157),
          ('2016-08-23 00:35:00', 157), ('2016-08-23 00:40:00', 157),
          ('2016-08-23 00:45:00', 157), ('2016-08-23 00:50:00', 157),
          ('2016-08-23 00:55:00', 157), ('2016-08-23 01:00:00', 157),
          ('2016-08-23 01:05:00', 157), ('2016-08-23 01:10:00', 157),
          ('2016-08-23 01:15:00', 157), ('2016-08-23 01:20:00', 157)]
db.initdb(hosts)
db.insertval('Dragon', hDragon)
db.insertval('Honor', hHonor)
#db.selectval(hosts)
Beispiel #45
0
import json
import requests
import time
import urllib
import datetime
import random
from flask import Flask
#from flask.ext.rq import job

from dbhelper import DBHelper
from chat2classconversion import MLhelper
from WHDintegration import APIintegration

#from logservicerequest import LogRequest

db = DBHelper()
ml = MLhelper()
whdapi = APIintegration()

TOKEN = "540902937:AAFvz9_nV7xagpxiaT_8YZ_TnE2UYSSYSH0"
URL = "https://api.telegram.org/bot{}/".format(TOKEN)

correspondent_list = (open('correspondent.txt').read()).split("\n")

application = Flask(__name__)

def get_url(url):
    response = requests.get(url)
    content = response.content.decode("utf8")
    return content
Beispiel #46
0
import cgi
import time

modulePath = os.path.dirname(__file__) + '/../../'
# modulePath = os.path.abspath('/home/weather') + '/'
sys.path.append(modulePath)
from dbhelper import DBHelper

method = 'mtd'
version = 'version'
minThr = 'min'
maxThr = 'max'

dbFileName = modulePath + 'weatherstation.db'
# dbFileName = modulePath + 'genweather.db'
db = DBHelper(dbFileName)

def makeJSON(records):
    return json.JSONEncoder().encode({'sensors': db.getSensors(), 'records': records})

args = cgi.FieldStorage()
if len(args) == 0:
    sensors = db.getSensors()
    records = db.getLast()
    print 'Content-Type: text/html; charset=utf-8'
    print
    defaulthtml = """
    <title>Метеостанция</title>
    <h1>Погода</h1>
    <hr>"""
    defaulthtml += '<P>' + time.strftime("%d.%m.%Y %H:%M", time.localtime(records[0]['time'])) + '</P>'