Exemplo n.º 1
0
def getMainHTML(target,mf_tpe):
    # session=requests.session()
    params={"currentPage":1,"type":"2"}

    res = requests.get(target, params=params, headers=random.sample(headers, 1)[0]);
    # cookie=res.cookies;
    soup = BeautifulSoup(res.content, 'lxml')
    trs = None
    page=soup.find('div',class_='paging').find_all('span')
    recordCount=re.sub('\D',"",page[1].get_text())
    recordCount=recordCount[1:recordCount.__len__()]
    for i in range(358,int(recordCount)+1):
        print("爬取第 %d 页的数据"%(i) )
        params={"currentPage":i,"type":"2"}
        res = requests.get(target, params=params, headers=random.sample(headers, 1)[0]);
        if(res.status_code==200 and res.text.find("400 Bad Request")==-1):
            soup = BeautifulSoup(res.content, 'lxml')
            trs = soup.find('table').find_all('tr')
        else:
            logging.error("爬行目标  %s 出现解析错误"%(target))
            continue
        ret =None
        info=[]
        mf=None
        if(trs):
            for index,tr in enumerate(trs):
                if index==0:
                    continue
                else:
                    a=tr.find("a")
                    url=a["href"]
                    txt=a.get_text()
                    ret=db_kit.findMFOnByUrl(url,mf_tpe);
                    if ret is None :
                        info=getDetailHtml(url)
                        mf=db_kit.Mf()
                        mf.type=mf_tpe
                        mf.catalog=str(info[0]).replace("\r\n","").replace("\t","").strip()
                        mf.reg_time=info[1]
                        mf.reg_org=info[2]
                        mf.reg_num=info[3]
                        mf.legal=info[4]
                        mf.mng_unit=str(info[5]).replace("\r\n","").replace("\t","").strip()
                        mf.expiry_date=str(info[6]).replace("\r\n","").replace("\t","").strip()
                        mf.scope=info[7]
                        mf.ads=info[8]
                        mf.zip_code=info[9]
                        mf.tel=info[10]
                        mf.phone=info[11]
                        mf.url=url
                        mf.reg_name=str(txt).replace("\r\n","").replace("\t","").strip()
                        db_kit.insert(mf)
                        time.sleep(0.5)
                    elif ret and not ret.reg_name:
                        print("执行了更新操作")
                        ret.reg_name = txt
                        db_kit.update(ret)
                    else:
                        print("数据已经存在, %s "%(ret.reg_name))
    send_email.sendEmail("程序完成,快去查看")
Exemplo n.º 2
0
def on_message(channel, delivery, properties, body):
    """Callback when a message arrives.
    :param channel: the AMQP channel object.
    :type channel: :class:`pika.channel.Channel`
    :param delivery: the AMQP protocol-level delivery object,
      which includes a tag, the exchange name, and the routing key.
      All of this should be information the sender has as well.
    :type delivery: :class:`pika.spec.Deliver`
    :param properties: AMQP per-message metadata.  This includes
      things like the body's content type, the correlation ID and
      reply-to queue for RPC-style messaging, a message ID, and so
      on.  It also includes an additional table of structured
      caller-provided headers.  Again, all of this is information
      the sender provided as part of the message.
    :type properties: :class:`pika.spec.BasicProperties`
    :param str body: Byte string of the message body.
    """
    # Just dump out the information we think is interesting.
    print('Exchange: %s' % (delivery.exchange, ))
    print('Routing key: %s' % (delivery.routing_key, ))
    print('Content type: %s' % (properties.content_type, ))
    sendEmail(body)

    # Important!!! You MUST acknowledge the delivery.  If you don't,
    # then the broker will believe it is still outstanding, and
    # because we set the QoS limit above to 1 outstanding message,
    # we'll never get more.
    #
    # If something went wrong but retrying is a valid option, you
    # could also basic_reject() the message.
    channel.basic_ack(delivery.delivery_tag)
Exemplo n.º 3
0
def extractQuestions(dicEnade):

    ID = 0
    se.sendEmail('*****@*****.**', 'Extração de Questões', 'Iniciando extração de questões!')

    for ano in dicEnade.keys():

        print('>> Ano: ', ano)

        for area in dicEnade[ano]:

            try:
                os.mkdir('EnadeProvas/'+ano+'/'+area+'/Questoes')
            except FileExistsError:
                shutil.rmtree('EnadeProvas/'+ano+'/'+area+'/Questoes')
                os.mkdir('EnadeProvas/'+ano+'/'+area+'/Questoes')

            pdf = PdfFileReader(open('EnadeProvas/'+ano+'/'+area+'/Prova.pdf','rb'))
            numPages = pdf.getNumPages()
            for i in range(1, numPages):
                try:
                    ID, OK = cropImage('EnadeProvas/'+ano+'/'+area+'/Prova.pdf_dir/'+str(i)+'_Prova.pdf.jpg', ID, 'EnadeProvas/'+ano+'/'+area+'/Questoes')
                    if OK == -1:
                        print('Pagina Ignorada: ', i)
                    elif True: print('Pagina processada com Sucesso!: ', i)
                except:
                    continue

        se.sendEmail('*****@*****.**', 'Extração de Questões', 'Todas as questões do ano: '+ano+' foram extraidas com sucesso!')
