Exemple #1
0
def GetDirty(request):
  category = request.GET.get('category')
  dirty = request.GET.get('dirty', '1')
  is_dirty = False
  if dirty == '1':
    is_dirty = True

  parents = db.Query(ResultParent)
  parents.filter('category =', category)

  dirtys = []
  for parent in parents.fetch(10):
    logging.info('parent %s' % parent.key())
    time = db.Query(ResultTime)
    if is_dirty:
      time.filter('dirty =', True)
    time.ancestor(parent)
    logging.info('time.count() %s' % time.count())
    if time.count() > 0:
      key = parent.key()
      dirtys.append(
          '<a href="/admin/schedule-dirty-update?result_parent_key=%s">'
          'Dirty ResultParent: %s. %s</a>' % (key, parent.user_agent.pretty(),
                                              key))

  return http.HttpResponse('<br>'.join(dirtys))
Exemple #2
0
def fs2_GoToTimestamp(*args):
    #get doc from scripting context which is made available to all scripts
    #desktop = XSCRIPTCONTEXT.getDesktop()
    desktop = unoObjs.desktop
    model = desktop.getCurrentComponent()
    oSelected = model.getCurrentSelection()
    #access annotations for the whole document
    oEnum = model.getTextFields().createEnumeration()
    cursor = desktop.getCurrentComponent().getCurrentController(
    ).getViewCursor()
    util.xray(cursor, unoObjs)
    while oEnum.hasMoreElements():
        oField = oEnum.nextElement()
        if oField.supportsService('com.sun.star.text.TextField.Annotation'):
            xTextRange = oField.getAnchor()
            cursor.gotoRange(xTextRange, False)
    oText = ""
    try:  #Grab the text selected/highlighted
        oSel = oSelected.getByIndex(0)
        oText = oSel.getString()
    except:
        pass
    try:
        if oText == "":  # Nothing selected grab the whole line
            cursor = desktop.getCurrentComponent().getCurrentController(
            ).getViewCursor()
            cursor.gotoStartOfLine(
                False)  #move cursor to start without selecting (False)
            cursor.gotoEndOfLine(
                True)  #now move cursor to end of line selecting all (True)
            oSelected = model.getCurrentSelection()
            oSel = oSelected.getByIndex(0)
            oText = oSel.getString()
            # Deselect line to avoid inadvertently deleting it on next keystroke
            cursor.gotoStartOfLine(False)
    except:
        pass
    time = str(oText)
    valid_chars = ('0123456789:')
    time = ''.join(char for char in time if char in valid_chars)
    if time.count(":") == 1:
        oM, oS = time.split(":")
        oH = "00"
    elif time.count(":") == 2:
        oH, oM, oS = time.split(":")
    else:
        return None
    if len(oS) != 2:
        oS = oS[:2]
    try:
        secs = int(oS)
        secs = secs + int(oM) * 60
        secs = secs + int(oH) * 3600
    except:
        return None
    seek_instruction = 'seek' + str(secs) + '\n'
Exemple #3
0
async def convert_time_to_words(time):

    if (time[-1] == 'h') and (time.count('h') == 1):
        return "hours"
    elif (time[-1] == 'm') and (time.count('m') == 1):
        return "minutes"
    elif (time[-1] == 's') and (time.count('s') == 1):
        return "seconds"

    return None
Exemple #4
0
async def convert_time_to_seconds(time):

    time_in_sec = 0
    if (time[-1] == 'h') and (time.count('h') == 1):
        time_in_sec = int(time[:-1]) * 3600
    elif (time[-1] == 'm') and (time.count('m') == 1):
        time_in_sec = int(time[:-1]) * 60
    elif (time[-1] == 's') and (time.count('s') == 1):
        time_in_sec = int(time[:-1])

    return time_in_sec
