예제 #1
0
def erase_duplicate(arr_Object, Object):
    arr_Object.reverse()
    for index in range(len(arr_Object)):
        if (Object.mac == arr_Object[index].mac):
            # print("新加入:", Object.mac, ",", Object.time)
            # print("在原陣列:", arr_Object[index].mac, ",", arr_Object[index].time)
            after = pd.to_datetime(arr_Object[index].time,
                                   format='%Y-%m-%d %H:%M:%S')
            before = pd.to_datetime(Object.time, format='%Y-%m-%d %H:%M:%S')
            # now = (datetime.datetime(before_time) - datetime.datetime(nowa_time)).total_seconds()
            time = before - after
            if (time.total_seconds() >= 120):
                arr_Object.reverse()
                arr_Object.append(Object)
                # print(time.total_seconds())
                break
            else:
                break
            # sys.exit(0)
            # if(arr_Object[index].time)
        else:
            if (index + 1 == len(arr_Object)):
                arr_Object.reverse()
                arr_Object.append(Object)
            continue
예제 #2
0
def do_parity_bench(parity_cmd):
    print("running parity-evm benchmark...\n{}\n".format(parity_cmd))
    parity_cmd = shlex.split(parity_cmd)
    stdoutlines = []
    with subprocess.Popen(parity_cmd,
                          cwd=PARITY_EVM_DIR,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT,
                          bufsize=1,
                          universal_newlines=True) as p:
        for line in p.stdout:  # b'\n'-separated lines
            print(line, end='')
            stdoutlines.append(line)  # pass bytes as is
        p.wait()

    timeregex = "code avg run time: ([\d\w\.]+)"
    gasregex = "gas used: (\d+)"
    # maybe --benchmark_format=json is better so dont have to parse "36.775k"
    time_line = stdoutlines[-1]
    gas_line = stdoutlines[-2]
    time_match = re.search(timeregex, time_line)
    time = durationpy.from_str(time_match.group(1))
    gas_match = re.search(gasregex, gas_line)
    gasused = gas_match.group(1)
    return {'gas_used': gasused, 'time': time.total_seconds()}
예제 #3
0
def get_panelers(title, date):
    #SQL
    df = qr.queryRedShift("select * from program_viewers\
                                            where prog_id in (select prog_id from programs\
                                                                            where title like {0}\
                                                                            and date = {1}\
                                                                            and channel_id in (3, 4, 5, 6, 7))\
                                           ".format(title, date))
    df2 = qr.queryRedShift("select (ended_at - started_at) as airtime\
                                               from programs\
                                               where title like {0}\
                                               and date = {1}\
                                               and channel_id in (3, 4, 5, 6, 7)"\
                                               .format(title, date))

    if len(df) == 0:
        print("program not found")
        return

    #秒換算
    time = df2["airtime"][0]
    seconds = time.total_seconds()

    #パネラー絞り込み
    result = []
    for i in range(len(df)):
        if df["viewing_seconds"][i] >= (seconds / 3):
            result.append(df["paneler_id"][i])

    return result
예제 #4
0
def autoMl():
    value = request.args
    app.logger.info('value: %s', value)
    try:
        fileId = value.get('fileId')
        modelId = value.get('modelId')
        fieldId = value.get('fieldId')
        headerEntity = headerInfoDao.getHeaderInfoById(fieldId)
        fileEntity = fileInfoDao.getFileInfoById(fileId)
        file_loc = fileEntity['location']
        traget_feature = headerEntity['fieldName']
        # get files
        dc = DataCleaning.DataCleaning(file_loc, traget_feature)
        X, y, is_classification = dc.dataTrans()
        if is_classification:
            classifier = Classification.AutoClassification(X, y)
            score, time = classifier.fit()
        else:
            regressor = Regression.AutoRegression(X, y)
            score, time = regressor.fit()

        print("Accuracy score: ", score)
        print("Cost time: ", time)
        modelDao.setModelTrained(modelId, True)
        modelDao.setModelResult(modelId, score, other_key='CostTime', other_value=time.total_seconds())
        return response()
    except Exception as error:
        print(error)
        return response({}, 400)
