예제 #1
0
 def analizar_command(self, comando, boton):
     if comando != None:
         if comando == "Enviado":
             clickeado_menu = self.botones[boton].enviado
             name_bot = self.botones[boton].name
             name_bot_men = self.botones[boton].Nbotones[clickeado_menu]
             send.send(name_bot, name_bot_men, self)
예제 #2
0
def sendEmail(values, server):
	print "in send email"
	values['from'] = 'BazaarFunda Team'
	values['url'] = 'http://www.bazaarfunda.com'
	template = EmailTemplate(template_name='PriceMovement.html', values=values)	
	msg = MailMessage(from_email='*****@*****.**', to_emails=[values['email']], subject='BazaarFunda Price Alert For You', body=template.render())
	send(mail_msg=msg, mail_server = server)
예제 #3
0
    def __init__(self, name, man):
        import time
        man[name] = 1

        temperature_file = '/sys/class/thermal/thermal_zone0/temp'
        interval = 10

        if os.path.isfile(temperature_file): 
            count = 0
            while 1:
                tempC = int(open(temperature_file).read()) / 1e3
                sendData=['CPU temperature', int(unix_time_millis(datetime.datetime.now())), ['Temperature']  , ['i'], [tempC], ['Celsius'], ['count='+str(count)]]
                print 'Sending data: ',sendData
                #packs and sends the data
                packet = packetmaker.make_data_packet(sendData)
                for pack in packet:
                    send(pack)
                #send a packet every 10 seconds
                time.sleep(interval)
                count = count + 1
        
        else:
            count = 0
            while 1:
                rint = random.randint(1, 100)
                sendData=['RandomNumber', int(unix_time_millis(datetime.datetime.now())), ['Random']  , ['i'], [rint], ['NA'], ['count='+str(count)]]
                print 'Sending data: ',sendData
                #packs and sends the data
                packet = packetmaker.make_data_packet(sendData)
                for pack in packet:
                    send(pack)
                #send a packet every 10 seconds
                time.sleep(interval)
                count = count + 1
예제 #4
0
파일: router.py 프로젝트: cdt2132/Router
def router():
    table, peers, listen_socket, port, send_sock = init()
    #Calls init
    t = time.time()
    #Gets current time
    log.print_log(port, table)
    #Prints initial routing table (this will be just neighbors)

    while(1):
        listen_socket.setblocking(0)
        ready = select.select([listen_socket],[],[], .005)
        #Sees if there is any data to be recieved, if so receive
        #If not, continue in the loop
        if ready[0]:
            data = listen_socket.recv(1024)
            #Receives data
            try:
                data = cPickle.loads(data)
                #After data is received, "unpickles" it
                #i.e turns it back into a list from a byte stream
                updated, peers, table = receive.update(data, table, peers, port)
                #calls the receive module's update function once the table is received
            except cPickle.UnpicklingError:
                continue
                #error handling
            if updated == True:
                log.print_log(port, table)
                #If the table was updated, print
        cur_t = time.time()
        #Gets current time
        if (cur_t - t) > 5:
            #If more than 5 seconds has gone by...
            t = cur_t
            #Sets the t to cur_t (so that the loop can be executed again)
            send.send(peers, table, send_sock, port)
예제 #5
0
    def post(self):
        file_body = self.request.files['pic'][0]['body']
        img = Image.open(BytesIO(file_body))
        img.save("current.jpg")
        img = np.array(img).astype('uint8')
        ml_response = yield predict.predict(img)
        gp = self.get_body_argument("gps")
        print(ml_response)

        # db = self.db()
        # details = yield db.find_one({"District": "Vellore"})
        with open("current.jpg", "rb") as f:
            ig = base64.b64encode(f.read())
            if int(send(gp, ig)) != 202:
                self.write(json.dumps({"status": "something went wrong"}))
            if not ml_response:
                if int(send(gp, ig,
                            em="*****@*****.**")) != 202 and int(
                                send(gp, ig)) != 202:
                    self.write(json.dumps({"status": "something went wrong"}))

            fire = firestore.Client()
            x = fire.collection("data").document("1")
            payload = {"gps": gp, "label": ml_response['img_label'], "img": ig}
            y = x.get().to_dict()['data']
            y.append(payload)
            x.set({"data": y})

        self.write(json.dumps({'flag': 'Everthing is coool'}))
예제 #6
0
def ssb():
    while 1:
        # print 'Thread sendsaveble start'
        o = 0
        while o < len(os.listdir('/home/pi')):
            if os.path.isfile('saveble' + str(o) +
                              '.csv') == True and os.path.getsize(
                                  '/home/pi/saveble' + str(o) + '.csv') > 0:
                saveble = open('saveble' + str(o) + '.csv', 'r')
                if saveble.readlines != []:
                    print 'i was there'
                    try:
                        if checkInternet() == True:
                            bcj('saveble' + str(o) + '.csv')
                            send('saveble' + str(o) + '.json')
                            saveble.close()
                            print 'saveble' + str(o) + ' has been send'
                            if os.path.isfile('saveble' + str(o) +
                                              '.csv') == True:
                                os.system('sudo rm saveble' + str(o) + '.csv')
                            else:
                                print 'not delete or not found'
                    except:
                        print 'error while sending'
            else:
                if os.path.isfile('saveble' + str(o) + '.csv') == True:
                    os.system('sudo rm saveble' + str(0) + '.csv')
            if os.path.isfile('saveble' + str(o) + '.json') == True:
                os.system('sudo rm saveble' + str(o) + '.json')
                print 'json delete'
            o = o + 1