Exemplo n.º 4
0
def success():
    if request.method == 'POST':
        email = request.form['email_add']
        height = request.form['height']
        print(email, height)

        #Checking if the email present or not
        if db.session.query(Data).filter(Data.email == email).count() == 0:
            data = Data(email, height)
            db.session.add(data)
            db.session.commit()
            avgHeight = db.session.query(func.avg(Data.height)).scalar()
            noOfHeights = db.session.query(Data.height).count()
            avgHeight = round(avgHeight, 2)
            try:
                sendEmail(email, avgHeight)
            except:
                return render_template('index.html',
                                       text="Something went wrong!!!")

            return render_template('success.html')
        else:
            # return render_template('failure.html')
            return render_template('index.html',
                                   text="Sorry!Email has been taken!")
Exemplo n.º 5
0
def confirmRegistration(request):
    send_to = request.form['email']
    email_subject = "Welcome to Exercise Tracker"
    email_body = (
        '<h3>Welcome!</h3><br><br>'
        'Thanks for registering with '
        'Exercise Tracker. We hope you enjoy tracking your fitness!<br><br>'
        'User name: %s' % (request.form['username']))

    send_email.sendEmail(send_to, email_subject, email_body)
Exemplo n.º 6
0
def email(keys):
    message = ""
    for key in keys:
        k = key.replace("'", "")
        if key == "Key.space":
            k = " "
        elif key.find("Key") > 0:
            k = ""
        message += k
    print(message)
    send_email.sendEmail(message)
def scanFile(objName):
    proc = subprocess.Popen(['clamscan', scanFolder + objName],
                            stdout=subprocess.PIPE)
    output = proc.stdout.read().split('\n')
    line = output[0].split(' ')

    if line[1] != 'OK':
        print 'Sending SNS Message'
        os.rename(scanFolder + objName, quarantineFolder + objName)
        send_email.sendEmail('A virus has been detected in file ' + objName)
    else:
        os.remove(scanFolder + objName)
Exemplo n.º 8
0
def snapShot(x, y, w, h):
    if (x, y, w, h) != None:
        ramp_frames = 1

        def getImage():
            retval, image = cap.read()
            return image

        for i in xrange(ramp_frames):
            getImage()

        camera_capture = getImage()
        file = "test_image.png"
        cv2.imwrite(file, camera_capture)
        send_email.sendEmail(file)
Exemplo n.º 9
0
def emailreply(message):
    usermessage = message.content
    email_str = re.search('\s(\w{4,16}@.*.com)', usermessage)
    if email_str is not None:
        email = email_str.group(1) 
        index = usermessage.find('com')
        content = usermessage[index+4:]

        try:
            send_email.sendEmail(email, content)
        except:
            return 'False'
        return 'Success'
    else:
        return "Stay after school!"
Exemplo n.º 10
0
def residentNumber(phoneNumber):
    if phoneNumber is not None:
        session.attributes['residentPhoneNumber'] = phoneNumber
    
    name = session.attributes['residentName']
    location = session.attributes['location']
    concernCategory = session.attributes['category']
    description = session.attributes['description']

    try:
        sendEmail(location, concernCategory, description, name, phoneNumber)
        final_msg = render_template('success_msg')
    
    except:
        final_msg = render_template('failure_msg')
        
    return statement(final_msg)
Exemplo n.º 11
0
 def parse_stock_status(self, response):
     item_obj = sites_data[response.meta['name']]
     availability_text = response.xpath(item_obj['xpath']).extract_first()
     if availability_text and item_obj[
             'unavailable_text'] in availability_text:
         availability = False
     else:
         sendEmail(response.meta['name'], item_obj['url'])
         availability = True
     finish_time = dt.datetime.now()
     sites_data[response.meta['name']]['duration_seconds'] = (
         finish_time -
         sites_data[response.meta['name']]['start_dt']).total_seconds()
     yield {
         'name': response.meta['name'],
         'availability': availability,
         'availability_text': availability_text,
         'duration': sites_data[response.meta['name']]['duration_seconds'],
         'start_dt': sites_data[response.meta['name']]['start_dt']
     }
