Ejemplo n.º 1
0
def from_to_mins(df, from_, to, smooth: bool = False):
    # Create times and temperatures from given data.
    dates, temps, solar = df["datetime"], df["temp"], df["solar"]
    times = dates.apply(lambda d: datetime.timestamp(d))
    # Create times that are expected to return.
    result_dates, result_times = [], []
    curr = from_
    while curr <= to:
        result_dates.append(curr)
        result_times.append(datetime.timestamp(curr))
        curr += timedelta(minutes=1)
    # Interpolate to get results.
    result_temps = interp1d(times, temps,
                            fill_value="extrapolate")(result_times)
    result_solar = interp1d(times, solar,
                            fill_value="extrapolate")(result_times)
    # Pack it into a DataFrame.
    df = pd.DataFrame(
        np.array([result_dates, result_temps, result_solar]).T,
        columns=["datetime", "temp", "solar"],
    )
    # Sort.
    df = df.sort_values(by=["datetime"])
    df["temp"] = pd.to_numeric(df["temp"])
    df["solar"] = pd.to_numeric(df["solar"])
    # Smooth.
    if smooth:
        df["temp"] = savgol_filter(df["temp"], 20, 3)
    return df
Ejemplo n.º 2
0
 def get_result(self):
     self.ensure_one()
     print_data = self.get_workbook()
     if print_data:
         result_filename = ''
         if platform.system() == 'Linux':
             result_filename = ('/tmp/TED_OPUK1-' +
                                str(datetime.timestamp()) + '.xls')
         else:
             result_filename = ('/tmp/TED_OPUK1-' +
                                str(datetime.timestamp()) + '.xls')
         result_filename = result_filename.split('/')[0]
         print_data.save(result_filename)
         file_handler = open(result_filename, "rb")
         result_data = file_handler.read()
         result_output = base64.encodestring(result_data)
         result_attachment = {
             'filename': result_filename,
             'filedata': result_output
         }
         result_object = self.env['purchase.request.docx.k1single'].create(
             result_attachment)
         return {
             'type': 'ir.actions.act_window',
             'res_model': 'purchase.request.opuk1.out',
             'res_id': result_object.id,
             'view_type': 'form',
             'view_mode': 'form',
             'context': self.env.context,
             'target': 'new',
         }
     else:
         return {}
Ejemplo n.º 3
0
 def testGetLastmonthList(self):
     header['X-Auth-Token'] = test_parameter['broadcaster_token']
     header['X-Auth-Nonce'] = test_parameter['broadcaster_nonce']
     stime = (datetime.today() -
              timedelta(days=datetime.today().day)).replace(day=1,
                                                            hour=0,
                                                            minute=0,
                                                            second=0)
     etime = (datetime.today() -
              timedelta(days=datetime.today().day)).replace(hour=15,
                                                            minute=59,
                                                            second=59)
     apiName = '/api/v2/liveMaster/giftGiversToSendIM?startTime={sTime}&endTime={eTime}&item=10&page=1'
     apiName = apiName.replace('{sTime}',
                               str(int(datetime.timestamp(stime))))
     apiName = apiName.replace('{eTime}',
                               str(int(datetime.timestamp(etime))))
     print(apiName)
     res = api.apiFunction(test_parameter['prefix'], header, apiName, 'get',
                           None)
     restext = json.loads(res.text)
     assert restext['totalCount'] == len(self.lastMonth)
     assert restext['sentCount'] == 0
     for i in restext['data']:
         i['user']['id'] in self.lastMonth
     assert restext['data'][0]['points'] >= restext['data'][1]['points']
