Esempio n. 1
0
def insert_message_info(state):
    response = requests.get('https://api.cai.tools.sap/connect/v1/conversations/' + data['conversation']['id'],
      headers={'Authorization': '54187a3945f3af9ea86d40ebca0400f2'}
    )
    d = response.json()
    l = ''
    for i in range(len(d['results']['messages'])):
        l = l + ' ' + str(d['results']['messages'][i]['attachment']['content'])

    len_of_message = len(re.split('Thank you!!! | Took a note on that ', l)[-1].split(' '))
    my_con = DBConnect("d51dpnoammut78","mfeteccnqkvtor","8c505e55eb950c9b8a5a8a3fb3118b103fc7dabac9b7eb0737b156c9f695fad5",
                    'ec2-54-217-235-87.eu-west-1.compute.amazonaws.com')

    if state == 'no':
        my_con.db_connection()
        my_con.cur.execute("INSERT INTO messages_info(bad_mess_len) VALUES(%s);", [len_of_message])
        my_con.cur.execute("SELECT ROUND(AVG(bad_mess_len)) FROM messages_info;")
        av = my_con.cur.fetchone()[0]
        my_con.cur.execute("UPDATE messages_stats SET bad_mess_avr = %s",[av])
        my_con.end_connection()
    elif state == 'yes':
        my_con.db_connection()
        my_con.cur.execute("INSERT INTO messages_info(good_mess_len) VALUES(%s);", [len_of_message])
        my_con.cur.execute("SELECT ROUND(AVG(good_mess_len)) FROM messages_info;")
        av = my_con.cur.fetchone()[0]
        my_con.cur.execute("UPDATE messages_stats SET good_mess_avr = %s",[av])
        my_con.end_connection()
Esempio n. 2
0
def geoYN(args, db_params):
    ''' Function that provides data translation between functions
        and contains main cycle for performing queries to API and
        updating data on sereve.
    '''
    # storage for distance and travel time
    km_time = [(0, 0), (0, 0)]
    kt = namedtuple('kt', ['km', 'time'])

    with DBConnect(**db_params) as sql:
        if args.count:
            print("Кол-во маршрутов без расстояния: ", sql.count_empty_rows())
            return

    start = time.localtime()
    print('Script started at {}.'.format(time.strftime("%d-%m-%Y %H:%M",
                                                       start)))

    while True:
        try:
            with DBConnect(**db_params) as sql:
                # Row without distance
                row = sql.empty_dist()
                if not row:
                    break  # if no rows - we're done

                id_, _pointA, latA, lonA, _pointB, latB, lonB = row

                # YN_fast = 1 selects the fastest route, 0 the shortest route
                for n in (0, 1):
                    km_time[n] = kt(
                        *get_km_time(n, latA, lonA, latB, lonB, id_))

                sql.update_dist(id_, km_time)

                # tracking because script appeares to be frozen sometimes
                print(
                    "id = {}; route_km = {}; time = {}; trips_km = {}; time = {}"
                    .format(id_, *km_time[1], *km_time[0]))
        except Exception as e:
            print('Row: ', row)
            print(e)
            time.sleep(3)

    end = time.localtime()
    print('Script ended at {}.'.format(time.strftime("%d-%m-%Y %H:%M", end)))
    print('Total duration: {}.'.format(
        timedelta(seconds=time.mktime(end) - time.mktime(start))))
Esempio n. 3
0
def process_card_lookup(matches):
    with DBConnect(settings.CARD_DB) as conn:
        conn.set_trace_callback(logging.info)
        cur = conn.cursor()

        results = []
        for match in matches:
            for group in match:  # a 2-tuple, [[group 1]] and \[\[group2\]\]
                if not group:
                    continue

                # try to search exact matches
                row = process_exact_match(group, cur)
                if (row is not None):
                    results.append(row)

                else:  # try to search for non-exact matches
                    row = process_nonexact_match(group, cur)
                    if row == "Error":
                        continue
                    if (row is not None):
                        results.append(row)

                    else:  # try to search by card ID
                        row = process_card_id_match(group, cur)
                        if (row is not None):
                            results.append(row)

        return generate_reply_message(results, cur)
Esempio n. 4
0
def clear():
    connection = DBConnect()
    try:
        cursor = connection.cursor()

        queries = Query.truncate_query(Tables.USER_TABLE_NAME, Tables.USER_FOLLOW_TABLE_NAME, Tables.THREAD_TABLE_NAME,
                                       Tables.THREAD_VOTES_TABLE_NAME, Tables.THREAD_SUBSCRIBES_TABLE_NAME,
                                       Tables.POST_TABLE_NAME, Tables.POST_VOTES_TABLE_NAME, Tables.FORUM_TABLE_NAME)
        for query in queries:
            cursor.execute(query)
    except Exception as e:
        return {'code': Codes.UNKNOWN_ERROR, 'response': str(e)}
    finally:
        connection.close()

    return {'code': Codes.OK, 'response': 'OK'}