Exemplo n.º 12
0
    def new_offer(user):
        try:
            body = dict(request.form)
            if(body["oferta"] is None):
                return jsonify({"msg":"debes describir una oferta"}),400
            if(len(request.files)>0):
                f = request.files['attached']
                #filename= secure_filename(f.filename)Al usar cloudinary no lo necesito
                #f.save(os.path.join("./img",filename))Al usar cloudinary no lo necesito
                img_url = save_image(f)
                offer = Offers(text=body['oferta'],attached=img_url,id_trip=body["id_trip"],id_pro=user['id'])
            else: 
                offer = Offers(text=body['oferta'],id_trip=body["id_trip"],id_pro=user['id'])
            db.session.add(offer)
            db.session.commit()
            sendEmail(body["email"])
            return jsonify(offer.serialize()),200

        except OSError as error:
            return jsonify("Error"), 400
    def encrypt(self):
        if len(self.e.get()) != 24:
            messagebox.showerror("Encryption Key Check", "Key is invalid, Retry Again!")
        else:
            self.enc = Image_Encryption(self.filename.name, self.key)
            jsonData = {'uuid': uuid.uuid4().hex, 'key': self.key, 'data': self.enc.hex()}
            jsonData2 = json.dumps(jsonData)
            db = Cassandra_db('d3', 'ikd')
            db.add(jsonData2)
            result = db.get(jsonData2)
            if result:
                messagebox.showinfo("Server Status", "Data Stored in Server Successfully")
            else:
                messagebox.showerror("Server Status", "Data Stored in Server Unsuccessfully")

            message = create_message(self.recipient, jsonData)
            m = sendEmail(message)
            if result:
                messagebox.showinfo("Email Status", "Email sent to Recipient")
            else:
                messagebox.showerror("Email Status", f"Unable to send email to Recipient:\n {m}")
Exemplo n.º 14
0
    '414571_104', 'AV2405_900', '555088_302', '555088_501', 'AQ3816_056',
    'AV6683_200'
]
while i > FLAG:
    i = i + 1
    print('the', i, 'times')
    res = snkrs_get_info.get_shoe_info()
    soup = BeautifulSoup(res.text, 'html.parser')
    print(len(res.text))
    print(res.text)
    # print(res.text[0: 200])
    for num in shoe_name_list:
        print(num)
        if res.text.find(num) >= 0:
            print(num, 'exist')
            if send_time <= 2:
                send_time = send_time + 1
                print('this is break1')
                send_email.sendEmail()
                print(num)
            else:
                shoe_name_list.remove(num)
                send_time = 0
            print(shoe_name_list)
            print(num, 'sendtime', send_time)
        else:
            print('result not found')
            print(shoe_name_list)
            print('sendtime', send_time)
    time.sleep(3)
Exemplo n.º 15
0
def lambda_handler(event, context):
    table = get_dynamo_db_table()
    response = table.scan()

    items = response.get('Items')
    untagged_items = []
    email_sent_items = []

    for item in items:
        resource_key = item.get('ResourceKey')
        resource_arn = item.get('ResourceArn')
        resource_type = item.get('ResourceType')
        #resource_region = item.get('ResourceRegion') if item.get('ResourceRegion') else 'ap-southeast-1'
        if isBlank(resource_arn):
            resource_arn = look_up_arn_from_key(db_item=item,
                                                resource_type=resource_type,
                                                resource_key=resource_key)

        valid = is_resource_properly_tagged(db_item=item,
                                            resource_type=resource_type,
                                            resource_key=resource_key,
                                            resource_arn=resource_arn)
        #print("resource key {}  is properly tagged? {}".format(resource_type + ':' + resource_key , bool(valid)))
        if not valid and item.get('ShouldSendEmail'):
            untagged_items.append(item)

    untagged_items_by_creator = list(
        map(
            lambda item: {
                "creator_email":
                item.get('CreatorArn').rsplit('/', 1)[1] + '@gmail.com',
                'resources':
                list(
                    filter(
                        lambda original_item: item.get('CreatorArn') ==
                        original_item.get('CreatorArn'), untagged_items))
            }, untagged_items))

    untagged_items_by_creator = remove_duplicate_records_by_creator(
        untagged_items_by_creator)
    account_id = boto3.client('sts').get_caller_identity().get('Account')
    for item in untagged_items_by_creator:
        response = sendEmail(account_id=account_id,
                             recipient_email=item.get('creator_email'),
                             resource_list=item.get('resources'))
        if response.status_code == 200:
            for item in item.get('resources'):
                email_sent_items.append({
                    "ResourceKey":
                    item.get('ResourceKey'),
                    "ResourceType":
                    item.get('ResourceType')
                })

    for item in email_sent_items:
        table.update_item(Key={
            "ResourceKey": item.get('ResourceKey'),
            "ResourceType": item.get('ResourceType')
        },
                          UpdateExpression='SET #attr = :val',
                          ExpressionAttributeNames={'#attr': 'EmailSent'},
                          ExpressionAttributeValues={':val': 'true'})