예제 #7
0
    def update_main_from_file_senegal(self):
        try:
            query = open(self.sql_main ,'r').read()
            abo_for_query =','.join(self.num_abo_list)
            query = query.replace( '#', '(' + abo_for_query + ')')
            print '\n'
            print query
            print  '\n'
            while  True:
                try:
                      db = DB()
                except:
                      time.sleep(10)
                else:
                     break
            db.excute_many_for_senegal(
                query, self.map
                )

        except:
            import sys
            print  '='*40, 'ERROR', "="*40
            print sys.exc_info()

        else:
            # send an email
            while True:
                try:
                    body  ="""
            Bonjour,</br>
            Les fichiers suivants on etes traites comme  des fichiers a charger.</br>
            Les clients y figurant sont en  production </br>
            %s</br>
            Pour un volume de (%s) lignes  recues </br>
            Ce volume est reparti comme suit</br>
            %s</br>
            Cordialement</br>
            Service Informatique</br>
                            """%("</br>".join(self.map.keys() or []),
                    len(self.num_abo_list),
                    self.main_fichier
                    )
                    to = [ '*****@*****.**']
                    
                    """
                    to = ['*****@*****.**',
                         '*****@*****.**']
                    """
                    subject="[PCCI] Chargement fichier du %s """%self.TODAY     
                    send.send(att_path = None , body =body,
                                    to = to , subject =subject)
                except:
                    # Outlook a des preoblemes mais nous devons absolument
                    # envoyer l'email puisque le chargement a deja eu lieu
                    print 'Exception into send Message'
                    traceback.print_exc()
                    time.sleep(30)
                else:
                    # L'email est partie tout va bien
                    break
예제 #8
0
def ssw():
    while 1:
        # print 'Thread sendsavewifi start'
        o = 0
        while o < len(os.listdir('/home/pi')):
            if os.path.isfile('savewifi' + str(o) +
                              '.csv') == True and os.path.getsize(
                                  '/home/pi/savewifi' + str(o) + '.csv') > 0:
                savewifi = open('savewifi' + str(o) + '.csv', 'r')
                if savewifi.readlines != []:
                    print 'Je suis passe par la'
                    try:
                        if checkInternet() == True:
                            wcj('savewifi' + str(o) + '.csv')
                            send('savewifi' + str(o) + '.json')
                            savewifi.close()
                            print '\nSavewifi' + str(o) + ' has been send \n'
                            if os.path.isfile('savewifi' + str(o) +
                                              '.csv') == True:
                                os.system('sudo rm savewifi' + str(o) + '.csv')
                            else:
                                print 'not delete or not found'
                        else:
                            print "OMG CA MARCHE PAS"
                    except:
                        print 'error while sending'
            else:
                if os.path.isfile('savewifi' + str(o) + '.csv') == True:
                    os.system('sudo rm savewifi' + str(o) + '.csv')
            if os.path.isfile('savewifi' + str(o) + '.json') == True:
                os.system('sudo rm savewifi' + str(o) + '.json')
                print 'json delete'
            o = o + 1
예제 #9
0
파일: pymail.py 프로젝트: Max00355/PyMail
 def do_send(self, line):
     if not self.username or not self.password:
         print "You must login"
     else:
         to = raw_input("To: ")
         title = raw_input("Title: ")
         message = raw_input("Message: ")
         print send.send(to, title, message, self.username, self.password)
예제 #10
0
def data_packet(data):
    """
    This script makes a sensor packet and sends it to the NC.
    :param string data: The sensor data.
    """
    packet = packetmaker.make_data_packet(data)
    for pack in packet:
        send(pack)
예제 #11
0
 def do_send(self, line):
     if not self.username or not self.password:
         print "You must login"
     else:
         to = raw_input("To: ")
         title = raw_input("Title: ")
         message = raw_input("Message: ")
         print send.send(to, title, message, self.username, self.password)
예제 #12
0
def sender():
    if request.method == "GET":
        return render_template('sender.html')
    else:
        path = request.form['path']
        send(path, 9999)
        message = "SentSuccessfully"
        return redirect(url_for('success', message=message))
예제 #13
0
def get_workout():
	json_key 	= 'new_test.json'
	scope 		= ['https://spreadsheets.google.com/feeds']
	credentials = ServiceAccountCredentials.from_json_keyfile_name(json_key, scope)
	gc 			= gspread.authorize(credentials)
	wks 		= gc.open("Races").get_worksheet(2)
	now 		= datetime.datetime.now()
	datecell	= wks.find(str(now.month)+"/"+str(now.day)+"/"+str(now.year))
	send(str(wks.cell(datecell.row, datecell.col + 2).value))
예제 #14
0
 def do_send(self, line):
     
     try:
         line = line.split()
         amt = int(line[0])
         to = line[1]
         print send.send(amt, to)
     except:
         pass
예제 #15
0
def sendEmail(values, server):
    print "in send email"
    values['from'] = 'BazaarFunda Team'
    values['url'] = 'http://www.bazaarfunda.com'
    template = EmailTemplate(template_name='PriceMovement.html', values=values)
    msg = MailMessage(from_email='*****@*****.**',
                      to_emails=[values['email']],
                      subject='BazaarFunda Price Alert For You',
                      body=template.render())
    send(mail_msg=msg, mail_server=server)
예제 #16
0
def data_packet(data):
    """
    This script makes a sensor packet and sends it to the NC. 
    
    :param string data: The sensor data.
    
    """
    packet = packetmaker.make_data_packet(data)
    for pack in packet:
            send(pack)
예제 #17
0
def main() :
    users_info = read_file()
    for user in users_info :
        qr_code = user[0]
        email = user[1]
        full_name = user[2]
        name_image = email.split("@")[0]
        # sendemail function
        make_qr_code(qr_code, "/home/khoa/working/sendmail/images/{}.png".format(name_image))
        send(email, name_image,full_name)
예제 #18
0
def list_commands(user):
    commands = ""
    commands += u"» status" + "\n"
    commands += u"» play" + "\n"
    commands += u"» give treat" + "\n"
    commands += u"» clean" + "\n"
    commands += u"» pet" + "\n"
    commands += u"» feed" + "\n"
    commands += u"» give vitamins"
    send(user.userid, commands)
