Python time.localtime() Examples

The following are 60 code examples for showing how to use time.localtime(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

You may also check out all available functions/classes of the module time , or try the search function .

Example 1
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: GradientClock.py    License: MIT License 6 votes vote down vote up
def step(self, amt=1):
        self.layout.all_off()
        t = time.localtime()
        hrs = t.tm_hour % 12
        mins = t.tm_min
        sec = t.tm_sec

        h_hrs = hrs * (256 // 12)
        h_min = mins * (256 // 60)
        h_sec = sec * (256 // 60)

        grad = []

        grad += hue_gradient(h_hrs, h_min, self.half)
        if self.odd:
            grad += [h_min]
        grad += hue_gradient(h_min, h_sec, self.half)

        log.debug('{}:{}:{}'.format(hrs, mins, sec))

        for x in range(self.cdim):
            self.layout.drawLine(x, 0, x, self.height - 1,
                                 self.palette(grad[x])) 
Example 2
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: AnalogClock.py    License: MIT License 6 votes vote down vote up
def step(self, amt=1):
        self.layout.all_off()
        t = time.localtime()
        hrs = t.tm_hour % 12
        mins = t.tm_min
        sec = t.tm_sec

        p_hrs = pointOnCircle(self._centerX, self._centerY, int(self.hand_length * 0.7), hrs * 30)
        p_min = pointOnCircle(self._centerX, self._centerY, self.hand_length, mins * 6)
        p_sec = pointOnCircle(self._centerX, self._centerY, self.hand_length, sec * 6)

        c_hrs = self.palette(hrs * (256 // 12))
        c_min = self.palette(mins * (256 // 60))
        c_sec = self.palette(sec * (256 // 60))

        self.layout.drawLine(self._centerX, self._centerY, p_hrs[0], p_hrs[1], c_hrs, aa=self.aa)
        self.layout.drawLine(self._centerX, self._centerY, p_min[0], p_min[1], c_min, aa=self.aa)
        self.layout.drawLine(self._centerX, self._centerY, p_sec[0], p_sec[1], c_sec, aa=self.aa) 
Example 3
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: GameOfLife.py    License: MIT License 6 votes vote down vote up
def create_time_table(self, t):
        t = time.localtime(t)
        hr = t.tm_hour
        if not self.mil_time:
            hr = hr % 12
        hrs = str(hr).zfill(2)
        mins = str(t.tm_min).zfill(2)
        val = hrs + ":" + mins
        w, h = font.str_dim(val, font=self.font_name,
                            font_scale=self.scale, final_sep=False)
        x = (self.width - w) // 2
        y = (self.height - h) // 2
        old_buf = copy.copy(self.layout.colors)
        self.layout.all_off()
        self.layout.drawText(val, x, y, color=COLORS.Red,
                             font=self.font_name, font_scale=self.scale)
        table = []
        for y in range(self.height):
            table.append([0] * self.width)
            for x in range(self.width):
                table[y][x] = int(any(self.layout.get(x, y)))
        self.layout.setBuffer(old_buf)
        return table 
Example 4
Project: InsightAgent   Author: insightfinder   File: getmetrics_nfdump.py    License: Apache License 2.0 6 votes vote down vote up
def getFileNameList():
    currentDate = time.strftime("%Y/%m/%d", time.localtime())
    fileNameList = []
    start_time_epoch = long(time.time())
    chunks = int(reportingConfigVars['reporting_interval'] / 5)
    startMin = time.strftime("%Y%m%d%H%M", time.localtime(start_time_epoch))
    closestMinute = closestNumber(int(startMin[-2:]), 5)
    if closestMinute < 10:
        closestMinStr = '0' + str(closestMinute)
        newDate = startMin[:-2] + str(closestMinStr)
    else:
        newDate = startMin[:-2] + str(closestMinute)
    chunks -= 1
    currentTime = datetime.datetime.strptime(newDate, "%Y%m%d%H%M") - datetime.timedelta(minutes=5)
    closestMinute = time.strftime("%Y%m%d%H%M", currentTime.timetuple())
    filename = os.path.join(currentDate, "nfcapd." + closestMinute)
    fileNameList.append(filename)
    while chunks >= 0:
        chunks -= 1
        currentTime = datetime.datetime.strptime(closestMinute, "%Y%m%d%H%M") - datetime.timedelta(minutes=5)
        closestMinute = time.strftime("%Y%m%d%H%M", currentTime.timetuple())
        filename = os.path.join(currentDate, "nfcapd." + closestMinute)
        fileNameList.append(filename)

    return set(fileNameList) - getLastSentFiles() 
Example 5
Project: SublimeKSP   Author: nojanath   File: cpp.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,lexer=None):
        if lexer is None:
            lexer = lex.lexer
        self.lexer = lexer
        self.macros = { }
        self.path = []
        self.temp_path = []

        # Probe the lexer for selected tokens
        self.lexprobe()

        tm = time.localtime()
        self.define("__DATE__ \"%s\"" % time.strftime("%b %d %Y",tm))
        self.define("__TIME__ \"%s\"" % time.strftime("%H:%M:%S",tm))
        self.parser = None

    # -----------------------------------------------------------------------------
    # tokenize()
    #
    # Utility function. Given a string of text, tokenize into a list of tokens
    # ----------------------------------------------------------------------------- 
Example 6
Project: SublimeKSP   Author: nojanath   File: preprocessor_plugins.py    License: GNU General Public License v3.0 6 votes vote down vote up
def createBuiltinDefines(lines):
	# Create date-time variables

	timecodes = ['%S', '%M', '%H', '%I', '%p', '%d', '%m', '%Y', '%y', '%B', '%b', '%x', '%X']
	timenames = ['__SEC__','__MIN__','__HOUR__','__HOUR12__','__AMPM__','__DAY__','__MONTH__','__YEAR__','__YEAR2__','__LOCALE_MONTH__','__LOCALE_MONTH_ABBR__','__LOCALE_DATE__','__LOCALE_TIME__']
	defines = ['define {0} := \"{1}\"'.format(timenames[i], strftime(timecodes[i], localtime())) for i in range(len(timecodes))]

	newLines = collections.deque()

	# append our defines on top of the script in a temporary deque
	for string in defines:
		newLines.append(lines[0].copy(string))

	# merge with the original unmodified script
	for line in lines:
		newLines.append(line)

	# replace original deque with modified one
	replaceLines(lines, newLines)

#================================================================================================= 
Example 7
Project: gw2pvo   Author: markruys   File: pvo_api.py    License: MIT License 6 votes vote down vote up
def add_status(self, pgrid_w, eday_kwh, temperature, voltage):
        t = time.localtime()
        payload = {
            'd' : "{:04}{:02}{:02}".format(t.tm_year, t.tm_mon, t.tm_mday),
            't' : "{:02}:{:02}".format(t.tm_hour, t.tm_min),
            'v1' : round(eday_kwh * 1000),
            'v2' : round(pgrid_w)
        }

        if temperature is not None:
            payload['v5'] = temperature

        if voltage is not None:
            payload['v6'] = voltage

        self.call("https://pvoutput.org/service/r2/addstatus.jsp", payload) 
Example 8
Project: BatteryMonitor   Author: simat   File: summary.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self):
    self.currenttime = time.localtime()
    printtime = time.strftime("%Y%m%d%H%M%S ", self.currenttime)
    self.logfile = open(config['files']['logfile'],'at',buffering=1)
    self.sampletime = time.time()
    self.prevtime = time.localtime()
    self.summary=loadsummary()

#      summary = open('/media/75cc9171-4331-4f88-ac3f-0278d132fae9/summary','w')
#      pickle.dump(hivolts, summary)
#      pickle.dump(lowvolts, summary)
#      summary.close()
    if self.summary['hour']['timestamp'][0:10] != printtime[0:10]:
      self.summary['hour'] = deepcopy(self.summary['current'])
    if self.summary['currentday']['timestamp'][0:8] != printtime[0:8]:
      self.summary['currentday'] = deepcopy(self.summary['current'])
    if self.summary['monthtodate']['timestamp'][0:6] != printtime[0:6]:
      self.summary['monthtodate'] = deepcopy(self.summary['current'])
    if self.summary['yeartodate']['timestamp'][0:4] != printtime[0:4]:
      self.summary['yeartodate'] = deepcopy(self.summary['current']) 
Example 9
Project: BatteryMonitor   Author: simat   File: alarms.py    License: GNU General Public License v2.0 6 votes vote down vote up
def scanalarms(self,batdata):
#    self.timedate = localtime()
#    print (self.timedate.tm_hour)
    for i in config['alarms']:
      if not self.alarmtriggered[i]:
        exec(config['alarms'][i][1])
  #      log.debug('{}{}{}'.format(self.test,batdata.maxcellv,batdata.lastmaxcellv))
        if self.test:
    #            sys.stderr.write('Alarm 1 triggered')
          log.info('alarm {} triggered'.format(i))
          self.alarmtriggered[i]=True
          exec(config['alarms'][i][2])

      if self.alarmtriggered[i]:
        exec(config['alarms'][i][3])
        if self.test:
          log.info('alarm {} reset'.format(i))
          self.alarmtriggered[i]=False
          exec(config['alarms'][i][4]) 
Example 10
Project: BatteryMonitor   Author: simat   File: getbms.py    License: GNU General Public License v2.0 6 votes vote down vote up
def getbmsdat(self,port,command):
    """ Issue BMS command and return data as byte data """
    """ assumes data port is open and configured """
    for i in range(5):
      try:
        port.write(command)
        reply = port.read(4)
#        raise serial.serialutil.SerialException('hithere')
        break
      except serial.serialutil.SerialException as err:
        errfile=open(config['files']['errfile'],'at')
        errfile.write(time.strftime("%Y%m%d%H%M%S ", time.localtime())+str(err.args)+'\n')
        errfile.close()

  #  print (reply)
    x = int.from_bytes(reply[3:5], byteorder = 'big')
#    print (x)
    data = port.read(x)
    end = port.read(3)
#    print (data)
    return data 
Example 11
Project: raspberrypi-examples   Author: timwaizenegger   File: tm1637.py    License: MIT License 6 votes vote down vote up
def clock(self, military_time):
        """Clock script modified from:
            https://github.com/johnlr/raspberrypi-tm1637"""
        self.ShowDoublepoint(True)
        while (not self.__stop_event.is_set()):
            t = localtime()
            hour = t.tm_hour
            if not military_time:
                hour = 12 if (t.tm_hour % 12) == 0 else t.tm_hour % 12
            d0 = hour // 10 if hour // 10 else 0
            d1 = hour % 10
            d2 = t.tm_min // 10
            d3 = t.tm_min % 10
            digits = [d0, d1, d2, d3]
            self.Show(digits)
            # # Optional visual feedback of running alarm:
            # print digits
            # for i in tqdm(range(60 - t.tm_sec)):
            for i in range(60 - t.tm_sec):
                if (not self.__stop_event.is_set()):
                    sleep(1) 
Example 12
Project: password_pwncheck   Author: CboeSecurity   File: password-pwncheck.py    License: MIT License 6 votes vote down vote up
def logmsg(request,type,message,args):
    is_dst = time.daylight and time.localtime().tm_isdst > 0
    tz =  - (time.altzone if is_dst else time.timezone) / 36
    if tz>=0:
        tz="+%04d"%tz
    else:
        tz="%05d"%tz
    datestr = '%d/%b/%Y %H:%M:%S'
    user = getattr(logStore,'user','')
    isValid = getattr(logStore,'isValid','')
    code = getattr(logStore,'code','')
    args = getLogDateTime(args)
    log = '%s %s,%s,%s,%s,%s,%s' % (datetime.now().strftime(datestr),tz,request.address_string(),user,isValid,code, message % args)
    with logLock:
        with open(cfg.logpath,'a') as fw:
            fw.write(log+os.linesep)
    return log 
Example 13
Project: jawfish   Author: war-and-code   File: __init__.py    License: MIT License 6 votes vote down vote up
def formatTime(self, record, datefmt=None):
        """
        Return the creation time of the specified LogRecord as formatted text.

        This method should be called from format() by a formatter which
        wants to make use of a formatted time. This method can be overridden
        in formatters to provide for any specific requirement, but the
        basic behaviour is as follows: if datefmt (a string) is specified,
        it is used with time.strftime() to format the creation time of the
        record. Otherwise, the ISO8601 format is used. The resulting
        string is returned. This function uses a user-configurable function
        to convert the creation time to a tuple. By default, time.localtime()
        is used; to change this for a particular formatter instance, set the
        'converter' attribute to a function with the same signature as
        time.localtime() or time.gmtime(). To change it for all formatters,
        for example if you want all logging times to be shown in GMT,
        set the 'converter' attribute in the Formatter class.
        """
        ct = self.converter(record.created)
        if datefmt:
            s = time.strftime(datefmt, ct)
        else:
            t = time.strftime(self.default_time_format, ct)
            s = self.default_msec_format % (t, record.msecs)
        return s 
Example 14
Project: Vxscan   Author: al0ne   File: sqldb.py    License: Apache License 2.0 6 votes vote down vote up
def get_ports(self, ipaddr, ports):
        self.create_ports()
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        for i in ports:
            service = i.get('server')
            port = i.get('port')
            banner = i.get('banner')
            banner = re.sub('<', '', banner)
            banner = re.sub('>', '', banner)
            md5sum = hashlib.md5()
            strings = str(ipaddr) + str(service) + str(port)
            md5sum.update(strings.encode('utf-8'))
            md5 = md5sum.hexdigest()
            values = (timestamp, ipaddr, service, port, banner, md5)
            query = "INSERT OR IGNORE INTO ports (time, ipaddr, service, port, banner,md5) VALUES (?,?,?,?,?,?)"
            self.insert_ports(query, values) 
Example 15
Project: Vxscan   Author: al0ne   File: sqldb.py    License: Apache License 2.0 6 votes vote down vote up
def get_crawl(self, domain, crawl):
        self.create_crawl()
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        for i in crawl:
            if 'Dynamic:' in i:
                type = 'Dynamic link'
            else:
                type = 'Leaks'
            md5sum = hashlib.md5()
            try:
                text = re.search(r'(?<=Email: ).*|(?<=Phone: ).*', i).group()
            except:
                text = str(i)
            strings = str(domain) + text
            md5sum.update(strings.encode('utf-8'))
            md5 = md5sum.hexdigest()
            values = (timestamp, domain, type, i, md5)
            query = "INSERT OR IGNORE INTO Crawl (time, domain, type, leaks, md5) VALUES (?,?,?,?,?)"
            self.insert_crawl(query, values)
        self.commit()
        self.close() 
Example 16
Project: risk-slim   Author: ustunb   File: helper_functions.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_log(msg, print_flag = True):
    """

    Parameters
    ----------
    msg
    print_flag

    Returns
    -------

    """
    if print_flag:
        if isinstance(msg, str):
            print('%s | %s' % (time.strftime("%m/%d/%y @ %I:%M %p", time.localtime()), msg))
        else:
            print('%s | %r' % (time.strftime("%m/%d/%y @ %I:%M %p", time.localtime()), msg))
        sys.stdout.flush() 
Example 17
Project: verge3d-blender-addon   Author: Soft8Soft   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def collapse_rfc2231_value(value, errors='replace',
                           fallback_charset='us-ascii'):
    if not isinstance(value, tuple) or len(value) != 3:
        return unquote(value)
    # While value comes to us as a unicode string, we need it to be a bytes
    # object.  We do not want bytes() normal utf-8 decoder, we want a straight
    # interpretation of the string as character bytes.
    charset, language, text = value
    rawbytes = bytes(text, 'raw-unicode-escape')
    try:
        return str(rawbytes, charset, errors)
    except LookupError:
        # charset is not a known codec.
        return unquote(text)


#
# datetime doesn't provide a localtime function yet, so provide one.  Code
# adapted from the patch in issue 9527.  This may not be perfect, but it is
# better than not having it.
# 
Example 18
Project: verge3d-blender-addon   Author: Soft8Soft   File: datetime.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __repr__(self):
        """Convert to formal string, for repr().

        >>> dt = datetime(2010, 1, 1)
        >>> repr(dt)
        'datetime.datetime(2010, 1, 1, 0, 0)'

        >>> dt = datetime(2010, 1, 1, tzinfo=timezone.utc)
        >>> repr(dt)
        'datetime.datetime(2010, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)'
        """
        return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
                                   self._year,
                                   self._month,
                                   self._day)
    # XXX These shouldn't depend on time.localtime(), because that
    # clips the usable dates to [1970 .. 2038).  At least ctime() is
    # easily done without using strftime() -- that's better too because
    # strftime("%c", ...) is locale specific. 
Example 19
Project: 21tb_robot   Author: iloghyr   File: study_robot.py    License: MIT License 5 votes vote down vote up
def log(info):
    """simple log"""
    print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), info
    sys.stdout.flush() 
Example 20
Project: controllable-text-attribute-transfer   Author: Nrgeup   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def add_log(ss):
    now_time = time.strftime("[%Y-%m-%d %H:%M:%S]: ", time.localtime())
    print(now_time + ss)
    with open(args.log_file, 'a') as f:
        f.write(now_time + str(ss) + '\n')
    return 
Example 21
Project: controllable-text-attribute-transfer   Author: Nrgeup   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def preparation():
    # set model save path
    if args.if_load_from_checkpoint:
        timestamp = args.checkpoint_name
    else:
        timestamp = str(int(time.time()))
        print("create new model save path: %s" % timestamp)
    args.current_save_path = 'save/%s/' % timestamp
    args.log_file = args.current_save_path + time.strftime("log_%Y_%m_%d_%H_%M_%S.txt", time.localtime())
    args.output_file = args.current_save_path + time.strftime("output_%Y_%m_%d_%H_%M_%S.txt", time.localtime())
    print("create log file at path: %s" % args.log_file)

    if os.path.exists(args.current_save_path):
        add_log("Load checkpoint model from Path: %s" % args.current_save_path)
    else:
        os.makedirs(args.current_save_path)
        add_log("Path: %s is created" % args.current_save_path)

    # set task type
    if args.task == 'yelp':
        args.data_path = '../../data/yelp/processed_files/'
    elif args.task == 'amazon':
        args.data_path = '../../data/amazon/processed_files/'
    elif args.task == 'imagecaption':
        pass
    else:
        raise TypeError('Wrong task type!')

    # prepare data
    args.id_to_word, args.vocab_size, \
    args.train_file_list, args.train_label_list = prepare_data(
        data_path=args.data_path, max_num=args.word_dict_max_num, task_type=args.task
    )
    return 
Example 22
Project: controllable-text-attribute-transfer   Author: Nrgeup   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def add_log(ss):
    now_time = time.strftime("[%Y-%m-%d %H:%M:%S]: ", time.localtime())
    print(now_time + ss)
    with open(args.log_file, 'a') as f:
        f.write(now_time + str(ss) + '\n')
    return 
Example 23
Project: controllable-text-attribute-transfer   Author: Nrgeup   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def preparation():
    # set model save path
    if args.if_load_from_checkpoint:
        timestamp = args.checkpoint_name
    else:
        timestamp = str(int(time.time()))
        print("create new model save path: %s" % timestamp)
    args.current_save_path = 'save/%s/' % timestamp
    args.log_file = args.current_save_path + time.strftime("log_%Y_%m_%d_%H_%M_%S.txt", time.localtime())
    args.output_file = args.current_save_path + time.strftime("output_%Y_%m_%d_%H_%M_%S.txt", time.localtime())
    print("create log file at path: %s" % args.log_file)

    if os.path.exists(args.current_save_path):
        add_log("Load checkpoint model from Path: %s" % args.current_save_path)
    else:
        os.makedirs(args.current_save_path)
        add_log("Path: %s is created" % args.current_save_path)

    # set task type
    if args.task == 'yelp':
        args.data_path = '../../data/yelp/processed_files/'
    elif args.task == 'amazon':
        args.data_path = '../../data/amazon/processed_files/'
    elif args.task == 'imagecaption':
        args.data_path = '../../data/imagecaption/processed_files/'
    else:
        raise TypeError('Wrong task type!')

    # prepare data
    args.id_to_word, args.vocab_size, \
    args.train_file_list, args.train_label_list = prepare_data(
        data_path=args.data_path, max_num=args.word_dict_max_num, task_type=args.task
    )
    return 
Example 24
Project: controllable-text-attribute-transfer   Author: Nrgeup   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def add_log(ss):
    now_time = time.strftime("[%Y-%m-%d %H:%M:%S]: ", time.localtime())
    print(now_time + ss)
    with open(args.log_file, 'a') as f:
        f.write(now_time + str(ss) + '\n')
    return 
Example 25
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: hexclock.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        t = time.localtime()
        hex = "#{0:0>2}{1:0>2}{2:0>2}".format(t.tm_hour, t.tm_min, t.tm_sec)
        c = COLORS[hex]
        self.layout.fill(c)

        self._step = 0 
Example 26
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: RGBClock.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        t = time.localtime()

        r, g, b = self.palette(t.tm_hour * (256 // 24))
        self.layout.fillRGB(r, g, b, self._hStart, self._hEnd)

        r, g, b = self.palette(t.tm_min * (256 // 60))
        self.layout.fillRGB(r, g, b, self._mStart, self._mEnd)

        r, g, b = self.palette(t.tm_sec * (256 // 60))
        self.layout.fillRGB(r, g, b, self._sStart, self._sEnd) 
Example 27
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: TallClock.py    License: MIT License 5 votes vote down vote up
def step(self, amt):
        self.layout.setTexture([[self.palette(
            y * 255 / self.height + self._step * 2)] * self.width for y in range(self.height)])
        self.layout.all_off()
        t = time.localtime()
        hrs = str(t.tm_hour).zfill(2)
        mins = str(t.tm_min).zfill(2)
        sec = str(t.tm_sec).zfill(2)
        self.layout.drawText(hrs, x=2, y=2, font_scale=2)
        self.layout.drawText(mins, x=2, y=18, font_scale=2)
        self.layout.drawText(sec, x=2, y=34, font_scale=2)

        self._step += amt
        self.layout.setTexture(tex=None) 
Example 28
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: OneKClock.py    License: MIT License 5 votes vote down vote up
def step(self, amt):
        self.layout.setTexture([[self.palette(
            y * 255 / self.height + self._step * 2)] * self.width for y in range(self.height)])
        self.layout.all_off()
        t = time.localtime()
        hrs = str(t.tm_hour).zfill(2)
        mins = str(t.tm_min).zfill(2)
        secs = str(t.tm_sec).zfill(2)
        self.layout.drawText(hrs, x=0, y=0, font_scale=2)
        self.layout.drawText(mins, x=0, y=18, font_scale=2)
        self.layout.drawText(secs[0], x=24, y=8)
        self.layout.drawText(secs[1], x=24, y=17)

        self._step += amt
        self.layout.setTexture(tex=None) 
Example 29
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: arc_clock.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        self.layout.all_off()
        t = time.localtime()
        for h in self.hands:
            segs = h['segments']
            end = (360 / segs) * (getattr(t, h['key']) % segs)
            if end:
                for i in h['rings']:
                    self.layout.fillRing(
                        i, h['color'], startAngle=0, endAngle=end) 
Example 30
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: ring_clock.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        self.layout.all_off()
        t = time.localtime()
        for h in self.hands:
            segs = h['segments']
            point = (360 / segs) * (getattr(t, h['key']) % segs)
            self.layout.set(h['ring'], point, h['color'])
            if h['tail'] > 0:
                for i in range(h['tail']):
                    scaled = color_scale(h['color'], 255 - ((256 // h['tail']) * i))
                    self.layout.set(h['ring'], point + i, scaled)
                    self.layout.set(h['ring'], point - i, scaled) 
Example 31
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: circle_clock.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        self.layout.all_off()
        t = time.localtime()

        for h in self.hands:
            segs = h['segments']
            angle = (360 / segs) * (getattr(t, h['key']) % h['segments'])
            self.layout.drawRadius(angle, h['color'], endRing=h['radius']) 
Example 32
Project: face-attendance-machine   Author: matiji66   File: facerec_from_webcam_mult_thread.py    License: Apache License 2.0 5 votes vote down vote up
def process_face_records(name):
    """
    处理每一条识别的记录 ,并在一定时间之后将数据持久化到文件中
    此处会碰到全局并发,导致锁的问题
    :param name:
    :return:
    """
    return
    print('process_face_records start', time.time())

    global current_names, last_time
    # myprint("global current_names {}, last_time {}".format(current_names, last_time))

    # 判断是不是在识别的列表中,不在的话就进行问候
    if name not in current_names:
        print("ts ====", last_time, time.time())
        current_names.append(name)
        myprint("Hello {}, nice to meet you! ".format(name))
        # speaker.Speak("Hello {}, nice to meet you! ".format(name))

    # 在一定时间内,清空已经识别的人, 并进行
    if last_time < time.time() - TIME_DIFF:  # 每隔一段时间清空一下检测到的人
        last_time = time.time()
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        myprint(time_format + " update last_time and clear current_names.")
        with open(name_record, 'a') as f:
            if len(current_names) > 0:
                f.writelines("{}:{} \n".format(time_format, str(current_names)))
        print("======", current_names)
        current_names = []  # clear()
        current_names = [name]
        myprint('process_face_records end', time.time()) 
Example 33
Project: face-attendance-machine   Author: matiji66   File: facerec_from_webcam_faster.py    License: Apache License 2.0 5 votes vote down vote up
def process_face_records(name):
    """
    处理每一条识别的记录 ,并在一定时间之后将数据持久化到文件中
    :param name:
    :return:
    """
    print('process_face_records start', time.time())

    global current_names, last_time
    # myprint("global current_names {}, last_time {}".format(current_names, last_time))

    # 判断是不是在识别的列表中,不在的话就进行问候
    if name not in current_names:
        print("ts ====", last_time, time.time())
        current_names.append(name)
        myprint("Hello {}, nice to meet you! ".format(name))
        # speaker.Speak("Hello {}, nice to meet you! ".format(name))

    # 在一定时间内,清空已经识别的人, 并进行
    if last_time < time.time() - TIME_DIFF:  # 每隔一段时间清空一下检测到的人
        last_time = time.time()
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        myprint(time_format + " update last_time and clear current_names.")
        with open(name_record, 'a') as f:
            if len(current_names) > 0:
                f.writelines("{}:{} \n".format(time_format, str(current_names)))
        print("======", current_names)
        current_names = []  # clear()
        current_names = [name]
        myprint('process_face_records end', time.time()) 
Example 34
Project: zmirror   Author: aploium   File: _logtime.py    License: MIT License 5 votes vote down vote up
def logtime(is_print_date=False, timesep=':', datesep='-'):
    from time import time, localtime, strftime
    _localtime = localtime(time())
    _dateformat = '%Y' + datesep + '%m' + datesep + '%d'
    _timeformat = '%H' + timesep + '%M' + timesep + '%S'
    if is_print_date:
        return strftime(_dateformat + " " + _timeformat, _localtime)
    else:
        return strftime(_timeformat, _localtime) 
Example 35
Project: neural-fingerprinting   Author: StephanZheng   File: master.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _show_status_for_work(self, work):
    """Shows status for given work pieces.

    Args:
      work: instance of either AttackWorkPieces or DefenseWorkPieces
    """
    work_count = len(work.work)
    work_completed = {}
    work_completed_count = 0
    for v in itervalues(work.work):
      if v['is_completed']:
        work_completed_count += 1
        worker_id = v['claimed_worker_id']
        if worker_id not in work_completed:
          work_completed[worker_id] = {
              'completed_count': 0,
              'last_update': 0.0,
          }
        work_completed[worker_id]['completed_count'] += 1
        work_completed[worker_id]['last_update'] = max(
            work_completed[worker_id]['last_update'],
            v['claimed_worker_start_time'])
    print('Completed {0}/{1} work'.format(work_completed_count,
                                          work_count))
    for k in sorted(iterkeys(work_completed)):
      last_update_time = time.strftime(
          '%Y-%m-%d %H:%M:%S',
          time.localtime(work_completed[k]['last_update']))
      print('Worker {0}: completed {1}   last claimed work at {2}'.format(
          k, work_completed[k]['completed_count'], last_update_time)) 
Example 36
Project: Starx_Pixiv_Collector   Author: SuzukiHonoka   File: start.py    License: MIT License 5 votes vote down vote up
def print_with_tag(tag, data ,debug=0):
    data_print = data
    if type(data) == list:
        data_print = ''
        for per_data in data:
            if len(data_print) == 0:
                data_print += str(per_data)
            else:
                data_print += ' ' + str(per_data)
    if debug == 1:
        print('[' + time.asctime(time.localtime(time.time())) + '] ' + tag + ' =>', data_print)
    else:
        print(data_print) 
Example 37
Project: DOTA_models   Author: ringringyi   File: evaluate.py    License: Apache License 2.0 5 votes vote down vote up
def run():
  """Runs evaluation in a loop, and logs summaries to TensorBoard."""
  # Create the evaluation directory if it doesn't exist.
  eval_dir = FLAGS.eval_dir
  if not tf.gfile.IsDirectory(eval_dir):
    tf.logging.info("Creating eval directory: %s", eval_dir)
    tf.gfile.MakeDirs(eval_dir)

  g = tf.Graph()
  with g.as_default():
    # Build the model for evaluation.
    model_config = configuration.ModelConfig()
    model_config.input_file_pattern = FLAGS.input_file_pattern
    model = show_and_tell_model.ShowAndTellModel(model_config, mode="eval")
    model.build()

    # Create the Saver to restore model Variables.
    saver = tf.train.Saver()

    # Create the summary operation and the summary writer.
    summary_op = tf.summary.merge_all()
    summary_writer = tf.summary.FileWriter(eval_dir)

    g.finalize()

    # Run a new evaluation run every eval_interval_secs.
    while True:
      start = time.time()
      tf.logging.info("Starting evaluation at " + time.strftime(
          "%Y-%m-%d-%H:%M:%S", time.localtime()))
      run_once(model, saver, summary_writer, summary_op)
      time_to_next_eval = start + FLAGS.eval_interval_secs - time.time()
      if time_to_next_eval > 0:
        time.sleep(time_to_next_eval) 
Example 38
Project: lyrebird-api-coverage   Author: Meituan-Dianping   File: result_handler.py    License: MIT License 5 votes vote down vote up
def make_result_dir(self):
        save_time = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
        test_data_dir = os.path.join(PLUGINS_DATA_DIR, str(save_time))
        if not os.path.exists(test_data_dir):
            os.makedirs(test_data_dir)
        return test_data_dir 
Example 39
Project: delocate   Author: matthew-brett   File: tools.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def dir2zip(in_dir, zip_fname):
    """ Make a zip file `zip_fname` with contents of directory `in_dir`

    The recorded filenames are relative to `in_dir`, so doing a standard zip
    unpack of the resulting `zip_fname` in an empty directory will result in
    the original directory contents.

    Parameters
    ----------
    in_dir : str
        Directory path containing files to go in the zip archive
    zip_fname : str
        Filename of zip archive to write
    """
    z = zipfile.ZipFile(zip_fname, 'w',
                        compression=zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(in_dir):
        for file in files:
            in_fname = pjoin(root, file)
            in_stat = os.stat(in_fname)
            # Preserve file permissions, but allow copy
            info = zipfile.ZipInfo(in_fname)
            info.filename = relpath(in_fname, in_dir)
            if os.path.sep == '\\':
                # Make the path unix friendly on windows.
                # PyPI won't accept wheels with windows path separators
                info.filename = relpath(in_fname, in_dir).replace('\\', '/')
            # Set time from modification time
            info.date_time = time.localtime(in_stat.st_mtime)
            # See https://stackoverflow.com/questions/434641/how-do-i-set-permissions-attributes-on-a-file-in-a-zip-file-using-pythons-zip/48435482#48435482 # noqa: E501
            # Also set regular file permissions
            perms = stat.S_IMODE(in_stat.st_mode) | stat.S_IFREG
            info.external_attr = perms << 16
            with open_readable(in_fname, 'rb') as fobj:
                contents = fobj.read()
            z.writestr(info, contents, zipfile.ZIP_DEFLATED)
    z.close() 
Example 40
Project: InsightAgent   Author: insightfinder   File: collectdReportMetrics.py    License: Apache License 2.0 5 votes vote down vote up
def update_endtime_in_config(metric_data_l, reporting_interval_l, new_prev_endtime_epoch_l, hostname_l):
    if new_prev_endtime_epoch_l == 0:
        print "No data is reported"
    else:
        new_prev_endtimeinsec = math.ceil(long(new_prev_endtime_epoch_l) / 1000.0)
        new_prev_endtime = time.strftime(
            "%Y%m%d%H%M%S", time.localtime(long(new_prev_endtimeinsec)))
        update_timestamp(new_prev_endtime)
        send_data(metric_data_l, reporting_interval_l, hostname_l)
    return 
Example 41
Project: Paradrop   Author: ParadropLabs   File: test_output.py    License: Apache License 2.0 5 votes vote down vote up
def setup():
    '''
    Make three log files, the current one and two old ones. Each file is three days apart.
    Each log entry is one hour apart. The logs are ordered ascending in time as written.
    '''
    os.makedirs(PATH)

    mockOut = {'extra': {}, 'owner': 'UNSET', 'message': 'Establishing API server, port: 14321', 'package': 'pdfcd', 'type': 'INFO', 'line': 272, 'module': 'server', 'pdid': 'pd.damouse.example'}

    days = [[mockOut] * 3 for x in range(3)]
    hour, day = 60 * 60, 24 * 60 * 60

    for i in range(0, len(days)):
        name = output.LOG_NAME

        if i != 0:
            name += '.' + time.strftime('%Y_%m_%d', time.localtime(time.time() - i * day))

        with open(PATH + name, 'w') as f:
            for k in range(0, len(days[i])):
                days[i][k]['timestamp'] = time.time() - i * day + k * hour

                d = json.dumps(days[i][k])
                f.write(d + '\n')

    global sourceLogs
    sourceLogs = days

    output.out.startLogging(filePath=PATH, stealStdio=False, printToConsole=False) 
Example 42
Project: SublimeKSP   Author: nojanath   File: ksp_compiler.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_compiled_code(self):
        buffer = StringIO()
        emitter = ksp_ast.Emitter(buffer, compact=self.compact)
        self.module.emit(emitter)
        self.compiled_code = buffer.getvalue()

        # NOTE(Sam): Add a ksp comment at the beginning of the compiled script to display the time and date it was compiled on
        if self.add_compiled_date_comment:
            localtime = time.asctime( time.localtime(time.time()) )
            self.compiled_code = "{ Compiled on " + localtime + " }\n" + self.compiled_code 
Example 43
Project: redditswapbot   Author: thelectronicnub   File: mySQLHandler.py    License: GNU General Public License v3.0 5 votes vote down vote up
def formatDBTime(self, record):
        """
        Time formatter
        @param record:
        @return: nothing
        """ 
        record.dbtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(record.created)) 
Example 44
Project: glazier   Author: google   File: ntp.py    License: Apache License 2.0 5 votes vote down vote up
def SyncClockToNtp(retries: int = 2, server: Text = 'time.google.com'):
  """Syncs the hardware clock to an NTP server."""
  logging.info('Reading time from NTP server %s.', server)

  attempts = 0
  client = ntplib.NTPClient()
  response = None

  while True:
    try:
      response = client.request(server, version=3)
    except (ntplib.NTPException, socket.gaierror) as e:
      logging.error('NTP client request error: %s', str(e))
    if response or attempts >= retries:
      break
    logging.info(
        'Unable to contact NTP server %s to sync machine clock.  This '
        'machine may not have an IP address yet; waiting %d seconds and '
        'trying again. Repeated failure may indicate network or driver '
        'problems.', server, RETRY_DELAY)
    time.sleep(RETRY_DELAY)
    attempts += 1

  if not response:
    raise NtpException('No response from NTP server.')

  local_time = time.localtime(response.ref_time)
  current_date = time.strftime('%m-%d-%Y', local_time)
  current_time = time.strftime('%H:%M:%S', local_time)
  logging.info('Current date/time is %s %s', current_date, current_time)

  date_set = r'%s\cmd.exe /c date %s' % (WINPE_SYSTEM32, current_date)
  result = subprocess.call(date_set, shell=True)
  logging.info('Setting date returned result %s', result)
  time_set = r'%s\cmd.exe /c time %s' % (WINPE_SYSTEM32, current_time)
  result = subprocess.call(time_set, shell=True)
  logging.info('Setting time returned result %s', result) 
Example 45
Project: script.module.inputstreamhelper   Author: emilsvennesson   File: __init__.py    License: MIT License 5 votes vote down vote up
def _update_widevine(self):
        """Prompts user to upgrade Widevine CDM when a newer version is available."""
        from time import localtime, strftime, time

        last_check = get_setting_float('last_check', 0.0)
        if last_check and not self._first_run():
            if last_check + 3600 * 24 * get_setting_int('update_frequency', 14) >= time():
                log(2, 'Widevine update check was made on {date}', date=strftime('%Y-%m-%d %H:%M', localtime(last_check)))
                return

        wv_config = load_widevine_config()
        if not wv_config:
            log(3, 'Widevine config missing. Could not determine current version, forcing update.')
            current_version = '0'
        elif 'x86' in arch():
            component = 'Widevine CDM'
            current_version = wv_config['version']
        else:
            component = 'Chrome OS'
            current_version = wv_config['version']

        latest_version = latest_widevine_version()
        if not latest_version:
            log(3, 'Updating widevine failed. Could not determine latest version.')
            return

        log(0, 'Latest {component} version is {version}', component=component, version=latest_version)
        log(0, 'Current {component} version installed is {version}', component=component, version=current_version)

        from distutils.version import LooseVersion  # pylint: disable=import-error,no-name-in-module,useless-suppression
        if LooseVersion(latest_version) > LooseVersion(current_version):
            log(2, 'There is an update available for {component}', component=component)
            if yesno_dialog(localize(30040), localize(30033), nolabel=localize(30028), yeslabel=localize(30034)):
                self.install_widevine()
            else:
                log(3, 'User declined to update {component}.', component=component)
        else:
            set_setting('last_check', time())
            log(0, 'User is on the latest available {component} version.', component=component) 
Example 46
Project: script.module.inputstreamhelper   Author: emilsvennesson   File: __init__.py    License: MIT License 5 votes vote down vote up
def info_dialog(self):
        """ Show an Info box with useful info e.g. for bug reports"""
        text = localize(30800, version=kodi_version(), system=system_os(), arch=arch()) + '\n'  # Kodi information
        text += '\n'

        disabled_str = ' ({disabled})'.format(disabled=localize(30054))
        ishelper_state = disabled_str if get_setting_bool('disabled', False) else ''
        istream_state = disabled_str if not self._inputstream_enabled() else ''
        text += localize(30810, version=addon_version(), state=ishelper_state) + '\n'
        text += localize(30811, version=self._inputstream_version(), state=istream_state) + '\n'
        text += '\n'

        if system_os() == 'Android':
            text += localize(30820) + '\n'
        else:
            from time import localtime, strftime
            if get_setting_float('last_modified', 0.0):
                wv_updated = strftime('%Y-%m-%d %H:%M', localtime(get_setting_float('last_modified', 0.0)))
            else:
                wv_updated = 'Never'
            text += localize(30821, version=self._get_lib_version(widevinecdm_path()), date=wv_updated) + '\n'
            if arch() in ('arm', 'arm64'):  # Chrome OS version
                wv_cfg = load_widevine_config()
                if wv_cfg:
                    text += localize(30822, name=wv_cfg['hwidmatch'].split()[0].lstrip('^'), version=wv_cfg['version']) + '\n'
            if get_setting_float('last_check', 0.0):
                wv_check = strftime('%Y-%m-%d %H:%M', localtime(get_setting_float('last_check', 0.0)))
            else:
                wv_check = 'Never'
            text += localize(30823, date=wv_check) + '\n'
            text += localize(30824, path=ia_cdm_path()) + '\n'

        text += '\n'

        text += localize(30830, url=config.SHORT_ISSUE_URL)  # Report issues

        log(2, '\n{info}'.format(info=kodi_to_ascii(text)))
        textviewer(localize(30901), text) 
Example 47
Project: rtp_cluster   Author: sippy   File: MonoTime.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def fptime(self, base = None):
        if base != None:
            realt = base.realt - (base.monot - self.monot)
        else:
            realt = self.realt
        return '%s.%.3d' % (strftime('%d %b %H:%M:%S', localtime(realt)), \
          (realt % 1) * 1000) 
Example 48
Project: rtp_cluster   Author: sippy   File: SipLogger.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def ftime(self, ltime):
        if self.offstime:
            ltime -= self.itime
        msec = (ltime % 1) * 1000
        if not self.offstime:
            return '%s.%.3d' % (strftime('%d %b %H:%M:%S', localtime(ltime)), msec)
        hrs = int(ltime / (60 * 60))
        ltime -= (hrs * 60 * 60)
        mins = int(ltime / 60)
        ltime -= (mins * 60)
        secs = int(ltime)
        return '%.2d:%.2d:%.2d.%.3d' % (hrs, mins, secs, msec) 
Example 49
Project: Andromeda   Author: liucaide   File: cd_tools.py    License: MIT License 5 votes vote down vote up
def cd_time_now(strftime="%Y-%m-%d %H:%M:%S"):
    """
    :param strftime: 时间格式 默认:%Y-%m-%d %H:%M:%S
    :return: 根据时间格式返回格式化当前时间
    """
    return time.strftime(strftime, time.localtime()) 
Example 50
Project: Andromeda   Author: liucaide   File: cd_tools.py    License: MIT License 5 votes vote down vote up
def cd_timestamp_to_time(timestamp, strftime="%Y-%m-%d %H:%M:%S"):
    """
    :param timestamp: 时间戳
    :param strftime: 时间格式
    :return: 根据时间戳返回格式化时间
    """
    return time.strftime(strftime, time.localtime(timestamp)) 
Example 51
Project: jawfish   Author: war-and-code   File: tarfile.py    License: MIT License 5 votes vote down vote up
def list(self, verbose=True):
        """Print a table of contents to sys.stdout. If `verbose' is False, only
           the names of the members are printed. If it is True, an `ls -l'-like
           output is produced.
        """
        self._check()

        for tarinfo in self:
            if verbose:
                print(stat.filemode(tarinfo.mode), end=' ')
                print("%s/%s" % (tarinfo.uname or tarinfo.uid,
                                 tarinfo.gname or tarinfo.gid), end=' ')
                if tarinfo.ischr() or tarinfo.isblk():
                    print("%10s" % ("%d,%d" \
                                    % (tarinfo.devmajor, tarinfo.devminor)), end=' ')
                else:
                    print("%10d" % tarinfo.size, end=' ')
                print("%d-%02d-%02d %02d:%02d:%02d" \
                      % time.localtime(tarinfo.mtime)[:6], end=' ')

            print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ')

            if verbose:
                if tarinfo.issym():
                    print("->", tarinfo.linkname, end=' ')
                if tarinfo.islnk():
                    print("link to", tarinfo.linkname, end=' ')
            print() 
Example 52
Project: jawfish   Author: war-and-code   File: datetime.py    License: MIT License 5 votes vote down vote up
def fromtimestamp(cls, t):
        "Construct a date from a POSIX timestamp (like time.time())."
        y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
        return cls(y, m, d) 
Example 53
Project: jawfish   Author: war-and-code   File: datetime.py    License: MIT License 5 votes vote down vote up
def timetuple(self):
        "Return local time tuple compatible with time.localtime()."
        return _build_struct_time(self._year, self._month, self._day,
                                  0, 0, 0, -1) 
Example 54
Project: jawfish   Author: war-and-code   File: datetime.py    License: MIT License 5 votes vote down vote up
def fromtimestamp(cls, t, tz=None):
        """Construct a datetime from a POSIX timestamp (like time.time()).

        A timezone info object may be passed in as well.
        """

        _check_tzinfo_arg(tz)

        converter = _time.localtime if tz is None else _time.gmtime

        t, frac = divmod(t, 1.0)
        us = int(frac * 1e6)

        # If timestamp is less than one microsecond smaller than a
        # full second, us can be rounded up to 1000000.  In this case,
        # roll over to seconds, otherwise, ValueError is raised
        # by the constructor.
        if us == 1000000:
            t += 1
            us = 0
        y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
        ss = min(ss, 59)    # clamp out leap seconds if the platform has them
        result = cls(y, m, d, hh, mm, ss, us, tz)
        if tz is not None:
            result = tz.fromutc(result)
        return result 
Example 55
Project: jawfish   Author: war-and-code   File: datetime.py    License: MIT License 5 votes vote down vote up
def timetuple(self):
        "Return local time tuple compatible with time.localtime()."
        dst = self.dst()
        if dst is None:
            dst = -1
        elif dst:
            dst = 1
        else:
            dst = 0
        return _build_struct_time(self.year, self.month, self.day,
                                  self.hour, self.minute, self.second,
                                  dst) 
Example 56
Project: Vxscan   Author: al0ne   File: report.py    License: Apache License 2.0 5 votes vote down vote up
def gener():
    out = []
    for i in [gen_webinfo(), gen_urls(), gen_ports(), gen_vuln(), gen_crawl()]:
        if i:
            out.append(i)
    result = {"table": out}
    result = json.dumps(result)
    result = re.sub(r'^{|}$', '', result)
    times = time.strftime("%Y%m%d%H%M%S", time.localtime())
    name = 'Vxscan_' + times + '.html'
    with open('report/report.htm', 'r', encoding='utf-8') as f, open(name, 'w') as f1:
        text = f.read()
        f1.write(text.replace("'summary': {}", result)) 
Example 57
Project: Vxscan   Author: al0ne   File: sqldb.py    License: Apache License 2.0 5 votes vote down vote up
def get_urls(self, urls):
        self.create_urls()
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        for url in urls:
            for k, v in url.items():
                md5sum = hashlib.md5()
                strings = str(k) + str(v.get('title')) + str(v.get('url'))
                md5sum.update(strings.encode('utf-8'))
                md5 = md5sum.hexdigest()
                values = (timestamp, k, v.get('title'), v.get('url'), v.get('contype'), v.get('rsp_len'),
                          v.get('rsp_code'), md5)
                query = "INSERT OR IGNORE INTO urls (time, domain, title, url, contype, rsp_len,rsp_code,md5) VALUES (?,?,?,?,?,?,?,?)"
                self.insert_urls(query, values)
        self.commit()
        self.close() 
Example 58
Project: Vxscan   Author: al0ne   File: sqldb.py    License: Apache License 2.0 5 votes vote down vote up
def get_vuln(self, domain, vuln):
        self.create_vuln()
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        for i in vuln:
            md5sum = hashlib.md5()
            strings = str(domain) + str(i)
            md5sum.update(strings.encode('utf-8'))
            md5 = md5sum.hexdigest()
            values = (timestamp, domain, i, md5)
            query = "INSERT OR IGNORE INTO vuln (time, domain, vuln, md5) VALUES (?,?,?,?)"
            self.insert_vuln(query, values)
        self.commit()
        self.close() 
Example 59
Project: Vxscan   Author: al0ne   File: cli_output.py    License: Apache License 2.0 5 votes vote down vote up
def console(plugins, domain, text):
    timestamp = time.strftime("%H:%M:%S", time.localtime())
    timestamp = Bcolors.OKBLUE + '[' + timestamp + ']' + Bcolors.ENDC
    plugins = Bcolors.RED + plugins + Bcolors.ENDC
    text = Bcolors.OKGREEN + text + Bcolors.ENDC
    sys.stdout.write(timestamp + ' - ' + plugins + ' - ' + domain + '    ' + text) 
Example 60
Project: MarkdownPicPicker   Author: kingname   File: OSXGrab.py    License: GNU General Public License v3.0 5 votes vote down vote up
def read_from_pastepoard(self):
        date_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
        picture_name = date_time + '.' + self.picture_suffix
        picture_path = os.path.join(self.picture_folder, picture_name)
        try:
            os.system('/usr/local/bin/pngpaste {}'.format(picture_path))
            if os.path.exists(picture_path):
                print('get image from pasteboard success.')
                return [picture_path]
            else:
                print('there is no picture in clipboard!')
        except Exception as e:
            print('get picture from clipboard error because: {}'.format(e))
        return []