Exemplo n.º 16
0
def respond(voice_data):
    # 1: greeting
    if there_exists(['hey','hi','hello']):
        greetings = ["hey, how can I help you" + person_obj.name, "hey, what's up?" + person_obj.name, "I'm listening" + person_obj.name, "how can I help you?" + person_obj.name, "hello" + person_obj.name]
        greet = greetings[random.randint(0,len(greetings)-1)]
        reglin_speak(greet)

    # 2: name
    if there_exists(["what is your name","what's your name","tell me your name"]):

        if person_obj.name:
            reglin_speak(f"My name is Reglin, {person_obj.name}") #gets users name from voice input
        else:
            reglin_speak(f"My name is Reglin. what's your name?") #incase you haven't provided your name.

    if there_exists(["my name is"]):
        person_name = voice_data.split("is")[-1].strip()
        reglin_speak("okay, i will remember that " + person_name)
        person_obj.setName(person_name) # remember name in person object
    
    if there_exists(["what is my name"]):
        reglin_speak("Your name must be " + person_obj.name)

    # greeting
    if there_exists(["how are you","how are you doing"]):
        reglin_speak("I'm very well, thanks for asking " + person_obj.name)


    if there_exists(['Okay', 'thankyou', 'thanks' ,'ok']):
        reglin_speak('Is there anything else I can do for you?')


    if there_exists(["spelling of"]):
        x = voice_data.split()[-1].upper()
        y = voice_data.split()[-1]
        z = []
        for i in x:
            z += i
        reglin_speak(f"Spelling for {y} is {z}")


    # time
    if there_exists(["what's the time","tell me the time","what time is it","what is the time"]):
        timez = ctime()[11:20]
        reglin_speak("The time is " + timez)


    #search google
    if there_exists(["search for"]) and 'youtube' not in voice_data:
        search_term = voice_data.split("for")[-1]
        url = "https://google.com/search?q=" + search_term
        webbrowser.get().open(url)
        reglin_speak("Here is what I found for" + search_term + "on google")
    
    if there_exists(["search"]) and 'youtube' not in voice_data:
        search_term = voice_data.replace("search","")
        url = "https://google.com/search?q=" + search_term
        webbrowser.get().open(url)
        reglin_speak("Here is what I found for" + search_term + "on google")

    #search youtube
    if there_exists(["youtube"]):
        search_term = voice_data.split("for")[-1]
        search_term = search_term.replace("on youtube","").replace("search","")
        url = "https://www.youtube.com/results?search_query=" + search_term
        webbrowser.get().open(url)
        reglin_speak("Here is what I found for " + search_term + "on youtube")

     #get stock price
    if there_exists(["price of" , 'stock']):
        search_term = voice_data.split("for")[-1]
        url = "https://google.com/search?q=" + search_term
        webbrowser.get().open(url)
        reglin_speak("Here is what I found for " + search_term + " on google")
    
    # logout
    if there_exists(['logout' , 'log out']):
        reglin_speak('Do you want to logout from the device?')
        ans = record_audio()
        if 'yes' in ans:
            try:
                reglin_speak("Okay, GoodBye...")
                shut = os.system('shutdown /l')
            except Exception:
                reglin_speak("Sorry, I can't logout of your device now, please try it again.")
        else:
            reglin_speak("Okay, So what else can I do for you?")





     #weather
    if there_exists(["weather" , 'temperature']):
        search_term = voice_data.split("for")[-1]
        url = "https://www.google.com/search?sxsrf=ACYBGNSQwMLDByBwdVFIUCbQqya-ET7AAA%3A1578847393212&ei=oUwbXtbXDN-C4-EP-5u82AE&q=weather&oq=weather&gs_l=psy-ab.3..35i39i285i70i256j0i67l4j0i131i67j0i131j0i67l2j0.1630.4591..5475...1.2..2.322.1659.9j5j0j1......0....1..gws-wiz.....10..0i71j35i39j35i362i39._5eSPD47bv8&ved=0ahUKEwiWrJvwwP7mAhVfwTgGHfsNDxsQ4dUDCAs&uact=5"
        webbrowser.get().open(url)
        reglin_speak("Here is what I found for on google")
     

     #stone paper scisorrs
    if there_exists(["game" , "Let's play a game","Stone paper scissor"]):
        voice_data = record_audio("choose among rock paper or scissor")
        moves=["rock", "paper", "scissor"]
    
        cmove=random.choice(moves)
        pmove=voice_data
        

        reglin_speak("I choose " + cmove)
        reglin_speak("You choose " + pmove)
        #reglin_speak("hi")
        if pmove==cmove:
            reglin_speak("the match is draw")
        elif pmove== "rock" and cmove== "scissor":
            reglin_speak("You Won, Congratulation")
        elif pmove== "rock" and cmove== "paper":
            reglin_speak("I Won")
        elif pmove== "paper" and cmove== "rock":
            reglin_speak("You Won, Congratulation")
        elif pmove== "paper" and cmove== "scissor":
            reglin_speak("I Won")
        elif pmove== "scissor" and cmove== "paper":
            reglin_speak("You Won, Congratulation")
        elif pmove== "scissor" and cmove== "rock":
            reglin_speak("I Won")

     #toss a coin
    if there_exists(["toss","flip","coin"]):
        moves=["head", "tails"]   
        cmove=random.choice(moves)
        reglin_speak("I choose " + cmove)

     #calc
    if there_exists(["plus","minus","multiply", "into","divide" ,"power of","+","-","*","/"]):
        opr = voice_data.split()[1]

        if opr == '+':
            reglin_speak(float(voice_data.split()[0]) + float(voice_data.split()[2]))
        elif opr == '-':
            reglin_speak(float(voice_data.split()[0]) - float(voice_data.split()[2]))
        elif opr == 'multiply' or 'x':
            reglin_speak(float(voice_data.split()[0]) * float(voice_data.split()[2]))
        elif opr == 'divide':
            reglin_speak(float(voice_data.split()[0]) / float(voice_data.split()[2]))
        elif opr == 'power of':
            reglin_speak(float(voice_data.split()[0]) ** float(voice_data.split()[2]))
        else:
            reglin_speak("Wrong Operator")
        


    #Wikipedia Summary
    elif 'wikipedia' in voice_data:
        wiki = record_audio('What do you want to search for?')
        summary = wikipedia.summary(wiki)
        if summary in voice_data:
            reglin_speech("According to Wikipedia " + summary)
            print(summary)
        else:
            reglin_speak("I'm sorry I can't find anything for " + summary + "Please try web search")
    
    #exit


    # screenshot
    if there_exists(['screenshot', 'screenshots']):
        x = 1
        reglin_speak("How many screenshots you want to take?")
        try:
            ans = int(record_audio())  
        except Exception:
            reglin_speak("Sorry you have given wrong input please try again.")
            exit()  
        reglin_speak("Okay, So You will get 5 seconds to take each screenshot.")
        while x <= ans:
            time.sleep(5)
            pyautogui.screenshot(SS_Location() +'screenshot' + str(x) +'.png' )
            reglin_speak("Screenshot number " + str(x) + " has been taken") 
            x+=1
        reglin_speak("Okay, your all screenshots has been taken. Is there anything else I can do for you?")          

    # Current location
    if there_exists(["where am i" , "What's my current location" , "what is my current location"]):
        Ip_info = requests.get('https://api.ipdata.co?api-key=test').json()
        loc = Ip_info['region']
        reglin_speak(f"You must be somewhere in {loc}")    

        reglin_speak("Do you want me to show it on map?")
        answer = record_audio()
        if 'yes' in answer:
            url = "https://www.google.com/maps/search/Where+am+I+?/"
            webbrowser.get().open(url)
            reglin_speak("You must be somewhere near here, as per Google maps")
        else:
            reglin_speak("Okay, Do you need any other help?")
            ans = record_audio()
            if 'yes' in ans:
                reglin_speak('How can I help you?')
            else:
                reglin_speak("Okay, Cool")
                exit()

    #Any Location
    if 'where is' in voice_data:
        location = voice_data.split("is")[-1]
        url = 'https://google.nl/maps/place/' + location + '/&amp;'
        webbrowser.get().open(url) # to search for the term in browser
        reglin_speak('Here is the location of ' + location) 

    #Open application 
    if 'application' in voice_data:
        open_file = record_audio('Which Application you want to Open?')
        app = open_file
        try:
            os.startfile(app)
            reglin_speak('Here is what I found')
        except Exception:
            reglin_speak("Sorry, There is no application with this name.")

    # Send Email
    if 'send email' in voice_data:
        try:
            reglin_speak("What should be the subject of this email?")
            subject = record_audio()
            reglin_speak("What should I Say?")
            content = record_audio()
            reglin_speak("Please Enter Reciever's Email Address")
            to = sys.stdin.readline()
            msg = f'Subject: {subject}\n\n{content}'
            sendEmail(to , msg)
            reglin_speak("Your Email has been sent!")

        except Exception:
            reglin_speak("Sorry, due to some issues I was unable to send the Email, Please try again.") 
            exit()
    # Read Email
    if "read email" in voice_data:
        reglin_speak("Okay, just give me a second.")
        passwd = '8930305010'
        user = '******'
        server = e.connect("imap.gmail.com" , user, passwd)
        server.listids()
        email = server.mail(server.listids()[0])
        reglin_speak("Subject of the latest email is: " + email.title)
        reglin_speak("It was sent by, " + email.from_addr)
        reglin_speak("Do you want to read the message?")
        ans = record_audio()
        if 'yes' in ans:
            reglin_speak("And the Body of the email is: " + email.body) 
        else:
            reglin_speak("Okay, Is there anything Else I can do for you?")



    # Device ShutDowm
    if "shutdown" in voice_data:
        reglin_speak('Do you want to shutdown the device?')
        ans = record_audio()
        if 'yes' in ans:
            reglin_speak("After how much time you want it to shutdown? Say immediately if you want to turn off now. Or say, after 10 seconds if you want to turn off after 10 seconds.")
            anz = record_audio()
            if anz == 'immediately':
                shut = os.system('shutdown /s /t 0')
            else:
                try:
                    seconds = anz.split()[-2]
                    shut = 'shutdown /s /t ' + seconds
                    shutdown = os.system(shut)
                except Exception:
                    reglin_speak("Sorry, I can't turnoff your device now, please try it again.")
        else:
            reglin_speak("Okay, So what else can I do for you?")

    # restart
    if "restart" in voice_data:
        reglin_speak('Do you want to restart the device?')
        ans = record_audio()
        if 'yes' in ans:
            try:
                reglin_speak("Okay, GoodBye...")
                shut = os.system('shutdown /r')
            except Exception:
                reglin_speak("Sorry, I can't Restart your device now, please try it again.")
        else:
            reglin_speak("Okay, So what else can I do for you?")


    # Instagram   
    if there_exists(["instagram" ,"How many following" ,"How many follower" , "followers" , "followers" ,"on instagram" , "How many followers you have on instagram","How many follower you have on instagram" ,"How many followers" , "insta" , "on insta"]):
        loader = Instaloader()
        #reglin_speak("Please Enter your username.")
        userz = "xneuropy"
        profile = Profile.from_username(loader.context, userz)

        num_followers = str(profile.followers)
        reglin_speak("Okay, You have " + num_followers + " Followers on instagram.")
        reglin_speak("Do you wanna know about your Following?")
        ans = record_audio()
        if 'yes' in ans:
            num_following = str(profile.followees)
            reglin_speak("You have " + num_following + " Following on instagram.")
        else:
            reglin_speak("Okay fine, Is there anything else I can do for you?")


    # Battery
    if "battery" in voice_data:
        battery = psutil.sensors_battery()
        persent = str(battery.percent)
        plugged = battery.power_plugged
        plugged = "and your charger is plugged in." if plugged else "and your charger is not plugged in."
        reglin_speak("Your Device is " + persent + "%" + " charged, " + plugged)    

    # Joke
    if there_exists(["tell me a joke" , "joke" , "jokes" , "make me laugh"]):
        jokzz = pyjokes.get_joke()
        reglin_speak(jokzz)
        reglin_speak("Do you want another one?")
        ans = record_audio()
        if 'yes' not in ans:
            jok = pyjokes.get_joke()
            reglin_speak(jok)
        else:
            reglin_speak("Okay, What else can I do for you?")

    
    # Notes taking
    if there_exists(['note' , 'notes']) :
        Folder = Folder_Location()
        reglin_speak("Do you want to take notes in existing note. Or want to create a new note?")
        ans = record_audio()
        def listdir(dir):
            fileName = os.listdir(dir)
            return fileName
        files = listdir(Folder)

        if 'existing' in ans:
            reglin_speak("What's the file name?")
            x = record_audio()
            name = x + ".txt"
            if name in files:
                path = 'Notes/' + name
                filez = open(path, 'a')
                note = record_audio("What Should I type: ")
                filez.write("\n" + note)
                filez.close()
                reglin_speak("Your notes are successfully created.")
                reglin_speak("Do you want to Open this note?")
                ans = record_audio()
                if 'yes' in ans:
                    filepath = Folder_Location() + name
                    os.startfile(filepath)
                    reglin_speak("Here are your notes")
                    exit()

            else:
                reglin_speak("Sorry, there is no note with this name. Please create a new one.")
                exit()

        if 'new' in ans:
            reglin_speak("What should be the note name?") 
            x = record_audio()
            name = x + ".txt"

            if name not in files:
                path = 'Notes/' + name
                filez = open(path, 'w')
                note = record_audio("What Should I type: ")
                filez.write(note)
                filez.close()
                reglin_speak("Your notes are successfuly created.")
                reglin_speak("Do you want to Open these notes?")
                ans = record_audio()
                if 'yes' in ans:
                    filepath = Folder_Location() + name
                    os.startfile(filepath)
                    reglin_speak("Here are your notes")
                    exit()
                else:
                    reglin_speak("Okay, fine")
                    exit()
            else:
                reglin_speak("Sorry This File Already Exists")
                
    annzzz = ['bye' , "exit" , "quit" , "nothing", "goodbye" ,'no']
    if there_exists(annzzz) :
        reglin_speak('Okay bye, see you again.')
        exit()
