Example #1
0
def schedule_lectures(ics_path, func):
    '''read ICS from @ics_path and schedule @func at given time'''
    utils.log('INFO', 'Starting scheduling capturing...')
    gcal = utils.get_cal(ics_path)
    utils.print_cal_events(gcal)
    Monitor.FUNC = func

    # initialize scheduler for events
    Monitor.SCHED = sched.scheduler(time.time, time.sleep)

    for component in gcal.walk():
        if component.name == "VEVENT":
            summary = component.get('summary')
            start_time = component.get('dtstart').dt
            end_time = component.get('dtend').dt
            time_delta = end_time - start_time
            seconds = time_delta.total_seconds()
            args = summary.split(' ')
            args.append(seconds)

            # create new Monitor
            if start_time < utils.utc_now():
                continue
            job = Monitor.Monitor(Monitor.SCHED, func, args, start_time)
            Monitor.MONITORS.append(job)

    # Schedule all events
    for mo in Monitor.MONITORS:
        mo.schedule_task()
    utils.log('INFO', 'Finished scheduling capturing...')

    cal_receiver.start_server()

    while 1:
        pass
def add_eve2cal(gcal, summary, delay, duration):
    '''Add event to gcal with delay and duration'''
    if not gcal:
        return None
    event = icalendar.Event()
    event.add('summary', summary)
    b = utils.utc_now() + timedelta(0, delay)
    event.add('dtstart', b)
    event.add('dtend', b + timedelta(0, duration))
    event.add('dtstamp', utils.utc_now())

    event['uid'] = str(datetime.strftime(utils.utc_now(), '%c').strip())
    event.add('priority', 5)

    gcal.add_component(event)
    return gcal
Example #3
0
def capture(*args):
    device = args[0]
    argv = args[1]
    path = args[2]

    cap = cv2.VideoCapture(int(device[-1]))

    then = utils.utc_now()

    last_update = None
    last_img = None

    while ((utils.utc_now() - then).total_seconds() < argv[2]):
        if (last_update is not None and
            (utils.utc_now() - last_update).total_seconds() < INTERVAL):
            continue
        # Capture frame-by-frame
        ret, frame = cap.read()
        # cv2.imshow('WHITEBOARD',frame)
        # if cv2.waitKey(1) & 0xFF == ord('q'):
        #     break

        # Our operations on the frame come here
        if last_img is not None and imgutils.im_diff(frame,
                                                     last_img) > THRESHHOLD:
            continue

        cv2.imwrite(
            path + 'whiteboard/' + str(int(utils.utc_now().timestamp())) +
            '.png', frame)

        # Display the resulting frame
        last_update = utils.utc_now()
        last_img = frame

    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()

    return
Example #4
0
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, autoincrement=True, primary_key=True)
    instagram_pk = Column(Integer, unique=True, nullable=False)
    username = Column(String(255))
    full_name = Column(String(255))
    followers = Column(Integer)
    publications = relationship("Publication", back_populates="user")
    last_modified = Column(DateTime, onupdate=utc_now())

    def __repr__(self):
        return '%s: %s' % (self.username, self.followers)
Example #5
0
def on_cal_changed(gcal):
    '''update scheduled lectures when calendar is changed'''
    utils.log('INFO', 'On Calendar Changed Callback...')
    m_temp = []
    utils.log('INFO', 'Printing New Calendar Info...')
    utils.print_cal_events(gcal)
    for component in gcal.walk():
        if component.name == "VEVENT":
            summary = component.get('summary')
            start_time = component.get('dtstart').dt
            end_time = component.get('dtend').dt
            time_delta = end_time - start_time
            seconds = time_delta.total_seconds()
            args = summary.split(' ')
            args.append(seconds)

            # create new Monitor
            if start_time < utils.utc_now():
                continue
            job = Monitor.Monitor(Monitor.SCHED, Monitor.FUNC, args,
                                  start_time)
            m_temp.append(job)

    # Cancel scheduled Tasks
    for mo in Monitor.MONITORS:
        status = mo.cancel_task()
        # remove task if cancelled
        if status == 0:
            Monitor.MONITORS.pop(mo)

    for mo in m_temp:
        if mo.dt < utils.utc_now():
            continue
        Monitor.MONITORS.append(mo)

    for mo in Monitor.MONITORS:
        mo.schedule_task()