Ejemplo n.º 4
0
def get_stock_data(symbol, crumbs, latest=5000, interval='1d'):
    current = datetime.now()
    period2 = int(datetime.timestamp(current))
    period1 = current - timedelta(days=latest)
    period1 = period1.replace(hour=0, minute=0, second=0, microsecond=0)
    period1 = int(datetime.timestamp(period1))
    includePrePost = 'true'
    url ='https://query1.finance.yahoo.com/v8/finance/chart/{}?symbol={}&period1={}&period2={}&interval={}' \
          '&includePrePost={}&events=div%7Csplit%7Cearn&lang=en-US&region=US&crumb={}&corsDomain=finance.yahoo.com'\
          ''.format(symbol, symbol, period1, period2, interval, includePrePost, crumbs)
    response = requests.get(url=url)
    if response.status_code == 200:
        response = json.loads(response.content)
        web_data = response['chart']['result'][0]['indicators']['quote'][0]
        df = pd.DataFrame()
        df['Datetime'] = response['chart']['result'][0]['timestamp']
        df['Datetime'] = df['Datetime'].apply(
            lambda x: datetime.fromtimestamp(x))
        ohlcv = ['Open', 'High', 'Low', 'Close', 'Volume']
        for item in ohlcv:
            df[item] = web_data[item.lower()]
        return df
    else:
        print('Web data fetch fail. Response code')
        print(response.status_code)
Ejemplo n.º 5
0
Archivo: views.py Proyecto: thup/bot
 def getTimestamp(self):
     reel_viewer_timestamp = self.device.find(
         resourceId=ResourceID.REEL_VIEWER_TIMESTAMP,
         className=ClassName.TEXT_VIEW,
     )
     if reel_viewer_timestamp.exists():
         timestamp = reel_viewer_timestamp.get_text().strip()
         value = int(re.sub("[^0-9]", "", timestamp))
         if timestamp[-1] == "s":
             return datetime.timestamp(
                 datetime.datetime.now() - datetime.timedelta(seconds=value)
             )
         elif timestamp[-1] == "m":
             return datetime.timestamp(
                 datetime.datetime.now() - datetime.timedelta(minutes=value)
             )
         elif timestamp[-1] == "h":
             return datetime.timestamp(
                 datetime.datetime.now() - datetime.timedelta(hours=value)
             )
         else:
             return datetime.timestamp(
                 datetime.datetime.now() - datetime.timedelta(days=value)
             )
     return None
Ejemplo n.º 6
0
 async def ping(self, ctx):
     start = datetime.timestamp(datetime.now())  #Starts the ping
     await ctx.send('Ping :ping_pong: Pong  `{0}ms`'.
                    format(  #Ends the ping and formats it
                        round((datetime.timestamp(datetime.now()) - start) *
                              1000000)))
     print(ctx.message.author.name + ' has pinged.')  #Logs who pinged
     return
Ejemplo n.º 7
0
 def __init__(self, name, email, access_token, refresh_token, id_token):
     self.name = name
     self.email = email
     self.access_token = access_token
     self.refresh_token = refresh_token
     self.id_token = id_token
     t1 = datetime.now()
     self.creation_date = datetime.timestamp(t1)
     self.last_login = datetime.timestamp(t1)
Ejemplo n.º 8
0
def testGenerateGraph(samples):
    timeArray = [None] * samples
    for i in range(0, samples):
        rows = i + 1
        columns = i + 1
        timestamp1 = datetime.timestamp(datetime.now())
        Maze.generateGraph(rows, columns)
        timestamp2 = datetime.timestamp(datetime.now())
        timeArray[i] = timestamp2 - timestamp1
    return timeArray
Ejemplo n.º 9
0
def testKruskal(samples):
    timeArray = [None] * samples
    for i in range(0, samples):
        rows = i + 1
        columns = i + 1
        G = Maze.generateGraph(rows, columns)
        timestamp1 = datetime.timestamp(datetime.now())
        Maze.kruskalAlgorithm(G)
        timestamp2 = datetime.timestamp(datetime.now())
        timeArray[i] = timestamp2 - timestamp1
    return timeArray
Ejemplo n.º 10
0
def conta_aminoacidos(value):

    conta = 0

    while (conta < 3):

        dt = datetime.today()

        seconds = dt.timestamp()

        print("SEGUNDOS:", seconds)

        for seconds in range(0, 3):

            print("seconds", seconds)

            print("saiu")

            value += 1

            print("value", value)

            time.sleep(1)

        print("CONTOU 3")

        conta += 1