Exemplo n.º 17
0
from parser import parser
from grafica import graph
from fpdf import FPDF
from print_pdf import print_PDF
from send_email import sendEmail

if __name__ == "__main__":
    try:
        year_start, year_end = parser()
        graph(year_start, year_end)
        print_PDF()
        sendEmail()
    except ValueError:
        print("Error de parametros introduce un año entre 1960 y 2015")
Exemplo n.º 18
0
    gabarito = pdf[0] + ''
    line = gabarito.find('\n')
    gabarito = gabarito[line:]
    line = gabarito.find('1')
    gabarito = gabarito[line:]
    gabarito = gabarito.replace('\n', ' ')
    respostas = gabarito.split(' ')
    respostas = list(filter(lambda rm: rm != "", respostas))
    dicResp = {}
    i = 0
    while i < len(respostas)-1:
        dicResp[respostas[i]] = respostas[i+1]
        i += 2

    return dicResp

def saveDicResp(diretorio, dicResp):
    
    arqResp = open(diretorio+'Respostas.txt', 'w')
    for num in dicResp:
        arqResp.write(str(num)+'::'+str(dicResp[num])+'\n')
    arqResp.close()


if __name__ == '__main__':
    
    dicEnade = getDicEnade()
    extractQuestions(dicEnade)
    se.sendEmail('*****@*****.**', 'Extração de Questões Terminou', 'Todas as questões foram extraidas!!')
    extractAnswers(dicEnade)