예제 #19
0
    def update_main_from_file_senegal(self):
      try:
        query1, query2 = self.sql_main.split(';')
        query1 = open(query1 ,'r').read()
        query2 = open(query2,'r').read()
        abo_for_query =','.join(self.num_abo_list)
        query2 = query2.replace( '#', '(' + abo_for_query + ')')
        while  True:
            try:
                  db = DB()
            except:
                  time.sleep(10)
            else:
                 break
        db.do_query(query2)
        db.excute_many_for_senegal(
            query1, self.map)
      
      except:
        import sys
        print sys.exc_info()

      else:
          # send an email
          while True:
                try:
                    body  ="""
        Bonjour,</br>
        Les fichiers suivants on etes traites comme des clients deja reabonnes.</br>
        Les clients y figurant ne seront plus contactes par le systeme.</br>
        %s</br>
        Pour un volume de (%s) lignes  recues </br> 
        Cordialement</br>
        Service Informatique</br>
                            """%("</br>".join(self.map.keys() or []),
                                 len(self.num_abo_list)
                                 )
                           
                    
                    to = [ '*****@*****.**']
                    """
                    to = ['*****@*****.**',
                         '*****@*****.**']
                    """
                    subject="[PCCI] Deja reabonnes du %s """%self.TODAY     
                    send.send(att_path = None , body =body,
                                      to = to , subject =subject)
                except:
                    # Outlook a des preoblemes mais nous devons absolument
                    # envoyer l'email puisque le chargement a deja eu lieu
                    time.sleep(10)
                else:
                    # L'email est partie tout va bien
                    break
예제 #20
0
파일: app.py 프로젝트: alhaponyfaraj/DMS
    def send_message(self, _):
        message1 = self.active_messages.text
        self.active_messages.text = ""
        if message1:
            self.chat_label.update_chat_log(
                f"[color=dd1920]{chat_instance.main_page.username_input.text}[/color] >{message1}"
            )
            send.send(username=chat_instance.main_page.username_input.text,
                      message=message1)

        Clock.schedule_once(self.focus_text_input, 0.1)
예제 #21
0
def decay_happiness():
    for user in User.query.all():
        user.happiness -= 1
        db.session.commit()
        if user.happiness == 30:
            send(user.userid, "I'm bored... Wanna play?")
        if user.happiness == 10:
            send(user.userid, "I'm really sad. Are you still there?")
        if user.happiness == 0:
            message = "Stitch ran away."
            death(user, message)
예제 #22
0
def decay_hunger():
    for user in User.query.all():
        user.hunger -= 1
        db.session.commit()
        if user.hunger == 30:
            send(user.userid, "Hey, I'm getting hungry. Feed me a snack!")
        if user.hunger == 10:
            send(user.userid, "I'm starving! Feed me or I'll die.")
        if user.hunger == 0:
            message = "Stitch died of hunger."
            death(user, message)
예제 #23
0
def decay_health():
    for user in User.query.all():
        user.health -= 1
        db.session.commit()
        if user.health == 30:
            send(user.userid,
                 "I'm feeling kind of gross. Maybe a bath will help.")
        if user.health == 10:
            send(user.userid, "Do you have any vitamins? I think I'm sick!")
        if user.health == 0:
            message = "Stitch died of an undetected terminal illness. RIP Stitch."
            death(user, message)
예제 #24
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-w",
                        "--word",
                        type=str,
                        help="Word to get sentiment for",
                        required=True)
    args = parser.parse_args()
    hero_name = args.word
    logger.info("Parameter Passed are " + str(args))
    key, host = load_config()
    send.send(key, host, hero_name)
예제 #25
0
def clean(user):
    if user.last_clean >= int(time.time()) - ONE_HOUR:
        send(user.userid, "I don't feel being cleaned right now.")
        return

    user.last_clean = int(time.time())
    user.health += 10
    if user.health >= 100:
        user.health = 100
    db.session.commit()

    message = "You cleaned me. I'm a bit healthier now!"
    send(user.userid, message)
예제 #26
0
def vitamin(user):
    if user.last_vitamin >= int(time.time()) - ONE_HOUR:
        send(user.userid, "I just had some vitamins, I don't want any more.")
        return

    user.last_vitamin = int(time.time())
    user.health += 20
    if user.health >= 100:
        user.health = 100
    db.session.commit()

    message = "You gave me vitamins. I'm much healthier now!"
    send(user.userid, message)
예제 #27
0
def feed(user):
    if user.last_feed >= int(time.time()) - ONE_HOUR:
        send(user.userid, "I just ate...")
        return

    user.last_feed = int(time.time())
    user.hunger += 20
    if user.hunger >= 100:
        user.hunger = 100
    db.session.commit()

    message = "You fed me. I'm " + hunger_to_state(user.hunger) + " now!"
    send(user.userid, message)
예제 #28
0
def pet(user):
    if user.last_pet >= int(time.time()) - ONE_HOUR:
        send(user.userid, "Give me some time, you just petted me!")
        return

    user.last_pet = int(time.time())
    user.happiness += 20
    if user.happiness >= 100:
        user.happiness = 100
    db.session.commit()

    message = "You petted me. I feel much happier!"
    send(user.userid, message)
예제 #29
0
def scanble(comp):
    dev_id = 0
    try:
        sock = bluez.hci_open_dev(dev_id)

    except:
        print "error accessing bluetooth device..."
        sys.exit(1)

    blescan.hci_le_set_scan_parameters(sock)
    blescan.hci_enable_le_scan(sock)
    stop = 0
    savebeacon = []
    c = open("scanble.csv", "w")
    while stop != 1:
        returnedList = blescan.parse_events(sock, 30)
        finalList = []
        for beacon in returnedList:
            if str(beacon[0:17]) not in str(finalList):
                finalList.append(str(beacon))
            else:
                pass
        savebeacon = finalList
        for beacon in finalList:
            stamp = time.time()
            beacon = beacon.replace("\"", "")
            macID = getserial()
            c.write(
                str(macID) + "," + str(stamp) + "," + beacon + ",ble_" +
                str(comp) + "\n")
        stop = stop + 1
        c.close()
    bcj('scanble.csv')
    o = 0
    if checkInternet() == True:
        try:
            send('scanble.json')
        except:
            print 'error while sending'
    else:
        while os.path.isfile('saveble' + str(o) + '.csv') == True:
            o = o + 1
        saveble = open('saveble' + str(o) + '.csv', 'a')
        z = o
        for beacon in savebeacon:
            stamp = time.time()
            fichtre = getserial()
            saveble.write(
                str(fichtre) + "," + str(stamp) + "," + beacon + ",sb_" +
                str(z) + "\n")
        saveble.close()