Ejemplo n.º 11
0
    def genObject(self):
        now = datetime.now()
        currentTimestamp = int(datetime.timestamp(now))

        catagory = np.random.randint(1, 6)
        wVar, hVar = [i + 0.99 for i in np.random.rand(2) * 0.2]

        #Object always appear from left except first frame,
        #each object might appear 3~5 frame
        #gen object width and height

        w, h = np.random.randint(100, 250), np.random.randint(70, 170)

        if self.imgId == 0:
            absCenterX = np.random.rand() * self.width
        else:
            xMid = self.leftMost / 2
            absCenterX = min((0.5 - np.random.rand()) * w + xMid,
                             self.width / 5)

        #Object won't directly has large overlap, it might continuously appear
        #but not overlap

        possibleIdx, = np.nonzero(self.validGenAreaY)
        possibleY = np.random.randint(
            5) if possibleIdx.size == 0 else np.random.choice(possibleIdx)

        centerRangeY = 0.2 * possibleY + 0.1 + (np.random.rand() - 0.5) * 0.1
        absCenterY = centerRangeY * self.height

        #make variation of detection bot
        absWH = Point(w * wVar, h * hVar)
        absC = Point(absCenterX, absCenterY)
        return detectionResult(currentTimestamp, catagory, self.objId, absWH,
                               absC, resolution)
Ejemplo n.º 12
0
    def save(self, *args, **kwargs):
        # super().save(*args, **kwargs)
        if self.avatar:
            from io import BytesIO
            from django.core.files.base import ContentFile
            from datetime import datetime
            import os
            from PIL import Image
            try:
                image_source = os.path.join(settings.BASE_DIR, self.avatar.path)
                output = os.path.splitext(image_source)[0] + '_thumbnail.jpg'
                img = Image.open(image_source)
                img.thumbnail((320,320), Image.ANTIALIAS)
                fp = BytesIO()
                img.save(fp, "JPEG", quality=90)
                fp.seek(0)
                filename = "%s__%s.jpg" % (self.user.username, datetime.timestamp(datetime.now()))
                self.avatar.delete(save=True)
                self.avatar.save( name=filename, content=ContentFile(fp.read()), save=False )
                fp.close()
            except Exception as e:
                print(e)
                print("Couldn't save image thumbnail")

        super(Profile, self).save(*args, **kwargs)
Ejemplo n.º 13
0
def produce_user_events():

    ##Generate randowm user events for producing on Kafka topic -- user_events
    random_key = str(randint(1, 10))
    randomstr = ''.join([
        random.choice(string.ascii_letters + string.digits) for n in range(4)
    ])
    random_time = int(datetime.timestamp(randomtimestamp(2019, False)))
    user_dict = {}
    metadata = {}
    metadata['messageid'] = str(uuid.uuid4())
    metadata['sent_at'] = random_time
    metadata['timestamp'] = random_time
    metadata['received_at'] = random_time + 100
    metadata['apikey'] = 'apikey' + random_key
    metadata['spaceid'] = 'spaceid' + random_key
    metadata['version'] = 'version' + random_key
    event_data = {}
    event_data['movieid'] = 'MIM' + randomstr
    user_dict['userid'] = 'user' + str(randint(1, 100))
    user_dict['type'] = 'event'
    user_dict['metadata'] = metadata
    user_dict['event'] = 'played movie'
    user_dict['event_data'] = event_data

    #print(user_dict)
    return json.dumps(user_dict)