Exemple #5
0
def time_to_int(time):
    if time.count(":") == 2:
        (hour, min, sec) = time.split(":")
        return (int(hour) * 3600) + (int(min) * 60) + int(sec) 
    else:
        (min, sec) = time.split(":")
        return (int(min) * 60) + int(sec)
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)
def conv_test(test_loader, loss, model, rate_losses, vel_losses, name, device):
    # Evaluates convolutional (i.e. one-shot) prediction models on robotic system motion test set
    i = 0
    time = []
    pred_steps = rate_losses.shape[1]

    with torch.no_grad():
        for data in test_loader:
            input = torch.transpose(data["input"].type(torch.FloatTensor), 1,
                                    2).to(device)  # Load Input data
            label = torch.transpose(data["label"].type(torch.FloatTensor), 1,
                                    2).to(device)  # Load labels

            output = label[:,
                           6:12, :]  # Ground truth label for truncated state
            feedforward = torch.zeros(label.shape)  # Future control inputs
            feedforward[:, 12:, :] = label[:, 12:, :]
            input = torch.cat((input, feedforward), 2)  # Full model input

            start = count()  # Timing forward pass
            pred = model(input)  # Future state predictions
            end = count()
            time.append(end - start)

            # Calculate prediction losses
            for j in range(pred_steps):
                rate_loss = loss(output[0, :3, j], pred[0, :3, j]).item()
                vel_loss = loss(output[0, 3:, j], pred[0, 3:, j]).item()

                vel_losses[i][j] = vel_loss
                rate_losses[i][j] = rate_loss

            i += 1
            if i % 10 == 0:
                print("Sample #{}".format(i))

        # Store results in CSV
        print("Average processing time: {} seconds".format(
            np.asarray(time).mean()))
        np.savetxt("{}_test_error_rates.csv".format(name),
                   rate_losses.cpu().numpy())
        np.savetxt("{}_test_error_vels.csv".format(name),
                   vel_losses.cpu().numpy())
Exemple #8
0
def str2secs(time):
    periods = time.count(':')
    if (periods == 2):
        h, m, s = map(int, time.split(":"))
        return h * 3600 + m * 60 + s
    else:
        app.warningBox("Error !",
                       "Please keep the proper time formatting",
                       parent=None)
        return 0
Exemple #9
0
 def is_exist_timestamp(self, **args):
     time = self.mongodb_timestamp.find({
         'recordTimestamp':
         args.get('recordTimestamp'),
         'isDone':
         args.get('isDone'),
         'cameraName':
         args.get('cameraName')
     })
     if time.count() > 0:
         return True
     return False
Exemple #10
0
 def process_formdata(self, valuelist):
     if valuelist and len(valuelist[0]) > 0:
         time = valuelist[0]
         ampm = time[-2:]
         time = time[:-2]
         count = time.count(':')
         if count == 0:
             time = time + ':00:00' + ampm
         elif count == 1:
             time = time + ':00' + ampm
         temp = self.string_toTime(time)
         print(temp)
         self.data = self.string_toTime(time).time()
     else:
         self.data = None 
Exemple #11
0
 def process_formdata(self, valuelist):
     if valuelist and len(valuelist[0]) > 0:
         time = valuelist[0]
         ampm = time[-2:]
         time = time[:-2]
         count = time.count(':')
         if count == 0:
             time = time + ':00:00' + ampm
         elif count == 1:
             time = time + ':00' + ampm
         temp = self.string_toTime(time)
         print(temp)
         self.data = self.string_toTime(time).time()
     else:
         self.data = None
def tokens_only_dates(time, alltimes, text):
    """Function that checks if same tokens also occur when not a date (unlikely given regex setup of HeidelTime)"""
    
    occurrences = text.count(time)
    
    identified_as_time = alltimes.count(time)
   
    
    if occurrences == identified_as_time:
        return True
    elif occurrences > identified_as_time:
        #FIXME: this is a hack, we should also look at punctuation, etc
        occurrences = time.count(time + ' ')
        if occurrences > identified_as_time:
            return False
        else:
            return True
    elif identified_as_time > occurrences:
        #FIXME: should be proper printed error
        print >> sys.stderr, 'Error: this string occurs more often as time expression than it occurs'
        
        return True