예제 #5
0
def do_geth_bench(geth_cmd):
    print("running geth-evm benchmark...\n{}\n".format(geth_cmd))
    geth_cmd = shlex.split(geth_cmd)
    stdoutlines = []
    with subprocess.Popen(geth_cmd,
                          cwd=GETH_EVM_DIR,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT,
                          bufsize=1) as p:
        for line in p.stdout:  # b'\n'-separated lines
            print(line.decode(), end='')
            stdoutlines.append(line.decode())  # pass bytes as is
        p.wait()

    msOpRegex = "evm execution time: ([\d]+.[\d]+)ms"
    qsOpRegex = "evm execution time: ([\d]+.[\d]+)µs"
    gasregex = "Gas used:\s+(\d+)"
    # maybe --benchmark_format=json is better so dont have to parse "36.775k"
    time_line = stdoutlines[0]
    gas_line = stdoutlines[-3]
    time_match = re.search(msOpRegex, time_line)
    time = None
    if time_match is None:
        time_match = re.search(qsOpRegex, time_line)
        time = durationpy.from_str("{}µs".format(time_match.group(1)))
    else:
        time = durationpy.from_str("{}ms".format(time_match.group(1)))
    gas_match = re.search(gasregex, gas_line)
    gasused = gas_match.group(1)
    return {'gas_used': gasused, 'time': time.total_seconds()}
예제 #6
0
    def be_finished_roomrecord(cls, room_id):
        try:
            roomrecord = VideoRoomRecord.objects.get(id=room_id)
            if not roomrecord.end_time:
                time = datetime.datetime.now() - roomrecord.start_time
            else:
                time = roomrecord.end_time - roomrecord.start_time
            time = int(time.total_seconds())
            minute = time / 60
            price = roomrecord.pay_times * roomrecord.now_price

            data = {}
            data['seconds'] = time
            data['price'] = price
            data['join_exp'] = price * 1
            if roomrecord.pay_times == 0:
                data['user_exp'] = minute * 10
            else:
                data['user_exp'] = (roomrecord.pay_times - 1) * 10
            data['spend'] = roomrecord.spend
            data['spend_exp'] = roomrecord.spend * 1

        except Exception, e:
            logging.error("be finished roomrecord:{0}".format(e))
            return False
예제 #7
0
def time_to_frame(time, fps=None, fps_base=None):
    """
    Returns a float frame number from a time given in seconds or
    as a timedate.timedelta object.

    If *fps* and *fps_base* are not given the current scene is used.

    :arg time: time in seconds.
    :type time: number or a timedate.timedelta object
    :return: the frame.
    :rtype: float
    """

    if fps is None:
        fps = _bpy.context.scene.render.fps

    if fps_base is None:
        fps_base = _bpy.context.scene.render.fps_base

    from datetime import timedelta

    if isinstance(time, timedelta):
        time = time.total_seconds()

    return (time / fps_base) * fps
예제 #8
0
def format_time(time, precision=timedelta(seconds=1)):
    precision_seconds = precision.total_seconds()

    if isinstance(time, float):
        try:
            time = timedelta(seconds=int(time))
        except OverflowError:
            time = None

    if isinstance(time, timedelta):
        seconds = time.total_seconds()
        seconds = seconds - (seconds % precision_seconds)
        return str(timedelta(seconds=seconds))
    elif isinstance(time, datetime):
        seconds = time.timestamp()
        seconds = seconds - (seconds % precision_seconds)

        try:
            dt = datetime.fromtimestamp(seconds)
        except ValueError:
            dt = datetime.max
        return str(dt)
    elif isinstance(time, dtdate):
        return str(time)
    elif time is None:
        return '--:--:--'
    else:
        raise TypeError(f"format_time: Unknown type {type(time)}")