예제 #30
0
def play(user):
    #ensures that commands aren't too frequent
    if user.last_play >= int(time.time()) - ONE_HOUR:
        send(user.userid, "I'm kinda tired, you just played with me!")
        return

    user.last_play = int(time.time())
    user.happiness += 10  #increment happiness levels
    if user.happiness >= 100:
        user.happiness = 100
    db.session.commit()  #push it to database

    message = "You played with me. I feel happier!"
    send(user.userid, message)
예제 #31
0
def treat(user):
    if user.last_treat >= int(time.time()) - ONE_HOUR:
        send(user.userid,
             "I don't feel like a treat right now, I just had one.")
        return

    user.last_treat = int(time.time())
    user.hunger += 10
    if user.hunger >= 100:
        user.hunger = 100
    db.session.commit()

    message = "You gave me a treat. Yay!"
    send(user.userid, message)
예제 #32
0
def scan_loop(sock):
    while True:
        returned_list = blescan.parse_events(sock, 10)

        if len(returned_list) > 0:
            keepalive.set_last_run()

            for beacon in returned_list:
                queue.queue_beacon(beacon)

        keepalive_message = keepalive.check_keepalive()

        if keepalive_message is not None:
            send.send(1, "KA:%s", keepalive_message)
예제 #33
0
파일: shell.py 프로젝트: Max00355/Chater
 def main(self):
     self.sock.connect(self.server)
     thread.start_new_thread(record.record, ())
     thread.start_new_thread(self.recv, ())
     while True:
         cmd = raw_input("> ")
         if cmd == "record":
             utils.record = True
             thread.start_new_thread(record.record, ())
         elif cmd == "stop":
             utils.record = False
         
         elif cmd == "send":
             send.send(self.sock)
         
         print len(list(utils.stream))
예제 #34
0
def main():
    verticalLine()
    puts("Welcome to EENX15-1919 UART test interface!")
    while True:
        verticalLine()
        action = prompt.options(colored.magenta("What would you like to do?"),
                                main_menu)
        if (action == "s"):
            send()
        elif (action == "r"):
            recieve()
        elif (action == "exit"):
            ser.close()
            exit()
        else:
            wrong_input
예제 #35
0
    def flow(self,conn):
        # s = send.client_connect()
        # while 1:
        #     record.record(self.username)
        #     send.send(s, self.username)
        #     for i in self.userlist:
        #         if self.username != i:
        #             send.recv(s)
        #             t = threading.Thread(target=play.play,args=i)
        #             t.start()

        while 1:
            record.record(self.username)
            send.send(conn, self.username)
            opp = send.recv(conn)
            play(opp)
예제 #36
0
def search():
    parse_config_s('config.config')
    print('\nBROWSE CATEGORIES\n')
    server = parse_config_l('config.config')
    browseList = server.browse()
    for b in browseList:
        catId = b['catId']
        print('\nBUSCANDO SUBCATEGORIAS DE %s\n' % catId)
        catList = server.list(catId)
        for c in catList:
            print('\nBUSCANDO APLICACIONES DE %s\n' % c)
            appList = server.listApps(catId, c, 5)
            for app in appList:
                a = app['docId']
                print('\nENVIO %s A LA COLA\n' % a)
                send(USER_NAME, PASSWORD, SERVER_IP, QUEUE, a)
예제 #37
0
파일: router.py 프로젝트: cdt2132/Router
def init():
    listen_port = int(sys.argv[1])
    #Gets listening port
    table = []
    peers = []
    #Sets up table and peers lists
    arg = 2
    #Adds arguments to peers and table
    while arg < len(sys.argv):
        a = sys.argv[arg]
        a = a.split(":")
        ip = a[0]
        if any(c.isalpha() for c in ip):
            try:
                ip = socket.gethostbyname(ip)
                a[0] = ip
            except:
                "Print invalid domain"
        port = int(a[1])
        hops = int(a[2])
        a.append(arg - 1)
        i = int(arg - 1)
        p = [i, ip, port, hops]
        peers.append(p)
        table.append(a)
        arg += 1
    #Creates listening socket
    try:
        listen_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        print "Listen Socket Created"
    except socket.error:
        print "Unable to create listen socket"
    #Binds to listening Socket
    try:
        listen_socket.bind(('', listen_port))
    except socket.error:
        print "Failed to bind"

    #Creates send socket
    send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    #Calls start-up send message
    send.send(peers, table, send_sock, listen_port)

    #Returns the routing table, list of peers, listen_socket and port
    #and send socket
    return table, peers, listen_socket, listen_port, send_sock
예제 #38
0
파일: router.py 프로젝트: cdt2132/Router
def init():
    listen_port = int(sys.argv[1])
    #Gets listening port
    table = []
    peers = []
    #Sets up table and peers lists
    arg = 2
    #Adds arguments to peers and table
    while arg < len(sys.argv):
        a = sys.argv[arg]
        a = a.split(":")
        ip = a[0]
        if any(c.isalpha() for c in ip):
            try:
                ip = socket.gethostbyname(ip)
                a[0] = ip
            except:
                "Print invalid domain"
        port = int(a[1])
        hops = int(a[2])
        a.append(arg - 1)
        i = int(arg-1)
        p = [i, ip, port, hops]
        peers.append(p)
        table.append(a)
        arg += 1
    #Creates listening socket
    try:
        listen_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        print "Listen Socket Created"
    except socket.error:
        print "Unable to create listen socket"
    #Binds to listening Socket
    try:
        listen_socket.bind(('', listen_port))
    except socket.error:
        print "Failed to bind"

    #Creates send socket
    send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    #Calls start-up send message
    send.send(peers, table, send_sock, listen_port)

    #Returns the routing table, list of peers, listen_socket and port
    #and send socket
    return table, peers, listen_socket, listen_port, send_sock
예제 #39
0
def main():
    parameters = pika.URLParameters('amqp://*****:*****@localhost:5672/%2f')
    connection = pika.BlockingConnection()
    channel = connection.channel()
    channel.queue_declare(queue='test-queue')
    print('opening connection\n...')
    while True:
        try:
            time.sleep(1)
            send(channel, str(datetime.now()))
            print('connection live')
        except KeyboardInterrupt:
            print('connection dead')
            break

    print('...\nclosing connection')
    connection.close()