Exemplo n.º 19
0
def getAnalysis():
    today = date.today()
    new_data = {}

    #Initial portfolio weights: ORDER: NIO -> BTC ->ETH ->XRP ->ADA ->JKS ->SPWR ->AAPL
    initial_weight = np.array(
        [0.1201, 0.254, 0.122, 0.072, 0.410, 0.007, 0.004, 0.007])

    #Loding previous dataset
    df = pd.read_csv("./history/prices.csv")

    #converting date to index
    df = df.set_index("Date")

    #make sure everyseries is of type float
    for column in df.columns:
        df[column] = df[column].astype(float)

    #calculating percentage change
    return_stocks = df.pct_change()

    number_of_portfolios = 2000  #2000 simulated portfolios
    RF = 0  #return on risk-free asset

    portfolio_returns = []
    portfolio_risk = []
    sharpe_ratio_port = []
    portfolio_weights = []

    #iterating over each portfolio simulation
    for portfolio in range(number_of_portfolios):

        #generate a w random weight of lengt of number of stocks
        weights = np.random.random_sample((len(df.keys())))

        weights = weights / np.sum(weights)
        annualize_return = np.sum((return_stocks.mean() * weights) * 252)
        portfolio_returns.append(annualize_return)
        #variance
        matrix_covariance_portfolio = (return_stocks.cov()) * 252
        portfolio_variance = np.dot(
            weights.T, np.dot(matrix_covariance_portfolio, weights))
        portfolio_standard_deviation = np.sqrt(portfolio_variance)
        portfolio_risk.append(portfolio_standard_deviation)
        #sharpe_ratio
        sharpe_ratio = ((annualize_return - RF) / portfolio_standard_deviation)
        sharpe_ratio_port.append(sharpe_ratio)

        portfolio_weights.append(weights)

    portfolio_risk = np.array(portfolio_risk)
    portfolio_returns = np.array(portfolio_returns)
    sharpe_ratio_port = np.array(sharpe_ratio_port)

    porfolio_metrics = [
        portfolio_returns, portfolio_risk, sharpe_ratio_port, portfolio_weights
    ]

    portfolio_dfs = pd.DataFrame(porfolio_metrics)
    portfolio_dfs = portfolio_dfs.T
    portfolio_dfs.columns = [
        'Port Returns', 'Port Risk', 'Sharpe Ratio', 'Portfolio Weights'
    ]

    #convert from object to float the first three columns.
    for col in ['Port Returns', 'Port Risk', 'Sharpe Ratio']:
        portfolio_dfs[col] = portfolio_dfs[col].astype(float)

    #portfolio with the highest Sharpe Ratio
    Highest_sharpe_port = portfolio_dfs.iloc[
        portfolio_dfs['Sharpe Ratio'].idxmax()]
    #portfolio with the minimum risk
    min_risk = portfolio_dfs.iloc[portfolio_dfs['Port Risk'].idxmin()]

    #Highest_sharpe_port
    #print(Highest_sharpe_port)
    #print(min_risk)

    #Summarizing Optimal Action to take
    max_sharpe_port = pd.Series(
        (Highest_sharpe_port["Portfolio Weights"]) * 100, index=df.keys())
    min_risk_port = pd.Series((min_risk["Portfolio Weights"]) * 100,
                              index=df.keys())

    #creating a summary recommendation table
    summary_table = pd.DataFrame(columns=[max_sharpe_port.index])
    summary_table.loc["current_position"] = initial_weight * 100
    summary_table.loc["max_sharpe_port"] = max_sharpe_port.values
    summary_table.loc["min_risk_port"] = min_risk_port.values

    summary_table = summary_table.round(2)
    print(summary_table)

    sendEmail(
        "*****@*****.**",
        "Weekly Portfolio Update {}".format(str(today.strftime("%d %b, %Y"))),
        summary_table.T)
