Ejemplo n.º 1
0
    def testGetTime(self):

        result = functions.get_time(1)
        self.assertEqual(result, "Morning")
        result = functions.get_time(2)
        self.assertEqual(result, "Afternoon")
        result = functions.get_time(3)
        self.assertEqual(result, "Evening")
        result = functions.get_time(4)
        self.assertEqual(result, "Red-Eye")
Ejemplo n.º 2
0
Archivo: bot.py Proyecto: ILLLIGION/-
def send_time(message):
    try:
        functions.get_time(message.text)
    except IndexError:
        bot.send_message(
            message.chat.id,
            "Я не знаю такой город или страну :(\nУточните название и напишите "
            "'/world_time' снова")
        return
    time = functions.get_time(message.text)
    bot.send_message(message.chat.id, time)
Ejemplo n.º 3
0
def main():

    if len(sys.argv) != 2:
        print(
            "\n **************USAGE ERROR************\n please have a carefull look at the usage of the program. \n"
        )
        print(
            "the usage of {} using the make file is : make hash='your hash' run. TIPS: do not put any sapce between the equal and your hash string\n"
            .format(sys.argv[0]))
        exit(-1)
    print(
        "***************DEBUT DE LA RECHERCHE DANS LA RAINBOW TABLE**************** \n\n",
        " \t HEURE DE DEBUT :", functions.get_time())

    #******import the parameters*******
    my_hash = str(sys.argv[1])
    data_base = params.data_base
    P = params.P
    i = P - 1

    print("Searching the password corresponding to the hash : \n", my_hash,
          "\n")
    #*******start the search in the ranbow table***********
    flag, returned_password = functions.check(my_hash, data_base)

    while i >= 0 and flag == False:
        j = i
        while j <= P:
            nom = functions.reduce_hash_to_pass(my_hash, j)
            my_hash = functions.sha256(nom)
            j += 1
        flag, returned_password = functions.check(my_hash, data_base)
        i -= 1

#*******cherk the result of the search***********
    if flag == True:
        print("Le mot de passe provient de : ", returned_password,
              " de la rainbow table, on applique : ", P - i + 1,
              " transformations de hachage et reduction")
        for j in range(i + 1):
            my_hash = functions.sha256(returned_password)
            returned_password = functions.reduce_hash_to_pass(my_hash, j)

        print("le mot de passe en clair est : ", returned_password)

    if flag == False:
        print("le mot de passe n existe pas dans notre base de donnée ")

    print("\tHEURE DE FIN  ", functions.get_time(), "\n")

    print("***************FIN DE LA RECHERCHE.***************")

    print("\nMERCI D AVOIR UTILISE NOTRE APP !!!")
Ejemplo n.º 4
0
 def __init__(self, **kargs):
     self.uid = kargs.get("uid", None)
     self.room_id = kargs.get("room_id", None)
     self.enter_time = kargs.get("enter_time", None)
     self.leave_time = kargs.get("leave_time", None)
     self.create_time = get_time()
     self.price = kargs.get("total_price", None)
     self.check_start()
Ejemplo n.º 5
0
	def create_recipe(self, url):
		dictionary = {}
		dictionary['rID'] = get_rID(url)
		direx = get_directions(url)
		dictionary['directions'] = []
		for d in direx:
			dictionary['directions'].append(
				DirectionCreator().create_direction(d, get_time(d), get_oven(d), get_stove(d)).export()
				)
		return Recipe(dictionary)
Ejemplo n.º 6
0
 def create_recipe(self, url):
     dictionary = {}
     dictionary['rID'] = get_rID(url)
     direx = get_directions(url)
     dictionary['directions'] = []
     for d in direx:
         dictionary['directions'].append(
             DirectionCreator().create_direction(d,
                                                 get_time(d), get_oven(d),
                                                 get_stove(d)).export())
     return Recipe(dictionary)
Ejemplo n.º 7
0
def save_follower_data(handle, data):
	time = get_time()

	follower_count = data[0]
	following_count = data[1]
	fav_count = data[2]
	latest_tweet_id = data[3]
	total_tweets = data[4]

	sql = """INSERT INTO {0} (handle_name, time, follower_count, following_count,fav_count,latest_tweet_id,total_tweets ) VALUES ("{1}", "{2}", "{3}", "{4}", "{5}", "{6}", "{7}")""".format(FOLLOWER_TABLE,handle, time, follower_count, following_count,fav_count,latest_tweet_id,total_tweets)
	print sql
	cursor.execute(sql)
	db.commit()
Ejemplo n.º 8
0
def check_session_data(data, jsondata):
    enter_time = data.get("enter_time", None)
    leave_time = data.get("leave_time", None)
    room_type = jsondata.get("room_type", None)
    if None or "" in (enter_time, leave_time, room_type):
        return False
    enter = datetime.strptime(enter_time, "%Y-%m-%d")
    leave = datetime.strptime(leave_time, "%Y-%m-%d")
    nowtime = get_time()
    nowtime = nowtime.split(" ")[0]
    now = datetime.strptime(nowtime, "%Y-%m-%d")
    if (leave - enter).days <= 0 or (enter - now).days < 0 or not room_type in ('A', 'B', 'C'):
        return False
    return True