예제 #40
0
def handle(userid, message):
    #if the user does not exist in the database, create a new user
    #add it to the database
    if db.session.query(User).filter(User.userid == userid).count() == 0:
        new_user = User(userid)
        db.session.add(new_user)
        db.session.commit()
        send(
            userid,
            "Hi! I'm your new pet, Stitch! I can tell we're gonna be great friends already."
        )
        send(
            userid,
            "I love to eat and play, but I can get bored easily. Be sure to check on me frequently."
        )
        send(userid, "Here are some things you can do:")
        list_commands(new_user)

    #check for keywords in the message
    else:
        user = User.query.get(userid)
        if "help" in message.lower() or "command" in message.lower():
            list_commands(user)
        elif "status" in message.lower():
            report_status(user)
        elif "play" in message.lower():
            play(user)
        elif "treat" in message.lower():
            treat(user)
        elif "clean" in message.lower():
            clean(user)
        elif "pet" in message.lower():
            pet(user)
        elif "feed" in message.lower():
            feed(user)
        elif "vitamin" in message.lower():
            vitamin(user)
        elif "hi" in message.lower() or "hey" in message.lower(
        ) or "hello" in message.lower():
            send(user.userid, "Hi there! Wanna play?")
            list_commands(user)
        else:
            msg = "Sorry, I couldn't understand you. Here are some commands you can do:"
            send(user.userid, msg)
            list_commands(user)
예제 #41
0
def post(): # will take in a post do something with it and then return it to show it has been received

    if  request.method == 'POST': # check if the request is a post
    
        message = str(request.form.get('message')) # get the post data
        #This is linking to the send to rabbitmq
        #currently not working
        err = send.send(message)

        return err #return the post data
    else:
        
        message = str(request.args.get('message')) # get the post data
        #This is linking to the send to rabbitmq
        #currently not working
        err = send.send(message)

        return err #return the post data
예제 #42
0
def main(ssid, password, send_flag, loss):
    # Get keys
    with open('config.json') as f:
        config = json.load(f)

    # Make sure data is divisible by 16
    data = '{}:{}'.format(ssid, password)

    # TODO: Be smarter about padding
    padding = 16 - (len(data) % 16)
    data = data + '\0' * padding

    send(data.encode(),
         config['encryption_key'].encode(),
         config['integrity_key'].encode(),
         id_=config['id'],
         send_flag=send_flag,
         possible_loss=loss)
예제 #43
0
파일: app.py 프로젝트: rghai/Docusign
    def POST(self):
        form = web.input(name="Nobody", email="*****@*****.**", title="Superstar")

        name = "%s" % (form.name)
        email = "%s" % (form.email)
        title = "%s" % (form.title)

        baseUrl, accountId, authenticateStr = login.login(username, password, integratorKey)
        print ("baseUrl = %s\naccountId = %s" % (baseUrl, accountId));  
        envId = send.send(accountId, templateId, email, name, title, baseUrl, authenticateStr)
        print ("Signature request sent!  EnvelopeId is: %s\n" % envId);
     

        return render.index(name = name, email = email, title = title, envId = envId)
예제 #44
0
파일: load.py 프로젝트: aliounedia/Tigo
def sendMail(data):
    map = {}
    for line in data:
        if not line[7] in map:
            map[line[7]] = 1
        else:
            map[line[7]] +=1


    flat     = '<br/>'.join( ['%s ** %s' %(one, two)
                          for (one, two) in map.items() ])

    
    
    to       = ['*****@*****.**',
                '*****@*****.**']
           
    subject   ="[Tigo] Chargement de fichiers %s """%\
                 date.today().strftime('%Y%m%d')
    
   
                    
    Mail ="""
Bonjour,<br/>
les chargements sur le l' emission des appels de Tigo<br/>.
Pour les segments suivants :<br/>
%s
<br/>
<br/>
<br/>
Cordialement<br/>
Service Informatique.<br/>
    """%(flat)

    send.send(att_path = None , body =Mail,
                    to = to , subject =subject)
예제 #45
0
 def do_send(self, line):
     line = line.split()
     amt = int(line[0])
     to = line[1]
     print send.send(amt, to)
예제 #46
0
def check_for_new_documents():
    send("check_for_new_documents")
예제 #47
0
파일: dotsync.py 프로젝트: Samathy/dotsync
       sys.exit()
    
    for x in range(1, (len(sys.argv) - 1)): #add all the file names following to the list.
        files.append(sys.argv[x+1])
    receive(sys.argv[2])
    sys.exit()

if sys.argv[1] == '-s':
    length = len(sys.argv)
    if length < 3:
       print("Missing argument after -s")
       sys.exit()
    address = sys.argv[2] #let address = the address entered through commanf line args.
    for x in range(1, (len(sys.argv) - 2)): #add all the file names to a list.
        files.append(sys.argv[x+2])
    send(files, sys.argv[2])
    sys.exit()

if sys.argv[1] == '-sf':
    length = len(sys.argv)
    if length < 3:
       print("Missing argument after -sf")
       sys.exit()
    address = sys.argv[2] #let address = the address entered through commanf line args.

    if os.path.exists(sys.argv[3]):
        f = open(sys.argv[3], 'r') #open the file containing lists of files.
    else:
        print ("File '"), sys.argv[3], ("' Does not exist")
        sys.exit()