예제 #9
0
파일: __init__.py 프로젝트: treasgu/blender
def time_to_frame(time, *, fps=None, fps_base=None):
    """
    Returns a float frame number from a time given in seconds or
    as a datetime.timedelta object.

    If *fps* and *fps_base* are not given the current scene is used.

    :arg time: time in seconds.
    :type time: number or a ``datetime.timedelta`` object
    :return: the frame.
    :rtype: float
    """

    if fps is None:
        fps = _bpy.context.scene.render.fps

    if fps_base is None:
        fps_base = _bpy.context.scene.render.fps_base

    fps = fps / fps_base

    from datetime import timedelta

    if isinstance(time, timedelta):
        time = time.total_seconds()

    return time * fps
예제 #10
0
 def timedeltaformat(time):
     time = time.total_seconds()
     hours, remainder = divmod(time, 3600)
     minutes, seconds = divmod(remainder, 60)
     hours = int(hours)
     minutes = int(minutes)
     duration_formatted = '%02d:%02d:%02d' % (hours, minutes, seconds)
     return duration_formatted
예제 #11
0
파일: redis.py 프로젝트: ugfly1210/fund
 async def setex(self, name, time, value):
     """
     Set the value of key ``name`` to ``value`` that expires in ``time``
     seconds. ``time`` can be represented by an integer or a Python
     timedelta object.
     """
     if isinstance(time, datetime.timedelta):
         time = int(time.total_seconds())
     return await self.execute('SETEX', name, time, value)
예제 #12
0
def toFfmpegDuration(time, startTime):
    timeobj = datetime.datetime.strptime(time, '%H:%M:%S.%f').time()
    time = datetime.datetime.combine(datetime.date.min,
                                     timeobj) - datetime.datetime.min

    timeobj = datetime.datetime.strptime(startTime, '%H:%M:%S.%f').time()
    startTime = datetime.datetime.combine(datetime.date.min,
                                          timeobj) - datetime.datetime.min
    return time.total_seconds() - startTime.total_seconds()
예제 #13
0
 def print_summary(self, time):
     print('\n############ Results for {} tests ###########'\
                     .format(self.name))
     for folder, result in sorted(self.test_result.folders.items()):
         print('{}: {}'.format(folder, result))
     print("----------------------------")
     print('Total: {}'.format(self.test_result))
     print('Time taken for {} tests: {} seconds\n'.format(self.name, round(time.total_seconds(),2)))
     sys.stdout.flush()
예제 #14
0
async def on_ready():
    with open('data.json', 'r') as f:
        data = json.load(f)

    for server in data:
        for category in data[server]:
            if category == "Muted":
                for index, muted in enumerate(data[server][category]):
                    if datetime.datetime.strptime(
                            data[server][category][index][1],
                            '%Y-%m-%d %H:%M:%S') < datetime.datetime.now():
                        guild = client.get_guild(data[server]["Server_id"])
                        member = guild.get_member(
                            data[server][category][index][0])
                        role = discord.utils.get(member.guild.roles,
                                                 name='Muted')
                        await member.remove_roles(role)
                        del data[server][category][index]
                    else:
                        time = datetime.datetime.now(
                        ) - datetime.datetime.strptime(
                            data[server][category][index][1],
                            '%Y-%m-%d %H:%M:%S')
                        await wait_unmute(member, time.total_seconds(), role)
            elif category == "Banned":
                for index, banned in enumerate(data[server][category]):
                    if datetime.datetime.strptime(
                            data[server][category][index][1],
                            '%Y-%m-%d %H:%M:%S') < datetime.datetime.now():
                        guild = client.get_guild(data[server]["Server_id"])
                        member = guild.get_member(
                            data[server][category][index][0])
                        await guild.unban(member)
                        del data[server][category][index]
                    else:
                        time = datetime.datetime.now(
                        ) - datetime.datetime.strptime(
                            data[server][category][index][1],
                            '%Y-%m-%d %H:%M:%S')
                        await wait_unban(member, time.total_seconds(), role,
                                         guild)
    with open('data.json', 'w') as f:
        json.dump(data, f)
예제 #15
0
def formatTime(time):
    seconds = time.total_seconds()
    hours = int(seconds / 3600)
    minutes = int((seconds % 3600) / 60)
    seconds = int(seconds % 60)

    if hours < 0:
        return ('0:0')

    return ('{}:{}'.format(hours, str(minutes).zfill(2)))
