Exemplo n.º 1
0
 def date_format(self, time):
     """This method change the format of date in mangahub example from  1 hour ago or 10-31-2020 into 20200619"""
     if "just" in time:
         time = datetime.datetime.now().strftime("%Y%m%d")
     elif "less than an hour" in time:
         time = datetime.datetime.now() - datetime.timedelta(seconds=50)
         time = time.strftime("%Y%m%d")
     elif "hour ago" in time:
         time = datetime.datetime.now() - datetime.timedelta(hours=1)
         time = time.strftime("%Y%m%d")
     elif "hours ago" in time:
         hour = int(time[:time.find("hours ago")].strip())
         time = datetime.datetime.now() - datetime.timedelta(hours=hour)
         time = time.strftime("%Y%m%d")
     elif "Yesterday" in time:
         time = datetime.datetime.now() - datetime.timedelta(days=1)
         time = time.strftime("%Y%m%d")
     elif "days ago" in time:
         day = int(time[:time.find("days ago")].strip())
         time = datetime.datetime.now() - datetime.timedelta(days=day)
         time = time.strftime("%Y%m%d")
     elif "weeks ago" in time:
         week = int(time[:time.find("weeks ago")].strip())
         time = datetime.datetime.now() - datetime.timedelta(weeks=week)
         time = time.strftime("%Y%m%d")
     else:
         time = time.split("-")
         time = time[2] + time[0] + time[1]
     return int(time)
Exemplo n.º 2
0
 def time_ms(self, time):
     f = '00:00:00.00'
     if time[-2:] == '+2':
         time = time[:-2]
     elif time[-3:] == 'dnf':
         time = time[:-3]
     time = '00' + time + '00'
     dec = time.find('.')
     col = time.find(':')
     col2 = time.rfind(':')
     if '.' in time:
         f = f[:9] + time[dec + 1:dec + 3]
         f = f[:6] + time[dec - 2:dec] + f[8:]
     if ':' in time:
         f = f[:6] + time[col2 + 1:col2 + 3] + f[8:]
         f = f[:3] + time[col2 - 2:col2] + f[5:]
     if col != col2:
         f = time[col - 2:col] + f[2:]
     if dec == col:
         time = time[2:-2]
         while len(time) < 8:
             time = '0' + time
         f = time[:2] + ':' + time[2:4] + ':' + time[4:6] + '.' + time[6:]
     ms = 0
     mul = 10
     for c in f[-1::-1]:
         if c.isnumeric():
             ms += int(c) * mul
             mul *= 10
         elif c == ':':
             mul *= 60
     return ms
Exemplo n.º 3
0
    def stringToTime(self, time):
        '''
        Desc:
            Turns a string in HH:MM:SS format into seconds

        Arguments:
            time (string) - the time in HH:MM:SS format
        
        Returns:
            int

        Raises:
            InvalidTimeFormatException
        '''
        sep1 = time.find(':')
        sep2 = time.find(':', sep1 + 1)
        if sep1 == -1 or sep2 == -2:
            raise InvalidTimeFormatException
        else:
            try:
                h = int(time[:sep1])
                m = int(time[sep1 + 1:sep2])
                s = int(time[sep2 + 1:])
            except:
                raise InvalidTimeFormatException
            if h < 0 or m >= 60 or m < 0 or s >= 60 or s < 0:
                raise InvalidTimeFormatException
            else:
                return (h * 3600) + (m * 60) + s