예제 #48
0
def msg_handler(msg):
    """
    
        Unpacks and acts on messages sent to the node. This is called by the communicator process whenever messages are received. 
        
        :param string msg: The packed message sent to the node.
        
    """
    #TODO Add new message types that are created for waggle
    header = None
    try:
        #unpacks the header
        header = get_header(msg)
    except: 
        print 'Message is corrupt.'
        raise
        
    #get the major header type
    major = chr(header['msg_mj_type'])
    minor = chr(header['msg_mi_type'])
    
    #large file transfer
    if major == 'F':
        #TODO pass to packet reassembler
        pass
    
    #small file transfer
    elif major == 'f':
        #TODO do something with this file
        pass
    
    #ping
    elif major == 'p':
        #ping request. 
        if minor == 'r':
            resp_header = {
                'msg_mj_type' : ord('p'),
                'msg_mi_type' : ord('a')
                }
            #send a ping response
            packet = pack(resp_header, 'Pong!')
            for pack in packet:
                send(pack)
         #ping answer
        else:
            #unpack the message
            ping = unpack(msg)
            #print out the body of the message
            print 'Node received: ', ping[1]
    #time
    elif major == 't':
        #time request
        if minor == 'r':
            #send time
            resp_header = {
                'msg_mj_type' : ord('t'),
                'msg_mi_type' : ord('a')
                }
            time = str(time.time())
            packet = pack(resp_header, time)
            for pack in packet:
                send(pack)
        #time answer
        else:
            #unpack the message
            time = unpack(msg)
            #print out the body of the message
            print 'Node received time: ', time[1]
    #sensor data
    elif major == 's':
        #TODO do stuff here 
        pass 
    
    #registration
    elif major =='r':
        #TODO do stuff here if ever neccessary
        #unpack the message
        reg = unpack(msg)
        #print out the body of the message
        print 'GN received: ', reg[1]
    
    #message type unrecognized 
    else: 
        print 'Message major type, ' , major, ' unrecognized.'
예제 #49
0
def reparse_all_deputies():
    send("scrape")
예제 #50
0
def reparse_all_documents():
    for document in list(Document.objects.all()):
        send("parse_a_document", [document.lachambre_id])
        sleep(30)
예제 #51
0
def check_for_new_deputies():
    send("check_for_new_deputies")
예제 #52
0
파일: test.py 프로젝트: adewinter/rmac
		def send_message(instance):
			print 'Text input text is: %s' % instance.text
			print 'Sending to number: %s' % number
			send(number, instance.text)
			add_entry_to_sent(number, instance.text)
예제 #53
0
파일: sensor.py 프로젝트: KauzClay/waggle
                                    sensorReading_bucket[which_row][4].append(reading_note[Sensor_Index.index(currentSensor[0])])
                                except:
                                    pass
                            else:
                                pass
                                try:
                                    temp_values=currentSensor[1].split(',')
                                    for k in range(len(temp_values)):
                                        temp_values[k] = float(temp_values[k])
                                    which_row = sensor_array_index[Sensor_Index.index(currentSensor[0])]
                                    sensorReading_bucket[which_row][0]=list(reading_names[Sensor_Index.index(currentSensor[0])])
                                    sensorReading_bucket[which_row][1]=list(reading_type[Sensor_Index.index(currentSensor[0])])
                                    sensorReading_bucket[which_row][2]=list(temp_values)
                                    sensorReading_bucket[which_row][3]=list(reading_unit[Sensor_Index.index(currentSensor[0])])
                                    sensorReading_bucket[which_row][4]=list(reading_note[Sensor_Index.index(currentSensor[0])])
                                except:
                                    pass
                        for all in range(len(sensorReading_bucket)):
                            if (sensorReading_bucket[all] <> [[],[],[],[],[]]):
                                sendData=[sensor_names[all],int(time.time()),sensorReading_bucket[all][0],sensorReading_bucket[all][1],sensorReading_bucket[all][2],sensorReading_bucket[all][3],sensorReading_bucket[all][4]]
                                #print sendData
                                #packs and sends the data
                                packet = packetmaker.make_data_packet(sendData)
                                for pack in packet:
                                    send(pack)
                        time.sleep(1)
except KeyboardInterrupt, k:
    try:
        wxsensor.close()
    except: 
        pass
예제 #54
0
lazythought = account.pubAccount('懒人在思考', 'http://weixin.sogou.com/gzh?openid=oIWsFtwo1az2FajUL609KV51jhrM')
taobaoguijiaoqi = account.pubAccount('鬼脚七', 'http://weixin.sogou.com/gzh?openid=oIWsFt2QQkOK0nDUqZzOvdkm3Ch4')
today_inspire = account.pubAccount('今日', 'http://weixin.sogou.com/gzh?openid=oIWsFtw-UpWgDR1FfxAvjJFNWmD8')
sanbiao1984 = account.pubAccount('三表龙门阵', 'http://weixin.sogou.com/gzh?openid=oIWsFty72GGlJl1Fa32fnPqybPV8')
speedweekly = account.pubAccount('速度周刊', 'http://weixin.sogou.com/gzh?openid=oIWsFt0ywvBlyiY4YxcZ-65kFqQo')
douban = account.pubAccount('豆瓣', 'http://weixin.sogou.com/gzh?openid=oIWsFt0ywvBlyiY4YxcZ-65kFqQo')
shaoxizhi214 = account.pubAccount('邵皙智工作室', 'http://weixin.sogou.com/gzh?openid=oIWsFtxpswbhJmMEeqzLhikQBzPc')
zenpark = account.pubAccount('精进学堂', 'http://weixin.sogou.com/gzh?openid=oIWsFt3VWonT9PvhnPyOGiTinHlk')
JulesandJim = account.pubAccount('法外之徒', 'http://weixin.sogou.com/gzh?openid=oIWsFt03yb4SrUnI1ihKKXRym4Us')
drink_oh_yeah = account.pubAccount('猎酒党', 'http://weixin.sogou.com/gzh?openid=oIWsFt-5RQHelxMU4k0zm3yx_x_8')
fakecountry = account.pubAccount('花家舍', 'http://weixin.sogou.com/gzh?openid=oIWsFt2kv0vULsU3ROdZgEZwts54')
taosay = account.pubAccount('道哥的黑板报', 'http://weixin.sogou.com/gzh?openid=oIWsFty5GrTq6kuv7Ny-PhQSOQh0')
tencent_blackboard = account.pubAccount('腾讯黑板报', 'http://weixin.sogou.com/gzh?openid=oIWsFt23D0QFnnZq3cjK3IDktk9c')
baibanbaonet = account.pubAccount('白板报', 'http://weixin.sogou.com/gzh?openid=oIWsFt-1VrJXMHgB-JB3iNhMcZ4M')
it_spy = account.pubAccount('IT八卦', 'http://weixin.sogou.com/gzh?openid=oIWsFty3AlNGjSB31Y-nSs5NGNhs')