Exemple #13
0
 def _parse_iso_8601(value):
     """
     Parses an ISO8601:2004 date time string.
     """
     # remove trailing 'Z'
     value = value.replace('Z', '')
     # split between date and time
     try:
         (date, time) = value.split("T")
     except:
         date = value
         time = ""
     # remove all hyphens in date
     date = date.replace('-', '')
     # remove colons in time
     time = time.replace(':', '')
     # guess date pattern
     length_date = len(date)
     if date.count('W') == 1 and length_date == 8:
         # we got a week date: YYYYWwwD
         # remove week indicator 'W'
         date = date.replace('W', '')
         date_pattern = "%Y%W%w"
         year = int(date[0:4])
         # [Www] is the week number prefixed by the letter 'W', from W01
         # through W53.
         # strpftime %W == Week number of the year (Monday as the first day
         # of the week) as a decimal number [00,53]. All days in a new year
         # preceding the first Monday are considered to be in week 0.
         week = int(date[4:6]) - 1
         # [D] is the weekday number, from 1 through 7, beginning with
         # Monday and ending with Sunday.
         # strpftime %w == Weekday as a decimal number [0(Sunday),6]
         day = int(date[6])
         if day == 7:
             day = 0
         date = "%04d%02d%1d" % (year, week, day)
     elif length_date == 7 and date.isdigit() and value.count('-') != 2:
         # we got a ordinal date: YYYYDDD
         date_pattern = "%Y%j"
     elif length_date == 8 and date.isdigit():
         # we got a calendar date: YYYYMMDD
         date_pattern = "%Y%m%d"
     else:
         raise ValueError("Wrong or incomplete ISO8601:2004 date format")
     # check for time zone information
     # note that the zone designator is the actual offset from UTC and
     # does not include any information on daylight saving time
     if time.count('+') == 1 and '+' in time[-6:]:
         (time, tz) = time.rsplit('+')
         delta = -1
     elif time.count('-') == 1 and '-' in time[-6:]:
         (time, tz) = time.rsplit('-')
         delta = 1
     else:
         delta = 0
     if delta:
         while len(tz) < 3:
             tz += '0'
         delta = delta * (int(tz[0:2]) * 60 * 60 + int(tz[2:]) * 60)
     # split microseconds
     ms = 0
     if '.' in time:
         (time, ms) = time.split(".")
         ms = float('0.' + ms.strip())
     # guess time pattern
     length_time = len(time)
     if length_time == 6 and time.isdigit():
         time_pattern = "%H%M%S"
     elif length_time == 4 and time.isdigit():
         time_pattern = "%H%M"
     elif length_time == 2 and time.isdigit():
         time_pattern = "%H"
     elif length_time == 0:
         time_pattern = ""
     else:
         raise ValueError("Wrong or incomplete ISO8601:2004 time format")
     # parse patterns
     dt = datetime.datetime.strptime(date + 'T' + time,
                                     date_pattern + 'T' + time_pattern)
     # add microseconds and eventually correct time zone
     return UTCDateTime(dt) + (float(delta) + ms)
Exemple #14
0
 def _parseISO8601(value):
     """
     Parses an ISO8601:2004 date time string.
     """
     # remove trailing 'Z'
     value = value.replace('Z', '')
     # split between date and time
     try:
         (date, time) = value.split("T")
     except:
         date = value
         time = ""
     # remove all hyphens in date
     date = date.replace('-', '')
     # remove colons in time
     time = time.replace(':', '')
     # guess date pattern
     length_date = len(date)
     if date.count('W') == 1 and length_date == 8:
         # we got a week date: YYYYWwwD
         # remove week indicator 'W'
         date = date.replace('W', '')
         date_pattern = "%Y%W%w"
         year = int(date[0:4])
         # [Www] is the week number prefixed by the letter 'W', from W01
         # through W53.
         # strpftime %W == Week number of the year (Monday as the first day
         # of the week) as a decimal number [00,53]. All days in a new year
         # preceding the first Monday are considered to be in week 0.
         week = int(date[4:6]) - 1
         # [D] is the weekday number, from 1 through 7, beginning with
         # Monday and ending with Sunday.
         # strpftime %w == Weekday as a decimal number [0(Sunday),6]
         day = int(date[6])
         if day == 7:
             day = 0
         date = "%04d%02d%1d" % (year, week, day)
     elif length_date == 7 and date.isdigit() and value.count('-') != 2:
         # we got a ordinal date: YYYYDDD
         date_pattern = "%Y%j"
     elif length_date == 8 and date.isdigit():
         # we got a calendar date: YYYYMMDD
         date_pattern = "%Y%m%d"
     else:
         raise ValueError("Wrong or incomplete ISO8601:2004 date format")
     # check for time zone information
     # note that the zone designator is the actual offset from UTC and
     # does not include any information on daylight saving time
     if time.count('+') == 1 and '+' in time[-6:]:
         (time, tz) = time.rsplit('+')
         delta = -1
     elif time.count('-') == 1 and '-' in time[-6:]:
         (time, tz) = time.rsplit('-')
         delta = 1
     else:
         delta = 0
     if delta:
         tz = tz.replace(':', '')  # XXX: not needed
         while len(tz) < 3:
             tz += '0'
         delta = delta * (int(tz[0:2]) * 60 * 60 + int(tz[2:]) * 60)
     # split microseconds
     ms = 0
     if '.' in time:
         (time, ms) = time.split(".")
         ms = float('0.' + ms.strip())
     # guess time pattern
     length_time = len(time)
     if length_time == 6 and time.isdigit():
         time_pattern = "%H%M%S"
     elif length_time == 4 and time.isdigit():
         time_pattern = "%H%M"
     elif length_time == 2 and time.isdigit():
         time_pattern = "%H"
     elif length_time == 0:
         time_pattern = ""
     else:
         raise ValueError("Wrong or incomplete ISO8601:2004 time format")
     # parse patterns
     dt = datetime.datetime.strptime(date + 'T' + time,
                                     date_pattern + 'T' + time_pattern)
     # add microseconds and eventually correct time zone
     return UTCDateTime(dt) + (float(delta) + ms)