Exemplo n.º 4
0
    def get_battery_status(self):
        import subprocess
        proc = subprocess.Popen(['pmset', '-g', 'batt'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)

        out, err = proc.communicate()
        out = out.split("\n")

        if len(out) == 2:
            return ("AC Power - No Battery", "No Battery or UPS", False, 0, 0,
                    0, 0)

        power_status = out[0].split("'")[1]
        data = out[1].split("\t")
        ups_model = data[0]
        data = data[1].split(";")
        percentage = data[0][0:-1]  #data[1][0:percent_locale]
        charging = data[1].find("discharging") == -1
        if not charging:
            time = data[2][0:data[2].find(":") + 3].strip()
            hours = data[2][0:time.find(":") + 1]
            min = data[2][time.find(":") + 2:time.find(":") + 4]
        else:
            time = 0
            hours = 0
            min = 0

        return (power_status, ups_model, charging, percentage, time, hours,
                min)
Exemplo n.º 5
0
    def cfbschedule(self, irc, msg, args, optteam):
        """[team]
        Display the schedule/results for team.
        """
        
        lookupteam = self._lookupTeam(optteam)
        
        if lookupteam == "0":
            irc.reply("I could not find a schedule for: %s" % optteam)
            return
        
        url = 'http://www.cbssports.com/collegefootball/teams/schedule/%s/' % lookupteam

        try:
            req = urllib2.Request(url)
            html = (urllib2.urlopen(req)).read()
        except:
            irc.reply("Failed to open: %s" % url)
            return
            
        html = html.replace('&amp;','&').replace(';','')
    
        soup = BeautifulSoup(html)
        
        if soup.find('table', attrs={'class':'data stacked'}).find('tr', attrs={'class':'title'}).find('td'):
            title = soup.find('table', attrs={'class':'data stacked'}).find('tr', attrs={'class':'title'}).find('td')
        else:
            irc.reply("Something broke with schedules. Did formatting change?")
            return

        div = soup.find('div', attrs={'id':'layoutTeamsPage'}) # must use this div first since there is an identical table.
        table = div.find('table', attrs={'class':'data', 'width':'100%'})
        rows = table.findAll('tr', attrs={'class':re.compile('^row[1|2]')})

        append_list = []
        
        for row in rows:
            date = row.find('td')
            team = date.findNext('td').find('a')
            time = team.findNext('td')
            
            if team.text.startswith('@'): # underline home
                team = team.text
            else:
                team = ircutils.underline(team.text)
        
            if time.find('span'): # span has score time. empty otherwise.
                time = time.find('span').string
                append_list.append(date.text + " - " + ircutils.bold(team) + " (" + time + ")")
            else:
                time = time.string
                append_list.append(date.text + " - " + ircutils.bold(team))

        descstring = string.join([item for item in append_list], " | ")
        output = "{0} for {1} :: {2}".format(title.text, ircutils.bold(optteam.title()), descstring)
        
        irc.reply(output)
Exemplo n.º 6
0
def parse(urlweb):
    textdecode=HTMLParser.HTMLParser()
    urldata=urlweb.read()
    ET=etree.HTML(urldata)
    tr=ET.xpath('//tr[2]/td/form/div')
    try:
        #------ time ----------------------------------------------------
        time = etree.tostring(tr[1][0][1])
        time=textdecode.unescape(time)
        _tag = u'乘車時間'
        t_value = time[time.find('"-1">')+len('"-1">')+2:time.find('</font>')-3]
        _time = _tag +' : '+ t_value
        #------ price ----------------------------------------------------
        price = etree.tostring(tr[0][0][1][0][0][0])
        price=textdecode.unescape(price)
        _tag = u'單程票價'
        p_value = price[price.find('">')+len('">'):price.find('</font>')-1]
        _price = _tag +' : '+ p_value        
        #------ route ----------------------------------------------------
        route = etree.tostring(tr[1][0][2])
        route=textdecode.unescape(route)
        _tag = u'轉乘資訊'
        beg = 0
        end = 0
        transfer = []
        while end != -1 and beg !=-1:
            beg = route.find('=>',end)+len('=>')+1
            end = route.find(u'轉乘',beg)
            if end != -1 and beg !=-1:
                transfer.append(route[beg:end])
            else:
                transfer.append(u'可直達')
                transfer.append(u'可直達')
                break
        _route = _tag +' : '

        i = 0
        for n in transfer:
            if n == u'可直達' and i>0:
                break
            else:
                _route = _route +'->'+ n +'\n\t   '
            i +=1
        #------ start -> destination ----------------------------------------------------
        _start = route[route.find('<font size="-1">')+len('<font size="-1">'):route.find(u'搭乘')]
        _dest = route[beg:route.find('</font>')]
        _station = _start +' -> '+ _dest
        info = _station+u'\n▪'+_time +u'分鐘\n▪'+ _price +u'元\n▪'+ _route
        app = _station+u'A▪'+_time +u'分鐘A▪'+ _price +u'元A▪'+ _route
        pxa = t_value+','+p_value+','+node.get(transfer[0])+','+node.get(transfer[1])
        TX = pxa+'QAQ'+info
        return TX
    except:
        pass
Exemplo n.º 7
0
    async def mute(self, ctx, member: discord.Member, time: str, *, reason):
        role = discord.utils.get(ctx.guild.roles, name="mute")

        if role == None:
            role = await ctx.guild.create_role(name="mute")

            for channel in ctx.guild.channels:
                await channel.set_permissions(role, send_messages=False)

        hour = 0
        minute = 0
        second = 0

        a = [time]
        if time.find("h") != -1:
            a = a[0].split("h")
            hour = a.pop(0).strip()

        if time.find("m") != -1:
            a = a[0].split("m")
            minute = a.pop(0).strip()

        if time.find("s") != -1:
            a = a[0].split("s")
            second = a.pop(0).strip()

        await member.add_roles(role)

        ending = datetime.datetime.now() + datetime.timedelta(
            hours=int(hour), minutes=int(minute), seconds=int(second))
        ending = ending.strftime('%Y-%m-%d %H:%M:%S')

        cur.execute(f"INSERT INTO ON_MUTED VALUES (?, ?, ?)",
                    (member.id, ending, ctx.guild.id))
        conn.commit()
        cur.execute(f"INSERT INTO MUTES VALUES (?, ?, ?)",
                    (member.id, time, reason))
        conn.commit()

        embed = discord.Embed(title="관리 로그",
                              colour=discord.Colour.red(),
                              timestamp=datetime.datetime.now())
        embed.add_field(name="처벌 내용", value=f"{time}동안 채팅 금지", inline=False)
        embed.add_field(name="유저", value=member.mention)
        embed.add_field(name="관리자", value=ctx.author.mention)
        embed.add_field(name="사유", value=reason, inline=False)

        await self.app.get_channel(749998827356029008).send(embed=embed)
        await self.app.get_channel(730016508859645992).send(embed=embed)
        await ctx.send(
            f"> :ballot_box_with_check: {member.mention}님에게 일시적으로 입을 막았습니다",
            delete_after=3)
def get_time(time):
    if time.find("前")!=-1:
        ret=time.split("前")[-1].split(" ")[0]
        return ret
    elif time.find("日")!=-1:
        tmp=time.replace(" ","")
        tmp=time.split("日")[0]
        tmp_lst=tmp.split("月")
        ret="-".join(tmp_lst)
        ret=ret.replace(" ","")
        return ret
    else:
        return "0-0"
Exemplo n.º 9
0
def convertTime(time):
    timeInSeconds = 0
    if time.find(":")>0:
        min,sec = time.split(":")
    elif time.find("m")>0:
         min,sec = time.split("m")
         sec = sec.replace("s","")
    else:
        min = 0
        sec = 0
    min = int(min)
    sec = int(sec)       
    return (min*60)+sec
Exemplo n.º 10
0
def check_time(time):
    index2 = time.find('秒前', 0, len(time))
    index3 = time == '刚刚'
    if index2 > 0 or index3:
        return 1

    smin = '分钟前'
    index = time.find(smin, 0, len(time))
    if index > 0:
        time = time.replace(smin, '', 1)
        return int(time)

    return -1
Exemplo n.º 11
0
 def date_format(self, time):
     """This method change the format of date in mangapark example from 1 hours ago into 20200619"""
     if "minutes ago" in time:
         time = int(time[:time.find("minutes ago")].strip()) / 1440
     elif "an hour ago" in time:
         time = 1 / 24
     elif "hours ago" in time:
         time = int(time[:time.find("hours ago")].strip()) / 24
     elif "days ago" in time:
         time = int(time[:time.find("days ago")].strip())
     elif "years ago" in time:
         time = int(time[:time.find("years ago")].strip()) * 365
     elif "a year ago" == time:
         time = 365
     return time
Exemplo n.º 12
0
    def market_recorder(self, product, path):

        ticker = self.api.ticker(product_code=product)
        board = self.api.board(product_code=product)

        time = ticker['timestamp']
        last_price = ticker['ltp']  # 最終取引値 -> 値動きの判断に利用する
        mid_price = board['mid_price']

        time = time.replace("T", " ")

        if time.find(".") == -1:
            tdatetime = dt.strptime(time, '%Y-%m-%d %H:%M:%S')
            tdatetime = tdatetime.timestamp()
        else:
            tdatetime = dt.strptime(time, '%Y-%m-%d %H:%M:%S.%f')
            tdatetime = tdatetime.timestamp()

        time = tdatetime

        print(time)

        w = pd.DataFrame([[time, last_price,
                           mid_price]])  # 取得したティッカーをデータフレームに入れる

        w.to_csv(path, index=False, encoding="utf-8", mode='a',
                 header=False)  # append to the CSV
Exemplo n.º 13
0
 def download_done(self, val):
     logging.debug('window_functions.py - MyQuery - download_done')
     time = str(val['download_time'])
     index1 = time.find(':')
     index2 = time.find(':', index1 + 1)
     hour = time[:index1]
     min = time[index1 + 1:index2]
     sec = time[index2 + 1:]
     if len(hour) == 1:
         hour = '0' + hour
     if len(min) == 1:
         min ='0' + min
     self.download_time = hour + 'h ' + min + 'mn ' + sec + 's'
     self.file_path = val['file_path']
     self.average_speed = val['average_speed']
     self.close()
Exemplo n.º 14
0
def getNimadili():
    for page in range(1, 2001):
        proxy_url = 'http://www.nimadaili.com/gaoni/' + str(page)
        proxy_headers = {
            'User-Agent':
            'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'
        }
        web_data = requests.get(proxy_url, headers=proxy_headers)
        soup = BeautifulSoup(web_data.text, 'lxml')
        ips = soup.find_all('tr')
        for i in range(1, len(ips)):
            ip_info = ips[i]
            try:
                tds = ip_info.find_all('td')
                time = tds[5].text
                if time.find('天') == -1:
                    continue
                ip = tds[0].text
                port = ''
                httpType = tds[1].text.lower()
                othreType = tds[2].text
                address = httpType + '://' + ip
                proxies = {httpType: address}
                response = requests.get('http://www.ip38.com/',
                                        headers=proxy_headers,
                                        proxies=proxies)
                if response.status_code == 200:
                    print(str(proxies) + '有效')
                    sql = 'insert into proxy_ip (`address`,`ip`,`port`,`httpType`,`otherType`) values (?,?,?,?,?)'
                    data = (address, ip, port, httpType, othreType)
                    poolSqlite.saveInfo(sql, data)
            except:
                #traceback.print_exc()
                print(str(proxies) + '不可用,继续下一个')
Exemplo n.º 15
0
def play():
    import time
    global score
    global playing
    global starttime
    t.forward(11)

    if random.randint(1, 7) == 1:
        ang = te.towards(t.pos())
        te.setheading(ang)

    if t.distance(te) < 12:
        time = str(time.time() - starttime)
        text = "Score : " + time[:time.find('.') + 2] + "'s"
        message("Game Over", text)
        playing = False
        score = 0

        #------------------------위치-------------
        y = t.ycor()
        x = t.xcor()

        if y > 230:
            t.sety(-230)
        if y < -230:
            t.sety(-230)
        if x > 230:
            t.setx(230)
        if x < -230:
            t.setx(-230)
        if playing:
            talk.goto(180, 180)
            time = time.time() - starttime
            speed = time + 5
        if speed > 12:
            speed = 12
            te.forward(speed)
            talk.clear()
            time = str(time)
            time = (time)[:time.find('.') + 2]
            talk.write(time + "'s", False, "center", ("", 40))

            t.ontimer(play, 1)
        elif not playing:
            import time
            time.sleep(2)
            finish()
Exemplo n.º 16
0
 def isValidTime(self, time): 
     result = False
     if len(time) <= 5: 
         if time.find(':'): 
             for num in time.split(':'): 
                 if not num.isdigit():
                     result = False
             result =  True
     return result
Exemplo n.º 17
0
def scrapped_movie(mov_link):
    new_url = requests.get(mov_link).text
    soup = BeautifulSoup(new_url, 'lxml')
    movie_dict = {}
    new_data = soup.find('div', class_="title_wrapper").h1.text
    movie_name = ''
    for i in new_data:
        if i == '(':
            break
        else:
            movie_name += i
    movie_Name = movie_name.replace('\xa0', '')
    movie_dict['Name'] = movie_Name
    Bio = soup.find('div', class_='summary_text').text
    plot = ''
    for i in Bio:
        if '\n' in i:
            i.replace('\n', '')
        plot += (i)
    movie_dict['Bio'] = plot.strip()
    dire = soup.find('div', class_="credit_summary_item")
    director = dire.find_all('a')
    director_list = []
    for i in director:
        director_list.append(i.text)
    movie_dict['Director'] = director_list
    pic = soup.find('div', class_="poster")
    movie_dict['Poster Url'] = pic.find('img')['src']
    genre_list = []
    gen = soup.find_all('div', class_="see-more inline canwrap")
    for i in gen:
        if 'Genres:' in i.text:
            genre = i
            break
    genres = genre.find_all('a')
    for i in genres:
        genre_list.append(i.text)
    movie_dict['Genres'] = genre_list
    detail = soup.find_all('div', class_="txt-block")
    for i in detail:
        if 'Country:' in i.text:
            movie_dict['Country'] = i.find('a').text
        elif 'Language:' in i.text:
            language = i.find_all('a')
    time = soup.find('div', class_="subtext")
    run = time.find('time').text.strip()
    if run[4] in string.digits:
        Runtime = (int(run[0]) * 60) + int(run[3] + run[4])
    else:
        Runtime = (int(run[0]) * 60) + int(run[3])
    movie_dict['Runtime'] = int(Runtime)
    language_list = []
    for i in language:
        language_list.append(i.text)
    movie_dict['Language'] = language_list
    return (movie_dict)
Exemplo n.º 18
0
def ParseTime(time):
    time = time.replace('PT', '')
    hours = 0
    minutes = 0
    seconds = 0
    if (time.find('H') != -1):
        hours = time[:time.find('H')]
        time = time[time.find('H') + 1:]
    if (time.find('M') != -1):
        minutes = time[:time.find('M')]
        time = time[time.find('M') + 1:]
    if (time.find('S') != -1):
        seconds = time[:time.find('S')]
        time = time[time.find('S') + 1:]
    return (((int(hours) * 60) + int(minutes)) * 60 + int(seconds))
Exemplo n.º 19
0
def time_calculate(time,origin):

    if origin=='sbaidu':
       if time.find(':')!=-1:
           time = str(datetime.datetime.now().strftime('%Y-%m-%d'))+" "+time
           return time+':00'
       else:
           if(int(time.split('-')[0])>1000):
               return time
           else:
               time = str(datetime.datetime.now().year)+"-"+time
               return time

    else:
        if time.count('-')==2:
            return time
        if time.find('刚'):
            time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 得到今天日期
            return str(time)
        if time.find('天前')==2:
            day = time[0:1]
            delta = datetime.timedelta(days=int(day))
            time = datetime.datetime.now().strftime('%Y-%m-%d')#得到今天日期
            time = datetime.datetime.strptime(time, '%Y-%m-%d')#转换成时间格式
            time = time - delta
            return str(time)
        if time.find('小时')==2:
            hour = time[0:1]
            if(hour=='半'):
                delta = datetime.timedelta(minutes=30)
            else:
                delta = datetime.timedelta(hours=int(hour))
            time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 得到今天日期
            time = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S')  # 转换成时间格式
            time = time - delta
            return str(time)
        if time.find('分钟')==2:
            minute = time[0:1]
            delta = datetime.timedelta(minutes=int(minute))
            time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 得到今天日期
            time = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S')  # 转换成时间格式
            time = time - delta
            return str(time)
        if time.find('昨天')==0:
            delta = datetime.timedelta(days=1)
            date = datetime.datetime.now().strftime('%Y-%m-%d')# 得到今天日期
            date = datetime.datetime.strptime(date, '%Y-%m-%d')  # 转换成时间格式
            date = date - delta#减一天
            time = date.strftime('%Y-%m-%d')+' '+ time[3:]+":00"
            return str(time)
        if time.find('前天')==0:
            delta = datetime.timedelta(days=2)
            date = datetime.datetime.now().strftime('%Y-%m-%d')# 得到今天日期
            date = datetime.datetime.strptime(date, '%Y-%m-%d')  # 转换成时间格式
            date = date - delta#减一天
            print(time[3:])
            time = date.strftime('%Y-%m-%d')+' '+ time[3:]+":00"
            return str(time)
Exemplo n.º 20
0
 def matchDayWeek(self, event):
     path = str(event.src_path)
     global days
     for day in days:
         if re.match(MUSIC_FOLDER + SHOWS + day, path):
             time = path[(path.find(day) + len(day) + 1):]
             time = time[0:(time.find("/"))]
             addValue = (dig, MUSIC_FOLDER + SHOWS + day, day + sho + time)
             return addValue
     return ("", "", "")
Exemplo n.º 21
0
def timezone():
    conf = open("default.conf")
    for time in conf.readlines():
        if (time.find('zonename') != -1):
            if (time[0] == '#'):
                continue
            cmd = "./config_image.sh --timezone %s" % (time.strip())
            os.system(cmd)
            break
    conf.close()
Exemplo n.º 22
0
    def save_article(self, num, content):
        '''
        :param content: a list get from screen
        '''
        chinese_keyword = {
            'board': '看板',
        }

        author_line = content[0].encode('utf-8').split()
        if not chinese_keyword['board'] in author_line:
            return
        _i = author_line.index(chinese_keyword['board'])
        author = ' '.join(author_line[1:_i])

        title_line = content[1].encode('utf-8').split()[1:]
        title = ' '.join(title_line)

        time_line = content[2].encode('utf-8').split()[1:]
        time = ' '.join(time_line)
        if not time.find('(') == -1:
            time = time[time.find('(') + 1:time.find(')')]
        time = time.split()
        time.pop(1)
        time = ' '.join(time)
        print time


        article = '\n'.join(content[3:]).encode('utf-8')

        try:
            post = Teacher.get(bbs_id=num)
            post.content = article
            post.save()
            logger.info('Update: {id}'.format(id=num))
        except Teacher.DoesNotExist:
            post = Teacher.create(author=author,
                title=title,
                pub_time=time,
                content=article,
                bbs_id=num
            )
            logger.info('Insert: {id}'.format(id=num))
Exemplo n.º 23
0
def modify_time(time):
    if ':' in time:#such as 20:30
        time=str(datetime.date.today())+' '+time
        date_time=datetime.datetime.strptime(time,'%Y-%m-%d %H:%M')
    else:
        if time.find('-')!=4:#such as 11-27
            time='2021-'+time
        else:#such as 2020-11-27
            pass
        date_time=datetime.datetime.strptime(time,'%Y-%m-%d').date()
    return date_time
Exemplo n.º 24
0
def get_start_time(block, date):
    L = np.array([])
    for time in block[:, 0]:
        a = time.find(" ")
        if a == 4:
            L = np.append(L, datetime.strptime\
                (date+time[a-4:a+3], '%Y-%m-%d %I:%M %p'))
        elif a == 5:
            L = np.append(L, datetime.strptime\
                (date+time[a-5:a+3], '%Y-%m-%d %I:%M %p'))
    block = np.insert(block, 0, L, axis=1)
    return block
Exemplo n.º 25
0
def timetoseconds(time):
    seconds = 0
    h = time.find("h")
    if (h != -1):
        seconds += int(time[0:h]) * 3600
        h += 1
    else:
        h = 0

    m = time.find("m")
    if (m != -1):
        seconds += int(time[h:m]) * 60
        m += 1
    else:
        m = 0

    s = time.find("s")
    if (s != -1):
        seconds += int(time[m:s])

    return (seconds)
Exemplo n.º 26
0
def get_runtime(soup):
    
    '''
    Function to get total movie time in minutes from the Box Office Mojo individual movie site's soup.
    
    Args:
        soup (BeautifulSoup): The beautiful soup that is obtained from requests.get(url)
    Returns: 
        runtime (int): The runtime of the movie
    
    '''  
    try:
        time = soup.find(text = 'Runtime: ').next_sibling.text
        if time.find('hrs.') > 0 and time.find('min.') > 0:
            hours = int(time[:time.find('hrs.')])
            minutes = int(time[time.find('min.') - 3:time.find('min.')])
            runtime = (hours*60) + minutes
            return runtime
        else:
            return None
    except:
        return 'N/A'
Exemplo n.º 27
0
	def __getIntFromTime(self, time):
		pm = False
		if "PM" in time.upper():
			pm = True
		
		if "." in time or ":" in time:
			time = time.replace(":",".")
			time = time[:time.find(".")]
		
		time = int(time.replace("AM", "").replace("PM", "").replace("am", "").replace("pm", ""))
		if pm: time = int(time)+12
		
		return str(time)
Exemplo n.º 28
0
def standard_work_article(target_url):
    return_data = []
    headers = {'User-Agent': UserAgent}
    res = requests.get(target_url, headers=headers)
    res.raise_for_status()
    reg_content = res.content.decode('utf8')
    html_page = bs4.BeautifulSoup(reg_content, 'lxml')
    infos = html_page.find(class_='detailCont').findAll('p')
    for one_info in infos:
        content_dir = re.search('<p[\\s\\S]+/p>', str(one_info))
        if content_dir:
            need_content = one_info.text
        else:
            if isinstance(one_info, bs4.NavigableString):
                need_content = one_info
            else:
                continue
        if not need_content.strip():
            continue
        return_data.append(need_content.strip())
    time = html_page.find(class_='Wh')
    time_year = time.find("span", {'class': ""}).text
    timer_hour = time.find("span", {'class': 'hour'}).text
    time = time_year + " " + timer_hour
    nian = urllib.parse.unquote_plus('%E5%B9%B4')
    yue = urllib.parse.unquote_plus('%E6%9C%88')
    ri = urllib.parse.unquote_plus('%E6%97%A5')
    datetime_dir = re.match(
        '(?P<year>\d{4})%s(?P<month>\d+?)%s(?P<day>\d+?)%s (?P<hour>\d+?):(?P<minute>\d+)'
        % (nian, yue, ri), time)

    tt_tmp = '%s-%s-%s %s:%s' % (datetime_dir['year'], datetime_dir['month'],
                                 datetime_dir['day'], datetime_dir['hour'],
                                 datetime_dir['minute'])
    _datetime = 0
    if datetime_dir:
        _datetime = get_time('%Y-%m-%d %H:%M', tt_tmp)
    _title = html_page.find('h2').text
    return _datetime, '%s<replace title>%s' % (_title, '\n'.join(return_data))
Exemplo n.º 29
0
def parse_time(time):
    """Given the time string, parse and turn into normalised minute count"""

    if time.endswith('m'):
        time = time[0:-1]

    if time.find('h') != -1:
        time = time.replace('h', ':')

    if time.find(':') != -1:
        hours, minutes = time.split(':')

        if minutes.strip() == "":
            minutes = 0

    else:
        hours = 0
        minutes = int(time.strip())

    total = int(minutes) + (int(hours) * 60)

    return total
Exemplo n.º 30
0
    def voice_manipulation(self, text):

        command = ''
        #Hours are requred, but I want to give minutes a default value
        minute = 0

        if 'a.m.' in text:
            command = 'a.m.'

        if 'p.m.' in text:
            command = 'p.m.'

        split_text = text.split()
        if ':' not in text:
            hour = int(split_text[split_text.index(command) - 1])
            print(hour, command)

        if ':' in text:
            split_text = text.split()
            time = split_text[split_text.index(command) - 1]
            hour = int(time[0:time.find(':')])
            minute = int(time[time.find(':') + 1:len(time)])

        try:
            if hour >= 1 and hour <= 12:
                if command == 'p.m.' and hour != 12:
                    hour += 12

                if command == 'a.m.' and hour == 12:
                    hour = 0

                self.action(command, alarm_hours=hour, alarm_minutes=minute)
            else:
                respond('Ivalid Input, Try Again')

        except Exception as e:
            print(e)
            respond('Invalid Input, Try Again')
Exemplo n.º 31
0
 def ParseTime(time):
     """ Parse time in format hh:mm:ss.
     
         :param time: input time
         :type time: str
         :returns: hours, minutes, seconds
         :rtype: tuple
     """
     f = time.find(':')
     l = time.rfind(':')
     h = time[:f]
     m = time[f + 1:l]
     s = time[l + 1:]
     return int(h), int(m), int(s)
def convert_to_24(time):
    """Converts 12 hours time format to 24 hours
    """
    time = time.replace(' ', '')
    time, half_day = time[:-2], time[-2:].lower()
    if half_day == 'am':
        return time
    elif half_day == 'pm':
        split = time.find(':')
        if split == -1:
            split = None
        return str(int(time[:split]) + 12) + time[split:]
    else:
        raise ValueError("Didn't finish with AM or PM.")
Exemplo n.º 33
0
def time_module():
    """
	Manages all the time related stuff
	Outputs time in HH:MM format (final version) & HH:MM:SS format (testing version)
	Time error depends on window.after() associated with time_module()
	Eg. If process is repeated every 10 secs, error = +- 10 secs which is ok
	"""
    time = datetime.datetime.now().time()
    time = str(time)
    pos = time.find(".")
    time = time[:pos]  #This is the time we want in format HH:MM:SS
    time = time[:pos - 3]  #To do in final display. format HH:MM

    L1 = Label(window, text=time, fg="white", bg="black", font="Helvetica 30")
    L1.place(x=1100, y=50)
    window.after(8353, time_module)  #updates after 7 secs
Exemplo n.º 34
0
def db_format_list(building):
    times = find_times(building)
    db_list = []
    for time in times:
        if "UNSCHED" in time:
            db_list.append([time[time.find(" "):-len(building)].strip(), "UNSCHED", "0", "0"])
        else:
            entry = db_format_entry(time, building)
            for indv_entry in entry:
                if indv_entry not in db_list: #prevents repeated entries
                    db_list.append(indv_entry)
    building = building.lower()
    if " " in building:
        building = building.replace(" ", "_")
        building = building.replace("\'", "")
    return building, tuple(db_list)
Exemplo n.º 35
0
def comment(request):
    data = json.loads(request.read())
    evtId = data['event_id']
    userId = data['user_id']
    comentario = data['comment']
    profile = Profile.objects.get(facebook_id=userId)
    evento = Event.objects.get(id=evtId)
    new_comment = Comment(event=evento,person=profile,text=comentario,time=datetime.datetime.now().time(),day=datetime.datetime.today().date())
    new_comment.save()
    foto = getUserImageUrl(profile.facebook_id)
    nome = profile.facebook_name
    date = datetime.datetime.now() - datetime.timedelta(hours=3)
    day = str(date).split(" ")[0]
    time = str(date).split(" ")[1]
    time = time[:time.find(".")]
    return HttpResponse(json.dumps({"photo":foto,"name":nome,"day":day, "time":time}), content_type="application/json")
Exemplo n.º 36
0
def db_format_entry(time, building):
    entries = []
    weekdays = ["M", "Tu", "W", "Th", "F"]
    for day in weekdays:
        if day in time[:time.find(" ")]:
            num1 = time[time.find(" "):time.find("-")].strip()
            num2 = time[time.find("-")+1:time.find(",")]
            num1, num2 = time_of_day(num1, num2)
            indv_ent = (time[time.find(",")+1:-len(building)].strip(), day, num1, num2)
            entries.append(indv_ent)
    return entries
Exemplo n.º 37
0
def increment_time(time):
    colon_index = time.find(":")
    old_hour = time[:colon_index]
    if old_hour != '12':
        new_hour = int(old_hour) + 1
        new_time = time.replace("{}".format(old_hour), "{}".format(new_hour),
                                1)
        return new_time
    else:
        new_hour = 1
        new_time = time.replace("{}".format(old_hour), "{}".format(new_hour),
                                1)
        if new_time[-2:] == "am":
            new_time = new_time.replace("am", "pm")
        else:
            new_time = new_time.replace("pm", "am")
        return new_time
Exemplo n.º 38
0
def get_projects(page):
    ret_projects = []
    curr = page.find("div",
                     {"class": "editable-item section-item current-position"})
    t_curr = {}
    try:
        t_curr["title"] = str(curr.find("a", {"name": "title"}).text)
    except:
        t_curr["title"] = "?"

    aux_str = ""

    time = curr.find("span", {"class": "experience-date-locale"})
    try:
        t_curr["duration"] = str(time.find("time").text + "Present")
    except:
        t_curr["duration"] = "?"
    try:
        t_curr["place"] = str(curr.find("span", {"class": "locality"}).text)
    except:
        t_curr["place"] = "?"
    ret_projects.append(t_curr)
    for link in page.find_all(
            "div", {"class": "editable-item section-item past-position"}):
        temp = {}
        try:
            temp["title"] = str(link.find("a", {"name": "title"}).text)
        except:
            temp["title"] = "?"
        try:

            time = link.find("span", {"class": "experience-date-locale"})
            aux_str = ""
            for tim in time.find_all("time"):
                aux_str += tim.text
            # print aux_str
            temp["duration"] = aux_str
        except:
            temp["duration"] = "?"
        try:
            temp["place"] = str(link.find("span", {"class": "locality"}).text)
        except:
            temp["place"] = "?"
        ret_projects.append(temp)

    return ret_projects
Exemplo n.º 39
0
def GetTime(bus, time):

    if time.find(bus.start)<0:
        bus.time = time
        return

    patterns = ("(?:.*)(\d+:\d\d(?:-|→)\d+?:\d\d)", 
                bus.start+"((?:(?:(?:\d+:\d\d(?:(?:-|→)\d+?:\d\d)*))|、)*)"
            )
    '''bus.start+"(\d+?:\d\d(?:-|→)\d+?:\d\d(?:、\d+?:\d\d(?:-|→)\d+?:\d\d)*)(?:,|,| |\|)"+bus.end+"(\d+?:\d\d(?:-|→)\d+?:\d\d(?:、\d+?:\d\d(?:-|→)\d+?:\d\d)*)"'''
    for pattern in patterns:
        o = re.search(pattern, time)
        if o:
            g = o.groups()
            if(len(g)==1):
                bus.time = g[0]
            if(len(g)==2):
                bus.time = g[0]
            break
Exemplo n.º 40
0
def play_note(dc, n, time):
    """
    plays a random note for a fixed number of times or 
    a random number of times in a range of times
    """
    for _ in range(n):
        notes = random.randrange(31, 110)
        if time.find(', ') == -1:
            int_time = int(time)
            dc.robot.playNote(notes, int_time)
            while True:
                song_playing = dc.robot.getSensor("SONG_PLAYING")
                if song_playing == 0:
                    break
        else:
            time_range = time.split(', ')
            random_time = random.randrange(int(time_range[0]), int(time_range[1]))
            dc.robot.playNote(notes, random_time)
            while True:
                song_playing = dc.robot.getSensor("SONG_PLAYING")
                if song_playing == 0:
                    break
Exemplo n.º 41
0
	def get(self):
	        global response
		the_url = self.request.url
		start_point = the_url.find('=') + 1
		encoded_city = the_url[start_point:]
		less_encoded_city = encoded_city.replace('+', chr(32))
		decoded_city = less_encoded_city.replace('%2C', chr(44))
		if decoded_city == 'City, State':
			self.redirect('/updates')
		day = str(int(strftime('%d')))
		month = str(int(strftime('%m')))
		keys = []
		for i in routes_library.keys():
			first = i.find('-')+1
			sec = i.find('-', first)
			city = i[first:sec]
			cur_m = i[sec+1: i.find('-', sec+1)]
			cur_d = i[i.find('-',sec+1)+1: ]
			if decoded_city == city and day == cur_d and month == cur_m:
				keys.append(i)
		response = ''
		for route in keys:
			#response += '<div><p name="route">' + route + '</p><ul>/n'
			response += '<div><input type="radio" name="route" value="%s"' % route + '><b>%s</b><ul style="list-style-type:none;">' % route
			for time in routes_library[route]:
				arrival_time = 'Arriving at ' + time[time.find('-')+1:]
				#response += '<li><input type="submit" name="time" value="%s"' % time + '>%s</li>'
				response += '<li><button name="time" value="%s"' % time + '>%s</button></li>' % arrival_time
			response += '</ul></div>'

		u = users.get_current_user()
		user = None
		if u:
			user = u.nickname() 
		logout = users.create_logout_url(self.request.uri)	
		self.render("times_choice.html", the_response=response, user=user, logout=logout)
Exemplo n.º 42
0
def untis(file, opts):

	import logs
	logs.logs('h1', 'Untis import')
	logs.logs(None, 'File: ' + file)

	from datetime import datetime
	# import base64 # broken
	import binascii
	import os
	import re
	import sys
	import time
	import xml.etree.ElementTree as ET

	os.environ['TZ'] = opts['timezone']
	time.tzset()

	# print('Reading XML from stdin ...')
	# file = "\n".join(sys.stdin)
	# tree = ET.fromstring(file)
	tree = ET.parse(file)
	tree = ET.ElementTree(tree)
	root = tree.getroot()

	termbegin = root.find('general').find('termbegindate').text
	termbegin = datetime.strptime(termbegin, '%Y%m%d')
	logs.logs(None, 'Term Begin: ' + termbegin.strftime('%Y-%m-%d'))
	termbegin = termbegin.strftime('%s')
	termbegin = int(termbegin)

	termend = root.find('general').find('termenddate').text
	termend = datetime.strptime(termend, '%Y%m%d')
	logs.logs(None, 'Term End: ' + termend.strftime('%Y-%m-%d'))
	termend = termend.strftime('%s')
	termend = int(termend)

	rooms = {}
	for room in root.find('rooms'):
		id = room.attrib['id']
		id2 = re.sub(r'^RM_', '', id)
		longname = room.find('longname')
		if longname is None:
			rooms[id] = id2
		else:
			rooms[id] = id2 + ' ' + strip(longname.text)
	logs.logs(None, 'Rooms: ' + str(len(rooms)))

	subjects = {}
	for subject in root.find('subjects'):
		id = subject.attrib['id']
		id2 = re.sub(r'^SU_', '', id)
		longname = subject.find('longname')
		if longname is None:
			subjects[id] = id2
		else:
			subjects[id] = strip(longname.text)

	teachers = {}
	for teacher in root.find('teachers'):
		id = teacher.attrib['id']
		id2 = re.sub(r'^TR_', '', id)
		surname = teacher.find('surname')
		if surname is None:
			teachers[id] = id2
		else:
			teachers[id] = strip(surname.text)
	logs.logs(None, 'Teachers: ' + str(len(teachers)))

	classes = {}
	for clss in root.find('classes'):
		id = clss.attrib['id']
		id2 = re.sub(r'^CL_', '', id)
		longname = clss.find('longname')
		if longname is None:
			classes[id] = id2
		else:
			classes[id] = strip(longname.text)
	logs.logs(None, 'Classes: ' + str(len(classes)))

	lessons = {}
	for lesson in root.find('lessons').findall('lesson'):

		subject_id = lesson.find('lesson_subject')
		if subject_id is None:
			subject = ''
			subject_id = ''
		else:
			subject_id = subject_id.attrib['id']
			subject = subjects[subject_id]

		teacher_id = lesson.find('lesson_teacher')
		if teacher_id is None:
			teacher = ''
			teacher_id = ''
		else:
			teacher_id = teacher_id.attrib['id']
			teacher = teachers[teacher_id]

		times = lesson.find('times')

		# class id-s may contain spaces, yuck!
		class_ids = lesson.find('lesson_classes')
		if class_ids is None:
			class_ids = ['']
		else:
			class_ids = class_ids.attrib['id']
			class_ids = re.split(r'\s*CL_', class_ids)
			class_ids = filter(lambda x: len(x) > 0, class_ids)
			class_ids = map(lambda x: 'CL_' + x, class_ids)

		for class_id in class_ids:
			class_id = class_id
			if len(class_id) > 0:
				clAss = classes[class_id]
			else:
				clAss = ''
			for time in times:
				room = time.find('assigned_room')
				if room is None:
					room_id = ''
					room = ''
				else:
					room_id = room.attrib['id']
					room = rooms[room_id]

				date = time.find('assigned_date').text

				start0 = time.find('assigned_starttime').text
				start = datetime.strptime(date + start0, '%Y%m%d%H%M').strftime('%s')
				start = int(start)

				end0 = time.find('assigned_endtime').text
				end = datetime.strptime(date + end0, '%Y%m%d%H%M').strftime('%s')
				end = int(end)

				id = [subject_id, teacher_id, class_id, room_id, str(start), str(end)]
				id = ':'.join(id)
				# b32encode() is unable to handle unicode
				id = id.encode('ascii', 'xmlcharrefreplace')
				# id = base64.b32encode(id) # broken
				id = binascii.hexlify(id)
				id = id.decode('utf-8')
				id = id.lower()

				lessons[id] = {
					'id': id,
					'subject_id': subject_id,
					'subject': subject,
					'teacher_id': teacher_id,
					'teacher': teacher,
					'room_id': room_id,
					'room': room,
					'class_id': class_id,
					'class': clAss,
					'start': start,
					'end': end,
					# for debugging timezone
					# 'start0': start0,
					# 'end0': end0,
					'timezone': opts['timezone'],
				}

	logs.logs(None, 'Lessons: ' + str(len(lessons)))

	return {
		'termbegin': termbegin,
		'termend': termend,
		'rooms': rooms,
		'classes': classes,
		'subjects': subjects,
		'teachers': teachers,
		'lessons': lessons
	}
Exemplo n.º 43
0
    image = gData[i].findPreviousSibling('div').find_all('div')[1].get('style')
    startPos = image.find("//") + 2
    imageUrl = image[startPos:-2]

    # Get movie name
    movieTitle = gData[i].find('h3', {'class': 'film-title'}).text

    # Get date when move is showing
    movieDate = gData[i].find('h4', {'class': 'session-date'}).text
    movieDate = movieDate.split(',')[1].strip()
    movieDate = time.mktime(datetime.strptime(movieDate, "%d %B %Y").timetuple())

    # Get movie Timings
    Timing = list(gData[i].find('div', {'class': 'session-times'}))
    Timing = [element for element in Timing if element != '\n']  # Remove '\n' from the timing list
    movieTiming = [time.find('time').text for time in Timing]

    # Storing everything in json format
    data.update({i: {'name': movieTitle, 'date': movieDate, 'timing': movieTiming, 'url':imageUrl}})

# Sorting dictionary by date
sortedData = sorted(data.values(), key=itemgetter('date'))

# Creating List with Dictionaries sorted by Date
for i,values in enumerate(sortedData):
    sortedJson.update({i:{'name': values['name'],
                       'timing': values['timing'],
                       'url': values['url'],
                       'date': str(datetime.fromtimestamp(int(values['date'])).strftime("%d %B %Y"))
                       }})
Exemplo n.º 44
0
    def post(self):
        global jars, openers, userclasses
        username = str(self.request.get("username"))
        password = str(self.request.get("password"))

        #setup cookies
        cj = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        try:  
		#here open url  
		#setup for logon through UWaterloo's central authentication system
		url = 'https://cas.uwaterloo.ca/cas/login'
		data = urllib.urlencode({'username':username,
			'password':password, #enter password to login
			'lt':'e1s1',
			'_eventId':'submit',
			'submit':'LOGIN'})

		#first request: GET to CAS, set up session cookies
		req = urllib2.Request(url, headers=headers)
		page = opener.open(req)

		#second request: POST to CAS, login
		req = urllib2.Request(url, data, headers=headers)
		page = opener.open(req)

		result = page.read()
		if "You have successfully logged into the University of Waterloo Central Authentication Service" in result:
		    self.login(username)

		    #setup for logon through Quest to get schedule
		    url = 'https://quest.pecs.uwaterloo.ca/psp/SS/?cmd=login&languageCd=ENG'
		    data = urllib.urlencode({'userid':username, 'pwd':password})

		    # POST to login to quest
		    req = urllib2.Request(url, data, headers=headers)
		    page = opener.open(req)

		    # GET classes
		    url = 'https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/SA/c/SA_LEARNER_SERVICES.SSR_SSENRL_LIST.GBL?Page=SSR_SSENRL_LIST&Action=A&ExactKeys=Y&TargetFrameName=None'
		    req = urllib2.Request(url, headers=headers)
		    page = opener.open(req) 
		    html = page.read()


		    class_name_start_match = "class='PAGROUPDIVIDER'  align='left'>"
		    class_nbr_match = "id='DERIVED_CLS_DTL_CLASS_NBR$"
		    class_time_match = "id='MTG_SCHED$"
		    courses = []
		    while class_name_start_match in html:
			[course_name, html] = parse(html, class_name_start_match, "</td>")
			course = CourseInfo(course_name)
			while (((html.find(class_name_start_match) > html.find(class_nbr_match)) and 
			       class_name_start_match in html) or
			       (class_name_start_match not in html and class_nbr_match in html)):
			    html = html[html.find("Class Section"):]
			    [section, html] = parse(html, "class='PSHYPERLINK' >", "</a>")
			    [component, html] = parse(html, "id='MTG_COMP$", "</span>")
			    component = component[component.find('>')+1:]
			    classes = []
			    [time, html] = parse(html, class_time_match, "</span>")
			    time = time[time.find('>')+1:]
			    [room, html] = parse(html, "id='MTG_LOC$", "</span>")
			    room = room[room.find('>')+1:]
			    [instructor, html] = parse(html, "id='DERIVED_CLS_DTL_SSR_INSTR_LONG$", "</span>")
			    instructor = instructor[instructor.find('>')+1:]
			    [dates, html] = parse(html, "id='MTG_DATES$", "</span>")
			    dates = dates[dates.find('>')+1:]
			    classes.append([room, time, dates])
			    while (html.find(class_name_start_match) > html.find(class_nbr_match)):
				number = findin(html, class_nbr_match, "</span>") 
				number = number[number.find('>')+1:]
				if number != '&nbsp;':
				    break;
				[time, html] = parse(html, class_time_match, "</span>")
				time = time[time.find('>')+1:]
				[room, html] = parse(html, "id='MTG_LOC$", "</span>")
				room = room[room.find('>')+1:]
				[dates, html] = parse(html, "id='MTG_DATES$", "</span>")
				dates = dates[dates.find('>')+1:]
				classes.append([room, time, dates])
			    course.addClass(component, section, instructor, classes)
			courses.append(course)
		    userclasses[username] = courses
		    jars[username] = cj
		    openers[username] = opener
		    self.redirect('/')
		else:
		    self.render("login.html", error="You don't even go here...")
        except urllib2.HTTPError:  
            self.redirect('/login') 
Exemplo n.º 45
0
def parseXML(root, number, book, key):
	newInvention = BachInvention(number, book, key)
	# Determine the number of divisions in the musicXML File (don't currently use)
	# 	Essentially the size of a quarter note
	# 	Should not change within a single score, but may differ across scores
	# for attributes in root.iter('attributes'):
		# divisions = attributes.find('divisions').text

	# Iterate through each part
	for part in root.findall('part'):
		partID = part.get('id')
		newPart = Part(part.get('id'))
		
		# Iterate through each measure and get a measure number
		for measure in part.findall('measure'):
			measureNumber = measure.get('number')

			# Iterate through all the measure's attributes
			for attributes in measure.iter('attributes'):
				

				# Get time signature - may not actually change
				for time in attributes.findall('time'):
					beats = time.find('beats').text
					beatType = time.find('beat-type').text
					timeSig = "%s/%s" % (beats, beatType)

			# May use to get note's exact position
			#measureLength = int(divisions) * int(beats)

			newMeasure = Measure(measureNumber, timeSig)
			
			# Get the notes in the measure
			noteNumber = 1
			for note in measure.findall('note'):
				duration = note.find('type').text # eg "whole"
				position = noteNumber

				# Check if note or rest
				if note.find('pitch') != None:
					# Get the note's pitch
					pitch = note.find('pitch')
					# Check if we are at a rest or a note
					step = pitch.find('step').text
					octave = int(pitch.find('octave').text)
					# Alter tag may or may not exist
					if pitch.find('alter') != None:
						alter = pitch.find('alter').text
					else:
						alter = "0"	
					stepWithAlter = step + alter
				else:
					stepWithAlter = 'Rest'
					octave = None
				
				newNote = Note(position, duration, stepWithAlter, octave)	
				newMeasure.notes.append(newNote) 
				
				noteNumber = noteNumber + 1

			newPart.measures.append(newMeasure)

		newInvention.parts.append(newPart)
	
	return newInvention