Ejemplo n.º 9
0
def planning():  # для отправки сообщений в заданное время
    while True:
        chats = data.get_chats()
        for user in chats:
            time_now = f.get_time(data.get_utc(user[0]))
            if time_now == '00-00-00':
                data.new_day(user[0])
                time.sleep(5)
            if time_now == '20-00-00':
                time.sleep(5)
                bot.send_message(
                    user[0],
                    'Привет! Я просто хочу напомнить. Пожалуйста, заполни дневник эмоций на сегодня)',
                    reply_markup=keyboard)
            if time_now == '15-00-00' and (check.get_tuesday(user[0])
                                           or check.get_friday(user[0])):
                if diary.analize(user[0]) != None:
                    bot.send_message(
                        user[0],
                        'Привет! Я недавно проанализировал твой дневник и вот твои результаты:',
                        reply_markup=keyboard)
                    res = ans.analysis_sentiment(
                        ans.analysis_data(diary.analize(user[0])))
                    if not res:
                        bot.send_message(
                            user[0],
                            'Знаешь, в последнее время я вижу в тебе много негативных эмоций. Пожалуйста, если ты часто чувствуешь себя плохо, обратись к специалисту. Можешь воспользоваться этим анонимным телефоном доверия: \n 8-800-2000-122, звонок анонимный и бесплатный. Помни, это не стыдно!',
                            reply_markup=keyboard)
                    if res == 1:
                        bot.send_message(
                            user[0],
                            'Судя по твоему дневнику, с тобой все в порядке, ура!',
                            reply_markup=keyboard)
                    else:
                        bot.send_message(
                            user[0],
                            'Ох, как бы странно это не звучало, но меня настораживает обильное количество позитива в твоем дневнике. Знаешь, не всегда много хороших эмоций - хорошо. Если тебя беспокоит твое состояние, обратись к специалисту',
                            reply_markup=keyboard)
                time.sleep(5)
                check.tuesday_set(user[0], 0)
                check.friday_set(user[0], 0)
        time.sleep(60)
Ejemplo n.º 10
0
    def error(self, path):
        """
        Page that loads for a 404 error
        """
        headers = {}
        headers['Content-Type'] = 'text/html; charset=utf-8'

        output = []
        addline = output.append

        contents = []
        title = 'Page Not Found'
        contents.append('<h2>%s</h2>' % title)
        contents.append('<p>Sorry, but the web page you are trying to reach does not seem to exist on this website.</p>')
        contents.append('<p>The website address (URL) is:</p>')
        contents.append('<ul><li><a href="http://elections.raisethehammer.org/%s">http://elections.raisethehammer.org/%s</a></li></ul>' % ('/'.join(path), '/'.join(path)))
        contents.append('<p>You may have followed a broken link from another site or mistyped the URL you are trying to load.</p>')
        contents.append('<p>If you believe this is an error on the site, please <a href="mailto:[email protected]?subject=Broken Link on RTH Elections Page&body=http://elections.raisethehammer.org/%s">send us an email</a> with the details.</p>' % ('/'.join(path)))

        template = t.default
        template = template.replace('[[date]]', f.get_date())
        template = template.replace('[[time]]', f.get_time())
        template = template.replace('[[title]]', title)
        template = template.replace('[[section]]', 'The Hall of Lost Pages')
        template = template.replace('[[description]]', 'The page you are looking for could not be found.')
        template = template.replace('[[content]]', '\n'.join(contents))
        addline(template)

        page = html.write(
            site_domain = c.SITE_DOMAIN,
            site_name = c.SITE_NAME,
            css_path = c.CSS_PATH,
            css_files = c.CSS_FILES,
            js_path = c.JS_PATH,
            js_files = c.JS_FILES,
            page_title = title,
            page_author = 'Ryan McGreal',
            favicon_url = c.FAVICON_URL,
            body_content='\n'.join(output),
            rss = 'http://raisethehammer.org/feeds/articles_blogs/'
            )
        raise web.notfound(page) # make sure page is returned with an HTTP 404 status code
Ejemplo n.º 11
0
import telebot
import config
import logging
import functions
import datetime
import sqlite3
import phrases
from telebot import types
import time

logging.basicConfig(filename=config.log_file_name, level=logging.ERROR)
bot = telebot.TeleBot(config.token, threaded=False)
logging.getLogger("requests").setLevel(logging.WARNING)

try:
    logging.info('Connected ' + functions.get_time())

    @bot.message_handler(commands=['start'])
    def start(message):
        if not functions.does_user_exist(str(message.from_user.id)):
            functions.fill_phone(message)
        else:
            bot.send_message(message.chat.id, 'Ты уже зарегестрирован')

    @bot.message_handler(commands=['balance'])
    def get_balance(message):
        conn = sqlite3.connect('users.db')
        cursor = conn.cursor()
        query = 'SELECT Balance FROM users WHERE Telegram_id=?'
        row = cursor.execute(query, [message.from_user.id])
        row = row.fetchone()