Esempio n. 5
0
def status():
    connection = DBConnect()
    try:
        cursor = connection.cursor()

        result = {}
        tables = [Tables.USER_TABLE_NAME, Tables.THREAD_TABLE_NAME, Tables.FORUM_TABLE_NAME, Tables.POST_TABLE_NAME]
        for table in tables:
            query = Query.select.format(columns='count(*)', table=table)
            cursor.execute(query)
            result[table] = cursor.fetchone()[0]
    except Exception as e:
        return {'code': Codes.UNKNOWN_ERROR, 'response': str(e)}
    finally:
        connection.close()

    return {'code': Codes.OK, 'response': result}
Esempio n. 6
0
def main():
    # Reading config and setting parameters
    config = {}
    try:
        with open('config.ini', 'r') as f:
            for line in f:
                # Ignore lines started with "#" and blank lines
                if not line.startswith('#') and line.strip():
                    k = line[:line.index(':')].strip()
                    v = line[line.index(':') + 1:].strip()
                    config[k] = v

    except ValueError:
        writelog('Error: config.ini have unappropriate lines: ' + line)
        sys.exit(1)

    conn = DBConnect(server=config['server'], db=config['db'])
    UserInfo = namedtuple(
        'UserInfo', ['UserID', 'ShortUserName', 'AccessType', 'isSuperUser'])
    refs = defaultdict(dict)
    try:
        with conn as sql:
            if sql.get_version_for_comparison() != version_info[:2]:
                raise tkr.UpdateRequiredError(version_info[:2])

            access_permitted = sql.access_check()
            if not access_permitted:
                tkr.AccessError()
                sys.exit()

            # load references
            user_info = UserInfo(*sql.get_user_info())
            for ref_type, ref_id, ref_name in sql.get_references():
                refs[ref_type][ref_name] = ref_id

        # Run app
        root = tkr.RepairTk()
        app = tkr.RepairApp(root=root,
                            connection=conn,
                            user_info=user_info,
                            references=refs)
        app.run()

    except SQLError as e:
        # login failed
        if e.args[0] in ('28000', '42000'):
            tkr.LoginError()
        else:
            raise

    except tkr.UpdateRequiredError as e:
        writelog(e)
        tkr.ReinstallRequiredError()
Esempio n. 7
0
def index():
    global data

    my_con = DBConnect("d51dpnoammut78","mfeteccnqkvtor","8c505e55eb950c9b8a5a8a3fb3118b103fc7dabac9b7eb0737b156c9f695fad5",
                    'ec2-54-217-235-87.eu-west-1.compute.amazonaws.com')
    
    data = json.loads(request.get_data())
    if data['nlp']['intents'][0]['slug'] == 'no':
        my_con.update_bad_conv()
        insert_message_info('no')
        return jsonify( 
        status=200, 
        replies=[{ 
          'type': 'text', 
          'content': 'Take a note on that!',
        }], 
        conversation={ 
          'memory': { 'key': 'value' } 
        } 
      ) 
    else:
        my_con.update_good_conv()
        insert_message_info('yes')
        return jsonify( 
        status=200, 
        replies=[{ 
          'type': 'text', 
          'content': 'Thank you!!!', 
        }], 
        conversation={ 
          'memory': { 'key': 'value' } 
        } 
      )

    return 'None'  
Esempio n. 8
0
def schedule():
    config = ConfigParser()
    config.read("./app_config.ini")
    db_name = config.get("APP_SETTINGS", "db_name")
    db_user = config.get("APP_SETTINGS", "db_user")
    db_password = config.get("APP_SETTINGS", "db_password")
    db_host = config.get("APP_SETTINGS", "db_host")
    db_port = config.get("APP_SETTINGS", "db_port")

    gcal_events = GetEvents(config.get("APP_SETTINGS", "rpc_server"))
    dbcon = DBConnect(db_user, db_password, db_host, db_port, db_name)
    users = dbcon.get_sms_users()
    today = datetime.date.today()

    for user in users:
        creds = pickle.loads(user[4])
        events_list = gcal_events.get_gcal_events(creds, "calendar", "v3",
                                                  today.strftime("%m/%d/%Y"))
        if events_list != "No events":
            message = format_message(events_list)
            send_events(config.get("APP_SETTINGS", "sms_url"), user[6],
                        message)