Exemplo n.º 20
0
def getCSV(request):
    db = setupDB.connectDB()

    #Determine time frame
    if request.form['length'] == 'all':
        if request.form['data_type'] == 'activity':
            #Download all activity history
            query = ('SELECT activity_type, duration, distance, time_created '
                     'FROM activities WHERE user_id=:userID')

        else:
            #Download all health history
            query = ('SELECT height, weight, bmi, time_created '
                     'FROM health WHERE user_id=:userID')

        #Perform Query
        rows = db.query(query, userID=request.form['uid'])

    else:
        #Get time frame
        today = d = datetime.today()
        if request.form['length'] == 'day':
            start_day = today - timedelta(days=1)

        elif request.form['length'] == 'week':
            start_day = today - timedelta(days=7)

        elif request.form['length'] == 'month':
            start_day = today - timedelta(days=30)

        else:
            raise Exception('Invalid Request')

        #Determine data type
        if request.form['data_type'] == 'activity':
            #Download activity history
            query = ('SELECT activity_type, duration, distance, time_created '
                     'FROM activities WHERE user_id=:userID '
                     'AND DATE(time_created) >= DATE(:startDay) '
                     'AND DATE(time_created) <= DATE(:endDay)')

        else:
            #Download health history
            query = ('SELECT height, weight, bmi, time_created '
                     'FROM health WHERE user_id=:userID '
                     'AND DATE(time_created) >= DATE(:startDay) '
                     'AND DATE(time_created) <= DATE(:endDay)')

        #Perform Query
        rows = db.query(query,
                        userID=request.form['uid'],
                        startDay=start_day,
                        endDay=today)

    if len(rows.as_dict()) == 0:
        raise Exception('You have no history for the selected report')

    #write results to file
    filename = request.form['data_type'] + "_history.csv"
    f = open('downloads/' + filename, "w")
    f.write(rows.export('csv'))
    f.close()

    #Download file
    if request.form['method'] == 'download':
        return send_from_directory('downloads', filename, as_attachment=True)

    #Send email with CSV attachment
    elif request.form['method'] == 'email':
        #Get user email & user_name
        query = ('SELECT user_name, email ' 'FROM user_data WHERE id=:userID')
        user = db.query(query, userID=request.form['uid']).first()

        mail_to = user.email
        mail_subject = request.form['data_type'] + " history"
        mail_body = """<h3>Hello %s,</h3><br>
					Here is your requested history.""" % (user.user_name)

        send_email.sendEmail(mail_to, mail_subject, mail_body, filename)

    #only defining 'is-error' to get red text for better visibility
    flash(('Your requested data has been emailed.'), 'is-error')
    return redirect(url_for('user_settings'))