Exemple #15
0
    async def start(self, ctx, channelid, winners, *, prize):

        channel = self.bot.get_channel(int(channelid))
        find = prize.find('user='******'#')
            user = discord.utils.get(ctx.message.channel.guild.members,
                                     name=user_name,
                                     discriminator=user_discriminator)

        else:
            user = ctx.message.author

        await ctx.send("How long will the giveaway run for? (d:h\:m:s)")

        while True:
            text = await self.bot.wait_for(
                "message", check=lambda message: message.author == ctx.author)
            time = text.content
            separators = time.count(':')
            days, hours, minutes, seconds = 0, 0, 0, 0
            colonIndex = [
                findN(time, 1),
                findN(time, 2),
                findN(time, 3),
                findN(time, 4)
            ]

            if separators == 3:
                days = time[:colonIndex[0]]
                hours = time[colonIndex[0] + 1:colonIndex[1]]
                minutes = time[colonIndex[1] + 1:colonIndex[2]]
                seconds = time[colonIndex[2] + 1:]

            elif separators == 2:
                hours = time[:colonIndex[0]]
                minutes = time[colonIndex[0] + 1:colonIndex[1]]
                seconds = time[colonIndex[1] + 1:]

            elif separators == 1:
                minutes = time[:colonIndex[0]]
                seconds = time[colonIndex[0] + 1:]

            else:
                seconds = time

            try:
                if "?g start" in time:
                    self.config[self.giveaways]['finished'] = True

                else:
                    sleepTime = (int(days) * 86400) + (int(hours) * 3600) + (
                        int(minutes) * 60) + int(seconds)
                    break

            except ValueError:
                pass

        embed = discord.Embed(
            title=f"{prize}",
            description=f"Hosted by: {user}\nReact with 🎉 to enter",
            colour=0xcbab58)
        embed.set_thumbnail(url=self.bot.user.avatar_url)

        self.config[self.giveaways] = {
            'channel': channel,
            'prize': prize,
            'ctx': ctx,
            'numWinners': int(winners),
            'embed': embed,
            'host': user,
            'totalSecondsRemaining': sleepTime,
            'days': days,
            'hours': hours,
            'minutes': minutes,
            'seconds': seconds,
            'loop': 0,
            'message': "",
            'entered': [],
            'totalEntrants': 0,
            'winners': [],
            'finished': False
        }

        if time != None:
            if sleepTime >= 10:
                embed = self.newEmbed(self.giveaways)
                self.config[self.giveaways]['message'] = await channel.send(
                    "🎉 ***GIVEAWAY*** 🎉", embed=embed)

                updatedEmbed = self.newEmbed(self.giveaways)
                await self.config[self.giveaways
                                  ]['message'].edit(embed=updatedEmbed)
                await self.config[self.giveaways
                                  ]['message'].add_reaction(self.emote)

                if not self.taskLoopActive:
                    self.updateTime.start()
                    self.taskLoopActive = True

                self.giveaways += 1

            else:
                await ctx.send("Must be at least 10 seconds.")
# One last scroll just in case 
driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight);")

# end_of_page()

page_soup = get_html() #gets the complete html, after scrolling down, with all the duration and title of videos

time_containers = page_soup.findAll('div', {'class':'style-scope ytd-thumbnail'})
time_containers[0].text

print(time_containers[0].text)

for container in time_containers: #create a list with timestamps
	time = container.text[7:].rstrip()
	if time.count(':') == 1: #make so the timestamp includes hours as 00 if its shorter than 1 hour
		time = '00:'+ time
	else:
		time = time

	times.append(time)

times = list(filter(None, times)) #filter all the ZERO values of the list
time_total = dt.timedelta() #sets a variable in the HH:MM:SS format

user_data = driver.find_elements_by_xpath('//*[@id="video-title"]')
links = []
outcome = []
for i in user_data:
    try:
        link = i.get_attribute('href')