예제 #16
0
파일: tasks.py 프로젝트: raheraperi/corpora
def transcribe_recordings_without_reviews():
    MAX_LOOP = 3500
    recordings = Recording.objects\
        .filter(transcription__isnull=True)\
        .distinct().order_by('created')

    # Once we're done with all the recordings,
    # let's see if there are some unfinished ones.
    if recordings.count() == 0:
        recordings = Recording.objects\
            .filter(quality_control__isnull=True)\
            .filter(transcription__text=None)\
            .distinct().order_by('created')

    total = recordings.count()

    start = timezone.now()

    if total == 0:
        return "No recordings to transcribe."

    logger.debug('Recordings that need reviewing: {0}'.format(total))

    recordings = recordings[:MAX_LOOP]

    source, created = Source.objects.get_or_create(
        source_name='Transcription API',
        source_type='M',
        source_url=settings.DEEPSPEECH_URL,
        author='Keoni Mahelona')
    source.save()

    error = 0
    e = 'None'
    for recording in recordings:
        t, created = Transcription.objects.get_or_create(
            recording=recording,
            source=source,
        )

    count = 0.0
    for recording in recordings:
        transcribe_recording.apply_async(args=[recording.pk], )
        count = count + 1

    if total > MAX_LOOP:
        t = MAX_LOOP
        left = total - MAX_LOOP
    else:
        t = total
        left = 0

    time = timezone.now() - start
    return "Done with {0} recordings. {1} to transcribe. Took {2}s" \
        .format(recordings.count(), left, time.total_seconds())
예제 #17
0
 async def _next(self, context):
     """When will the next occurance happen?"""
     if self.next:
         time = abs(datetime.datetime.utcnow() - self.next)
         total_seconds = int(time.total_seconds())
         hours, remainder = divmod(total_seconds, 60*60)
         minutes, seconds = divmod(remainder, 60)
         message = '**The next occurance will be in {} hours and {} minutes.**'.format(hours, minutes)
     else:
         message = '**There is currently no hunt.**'
     await self.bot.say(message)
예제 #18
0
def datetime_to_seconds(time):
    ''' 
    this function takes the time in datetime format
    and returns the total number of seconds
    '''
    if (isinstance(time, datetime.datetime)):
        return int(time.timestamp())
    elif (isinstance(time, datetime.timedelta)):
        return time.total_seconds()
    else:
        print("datetime_to_seconds(time): invalid input")
예제 #19
0
def preprocess(log):
    """
        Transform every trace in the log file, which is represented as a json,
        in a array that we will have easy access to times for every event in a trace
        and the sequence of these events. Also uses standarization to transofrm
        the time values per activity.
    """
    activities_all = log_attributes_filter.get_attribute_values(
        log, "concept:name")
    activities = list(activities_all.keys())
    dataVectors = []
    sequentialData = [[] for i in range(len(log))]
    for outerIndex, trace in enumerate(log):
        times = [[] for i in range(len(activities))]
        previousTime = trace.attributes["REG_DATE"]
        for index, event in enumerate(trace):
            indexActivity = activities.index(event["concept:name"])
            time = event["time:timestamp"] - previousTime
            times[indexActivity].append(time)
            previousTime = event["time:timestamp"]
            timesSeconds = [[i.total_seconds() for i in x] for x in times]
            sequentialData[outerIndex].append(
                [indexActivity, time.total_seconds()])
        dataVectors.append(timesSeconds)
    #transofrm datavectors to contain times per activity
    timesPerActivity = [[
        k for i in [x[index] for x in dataVectors] for k in i
    ] for index in range(len(dataVectors[0]))]
    #standard scalers
    standarScalers = [
    ]  #contains all the scalers that have been fitting to the allTimesSeconds
    for index, i in enumerate(timesPerActivity):
        sc = StandardScaler()
        numpyArray = np.array(i)
        numpyArray = numpyArray.reshape(-1, 1)
        sc.fit(numpyArray)  #fit to the all of the times spend
        standarScalers.append(sc)

    #create pairwise data [traceIndex,activityA,activityB,standarizedTimeA,standarizedTimeB]
    data = []
    for traceIndex, trace in enumerate(sequentialData):
        for eventIndex, event in enumerate(trace[:-1]):
            eventNext = sequentialData[traceIndex][eventIndex + 1]
            timeA = standarScalers[event[0]].transform(
                np.array(event[1]).reshape(1, -1))
            timeB = standarScalers[eventNext[0]].transform(
                np.array(eventNext[1]).reshape(1, -1))
            data.append([
                traceIndex, event[0], eventNext[0],
                round(float(timeA), 5),
                round(float(timeB), 5), eventIndex
            ])
    return data