Example #6
0
    def schedule_task(self):
        func = self.func
        args = self.args
        dt = self.dt
        utils.log('INFO',
                  'Scheduling task: ' + func.__name__ + ' at ' + str(dt))
        timezone = pytz.timezone("US/Eastern")
        self.t = Timer((dt - utils.utc_now()).total_seconds(),
                       self.start_task,
                       args=(func, args))
        self.t.start()

        self._scheduled = True
        utils.log('INFO',
                  'Scheduled task: ' + func.__name__ + ' at ' + str(dt))
Example #7
0
class Publication(Base):
    __tablename__ = 'publications'

    id = Column(Integer, autoincrement=True, primary_key=True)
    instagram_pk = Column(Integer, unique=True, nullable=False)
    link_code = Column(String(255), unique=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    user = relationship("User", back_populates="publications")
    tags = relationship('Tag', secondary=association_tags_publications,
                        back_populates='publications', lazy="dynamic")
    like_count = Column(Integer)
    device_timestamp = Column(DateTime)
    last_modified = Column(DateTime, onupdate=utc_now())

    def __repr__(self):
        return '%s: %s user, %s likes at %s' % (self.instagram_pk, self.user,
                                                self.like_count, self.device_timestamp)
Example #8
0
def create_proposal(case_dict, imp, logger=task_logger):
    """Helper function to create new Proposal objects.
    """
    try:
        (_, p) = Proposal.create_or_update_from_dict(case_dict, importer=imp)
        return p
    except Exception as exc:
        buff = StringIO()
        pprint.pprint(case_dict, buff)
        buff.seek(0)
        logger.exception("Could not create proposal from dictionary: %s",
                         buff.read())
        append_to_key(
            f"cornerwise:importer:{imp.pk}:import_errors",
            {"when": utc_now(), "dict": case_dict, "message": str(exc)},
            limit=100)
        return None
 def apparent(self, observer=None, latitude=None, longitude=None, timestamp=None, temperature=settings.DEFAULT_TEMPERATURE, pressure=settings.DEFAULT_PRESSURE, elevation=settings.DEFAULT_ELEVATION):
     """
     Takes this RADec co-ordinate and maps it to the apparent position on the sky given local atmospheric refraction
     
         Uses functions from PyEphem [http://rhodesmill.org/pyephem/index.html]
     """
     if timestamp is None:
         timestamp = utc_now()
     if not observer:
         #First set up an observer
         observer = ephem.Observer()
         observer.lat = unicode(latitude.dd) #Accepts as a string only
         observer.lon = unicode(longitude.dd)#Accepts as a string only
         observer.temp = temperature
         observer.pressure = pressure
     else:
         original_observer_date = observer.date
         
     #Now update the observer to the specified time:
     observer.date = timestamp.strftime("%Y/%m/%d %H:%i:%s")
     
     if self.apparent_position: #This has already been corrected, so we need to work it all backwards to adjust for the new time / observer:
         ra_hr, ra_min, ra_sec = self.uncorrected_position.X.hms
         dec_deg, dec_min, dec_sec = self.uncorrected_position.Y.hms
     else: #Not already corrected, so use raw ra dec from self
         ra_hr, ra_min, ra_sec = self.X.hms
         dec_deg, dec_min, dec_sec = self.Y.dms
     target = ephem.readdb("Target,f|S|??,{ra_hr}:{ra_min}:{ra_sec},{dec_deg}:{dec_min}:{dec_sec},0.0,{epoch}".format(
                             ra_hr = ra_hr,
                             ra_min = ra_min,
                             ra_sec = ra_sec,
                             dec_deg = dec_deg,
                             dec_min = dec_min,
                             dec_sec = dec_sec,
                             epoch = timestamp.strftime(settings.EPHEM_DB_DATE_FORMAT)
                         ))
     target.compute(observer, epoch=observer.date) #Works out its Celestial position taking into account precession and refraction etc
     #Now generate a new object
     corrected_ra_dec = ApparentRADec(target.ra.split(":"), target.dec.split(":"))
     corrected_ra_dec.uncorrected_position = RADec(target.a_ra.split(":"), target.a_dec.split(":")) #Store the original position so we can work it back later
     #Mark it as an apparent position:
     corrected_ra_dec.apparent_position=True #Simple flag to allow us to track which positions are apparent vs real
     return corrected_ra_dec
Example #10
0
 def right_ascension(self, longitude, timestamp=None):
     """
     Gives the Right Ascension of this hour_angle coordinate if time and longitude of observer supplied!
     
     @param longitude: The longitude of the observer (as a true SmartLon object, or a string)
     @keyword timestamp:    The UTC time of the observer (will assume now if none supplied)
     
     @returns an RightAscension object with the RA in it!
     """
     if timestamp is None: #Default to real now
         timestamp = utc_now()
     if not isinstance(longitude, SmartLon): #Cast strings / decimals for longitude into a SmartLon Longitude object
         longitude = SmartLon(Decimal(longitude))
     #Convert all our values into radian floats which sidereal loves:
     long_rad = float(longitude.radians) 
     hr_rad = float(self.radians)
     #Now call upon Sidereal's function
     ra_rad =  sidereal.hourAngleToRA(hr_rad, timestamp, long_rad) #Outputs hour angle in radians
     #Now inflate the output hour angle into a proper object
     return ApparentRightAscension(ra_rad, mode="rad") #Will accept a rad, and return a properly filled HourAngle
Example #11
0
 def apply(self, updates: Dict[str, Any]):
     for key, value in updates.items():
         if isinstance(value, str):
             offset = parse_offset(value)
             if offset:
                 value = dump_datetime(utc_now() + offset)
         if key.startswith("+"):
             append = True
             key = key[1:]
         else:
             append = False
         ismeta = (key in ('meta', 'id')) or (key not in get_factory(type(self)).__self__.get_props())
         data = self.meta if ismeta else self.__dict__
         if append:
             data[key] += value
         elif value is None and ismeta:
             del data[key]
         else:
             data[key] = value
     device.log(f"Applied data update to point: {json.dumps(self)}", "debug")
Example #12
0
 def hour_angle(self, longitude, timestamp=None):
     """
     Gives the hour_angle of this RA coordinate if time and longitude of observer supplied!
     
     @param longitude: The longitude of the observer (as a true SmartLon object, or a string)
     @keyword timestamp:    The UTC time of the observer (will assume now if none supplied)
     
     @returns an HourAngle object with the HourAngle in it!
     """
     if timestamp is None: #Default to real now
         timestamp = utc_now()
     if not isinstance(longitude, SmartLon): #Cast strings / decimals for longitude into a SmartLon Longitude object
         longitude = SmartLon(Decimal(longitude))
     #Convert all our values into radian floats which sidereal loves:
     long_rad = float(longitude.radians) 
     ra_rad = float(self.radians)
     #Now call upon Sidereal's function
     hour_angle_rad =  sidereal.raToHourAngle(ra_rad, timestamp, long_rad) #Outputs hour angle in radians
     #Now inflate the output hour angle into a proper object
     ha = HourAngle(hour_angle_rad, mode="rad") #Will accept a rad, and return a properly filled HourAngle
     ha.apparent_position = self.apparent_position #Make sure it knows if this is apparent or not!
     return ha
Example #13
0
def add_admin():
    """
        Create admin user for the web interface if it does not exists already
    :param _mongo:
    :param _secrets:
    :return:
    """
    ex_admin = mongo.db.users.find_one(
        {'_id': secrets['database']['admin_username']})
    if ex_admin is None or len(ex_admin) == 0:
        try:
            mongo.db.users.insert_one({
                '_id':
                secrets['database']['admin_username'],
                'password':
                generate_password_hash(secrets['database']['admin_password']),
                'permissions': {},
                'last_modified':
                utc_now()
            })
        except Exception as e:
            print(e)
Example #14
0
 def plant_age(self) -> int:
     if self.plant_stage in ('planned', 'harvested'):
         return 0
     if self.planted_at is None:
         return 0
     return (utc_now() - self.planted_at).days + 1
Example #15
0
from ticket import TicketTools
from utils import log, utc_now

# args
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--username', type=str)
parser.add_argument('-p', '--password', type=str)
parser.add_argument('-m', '--max-run-time', type=int, default=60)
args = parser.parse_args()

username = args.username
password = args.password
max_run_time = args.max_run_time

# start time
start_time = utc_now()

# ticket tools
tools = TicketTools(username, password)

# login
do = tools.login()
log('登录', '成功' if do else '失败')

while do and utc_now() - start_time < timedelta(minutes=max_run_time):
    # get UTC+8 time
    now = utc_now()
    log('当前时间', now.date())

    act_date = tools.update_links()
    log('最新活动', act_date)
Example #16
0
 def create(self, content, author):
     self['content'] = content
     self['author_id'] = author['id']
     self['created_time'] = utc_now()
     self['refer_id'] = None
     return self
Example #17
0
 def generate_token(self):
     self['token'] = encrypt('%s%s%s' % (
                             self['name'], self['password'], utc_now()))
     self.save()
     return self['token']