Ejemplo n.º 14
0
def get_claim_ids():
    claim_ids = []
    limit = datetime.now() - timedelta(days=DAYS_BACK)  # days back to search
    timestamp_limit = str(int(datetime.timestamp(limit)))
    for page in range(1, 30):
        call = requests.post("http://localhost:5279",
                             json={
                                 "method": "claim_search",
                                 "params": {
                                     "claim_ids": [],
                                     "channel_ids": CHANNEL_IDS,
                                     'release_time': f'>{timestamp_limit}',
                                     "not_channel_ids": [],
                                     "stream_types": [],
                                     "media_types": [],
                                     "any_tags": [],
                                     "all_tags": [],
                                     "not_tags": [],
                                     "any_languages": [],
                                     "all_languages": [],
                                     "not_languages": [],
                                     "any_locations": [],
                                     "all_locations": [],
                                     "not_locations": [],
                                     "order_by": [],
                                     "page_size": 50,
                                     "page": page,
                                     'no_totals': True,
                                 }
                             }).json().get('result').get('items')
        for claim in call:
            claim_id = claim.get('claim_id')
            claim_ids.append(claim_id)
    print(f'Searching spam on {len(claim_ids)} claims...%')
    return claim_ids
Ejemplo n.º 15
0
    def _to_timestamp(datetime):
        '''convert datetime to unix timestamp in python2 compatible manner.'''

        try:
            return datetime.timestamp()
        except AttributeError:
            return int(datetime.strftime('%s'))
Ejemplo n.º 16
0
 def update_next_update():
     timer = Timer.objects.get(id=1)
     timer.timer_is_started = True
     timer.current_quarter += 1
     timer.next_update = (datetime.timestamp(datetime.now()) +
                          Settings.objects.get(pk=1).quarter_time * 60)
     timer.save()
Ejemplo n.º 17
0
def convert_datetime_to_unix_time(datetime: datetime.datetime):
    """
    Converts a datetime object to a unix time.
    :param datetime: The datetime object to convert.
    :return: A unix time.
    """
    return datetime.timestamp()
Ejemplo n.º 18
0
    def get_last_midnight(dt):

        if dt is not None:
            dt_timestamp = datetime.fromtimestamp(dt)
            midnight = datetime.combine(dt_timestamp.today(),
                                        dt_timestamp.min.time())
            next_midnight = datetime.timestamp(midnight + timedelta(days=1))
            return next_midnight
Ejemplo n.º 19
0
        def just_rename():
            now = datetime.now()
            timestamp = datetime.timestamp(now)
            src = os.path.join(path_img_dump, folders)
            dst = os.path.join(path_img_dump, today + '-' + str(timestamp))

            os.rename(src, dst)
            print('renamed', src, 'to', dst)
Ejemplo n.º 20
0
 def gen_next_block(self, public_key, transactions):
     prev_block = self.chain[-1]
     index = prev_block.index + 1
     timestamp = datetime.timestamp(datetime.datetime.now())
     data = transactions
     hashed_block = prev_block.gen_hashed_block()
     self.chain.append(
         Block(index, timestamp, data, hashed_block, public_key))
Ejemplo n.º 21
0
def getRegularMarketData(symbol, crumbs, latest=2, interval='1d'):
    current = datetime.now()
    period2 = int(datetime.timestamp(current))
    period1 = current - timedelta(days=latest)
    period1 = period1.replace(hour=0, minute=0, second=0, microsecond=0)
    period1 = int(datetime.timestamp(period1))
    includePrePost = 'true'
    url ='https://query1.finance.yahoo.com/v8/finance/chart/{}?symbol={}&period1={}&period2={}&interval={}' \
          '&includePrePost={}&events=div%7Csplit%7Cearn&lang=en-US&region=US&crumb={}&corsDomain=finance.yahoo.com'\
          ''.format(symbol, symbol, period1, period2, interval, includePrePost, crumbs)
    response = requests.get(url=url)
    if response.status_code == 200:
        response = json.loads(response.content)
        web_data = response['chart']['result'][0]['meta']['regularMarketPrice']
        return web_data
    else:
        print('Web data fetch fail. Response code')
        print(response.status_code)
Ejemplo n.º 22
0
    def round_minutes(timestamp, direction, resolution):

        # Function to get last time specify by up or down resolution
        now = datetime.fromtimestamp(timestamp)
        dt = now.replace(second=0, microsecond=0)
        new_minute = (dt.minute // resolution +
                      (1 if direction == 'up' else 0)) * resolution
        result = dt + timedelta(minutes=new_minute - dt.minute)

        return int(datetime.timestamp(result))