예제 #20
0
 async def next(self, ctx):
     """When will the next occurrence happen?"""
     try:
         self.next_bang[ctx.guild.id]
         time = abs(datetime.datetime.utcnow() -
                    self.next_bang[ctx.guild.id])
         total_seconds = int(time.total_seconds())
         hours, remainder = divmod(total_seconds, 60 * 60)
         minutes, seconds = divmod(remainder, 60)
         message = f"The next occurrence will be in {hours} hours and {minutes} minutes."
     except KeyError:
         message = "There is currently no hunt."
     await ctx.send(bold(message))
def tv():
    time = timedelta()
    for content_item in db.query(ContentItem).filter(ContentItem.type == "movie", ContentItem.created_at >= start, ContentItem.created_at <= end):
        this_time = content_item.created_at - content_item.started_at
        if this_time > timedelta(hours=3):
            this_time = timedelta(hours=3)

        time += this_time

    if time:
        return u"%d%% времени перед телевизором." % (time.total_seconds() / (end - start).total_seconds() * 100)
    else:
        return None
예제 #22
0
def clean_workstation_users(request, format=None):

	if request.method == 'POST':
		cpt = 0 
		now = datetime.today()
		wuc = WorkstationUser.objects.filter(logged=True)
		for wu in wuc:
			if not wu.logged:
				if wu.connection_end:
					time = now - wu.connection_end
					if time.total_seconds() > (3600 * 72):
						wu.delete()
						cpt += 1
				else:
					time = now - wu.connection_start
					if time.total_seconds() > (3600 * 72):
						wu.delete()
						cpt += 1

		msg = "%d workstation_user have been removed from the database." % (cpt)
		print msg 
		data = {"code": 0, "content": msg}
		return Response(data, status=status.HTTP_200_OK)
예제 #23
0
    async def subscription(self, ctx, role: discord.Role, *, interval: str):
        """
        Sets a role to be a subscription, must set cost first.
        Will charge role's cost every interval, and remove the role if they run out of money
        Set to 0 to disable
        **__Minimum subscription duration is 1 hour__**
        Intervals look like:
           5 minutes
           1 minute 30 seconds
           1 hour
           2 days
           30 days
           5h30m
           (etc)
        """
        if not await self.all_are_valid_roles(ctx, role):
            return await ctx.maybe_send_embed("Can't do that. Discord role heirarchy applies here.")
        role_cost = await self.config.role(role).cost()

        if role_cost == 0:
            await ctx.send(warning("Please set a cost for the role first."))
            return

        time = parse_timedelta(interval)
        if int(time.total_seconds()) == 0:
            await ctx.send("Subscription removed.")
            async with self.config.guild(ctx.guild).s_roles() as s:
                s.remove(role.id)
            return
        elif int(time.total_seconds()) < MIN_SUB_TIME:
            await ctx.send("Subscriptions must be 1 hour or longer.")
            return

        await self.config.role(role).subscription.set(int(time.total_seconds()))
        async with self.config.guild(ctx.guild).s_roles() as s:
            s.append(role.id)
        await ctx.send(f"Subscription set to {parse_seconds(time.total_seconds())}.")