Esempio n. 9
0
def main():
    check_meta_update()
    # Check connection to db and permission to work with app
    try:
        with DBConnect(server='s-kv-center-s59', db='LogisticFinance') as sql:
            access_permitted = sql.access_check()
            if not access_permitted:
                tkp.AccessError()
                sys.exit()

            UserInfo = namedtuple('UserInfo',
                ['UserID', 'ShortUserName', 'AccessType', 'isSuperUser',
                 'GroupID', 'PayConditionsID']
            )

            # load references
            user_info = UserInfo(*sql.get_user_info())

            print(user_info)
            # user_info = UserInfo(24, 'TestName', 2, 1, None, 2)
            # Restriction: users in approvals_for_first_stage
            # should have different names to be distinguished
            refs = {'connection': sql,
                    'user_info': user_info,
                    'mvz': sql.get_MVZ(user_info),
                    'categories': sql.get_categories(user_info),
                    'pay_conditions': sql.get_pay_conditions(),
                    'allowed_initiators':
                        sql.get_allowed_initiators(user_info.UserID,
                                                   user_info.AccessType,
                                                   user_info.isSuperUser),
                    'approvals_for_first_stage':
                        sql.get_approvals_for_first_stage(),
                    'status_list': sql.get_status_list()
                    }
            for k, v in refs.items():
                assert v is not None, 'refs[' + k + '] value is None'
            # Run app
            app = tkp.PaymentApp(**refs)
            app.mainloop()

    except SQLError as e:
        # login failed
        if e.args[0] in ('28000', '42000'):
            #writelog(e)
            tkp.LoginError()
        else:
            raise
Esempio n. 10
0
def main():
    check_meta_update()
    # Check connection to db and permission to work with app
    # If development mode then 1 else 0
    db_info = pwd.access_return(0)
    conn = DBConnect(server=db_info.get('Server'),
                     db=db_info.get('DB'),
                     uid=db_info.get('UID'),
                     pwd=db_info.get('PWD'))
    try:
        with conn as sql:
            UserLogin = getpass.getuser()
            # UserLogin = '******'
            access_permitted = sql.access_check(UserLogin)
            if not access_permitted:
                tkp.AccessError()
                sys.exit()

            UserInfo = namedtuple(
                'UserInfo',
                ['UserID', 'ShortUserName', 'AccessType', 'isSuperUser'])

            # load references
            user_info = UserInfo(*sql.get_user_info(UserLogin))
            # print(user_info)
            # Restriction: users in approvals_for_first_stage
            # should have different names to be distinguished
            refs = {
                'connection': sql,
                'user_info': user_info,
                'mvz': sql.get_objects(),
                'type_business': sql.get_type_business(),
                'status_list': sql.get_status_list()
            }
            for k, v in refs.items():
                assert v is not None, 'refs[' + k + '] value is None'
            # Run app
            app = tkp.PaymentApp(**refs)
            app.mainloop()

    except SQLError as e:
        # login failed
        if e.args[0] in ('28000', '42000'):
            # writelog(e)
            tkp.LoginError()
        else:
            raise
Esempio n. 11
0
    def shorten_url(self):
        db_connect = DBConnect("url.db")

        if not db_connect.is_long_url_in_database(self.long_url):
            '''generate a unique token for the url
               if we find a unique token that is 6 characters we can stop
               otherwise increase the length of the characters by 1 until we find a unique token'''
            for index in range(6, 11):
                short_url = self.__generate_token(index)

                if not db_connect.is_short_url_in_database(short_url):
                    url_shortener_model = UrlShortenerModel(
                        0, self.long_url, short_url)
                    db_connect.insert_url(url_shortener_model)
                    return "https://r.com/" + short_url
        else:
            url_shortener_model = db_connect.get_shortened_url(self.long_url)
            return "https://r.com/" + url_shortener_model.short_url
Esempio n. 12
0

# 키:해시태그, 값:횟수 형식으로 저장하기 위한 빈 딕셔너리 선언
dict_data = {}
# alt 속성의 값인 제목과 해시태그 중 해시태그 만을 가져오기 위한 Okt(Tiwitter) 객체 생성
tw = Okt()
# alt_list에 담긴 값의 크기만큼 반복한다.
for alt in alt_list:
    # pos 메서드를 통해 alt 속성의 모든 해시태그의 값을 (값, 품사) 형태의 튜플을 요소로 갖는 리스트로 반환한다.
    temp = tw.pos(alt, norm = True)
    # 리스트의 크기만큼 반복한다.
    for data in temp:
        # 품사가 만약 해시태그이면
        if data[1] == "Hashtag":
            # 결과 값을 저장할 딕셔너리에 값이 있는지 확인하고 없다면 새로이 키를 추가하고 0, 있다면 기존 키에 1을 더해준다.
            if not (data[0] in dict_data):
                dict_data[data[0]] = 0
            dict_data[data[0]] += 1