wz = users.user('wz', '*****@*****.**', [mintshow, sagacitymac, duhaoshu, foodtonight,
                                                doubanshiqing, seniorplayer, everydayfunengliang,
                                                lazythought, taobaoguijiaoqi, today_inspire, sanbiao1984,
                                                speedweekly, douban, shaoxizhi214, zenpark,
                                                JulesandJim, drink_oh_yeah, fakecountry, taosay, tencent_blackboard,
                                                baibanbaonet, it_spy])

if wz.checkList():
    mk.mkmobi(wz)
    send.send(wz)
예제 #55
0
from EmailStandards.EmailTemplate import EmailTemplate
from EmailStandards.MailServer import MailServer
from EmailStandards.MailMessage import MailMessage
from send import send
values = {}
values['username'] = '******'
values['from'] = 'The Team'
values['url'] = 'http://www.bazaarfunda.com'
temp = EmailTemplate(template_name='TestTemplate.html', values=values)

server = MailServer(server_name='smtp.gmail.com', username='******', password='******', port=0,   require_starttls=True)
msg = MailMessage(from_email='*****@*****.**', to_emails=['*****@*****.**'], subject='Welcome')
send(mail_msg=msg, mail_server=server, template=temp)
예제 #56
0
def msg_handler(msg):
    """
    
        Unpacks and acts on messages sent to the node.
        
        :param string msg: The packed message sent to the node.
        
    """
    
    try:
        #unpacks the header
        header = get_header(msg)
    except: 
        print 'Message is corrupt.' #TODO should this send some kind of error response? 
        
    #get the major header type
    major = chr(header['msg_mj_type'])
    minor = chr(header['msg_mi_type'])
    
    #large file transfer
    if major == 'F':
        #TODO pass to packet reassembler
        pass
    
    #small file transfer
    elif major == 'f':
        #TODO do something with this file
        pass
    
    #ping
    elif major == 'p':
        #ping request. 
        if minor == 'r':
            resp_header = {
                'msg_mj_type' : ord('p'),
                'msg_mi_type' : ord('a')
                }
            #send a ping response
            packet = pack(resp_header, 'Pong!')
            for pack in packet:
                send(pack)
         #ping answer
        else:
            #unpack the message
            ping = unpack(msg)
            #print out the body of the message
            print 'Node received: ', ping[1]
    #time
    elif major == 't':
        #time request
        if minor == 'r':
            #send time
            resp_header = {
                'msg_mj_type' : ord('t'),
                'msg_mi_type' : ord('a')
                }
            time = str(time.time())
            packet = pack(resp_header, time)
            for pack in packet:
                send(pack)
        #time answer
        else:
            #unpack the message
            time = unpack(msg)
            #print out the body of the message
            print 'Node received time: ', time[1]
    #sensor data
    elif major == 's':
        #TODO do stuff here 
        pass 
    
    #registration
    elif major =='r':
        #TODO do stuff here 
        #unpack the message
        reg = unpack(msg)
        #print out the body of the message
        print 'NC received registration: ', reg[1]
    
    #message type unrecognized 
    else: 
        print 'Message major type, ' , major, ' unrecognized.'