예제 #24
0
파일: util.py 프로젝트: yashodhank/lore
def timer(message="elapsed time:",
          level=logging.INFO,
          logger=None,
          librato=True):
    global _librato, _nested_timers, _previous_timer_level, _ascii_pipes, _timer_logger

    if logger is None:
        logger = _timer_logger

    if level < logger.level:
        yield
        return
    _nested_timers += 1
    start = datetime.now()
    try:
        yield
    finally:
        time = datetime.now() - start
        if librato and _librato and level >= logging.INFO:
            librato_name = 'timer.' + message.lower()
            librato_name = librato_name.split(':')[0]
            librato_name = re.sub(r'[^A-Za-z0-9\.\-_]', '',
                                  librato_name)[0:255]
            librato_record(librato_name, time.total_seconds())

        _nested_timers -= 1
        if _nested_timers == 0 or not env.unicode_locale:
            _ascii_pipes = ''
        else:
            delta = (_nested_timers - _previous_timer_level)
            length = _nested_timers * 2
            if delta < 0:
                _ascii_pipes = _ascii_pipes[0:length]
                join = '┌' if _ascii_pipes[-2] == ' ' else '├'
                _ascii_pipes = _ascii_pipes[0:-2] + join + '─'
            else:
                _ascii_pipes = re.sub(r'[├┌]', '│',
                                      _ascii_pipes).replace('─', ' ')
                if delta == 0:
                    _ascii_pipes = _ascii_pipes[:-2] + '├─'
                else:
                    gap = length - len(_ascii_pipes) - 2
                    _ascii_pipes = _ascii_pipes + ' ' * gap + '┌─'

        _previous_timer_level = _nested_timers
        logger.log(
            level,
            (ansi.bold(_ascii_pipes + '[' + str(time) + '] ') + message))
예제 #25
0
    def format_time(self, time: datetime) -> str:
        tot_sec = time.total_seconds()
        days = tot_sec // 86400
        tot_sec -= 86400 * days
        hours = tot_sec // 3600
        tot_sec -= 3600 * hours
        mins = tot_sec // 60
        tot_sec -= 60 * mins
        secs = tot_sec

        print("days", days)
        print("hours", hours)
        print("minutes", mins)
        print("seconds", secs)

        time_str = days, "day(s),", hours, "hour(s),", mins, "minute(s), and", secs, "second(s)"

        return time_str
예제 #26
0
    def be_finished_roomrecord(cls, room_id):
        try:
            roomrecord = AudioRoomRecord.objects.get(id=room_id)
            if not roomrecord.end_time:
                time = datetime.datetime.now() - roomrecord.start_time
            else:
                time = roomrecord.end_time - roomrecord.start_time
            time = int(time.total_seconds())
            minute = time / 60
            price = roomrecord.pay_times * roomrecord.now_price

            data = {}
            data['seconds'] = time
            data['price'] = price
            data['join_exp'] = price * 1
            if roomrecord.pay_times == 0:
                data['user_exp'] = minute * 10
            else:
                data['user_exp'] = (roomrecord.pay_times - 1) * 10
            data['spend'] = roomrecord.gift_value
            data['spend_exp'] = roomrecord.gift_value
            # 防止没有上报quit接口
            if roomrecord.status != 0:
                roomrecord.status = 0
                roomrecord.end_time = datetime.datetime.now()
                AudioRoomRecord.recreate_roomrecord(user_id=roomrecord.user_id)
                new_id = AudioRoomRecord.recreate_roomrecord(
                    user_id=roomrecord.user_id)
                user = User.objects.get(id=roomrecord.user_id)
                user.audio_room_id = new_id
                user.save()
                join_id = roomrecord.join_id
                if join_id:
                    join_status = AudioRoomRecord.get_room_status(
                        user_id=join_id)
                    if join_status == 3:
                        AudioRoomRecord.set_room_status(user_id=join_id,
                                                        status=1)
                roomrecord.save()
                RoomRedis.close_room(room_id)
                UserRedis.add_user_recommed_id_v3_one(roomrecord.user_id)
        except Exception, e:
            logging.error("be finished roomrecord:{0}".format(e))
            return False
예제 #27
0
def flash(colors, delay, exit=None):
    """
	flashes a list of colors for time on and time off
	"""
    seconds = delay
    if isinstance(time, dt.timedelta):
        seconds = time.total_seconds()
    i = 0
    l = len(colors)
    while True:
        show(colors[i])
        time.sleep(seconds)
        show((0, 0, 0))

        if exit.stop:
            break

        time.sleep(seconds)
        i = (i + 1) % l