Ejemplo n.º 23
0
def addpicture():
    update_this = users.query.filter(users.id == session['user']['id']).first()
    now = datetime.now()
    timestamp = datetime.timestamp(now)
    file = request.files['picture']
    filename = secure_filename(str(timestamp) + file.filename)
    update_this.picture = filename
    file.save(os.path.join('static/picture', filename))
    db.session.commit()
    return redirect(url_for('links.index'))
Ejemplo n.º 24
0
 def update(self,
            *values,
            timestamp: Union[datetime.datetime, str] = "N") -> None:
     if len(values) == 1 and isinstance(values[0], tuple):
         args = list(values[0])
     else:
         args = values
     if isinstance(timestamp, datetime.datetime):
         args.insert(0, datetime.timestamp())
     rrdtool.update(self.rrd_file, ":".join(str(arg) for arg in args))
Ejemplo n.º 25
0
def convert_datestr_to_timestamp(datestr):
    year = int(datestr[0:4])
    month = int(datestr[4:6])
    day = int(datestr[6:])

    date = datetime(year, month, day)
    tz = pytz.timezone(secrets.timezone)
    tz_aware_date = tz.localize(date, is_dst=None)
    ts = datetime.timestamp(tz_aware_date) + tz_aware_date.tzinfo._dst.seconds

    return ts
Ejemplo n.º 26
0
    def on(self,
           datetime: datetime.datetime,
           ps: Promise,
           priority=0,
           now=False):
        if now: self.push(ps)

        return self.scheduler.enterabs(datetime.timestamp(),
                                       priority=priority,
                                       action=self.push,
                                       argument=(ps, ))
Ejemplo n.º 27
0
def guild_premium_set(guild_id: int, date: date.datetime) -> None:
    """Sets the premium end's date

    Arguments:
        guild_id {int} -- The guild ID
        date {date.datetime} -- The ending time
    """
    sql = "UPDATE guilds SET premium = ? WHERE guilds.id = ?"
    args = [date.timestamp(), guild_id]

    exec(sql, args)
Ejemplo n.º 28
0
 def getTimestamp(self):
     reel_viewer_timestamp = self.device.find(
         resourceId=f"{self.device.app_id}:id/reel_viewer_timestamp",
         className="android.widget.TextView",
     )
     if reel_viewer_timestamp.exists():
         timestamp = reel_viewer_timestamp.get_text().strip()
         value = int(re.sub("[^0-9]", "", timestamp))
         if timestamp[-1] == "s":
             return datetime.timestamp(datetime.datetime.now() -
                                       datetime.timedelta(seconds=value))
         elif timestamp[-1] == "m":
             return datetime.timestamp(datetime.datetime.now() -
                                       datetime.timedelta(minutes=value))
         elif timestamp[-1] == "h":
             return datetime.timestamp(datetime.datetime.now() -
                                       datetime.timedelta(hours=value))
         else:
             return datetime.timestamp(datetime.datetime.now() -
                                       datetime.timedelta(days=value))
     return None
Ejemplo n.º 29
0
 def testGetTodayList(self):
     header['X-Auth-Token'] = test_parameter['broadcaster_token']
     header['X-Auth-Nonce'] = test_parameter['broadcaster_nonce']
     stime = (datetime.today() - timedelta(hours=9))
     etime = (datetime.today() + timedelta(hours=1))
     apiName = '/api/v2/liveMaster/giftGiversToSendIM?startTime={sTime}&endTime={eTime}&item=10&page=1'
     apiName = apiName.replace('{sTime}',
                               str(int(datetime.timestamp(stime))))
     apiName = apiName.replace('{eTime}',
                               str(int(datetime.timestamp(etime))))
     res = api.apiFunction(test_parameter['prefix'], header, apiName, 'get',
                           None)
     restext = json.loads(res.text)
     pprint(restext)
     pprint(self.today)
     print('user=%s' % idList[1])
     assert restext['totalCount'] == len(self.today)
     assert restext['sentCount'] == 0
     for i in restext['data']:
         i['user']['id'] in self.today
     assert restext['data'][0]['points'] >= restext['data'][1]['points']