Ejemplo n.º 12
0
import params
import functions

data_base_clair = params.data_base_clair
output_path = params.output_path
P = params.P

try:
    f_in = open(data_base_clair, "r")
    f_out = open(output_path, "w+")

except IOError:
    print(
        "Could not open either input or ouput file! Please check the correctness of both paths"
    )

print("DEBUT DE LA CREATION DE LA BASE DE DONNE A L'HEURE: ",
      functions.get_time())
for pass_clair in f_in:
    if len(pass_clair) != 0:
        #f_out.write(pass_clair)
        for i in range(P - 900):
            my_hash = functions.sha256(pass_clair)
            clair = functions.reduce_hash_to_pass(my_hash, i)
        f_out.write(pass_clair.rstrip("  \n") + " " + my_hash + "\n")

f_in.close()
f_out.close()

print("FIN DE LA CREATION DE LA BASE DE DONNE ", functions.get_time())
Ejemplo n.º 13
0
import functions as f
from functions import Event

INCLUDE_MANUAL_EXAMPLE = True

# open the data base
cal = f.Main_Calendar("demoDB.csv")

# print the week of the 7/8/2019
# you can choose any day of the week, and it will print the week sunday to saturday
cal.print_week("7/8/2019")

# creating new event
if INCLUDE_MANUAL_EXAMPLE:
    start = f.time_format(f.get_date("start"), f.get_time("start"))
    check_end = False
    while not check_end:
        end = f.time_format(f.get_date("end"), f.get_time("end"))
        check_end = f.date_validation(start, end)
    title = input("Title: ")
    event_type = input("Event type: ")
    price = input("Price: ")
    invitees = input("Invitees: ")
    location = input("Location: ")
    event = f.Event(start,
                    end,
                    title,
                    event_type=event_type,
                    price=price,
                    invitees=invitees,
                    location=location)
Ejemplo n.º 14
0
from keyword_finder import find_city
from keyword_finder import find_day
from training_functions import get_bow_vector


with open(r'models\MultinominalNB_model.pkl', 'rb') as m:
    ML_model = pickle.load(m)

previous_params = [None, None]
previous_intent = None
while(True):
    phraze = input()
    intent = ML_model.predict([get_bow_vector(phraze)])

    if intent == 0:
        params = [find_day(phraze), find_city(phraze)]

        if previous_intent == intent:
            if not params[0]:
                params[0] = previous_params[0]
            if not params[1]:
                params[1] = previous_params[1]

        previous_params = params
        previous_intent = intent
        print(get_weather(params[0], params[1]))
    if intent == 1:
        print(get_time())
    if intent == 2:
        play(phraze)
Ejemplo n.º 15
0
port_kamil = 4790
address_michal = '192.168.192.123'  #Michał
port_michal = 43516
address_przemek = '192.168.192.120'  #Przemek
port_przemek = 55555
address_adam = '192.168.192.15'  #Adam
port_adam = 8080
host_t = '192.168.192.253'
port_t = 8123
host = '192.168.192.12'
port = 52345
host = '127.0.0.1'
port = 52344

time_client = NTPClient()  #serwer
t = functions.get_time(host_t, port_t, time_client)
ntp = NTPClient()
#t = ntp.request('europe.pool.ntp.org').tx_time
sock_michal = functions.SockClient(address_michal, port_michal)
sock_przemek = functions.SockClient(address_przemek, port_przemek)
sock_adam = functions.SockClient(address_adam, port_adam)
sock_kamil = functions.SockClient(addres_kamil, port_kamil)
print("a")

last_t = t
while True:

    rec_zco = sock_michal.receive()
    T_ZCO = rec_zco['Tzco']

    resp = sock_michal & sock_adam
Ejemplo n.º 16
0
        for row in reader:
            videos.append([
                row['Title'], row['Author'], row['Author URL'],
                row['Timestamp'], row['Duration'], row['ID']
            ])

# grabbing the title, author, url and timestamp from the JSON about the videos available on YouTube storing them in a 2D array
data = json.loads(data)
for video in data:
    if check_videos(video['time'], videos):
        if "titleUrl" in video and "subtitles" in video:
            author = video['subtitles'][0]['name']
            author_url = video['subtitles'][0]['url']
            title = video['title'].replace("Watched ", "", 1)
            id = re.findall("watch\?v=(.*)", video['titleUrl'])[0]
            time = get_time(video['time'])
            duration = get_duration(url, id)
            if duration == -1:
                print(
                    "Daily API call limit has been reached, this will reset at midnight of your local time."
                )
                print("Saving the data that has been scraped already.")
                break
            elif duration == -2:
                continue
            videos.append([title, author, author_url, time, duration, id])
            print("+ " + title)

# store the 2D array containing videos into a CSV file called 'output.csv'
c_filepath = c_filepath if c_filepath else "output.csv"
with open(c_filepath, "w") as file:
Ejemplo n.º 17
0
 def test_get_time(self):
     with unittest.mock.patch('builtins.input',
                              side_effect=['asdfasdf', '', '5:5:5']):
         self.assertIsInstance(get_time("Text"), datetime.time)