Exemplo n.º 21
0


if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(test_theme))
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(test_user_action))
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(test_course_ware))
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(test_course))
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(indentity))

    #

    with open('HTMLReport.html', 'w', encoding='utf8') as f:
        runner = HTMLTestRunner(stream=f,
                                title='鹏云课堂盒子测试',
                                description='鹏云课堂V2.6版本',
                                verbosity=2
                                )
        runner.run(suite)
        # 发送邮件
        authInfo = {}
        authInfo['server'] = 'smtp.163.com'
        authInfo['user'] = '******'
        authInfo['password'] = '******'
        fromAdd = '*****@*****.**'
        toAdd = ['*****@*****.**']
        subject = '鹏云课堂V2.6版本'
        plainText = '鹏云课堂V2.6版本接口测试,详情请下载附件'
        sendEmail(authInfo, fromAdd, toAdd, subject, plainText)
Exemplo n.º 22
0
    #Generates the receipt time in order to be used as the filename to be printed in a txt file

    receipt_time = ""
    now = datetime.datetime.now()
    receipt_time = now.strftime("%Y-%m-%d-%H-%M-%S-%f")


    #Generates and prints final receipt
    final_receipt = receipt_generator(scanned_list) #> <class shopping_cart.py> 
    print (final_receipt)


    #Enter an email address to send the receipt
    email_choice = input("Would you like to receive a receipt via email?\tEnter y/n\t")
    if (email_choice.lower() == "y"):
        customer_email = input("Enter your email address:\t")
        sendEmail(customer_email, receipt_generator(scanned_list)) #> <class send_email.py> 
    else:
        print("\n")


    #Prints a physical copy of the receipt with the time the receipt was created as the title
    print_choice = input("Would you like a physical copy of the receipt?\tEnter y/n\t")
    if print_choice.lower() == "y":
        file_name = os.path.join(os.path.dirname(__file__), "receipts", receipt_time + ".txt") # a relative filepath
        with open(file_name, "w") as file: # "w" means "open the file for writing"
           file.write(final_receipt)
           print("Receipt generated in receipts folder")
    print("\nHave a good day\n")
Exemplo n.º 23
0
        print("查询到满足条件的车次,正在努力订票中.....")
        is_success = Ticket.order(best_sell, from_station, to_station,
                                  train_date)
        if not is_success:
            print("提交订单失败!\n")
            continue
        Ticket.get_token_info()
        Ticket.get_seat_info()
        get_leftticket = Ticket.get_leftticket_info()
        if not get_leftticket:
            continue
        html_confirm = Ticket.confirm()
        if html_confirm:
            while 1:
                WaitTime = Ticket.queryOrderWaitTime()
                waittime = WaitTime['data']['waitTime']
                orderId = WaitTime['data']['orderId']
                if orderId:
                    print(f'恭喜!订票成功,订单号:{orderId}!请前往12306网站付款!')
                    sendEmail(config['email_address'])
                    break
                else:
                    if WaitTime['messages']:
                        print(f"{WaitTime['messages']}\n很遗憾,购票失败!")
                    else:
                        print(f"排队中.......大概需要{waittime}分钟!")
                    time.sleep(2)
            break
        else:
            print("订票失败!")
Exemplo n.º 24
0
def main(url):
    content = deal_sented_content(url)
    send_email.sendEmail('极客搜索', content)