Ejemplo n.º 30
0
    def Mttr():

        for row in comread:

            tiempoin = datetime.strptime(row[1], '%Y-%m-%d %H:%M:%S')
            inicio_reparacion.append(datetime.timestamp(tiempoin))

        for row in terread:
            tiempoter = datetime.strptime(row[1], '%Y-%m-%d %H:%M:%S')
            termino_reparacion.append(datetime.timestamp(tiempoter))

        for i in range(len(inicio_reparacion)):
            ttr.append(termino_reparacion[i] - inicio_reparacion[i])
            mttr = (ttr[i - 1] + ttr[i]) / len(inicio_reparacion)

        for i in range(len(termino_reparacion) - 1):

            tbf.append(inicio_reparacion[i + 1] - termino_reparacion[i])
            mtbf = (tbf[i - 1] + tbf[i]) / len(termino_reparacion)

        return print(mttr, mtbf)
Ejemplo n.º 31
0
    def __init__(self, *args, **kwd):
        Exception.__init__(self)

        message, inner = None, None
        for arg in args:
            if isinstance(arg, basestring) is True:
                message = arg
            elif isinstance(arg, Exception) is True:
                inner = arg

        if inner is None:
            inner = kwd.get("inner", kwd.get("ex", None))

        if message is None:
            if inner is not None:
                message = inner.message
            if message is None:
                message = kwd.get("message", "An error occurred.")

        self.message = message
        self.inner = inner
        self.timestamp = datetime.timestamp()
Ejemplo n.º 32
0
def to_unix_timestamp(datetime):
    return int(datetime.timestamp())
Ejemplo n.º 33
0
 def __init__(self):
     self.timestamp = datetime.timestamp()
     self.flavors = {}
Ejemplo n.º 34
0
 def time_in_seconds(dt):
     start_of_day = dt.replace(hour=0, minute=0, second=0, microsecond=0)
     return int(dt.timestamp() - start_of_day.timestamp())
Ejemplo n.º 35
0
 def __init__(self):
     self.timestamp = datetime.timestamp()
     self.images = {}
Ejemplo n.º 36
0
                                args.expiration, fee_required, fee_provided, unsigned=args.unsigned)
        print(unsigned_tx_hex) if args.unsigned else json_print(bitcoin.transmit(unsigned_tx_hex))

    elif args.action == 'btcpay':
        unsigned_tx_hex = btcpay.create(db, args.order_match_id, unsigned=args.unsigned)
        print(unsigned_tx_hex) if args.unsigned else json_print(bitcoin.transmit(unsigned_tx_hex))

    elif args.action == 'issuance':
        quantity = util.devise(db, args.quantity, None, 'input',
                               divisible=args.divisible)
        if args.callable_:
            if not args.call_date:
                parser.error('must specify call date of callable asset', )
            if not args.call_price:
                parser.error('must specify call price of callable asset')
            call_date = round(datetime.timestamp(dateutil.parser.parse(args.call_date)))
            call_price = float(args.call_price)
        else:
            call_date, call_price = 0, 0

        unsigned_tx_hex = issuance.create(db, args.source,
                                          args.transfer_destination,
                                          args.asset, quantity, args.divisible, args.callable_, call_date, call_price, args.description, unsigned=args.unsigned)
        print(unsigned_tx_hex) if args.unsigned else json_print(bitcoin.transmit(unsigned_tx_hex))

    elif args.action == 'broadcast':
        value = util.devise(db, args.value, 'value', 'input')
        unsigned_tx_hex = broadcast.create(db, args.source, int(time.time()),
                                           value, args.fee_multiplier,
                                           args.text, unsigned=args.unsigned)
        print(unsigned_tx_hex) if args.unsigned else json_print(bitcoin.transmit(unsigned_tx_hex))