예제 #28
0
 def closed_waitingrooms(cls):
     """
     拨打超过三分钟就自动关闭
     """
     try:
         objs = AudioRoomRecord.objects.filter(
             status=3).order_by('-created_at')
         for obj in objs:
             if obj.report_join:
                 time = datetime.datetime.now() - obj.report_join
                 time = int(time.total_seconds())
                 if time > 180:
                     obj.status = 1
                     obj.report_join = None
                     obj.save()
         return True
     except Exception, e:
         logging.error("close waitingrooms error:{0}".format(e))
         return False
예제 #29
0
    async def run(self, period, estimator, controller):
        periodic = Periodic_Delay(period)
        while True:
            time = datetime.now() - self._start_time

            state = estimator.state
            motors = controller.motors

            if controller.armed:
                self._logger.writerow([
                    time.total_seconds(), state.roll, state.pitch, state.yaw,
                    state.gyro_x, state.gyro_y, state.gyro_z, state.acc_x,
                    state.acc_y, state.acc_z, state.mag_x, state.mag_y,
                    state.mag_z, controller.armed, controller.thrust,
                    controller.lift, controller.yawrate_ref, motors.motor_DL,
                    motors.motor_DR, motors.motor_L, motors.motor_R
                ])

            await periodic.sleep()
예제 #30
0
    def calculateOfflineCash(self):
        playerLevel = self.getSkillInfo(0).skillLevel                   # 主角技能
        playerRevial = self.getSkillInfo(7).skillLevel                  # 重生技能

        # 玩家获取离线奖励技能检测
        if playerLevel == 0 and playerRevial == 0:
            self.offlineCash = 0
            return

        timeLast = GameTools.string2datetime(self.last_cmd_time)        # 最后操作时间
        timeNow =  GameTools.getDatetimeNow()                           # 当前时间

        # 玩家获取离线奖励时间检测
        if timeNow > timeLast + datetime.timedelta(seconds = ConstValue.tokenEffectTime):
            time = timeNow - timeLast
            time = time.total_seconds()
            gold = OfflineCash.calculateOfflineCash(self.game_level,time)           # 获取奖励金币
            self.offlineCash = gold
            self.cash += gold
        else:
            self.offlineCash = 0
예제 #31
0
def do_evmone_bench(evmone_bench_cmd):
    evmone_cmd = shlex.split(evmone_bench_cmd)
    print("running evmone benchmark...\n{}".format(evmone_bench_cmd))

    stdoutlines = []
    with subprocess.Popen(evmone_cmd,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT,
                          bufsize=1,
                          universal_newlines=True) as p:
        for line in p.stdout:  # b'\n'-separated lines
            print(line, end='')
            stdoutlines.append(line)  # pass bytes as is
        p.wait()

    json_result = json.loads("".join(stdoutlines[2:]))
    benchmarks = json_result['benchmarks']
    benchmark_results = benchmarks[0]
    gasused = int(benchmark_results['gas_used'])
    total_time = str(
        benchmark_results['real_time']) + benchmark_results['time_unit']
    time = durationpy.from_str(total_time)
    return {'gas_used': gasused, 'time': time.total_seconds()}
예제 #32
0
 def _convert_time_to_seconds(self, time):
     if isinstance(time, timedelta):
         return time.total_seconds()
     return timestr_to_secs(time, round_to=None)
예제 #33
0
 def _convert_time_to_seconds(self, time):
     if isinstance(time, timedelta):
         return time.total_seconds()
     return timestr_to_secs(time, round_to=None)
예제 #34
0
 def schedule_after(self, time, task, *args, **kwargs):
     """
     Schedule a task to run after a given amount of time.
     """
     self._schedule_work(task,
                         Work(time.total_seconds(), None, args, kwargs))
예제 #35
0
def next_reminder(time, event):
  current_time = datetime.datetime.now(timezone)
  while time < current_time:
    time = repeats(time, event['repeat_type'])
  time = time - current_time
  return time.total_seconds()
예제 #36
0
def ConvertToMs(time):
    convert = str(round(time.total_seconds() * 1000)) + 'ms'
    return convert