# 딕셔너리를 횟수를 가지고 내림차순으로 정렬한다.
keys = sorted(dict_data.items(), key = lambda x:x[1], reverse = True)
# 1~15위 까지의 키:값을 출력한다.
for k, v in keys[:15]:
    print("{}({})".format(k, v))

# 드라이버를 종료한다.
driver.close() 

# 객체 생성 및 insert 메서드 호출
db = DBConnect()    
db.insert(keys[:15])
Esempio n. 13
0
def db_cursor():
    with DBConnect(settings.CARD_DB) as conn:
        cur = conn.cursor()
        yield cur
# Mutable dictionary for checking if the image is a street view image from Bing Maps, initially set to false
_street_view = {'streetView': False}

connect_to_db = False

# Creating a instance of Flask
app = Flask(__name__)
# Specifying the file upload directory using the Flask config method
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Creating a 24 character secret key using the os.urandom method, this is required when submitting a form using a
# csrf token
app.secret_key = os.urandom(24)

# Creating a instance of the class DBConnect
if connect_to_db == True:
    db = DBConnect()


# Defining a function for the file types that the user is allowed to upload to server, which takes the
# uploaded file as an argument
def allowedFile(filename):
    # Returning files that contain a . in their name, retrieving the extension by splitting the extension and
    # filename, then checking if the extension is in the ALLOWED_EXTENSIONS set
    return '.' in filename and \
    filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


# Home page
@app.route('/')
def index():
    # Displaying the home page
Esempio n. 15
0
from gui.filial_cp import Ui_MainWindow
from gui.splash_screen import Ui_SplashScreen
# from pyodbc import Error as SQLError
from log_error import writelog
from singleinstance import Singleinstance
from db_connect import DBConnect
from _version import __version__
import access
import sys
import os
import getpass

# connection properties
db_info = access.conn_info
sql = DBConnect(server=db_info.get('Server'),
                db=db_info.get('DB'),
                uid=db_info.get('UID'),
                pwd=db_info.get('PWD'))

LastStateRole = QtCore.Qt.UserRole


def _add_user_label(self):
    """ Adds user name in top right corner. """
    user_label = tk.Label(parent,
                          text='Пользователь: ' +
                          self.user_info.ShortUserName + '  Версия ' +
                          __version__,
                          font=('Arial', 8))
    user_label.pack(side=tk.RIGHT, anchor=tk.NE)

Esempio n. 16
0
def main():
    check_meta_update()
    # Check connection to db and permission to work with app
    # If debug mode then 1 else 0
    db_info = pwd.access_return(0)
    conn = DBConnect(server=db_info.get('Server'),
                     db=db_info.get('DB'),
                     uid=db_info.get('UID'),
                     pwd=db_info.get('PWD'))
    try:
        with conn as sql:
            UserLogin = getpass.getuser()
            # UserLogin = '******'
            access_permitted = sql.access_check(UserLogin)
            if not access_permitted:
                tkp.AccessError()
                sys.exit()

            UserInfo = namedtuple('UserInfo', [
                'UserID', 'ShortUserName', 'AccessType', 'isSuperUser',
                'GroupID', 'PayConditionsID'
            ])

            # load references
            user_info = UserInfo(*sql.get_user_info(UserLogin))
            # print(user_info)
            # Restriction: users in approvals_for_first_stage
            # should have different names to be distinguished
            refs = {
                'connection':
                sql,
                'user_info':
                user_info,
                'mvz':
                sql.get_MVZ(user_info),
                'categories':
                sql.get_categories(user_info),
                'pay_conditions':
                sql.get_pay_conditions(),
                'allowed_initiators':
                sql.get_allowed_initiators(user_info.UserID,
                                           user_info.AccessType,
                                           user_info.isSuperUser),
                'approvals_for_first_stage':
                sql.get_approvals_for_first_stage(),
                'status_list':
                sql.get_status_list()
            }

            # with open('payments.inf') as f:
            #     f.read(6)
            #     info_window = f.read(7)
            #     if info_window == '0':
            #         print('hello')
            for k, v in refs.items():
                assert v is not None, 'refs[' + k + '] value is None'
            # Run app
            app = tkp.PaymentApp(**refs)
            app.mainloop()

    except SQLError as e:
        # login failed
        if e.args[0] in ('28000', '42000'):
            # writelog(e)
            tkp.LoginError()
        else:
            raise