예제 #57
0
def sensor_read():
    import time, serial, sys
    sys.path.append('../waggle_protocol/')
    from utilities import packetmaker
    from send import send
    """
       This connects to a sensor board via a serial connection. It reads and parses the sensor data into meaningful information, packs, and sends the data packet to the cloud. 
       
       
    """
    print 'Beginning sensor script...'

    Sensor_Index=["D6T_44L_06_1_T_C","MMA8452_1_A_X_Units","MMA8452_1_A_Y_Units",
                  "MMA8452_1_A_Z_Units","MMA8452_1_A_RMS_Units","SHT15_1_T_C","SHT15_1_H_%","SHT75_1_T_C",
                  "SHT75_1_H_%","MAX4466_1_Units","AMBI_1_Units","PhoRes_10K4.7K_Units","HIH4030_Units",
                  "THERMIS_100K_Units","DS18B20_1_T_C","TMP421_1_T_C","RHT03_1_T_C","RHT03_1_H_%",
                  "BMP_180_1_T_C","BMP_180_1_P_PA","TMP102_1_T_F","HIH_6130_1_T_C","HIH_6130_1_H_%",
                  "MLX90614_T_F"]

    reading_names = [ ["Temperature",
                       "Temperature","Temperature","Temperature","Temperature",
                       "Temperature","Temperature","Temperature","Temperature",
                       "Temperature","Temperature","Temperature","Temperature",
                       "Temperature","Temperature","Temperature","Temperature"],
                        "Acceleration",
                        "Acceleration",
                        "Acceleration",
                        "Vibration",
                        "Temperature",
                        "Humidity",
                        "Temperature",
                        "Humidity",
                        "Acoustic_Intensity",
                        "Luminous_Intensity",
                        "Luminous_Intensity",
                        "Humidity",
                        "Temperature",
                        "Temperature",
                        "Temperature",
                        "Temperature",
                        "Humidity",
                        "Temperature",
                        "Pressure",
                        "Temperature",
                        "Temperature",
                        "Humidity",
                        "Temperature"]

    reading_type = [['f','f','f','f','f','f','f','f','f','f','f','f','f','f','f','f','f'],
                    'f','f','f','f','f','f','f','f','f','f','f','f','f','f','f','f','f','f','f','f','f','f','f']

    reading_unit = [["C","C","C","C","C","C","C","C","C","C","C","C","C","C","C","C","C"],
                    "g","g","g","g","C","%RH","C","%RH","Units10B0V5","Units10B0V5","Units10B0V5","Units10B0V5",
                    "Units10B0V5","C","C","C","%RH","C","PA","F","C","%RH","F"]

    reading_note = [["PTAT",
                       "1x1","1x2","1x3","1x4",
                       "2x1","2x2","2x3","2x4",
                       "3x1","3x2","3x3","3x4",
                       "4x1","4x2","4x3","4x4"],
                        "X",
                        "Y",
                        "Z",
                        "RMS_3Axis",
                        "",
                        "RH",
                        "", 
                        "RH",
                        "non-standard",
                        "non-standard",
                        "Voltage_Divider_5V_PDV_Tap_4K7_GND", 
                        "RH",
                        "Voltage_Divider_5V_NTC_Tap_68K_GND",
                        "",
                        "",
                        "",
                        "RH", 
                        "", 
                        "Barometric",
                        "",
                        "", 
                        "", 
                        ""]    

    sensor_array_index = [2,7,7,7,7,5,5,12,12,15,14,0,13,3,8,9,10,10,6,6,11,4,4,1]

    sensor_names = ["PDV_P8104.API.2006", "MLX90614ESF-DAA.Melexis.008-2013", "D6T-44L-06.Omron.2012", "Thermistor_NTC_PR103J2.US_Sensor.2003", 
            "HIH6130.Honeywell.2011", "SHT15.Sensirion.4_3-2010", "BMP180.Bosch.2_5-2013", "MMA8452Q.Freescale.8_1-2013", 
            "DS18B20.Maxim.2008", "TMP421.Texas_Instruments.2012", "RHT03.Maxdetect.2011", "TMP102.Texas_Instruments.2008", 
            "SHT75.Sensirion.5_2011", "HIH4030.Honeywell.2008", "GA1A1S201WP.Sharp.2007", "MAX4466.Maxim.1_2001"]
    try:
        while True:
            wxconnection = False
            while wxconnection == False:
                try:
                    #TODO change this if the serial port is different than the one specified.
                    #TODO may want to create a rule to specify which port the board will use
                    print 'wxconnection == false, now assigns serial port'
		    wxsensor = serial.Serial('/dev/ttyACM0',9600,timeout=300)
                    wxconnection = True
                except:
                    #Will not work if sensor board is not plugged in. 
                    #If sensor board is plugged in, check to see if it is trying to connect to the right port
                    print "Still Waiting for Connection... Is the sensor board plugged in?"
                    time.sleep(1)
            try:
                wxsensor.flushInput()
                wxsensor.flushOutput()
            except:
                wxsensor.close()
                wxconnection = False
            while wxconnection == True:
                try:
                    readData = ' '
                    readData=wxsensor.readline()
		    print readData
                except:
		    print "failed to read data"
                    wxsensor.close()
                    wxconnection = False
                if len(readData) > 0 and wxconnection == True:
                    try:
                        sensorsData = readData.split(';')
                        if len(sensorsData) > 2:
                            sensorDataAvail = True
                        else:
                            sensorDataAvail = False
                    except:
                        sensorDataAvail = False

                    if sensorDataAvail == True:
			print "sensorDataAvail == True"
                        if sensorsData[0] == 'WXSensor' and sensorsData[-1]=='WXSensor\r\n':
                            print "printing data"
			    print sensorsData[1:-1]
			    print "bucketing data"
                            sensorReading_bucket = [[[] for col in range(5)] for row in range(16)]
                            for i in range(len(sensorsData)-2):
                                print sensorsData[i+1]
                                currentSensor = sensorsData[i+1].split(':')
                                if currentSensor[0] <> 'D6T_44L_06_1_T_C':
                                    try:
                                        temp_values = float(currentSensor[1])
                                        which_row = sensor_array_index[Sensor_Index.index(currentSensor[0])]
                                        sensorReading_bucket[which_row][0].append(reading_names[Sensor_Index.index(currentSensor[0])])
                                        sensorReading_bucket[which_row][1].append(reading_type[Sensor_Index.index(currentSensor[0])])
                                        sensorReading_bucket[which_row][2].append(temp_values)
                                        sensorReading_bucket[which_row][3].append(reading_unit[Sensor_Index.index(currentSensor[0])])
                                        sensorReading_bucket[which_row][4].append(reading_note[Sensor_Index.index(currentSensor[0])])
                                    except:
                                        pass
                                else:
                                    pass
                                    try:
                                        temp_values=currentSensor[1].split(',')
                                        for k in range(len(temp_values)):
                                            temp_values[k] = float(temp_values[k])
                                        which_row = sensor_array_index[Sensor_Index.index(currentSensor[0])]
                                        sensorReading_bucket[which_row][0]=list(reading_names[Sensor_Index.index(currentSensor[0])])
                                        sensorReading_bucket[which_row][1]=list(reading_type[Sensor_Index.index(currentSensor[0])])
                                        sensorReading_bucket[which_row][2]=list(temp_values)
                                        sensorReading_bucket[which_row][3]=list(reading_unit[Sensor_Index.index(currentSensor[0])])
                                        sensorReading_bucket[which_row][4]=list(reading_note[Sensor_Index.index(currentSensor[0])])
                                    except:
                                        pass
                            for all in range(len(sensorReading_bucket)):
                                if (sensorReading_bucket[all] <> [[],[],[],[],[]]):
                                    sendData=[sensor_names[all],int(time.time()),sensorReading_bucket[all][0],sensorReading_bucket[all][1],sensorReading_bucket[all][2],sensorReading_bucket[all][3],sensorReading_bucket[all][4]]
                                    print "sending data"
				    print sendData
                                    #packs and sends the data
                                    packet = packetmaker.make_data_packet(sendData)
                                    for pack in packet:
                                        send(pack)
                            time.sleep(1)
    except KeyboardInterrupt, k:
        try:
            wxsensor.close()
        except: 
            pass
예제 #58
0
    return sock


def scan_loop(sock):
    while True:
        returned_list = blescan.parse_events(sock, 10)

        if len(returned_list) > 0:
            keepalive.set_last_run()

            for beacon in returned_list:
                queue.queue_beacon(beacon)

        keepalive_message = keepalive.check_keepalive()

        if keepalive_message is not None:
            send.send(1, "KA:%s", keepalive_message)


if __name__ == "__main__":
    send.send(1, "Starting BLE watcher")

    device, size, used, available, percent, mountpoint = diagnostics.disk_space()
    send.send(1, "m:%s a:%s s:%s p:%s" % (mountpoint, available, size, percent))

    keepalive.initialise()

    sock = start_scanner()
    scan_loop(sock)