class CalendarTestNavigateEvents(unittest.TestCase):
    def setUp(self) -> None:
        self.mock_api = MagicMock()
        self.Calendar = Calendar(self.mock_api)

    def test_navigate_events_with_reminders(self):
        self.Calendar.get_past_events = MagicMock(return_value=[{'id': '1olba0rgbijmfv72m1126kpftf',
                                                                 'summary': 'Past Event Summary',
                                                                 'start': {'date': '2020-10-13'},
                                                                 'reminders': {'useDefault': True}},
                                                                {'id': '2insr0pnrijmfv72m1126kpftf',
                                                                 'summary': 'Past Event 2 Summary',
                                                                 'start': {'date': '2020-11-13'},
                                                                 'reminders': {'useDefault': True}}])
        self.Calendar.get_future_events = MagicMock(return_value=[{'id': '4odta0egtjvboj82p4326esnvw',
                                                                   'summary': 'Future Event Summary',
                                                                   'start': {'dateTime': '2020-10-22T18:30:00+05:30'},
                                                                   'reminders': {'useDefault': False, 'overrides': [
                                                                       {'method': 'email', 'minutes': 20},
                                                                       {'method': 'popup', 'minutes': 10}]}}])

        searchResult = self.Calendar.navigate_to_events('2020-10')
        self.assertEqual(
            ['Event:Past Event Summary at 2020-10-13\nReminder in 10 minutes before event',
             'Event:Future Event Summary at 2020-10-22T18:30:00+05:30\nReminder in 20 minutes before event as email\nReminder in 10 minutes before event as popup'],
            searchResult)

    def test_navigate_to_non_existent_events_(self):
        searchResult = self.Calendar.navigate_to_events('2020-10')
        self.assertEqual("Nothing showed up at this time: 2020-10", searchResult)
Example #2
0
class Agent:

    HOST = '127.0.0.1'  # The server's hostname or IP address
    PORT = 65430  # The port used by the server
    calendar = Calendar()
    s = None

    def listen(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((self.HOST, self.PORT))

        while True:
            data = self.s.recv(1024).decode()
            if data.startswith('BOOKING:'):
                newTimeData = json.loads(data.replace('BOOKING:', ''))
                print(
                    'Reveived calendar update:\n\n{}\n\n'.format(newTimeData))
                self.calendar = Calendar(newTimeData)
            elif data.startswith('CHECK:'):
                print('Received check request, reponding with calendar')
                self.s.sendall(
                    str.encode('RESPONSE:{}'.format(
                        json.dumps(self.calendar.timeData))))

    def issueBooking(self, hours):
        if self.calendar.canBookAppointment(hours):
            self.s.sendall(str.encode('BOOKING:{}'.format(hours)))
        else:
            print(
                'Booking not possible for timeslot of {} hours'.format(hours))
Example #3
0
def calendar():
    from hashlib import md5
    #  Calendar
    cal = Calendar()
    with open('calendars.cfg') as f:
        c = f.readline()
        events = []
        while c:
            cid, cname = c.split(',')
            events += cal.get_events(cid.strip(), cname.strip())
            c = f.readline()
    # Remove duplicates, only for 2 cals
    single_events = {}
    for e in events:
        key = ''
        if e['name']:
            key += e['name'].encode('ascii', 'ignore')
        if e['start']:
            key += e['start'].encode('ascii', 'ignore')
        key = md5(key).hexdigest()
        if key not in single_events:
            single_events[key] = e
        else:
            single_events[key]['calendar'] = 'all'
    
    events = sorted(single_events.values(), key=lambda event: event['start'])
    data = { 'events': events }

    res = make_response(json.dumps(data))
    res.mimetype = 'application/json'
    res.headers['Access-Control-Allow-Origin'] = '*'
    return res
Example #4
0
class FullscreenWindow:
    def __init__(self):
        self.tk = Tk()
        self.tk.configure(background='black')
        self.topFrame = Frame(self.tk, background='black')
        self.bottomFrame = Frame(self.tk, background='black')
        self.topFrame.pack(side=TOP, fill=BOTH, expand=YES)
        self.bottomFrame.pack(side=BOTTOM, fill=BOTH, expand=YES)
        self.state = False
        self.tk.bind("<Return>", self.toggle_fullscreen)
        self.tk.bind("<Escape>", self.end_fullscreen)
        # weather
        self.weather = Weather(self.topFrame)
        self.weather.place(x=0, y=5, anchor=NW, width=700, height=400)
        # Date
        self.date = Date(self.topFrame)
        self.date.place(x=1015, y=10, anchor=NE, width=350, height=90)
        # Day
        self.day = Day(self.topFrame)
        self.day.place(x=860, y=10, anchor=NE, width=300, height=90)
        # clock
        self.clock = Clock(self.topFrame)
        self.clock.place(x=940, y=60, anchor=NE, width=250, height=90)
        #Seconds
        self.sec = Sec(self.topFrame)
        self.sec.place(x=1015, y=60, anchor=NE, width=80, height=85)
        # news
        self.news = News(self.bottomFrame)
        self.news.pack(side=LEFT, anchor=S, padx=0, pady=10)
        # Facial rec
        #self.FacialRecognition = News(self.bottomFrame)
        #self.FacialRecognition.pack(side=LEFT, anchor=N, padx=100, pady=60)
        # calender
        self.calender = Calendar(self.topFrame)
        self.calender.place(x=1015, y=150, width=250, anchor=NE)
        # calender Time
        self.calenderTime = CalendarTime(self.topFrame)
        self.calenderTime.place(x=850, y=172, width=250, anchor=NE)
        #Traffic
        self.traffic = Traffic(self.topFrame)
        #Launch
        self.launch = Launch(self.topFrame)
        #crypto name
        self.crypto = Crypto(self.topFrame)
        self.crypto.pack(side=TOP, anchor=NE)
        #Crypto Time
        self.cryptoPrice = CryptoPrice(self.topFrame)
        self.cryptoPrice.pack(side=TOP, anchor=NE)
        #camera
        s = FacialRec()

    def toggle_fullscreen(self, event=None):
        self.state = not self.state  # Just toggling the boolean
        self.tk.attributes("-fullscreen", self.state)
        return "break"

    def end_fullscreen(self, event=None):
        self.state = False
        self.tk.attributes("-fullscreen", False)
        return "break"
    def delete(self, appointment):
        """Delete an Appointment in this Node's Calendar."""
        #First create new Calendar without appointment
        from copy import deepcopy
        new_calendar = Calendar()
        for self_appointment in self._calendar:
            if self_appointment != appointment:
                new_calendar += deepcopy(self_appointment)

        if self._log.keys():
            next_log_slot = max(self._log.keys()) + 1
        else:
            next_log_slot = 0

        #Then ask leader to propose the new Calendar
        try:
            leader_IP, leader_TCP, leader_UDP = self._ip_table[self._leader]
            proposal_message = pickle.dumps(
                ("propose", Calendar.serialize(new_calendar), next_log_slot))
            udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            udp_socket.sendto(proposal_message, (leader_IP, leader_UDP))
            udp_socket.close()
        except KeyError as excinfo:
            print "Unable to find leader, waiting until one is selected..."
            while self._leader == None:
                pass
            print "Found leader, continuing...\n"
            self.delete(appointment)
Example #6
0
 def export_gtfs(cls, directory):
     Agency.write_agencies(directory)
     Calendar.write_calendars(directory)
     Stop.write_stops(directory)
     Route.write_routes(directory)
     Trip.write_trips(directory)
     Frequency.write_frequencies(directory)
     Path.write_paths(directory)
Example #7
0
    def __init__(self):
        self.engine = pyttsx3.init()
        self.engine.setProperty('rate', 130)
        self.engine.setProperty('volume', 0.9)

        self.contactnumber = 610890608
        self.BASE_PATH = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/da417be9-5a0f-4e02-972a-d16c59ee77f8?subscription-key=855fe00606ef48ecb4dafc6a30b92845&verbose=true&timezoneOffset=0&q="
        self.calendar = Calendar()
Example #8
0
 def import_gtfs(cls, directory):
     Agency.import_agencies(directory)
     Calendar.import_calendars(directory)
     Stop.import_stops(directory)
     Path.import_paths(directory)
     Route.import_routes(directory)
     Trip.import_trips(directory)
     Frequency.import_frequencies(directory)
Example #9
0
 def load(self):
     self.calendar = Calendar()
     with open("save.csv", "r") as f:
         for line in f.readlines():
             fields = line.strip().split(",")
             self.calendar.add_event(*fields)
         path = os.getcwd() + "/save.csv"
         logging.debug("%s, Loaded calendar from %s" %
                       (datetime.now().isoformat(), path))
class CalendarTestSearchEvents(unittest.TestCase):
    def setUp(self) -> None:
        self.mock_api = MagicMock()
        self.Calendar = Calendar(self.mock_api)

    def test_search_events_with_default_reminders(self):
        self.Calendar.get_past_events = MagicMock(return_value=[{'id': '1olba0rgbijmfv72m1126kpftf',
                                                                 'summary': 'Past Event Summary',
                                                                 'start': {'dateTime': '2020-10-13T11:30:00+05:30'},
                                                                 'reminders': {'useDefault': True}}])
        self.Calendar.get_future_events = MagicMock(return_value=[{'id': '4odta0egtjvboj82p4326esnvw',
                                                                   'summary': 'Future Event Summary',
                                                                   'start': {'dateTime': '2020-10-22T18:30:00+05:30'},
                                                                   'reminders': {'useDefault': True}}])

        searchResult = self.Calendar.search_events('past')
        self.assertEqual(
            ['Event:Past Event Summary at 2020-10-13T11:30:00+05:30\nReminder in 10 minutes before event'],
            searchResult)

    def test_search_events_with_user_reminders(self):
        self.Calendar.get_past_events = MagicMock(return_value=[{'id': '1olba0rgbijmfv72m1126kpftf',
                                                                 'summary': 'Past Event Summary',
                                                                 'start': {'dateTime': '2020-10-13T11:30:00+05:30'},
                                                                 'reminders': {'useDefault': True}}])
        self.Calendar.get_future_events = MagicMock(return_value=[{'id': '4odta0egtjvboj82p4326esnvw',
                                                                   'summary': 'Future Event Summary',
                                                                   'start': {'dateTime': '2020-10-22T18:30:00+05:30'},
                                                                   'reminders': {'useDefault': False, 'overrides': [
                                                                       {'method': 'email', 'minutes': 20},
                                                                       {'method': 'popup', 'minutes': 10}]}
                                                                   }])

        searchResult = self.Calendar.search_events('future')
        self.assertEqual(
            [
                'Event:Future Event Summary at 2020-10-22T18:30:00+05:30\nReminder in 20 minutes before event as email\nReminder in 10 minutes before event as popup'],
            searchResult)

    def test_search_non_existent_events(self):
        self.Calendar.get_past_events = MagicMock(return_value=[{'id': '1olba0rgbijmfv72m1126kpftf',
                                                                 'summary': 'Past Event Summary',
                                                                 'start': {'dateTime': '2020-10-13T11:30:00+05:30'},
                                                                 'reminders': {'useDefault': True}}])
        self.Calendar.get_future_events = MagicMock(return_value=[{'id': '4odta0egtjvboj82p4326esnvw',
                                                                   'summary': 'Future Event Summary',
                                                                   'start': {
                                                                       'dateTime': '2020-10-22T18:30:00+05:30'},
                                                                   'reminders': {'useDefault': True}}])
        searchResult = self.Calendar.search_events('anything')
        self.assertEqual(
            ["Nothing showed up in your search"],
            searchResult)
Example #11
0
    def __init__(self):
        self.calendar = Calendar()

        self.choices = {
            "view": self.view,
            "create": self.create,
            "contacts": self.contacts,
            "delete": self.delete,
            "load": self.load,
            "save": self.save,
            "quit": self.quit
        }
class CalendarTestDeleteEvents(unittest.TestCase):
    def setUp(self) -> None:
        self.mock_api = MagicMock()
        self.Calendar = Calendar(self.mock_api)

    def test_delete_api_call(self):

        event = {'id': '1olba0rgbijmfv72m1126kpftf', 'summary': 'Past Event Summary',
                 'start': {'dateTime': '2020-10-13T11:30:00+05:30'}, 'reminders': {'useDefault': True}}

        self.mock_api.events().delete().execute = MagicMock()
        self.Calendar.delete_events(event)
        self.mock_api.events().delete().execute.assert_called_once()
Example #13
0
 def close(self):
     self._is_open = False
     self._dbname = None
     
     # clear everything
     Agency.clear()
     Calendar.clear()
     Stop.clear()
     Path.clear()
     Route.clear()
     TripRoute.clear()
     Trip.clear()
     Frequency.clear()
     Picture.clear()
Example #14
0
def main():
    calendar = Calendar()
    calendar.appendPlan(Plan('剣道', '2019/10/26 9:00', '2019/10/26 12:00'))
    calendar.appendPlan(Plan('友達と遊ぶ', '2019/10/26 11:00', '2019/10/26 22:00'))
    calendar.appendPlan(Plan('本を読む', '2019/10/27 13:00', '2019/10/27 19:00'))
    it = calendar.iterator()
    while it.hasNext():
        plan = it.next()
        print('----------------------')
        print(plan.getName())
        print(plan.getStartDate())
        print(plan.getEndDate())
def main():

    UDP_IP = sys.argv[1]
    UDP_PORT = sys.argv[2]

    from Calendar import Calendar
    c = Calendar()

    test_prepare = ("prepare", 2)
    test_commit = ("commit", c)
    test_accept = ("accept", 2, c)
    test_promise = ("promise", 1, c)
    test_ack = ("ack", 1, c)

    thread.start_new_thread(listen, ())

    print("@> UDP client started")
    while True:
        message = raw_input('')
        if message == "quit":
            break
        elif message == "prepare":
            UDP_transmission(test_prepare, UDP_IP, int(UDP_PORT))
        elif message == "promise":
            UDP_transmission(test_promise, UDP_IP, int(UDP_PORT))
        elif message == "accept":
            UDP_transmission(test_accept, UDP_IP, int(UDP_PORT))
        elif message == "ack":
            UDP_transmission(test_ack, UDP_IP, int(UDP_PORT))
        elif message == "commit":
            UDP_transmission(test_commit, UDP_IP, int(UDP_PORT))
        else:
            pass
Example #16
0
    def __replicate_old_nav_files(self):
        """
            对于当日数据文件缺失情况,如果需要的文件在邮件中没有找到,
            则复制前一日的数据文件作为代替,这样实现最简单,后续的解析
            文件程序直接把前一日数据当作当日数据解析,但必须保证前一日
            数据文件存在。
        :return:
        """
        rep_date = Calendar.instance().get_prev_trading_day(
            ref_date=self.dt_date)  # 再向前一个交易日 T-2
        # 遍历文件映射
        for i, (expt_file, v) in self.nav_map.items():
            if not v:  # 未找到的文件
                old_file = __make_file_name(ref_date, self.date_ptn[i],
                                            self.data_files[i])
                old_path = os.path.join(self.nav_save_path, old_file)
                new_path = os.path.join(self.nav_save_path, expt_file)
                shutils.copy(old_path, new_path)

        def __make_file_name(ref_date, date_ptn, file_name):
            if date_ptn == 'yyyymmdd':
                ret_name = ''.join(
                    [file_name, ref_date.strftime('%Y%m%d'), '.xls'])
            elif date_ptn == 'yyyy-mm-dd':
                ret_name = ''.join(
                    [file_name,
                     ref_date.strftime('%Y-%m-%d'), '.xls'])
            else:
                ret_name = ''
            return ret_name
Example #17
0
    def listen(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((self.HOST, self.PORT))

        while True:
            data = self.s.recv(1024).decode()
            if data.startswith('BOOKING:'):
                newTimeData = json.loads(data.replace('BOOKING:', ''))
                print(
                    'Reveived calendar update:\n\n{}\n\n'.format(newTimeData))
                self.calendar = Calendar(newTimeData)
            elif data.startswith('CHECK:'):
                print('Received check request, reponding with calendar')
                self.s.sendall(
                    str.encode('RESPONSE:{}'.format(
                        json.dumps(self.calendar.timeData))))
Example #18
0
def main():
    """program entrypoint, handles args and objects"""
    calendar = Calendar(".", "Joe's Calendar")
    calendar.set_calendar_vars()
    event = Event()
    event.create(
        cal=calendar,
        summary="Test",
        location="Test Location",
        description="Test description",
        start_dt="2016-08-06T09:00:00-07:00",
        end_dt="2016-08-06T10:00:00-07:00",
        rec_freq="DAILY",
        rec_count="3"
    )
    event.get_events(10, calendar.service)
Example #19
0
 def set_conf_params(self, mod_config):
     self.dt_date = Calendar.instance().get_prev_trading_day()
     self.src_smtp = mod_config.src_smtp
     self.smtp_user = mod_config.src_user
     self.smtp_pass = mod_config.src_password
     self.des_accounts = mod_config.des_accounts
     self.msg_accounts = mod_config.msg_accounts
     self.report_file = mod_config.report_file
Example #20
0
 def run(self, conf_file):
     try:
         conf_mod = Config(conf_file)
         conf_mod.load_config()
         conf_info = conf_mod.parse_config()
         Calendar.instance().load_calendar_file(conf_info.calendar.calendar_file)
         if Calendar.instance().is_trading_day():
             self.scanner.set_conf_params(conf_info.scanner)
             self.parser.set_conf_params(conf_info.parser)
             self.filler.set_conf_params(conf_info.filler)
             self.sender.set_conf_params(conf_info.sender)
             #
             self.scanner.scan_nav_files()
             nav_dict = self.parser.parse_nav_files()
             self.filler.fill_report_files(nav_dict)
             self.sender.send_report_mail()
         else:
             pass
     except Exception as e:
         err_msg = '程序运行出现异常,相关信息:{e_info}。请检查报告程序'.format(e_info=e)
         self.sender.send_error_message(err_msg)
def main():
    """Quick tests."""
    "schedule yaboi (user0,user1,user2,user3) (4:00pm,6:00pm) Friday"
    "schedule xxboi (user1,user3,user4) (1:30am,11:30am) Wednesday"
    "schedule beez (user0,user1,user2,user3) (4:00pm,6:00pm) Saturday"
    "schedule beez2 (user0,user1,user2,user3) (3:00pm,4:00pm) Saturday"
    "schedule zo (user1,user2,user3) (12:30pm,1:30pm) Friday"
    "schedule hamma (user1,user2,user3) (1:00am,1:30am) Friday"
    "cancel yaboi (user0,user1,user2,user3) (4:00pm,6:00pm) Friday"
    "cancel xxboi (user1,user3,user4) (1:30am,11:30am) Wednesday"

    a1 = Appointment("zo", "Friday", "12:30pm", "1:30pm", [1, 2, 8])
    a2 = Appointment("xxboi", "Wednesday", "1:30am", "11:30am", [1, 4, 5])
    a3 = Appointment("lol", "saturday", "11:30am", "12:30pm", [1])
    a4 = Appointment("yeee", "MondAy", "11:30am", "12:30pm", [1])
    a5 = Appointment("lolololol", "Thursday", "11:30am", "12:30pm", [1])

    c = Calendar()
    c1 = Calendar(a1)
    c2 = Calendar(a1, a2)
    c3 = Calendar(a1, a2, a3)
    c4 = Calendar(a1, a2, a3, a4)
    c5 = Calendar(a1, a2, a3, a4, a5)

    set_verbosity(4)

    N = Node(int(sys.argv[1]))
    '''
    N._log[0] = c1
    N._log[1] = c2
    N._log[2] = c3
    N._log[3] = c4
    N._log[4] = c5
    '''
    N._calendar = c

    #try to load a previous state of this Node
    #'''
    try:
        N = Node.load()
    except ValueError:
        pass
    except IOError:
        pass
    #'''

    N.elect_leader(poll_time=6, timeout=3)
    N.paxos()

    print("@> Node Started")
    while True:
        message = raw_input('')
        if message == "quit":
            Node.save(N)
            N.terminate()
            break
        else:
            Node._parse_command(message, N)
Example #22
0
File: Trip.py Project: line72/subte
    def import_trips(cls, directory):
        from Route import Route
        from Calendar import Calendar
        from TripRoute import TripRoute
        from Path import Path
        from Stop import Stop

        try:
            f = open(os.path.join(directory, 'trips.txt'), 'rb')
            reader = csv.reader(f)

            mappings = {'route_id': ('route', lambda x: Route.get_by_gtfs_id(x)),
                        'service_id': ('calendar', lambda x: Calendar.get_by_gtfs_id(x)),
                        'trip_id': ('name', lambda x: x),
                        'trip_headsign': ('headsign', lambda x: x),
                        'direction_id': ('direction', lambda x: int(x) if x else 0),
                        'shape_id': ('path', lambda x: Path.get_by_gtfs_id(x)),
            }

            # create a headers with an index
            headers = reader.next()
            r_headers = dict([(x, i) for i, x in enumerate(headers)])

            for l2 in reader:
                if len(l2) != len(headers):
                    print >> sys.stderr, 'Invalid line', l2, headers
                    continue
                
                kw = {}
                for i, a in enumerate(l2):
                    key = headers[i]
                    if key in mappings:
                        kw[mappings[key][0]] = mappings[key][1](BaseObject.unquote(a))
                # create the trip route
                trip_route = TripRoute(**kw)
                # set the id
                trip_route.gtfs_id = BaseObject.unquote(l2[r_headers['trip_id']])
                # create a trip
                trip = trip_route.add_trip()
                trip.gtfs_id = BaseObject.unquote(l2[r_headers['trip_id']])

            # go through the list again and set block ids
            #!mwd - I'm not sure how to do this. We link
            #  blocks by trip ids, but block ids are 
            #  random in gtfs, so we have no way to link
            #  them back

        except IOError, e:
            print >> sys.stderr, 'Unable to open trips.txt:', e
Example #23
0
    def view(self, view_name):
        for button in self.mainbuttons:
            button.not_chosen()

        if view_name == 'activate_overview':
            pass
            #self.B1.chosen()

        elif view_name == 'activate_food_iniput':
            pass
            #self.B2.chosen()

        elif view_name == 'activate_calender':
            print('called')
            view = Calendar(self.operationframe, Month.from_date())
Example #24
0
def parse_calendar():
    file_lines  = open("Weight.ics", "r").readlines()
    weight_entries = []
    date_entries = []
    last_line_was_weight = False
    for line in file_lines:
        if last_line_was_weight:
            last_line_was_weight = False
            date = line[-17:-9]
            date_entries.append(date)
        if line.startswith("SUMMARY:"):
            weight = line[8:-2]
            if not weight.startswith("Target:"):
                weight_entries.append(weight)
                last_line_was_weight = True
    return Calendar(weight_entries, date_entries)
Example #25
0
def main():
    calendar = Calendar()
    calendar.init_credentials()
    calendar.init_create_calendar()

    event_list = Priority_Event_List(calendar)

    priority(event_list.priority_events)

    app = QApplication([])
    gui = Gui(calendar, event_list)
    sys.exit(app.exec_())
Example #26
0
    def set_conf_params(self, mod_config):
        self.dt_date = Calendar.instance().get_prev_trading_day()
        self.data_files = mod_config.data_files
        self.prod_names = mod_config.prod_names
        self.date_patterns = mod_config.date_patterns
        self.input_path = mod_config.input_path
        self.unit_nav_items = mod_config.unit_nav_items
        self.accum_ret_items = mod_config.accum_ret_items
        self.ttl_nav_items = mod_config.ttl_nav_items

        for i, (f_name, date_ptn) in enumerate(zip(self.data_files, self.date_patterns)):
            # date_pattern 和 data_file 两个 列表必须一一对应,否则会出错
            if date_ptn == 'yyyymmdd':
                self.data_files[i] = ''.join([f_name, self.dt_date.strftime('%Y%m%d'), '.xls'])
            elif date_ptn == 'yyyy-mm-dd':
                self.data_files[i] = ''.join([f_name, self.dt_date.strftime('%Y-%m-%d'), '.xls'])
        self.nav_map = {f_:0 for f_ in self.data_files} # 文件映射
        self.res_dict = {prod_:NavNode() for prod_ in self.prod_names}
Example #27
0
def main():
    bukva = BookStore()

    book1 = Books("Stephan King", 1, 5, 100.0, 200, "Fog",
                  18, "O'Relly", 6437484355314, "Nice book")

    coloring1 = Coloring(5, 25, 15, "Sun", 0, "Rainbow",
                         5634264385168, "Nice Coloring")

    calendar1 = Calendar(1, 10, 12, "2019", 7, "Cal",
                         7134264385168, "Nice Calendar")

    bukva.add_item(book1)
    bukva.add_item(coloring1)
    bukva.add_item(calendar1)

    for element in bukva.get_list_of_items():
        print("Bukva: " + element)
        def _do_paxos(self):
            """Do Paxos algorithm for this Node."""
            #Begin running the Acceptor and Proposer in the background
            thread.start_new_thread(self._proposer.start, ())
            thread.start_new_thread(self._acceptor.start, ())
            thread.start_new_thread(_learner, (self, ))
            thread.start_new_thread(_shut_down, (self, ))

            IP, UDP_PORT = '0.0.0.0', self._ip_table[self._node_id][2]

            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.bind((IP, UDP_PORT))
            while True:
                data, addr = sock.recvfrom(4096)  # buffer size is 1024 bytes

                if data == "terminate":
                    sock.close()
                    break

                #Quick lookup of ID of sender from IP received
                sender_ID = filter(lambda row: row[1][0] == addr[0],
                                   self._ip_table.items())[0][0]

                message = pickle.loads(data)
                #bind sender_ID to message
                message = message + (sender_ID, )

                #construct deserailized version of message
                new_message = []
                for field in message:
                    if type(field) == str:
                        try:
                            deserialized_calendar = Calendar.deserialize(field)
                            new_message.append(deserialized_calendar)
                        except:
                            new_message.append(field)
                    else:
                        new_message.append(field)

                new_message = tuple(new_message)
                _parse_message(new_message)
Example #29
0
 def set_conf_params(self, mod_config):
     self.dt_date = Calendar.instance().get_prev_trading_day()
     self.pop3_host = mod_config.pop3_host
     self.pop3_user = mod_config.pop3_user
     self.pop3_pass = mod_config.pop3_password
     self.data_files = mod_config.data_files
     self.data_providers = mod_config.data_providers
     self.date_patterns = mod_config.date_patterns
     self.nav_save_path = mod_config.output_path  # Data file path
     for i, (f_name,
             date_ptn) in enumerate(zip(self.data_files,
                                        self.date_patterns)):
         # date_pattern 和 data_file 两个列表必须一一对应,否则会出错
         # 上述实现效率并不高,但方便,如果讲求效率需要优化
         if date_ptn == 'yyyymmdd':
             self.data_files[i] = ''.join(
                 [f_name, self.dt_date.strftime('%Y%m%d'), '.xls'])
         elif date_ptn == 'yyyy-mm-dd':
             self.data_files[i] = ''.join(
                 [f_name, self.dt_date.strftime('%Y-%m-%d'), '.xls'])
     self.nav_map = {f_: 0 for f_ in self.data_files}  # 文件映射
    def __init__(self, node_id):
        """Construct a Node object."""
        if type(node_id) != int:
            raise TypeError("node_id must be an int")
        if node_id < 0:
            raise ValueError("node id must be a nonnegative integer")

        try:
            Node._ip_table = Node._make_ip_table()
        except IOError:
            raise IOError("Node-to-IP translation file: " + ip_filename +
                          " not found.")

        self._node_id = node_id
        self._calendar = Calendar()
        self._proposer = Proposer(node_id, self._ip_table)
        self._acceptor = Acceptor(self._ip_table)
        self._log = {}
        self._leader = None
        self._terminate = False
        self._is_Node = True
	def __init__(self, parent, id = -1, style=0, model=None, cellAttributesDict=None):
		super(CalendarPanel, self).__init__(parent, id)

		if cellAttributesDict is None:
			import config
			cellAttributesDict = config.CELL_ATTRIBUTES_DICT

		self.SetSizer(wx.BoxSizer(wx.VERTICAL))

		buttonsSizer = wx.BoxSizer(wx.HORIZONTAL)

		self.__buttons = [wx.Button(self, -1, "", style=wx.TAB_TRAVERSAL) for i in xrange(4)]

		#self.__label = wx.StaticText(self, -1, "", style=labelAttributes.textAlign if labelAttributes.textAlign is not None else wx.ALIGN_CENTER)
		self.__label = Label(self, cellAttributesDict['label'])
		self.__calendar = Calendar(self, -1, style=style, model=model, cellAttributesDict = cellAttributesDict)

		#if labelAttributes.font:		self.__label.SetFont(labelAttributes.font)
		#if labelAttributes.textColor:	self.__label.SetForegroundColour(labelAttributes.textColor)
		#if labelAttributes.bgColor:		self.__label.SetBackgroundColour(labelAttributes.bgColor)

		for b in self.__buttons[:2]:
			buttonsSizer.Add(b, 0, wx.RIGHT | wx.BOTTOM, GAP)
		
		buttonsSizer.Add(self.__label, 1, wx.BOTTOM | wx.GROW, GAP)
		
		for b in self.__buttons[2:]:
			buttonsSizer.Add(b, 0, wx.LEFT | wx.BOTTOM, GAP)

		self.GetSizer().Add(buttonsSizer, 0, wx.GROW)
		self.GetSizer().Add(self.__calendar, 1, wx.GROW)

		self._updateButtons()

		self.__buttons[0].Bind(wx.EVT_BUTTON, lambda event: self.__calendar.getModel().incMonth(-12))
		self.__buttons[1].Bind(wx.EVT_BUTTON, lambda event: self.__calendar.getModel().incMonth(-1))
		self.__buttons[2].Bind(wx.EVT_BUTTON, lambda event: self.__calendar.getModel().incMonth( 1))
		self.__buttons[3].Bind(wx.EVT_BUTTON, lambda event: self.__calendar.getModel().incMonth( 12))

		self.__calendar.getModel().listeners.bind("propertyChanged", self.__onPropertyChange)
Example #32
0
    def processConnection(self, conn):
        print('Processing new connection {}'.format(conn))
        while True:
            data = conn.recv(1024).decode()
            if data.startswith('BOOKING:'):
                timeToBook = float(data.replace('BOOKING:', ''))
                thread = threading.Thread(target=self.issueBooking,
                                          args=[timeToBook])
                thread.start()
            elif data.startswith('RESPONSE:'):
                responseValue = json.loads(data.replace('RESPONSE:', ''))
                clientCalendar = Calendar(responseValue)
                self.respondingClients.append({
                    'conn': conn,
                    'calendar': clientCalendar
                })

        self.connections.remove(conn)
        self.agentCount -= 1
        print('Removed an agent - current agent count: {}'.format(
            self.agentCount))
        conn.close()
Example #33
0
def read_from_file(file_name):
    program = []
    calendars = []
    f = open(file_name, "r")

    content = f.read()

    meeting_time_string = "Meeting Time Minutes:"
    index = content.find(meeting_time_string)
    meeting_time = int(content[index + len(meeting_time_string):].strip())

    lis_of_content = content.split("calendar")

    for element in lis_of_content:
        m = re.findall("\d{1,2}:\d{2}", element)
        if m:
            # We append all the hours found in the string to the program list
            each_program = []
            for timeline in m:
                format_time = time.strptime(timeline, '%H:%M')
                each_program.append(format_time)
            program.append(each_program)

    for j in range(0, len(program), 2):
        booked = []
        range_limit = []

        # We group the booked calendar two by two and the range limit calendar as well
        for i in range(0, len(program[j]), 2):
            booked.append([program[j][i], program[j][i + 1]])
        for k in range(0, len(program[j + 1]), 2):
            range_limit = [program[j + 1][k], program[j + 1][k + 1]]

        # We create a new Calendar and append it to the list of all calendars
        calendars.append(Calendar(booked, range_limit))

    return calendars, meeting_time
 def __str__(self):
     return Calendar.__str__(self) + ", " + Clock.__str__(self)
 def __init__(self, day,month,year,hours=0, minutes=0,seconds=0):
      Calendar.__init__(self, day, month, year)
      Clock.__init__(self, hours, minutes, seconds)
	def __init__(self,url):
		Calendar.__init__(self, url)
		self.url = url
		self.GHelper = GlobalHelper()
		self.reqBuilder = SysUtils.getRequestBuilder()
Example #37
0
def showCalendar(year, month, day):
	cal = Calendar(year, month, day)
	return cal.render()
Example #38
0
 def __init__(self, day, month, year, hour, minute, second):
     Clock.__init__(self, hour, minute, second)
     Calendar.__init__(self, day, monts, year)
Example #39
0
 def __init__(self, down_payment_percentage):
     self.savings_history.append(self.INITIAL_SAVINGS)
     self.down_payment_percentage = down_payment_percentage
     self.calendar = Calendar()
     self.net_worth_history.append(self.INITIAL_SAVINGS)
Example #40
0
                          url = url, color = color, text_color = text_color)
                r.route_id = int(route_id)
                r.gtfs_id = gtfs_id

            for trip_route_node in tree.getroot().findall('TripRoute'):
                trip_route_id = trip_route_node.get('id', TripRoute.new_id())
                gtfs_id = trip_route_node.get('gtfs_id', None)
                name = trip_route_node.findtext('name')
                route_id = trip_route_node.findtext('route_id')
                calendar_id = trip_route_node.findtext('calendar_id')
                headsign = trip_route_node.findtext('headsign')
                direction = trip_route_node.findtext('direction')
                path_id = trip_route_node.findtext('path_id')

                route = Route.get(int(route_id))
                calendar = Calendar.get(int(calendar_id))
                path = None
                if path_id != '':
                    path = Path.get(int(path_id))

                tr = TripRoute(name, route, calendar, headsign, int(direction), path)
                tr.trip_route_id = int(trip_route_id)
                tr.gtfs_id = gtfs_id
                route.add_trip_route(tr)

                # stops
                stops_node = trip_route_node.find('Stops')
                for stop_node in stops_node.findall('Stop'):
                    stop_id = stop_node.get('id')

                    stop = Stop.get(int(stop_id))
Example #41
0
 def test_initialize():
     instrument = Dict(Name = 'IF_01',FeedCode='IF1509')
     feeder = LocalFeeder(instrument,Dict(tradingDay = Calendar.dateFromInt(20150629),time=datetime.strptime('20150629 09:20:00.000','%Y%m%d %H:%M:%S.%f')),'/home/shgli/data')
     feeder.initialize(Dict(name='AM'))
     print feeder.data.Ask1Price
     assert feeder.data
class CalendarPanel(wx.Panel):
	
	def __init__(self, parent, id = -1, style=0, model=None, cellAttributesDict=None):
		super(CalendarPanel, self).__init__(parent, id)

		if cellAttributesDict is None:
			import config
			cellAttributesDict = config.CELL_ATTRIBUTES_DICT

		self.SetSizer(wx.BoxSizer(wx.VERTICAL))

		buttonsSizer = wx.BoxSizer(wx.HORIZONTAL)

		self.__buttons = [wx.Button(self, -1, "", style=wx.TAB_TRAVERSAL) for i in xrange(4)]

		#self.__label = wx.StaticText(self, -1, "", style=labelAttributes.textAlign if labelAttributes.textAlign is not None else wx.ALIGN_CENTER)
		self.__label = Label(self, cellAttributesDict['label'])
		self.__calendar = Calendar(self, -1, style=style, model=model, cellAttributesDict = cellAttributesDict)

		#if labelAttributes.font:		self.__label.SetFont(labelAttributes.font)
		#if labelAttributes.textColor:	self.__label.SetForegroundColour(labelAttributes.textColor)
		#if labelAttributes.bgColor:		self.__label.SetBackgroundColour(labelAttributes.bgColor)

		for b in self.__buttons[:2]:
			buttonsSizer.Add(b, 0, wx.RIGHT | wx.BOTTOM, GAP)
		
		buttonsSizer.Add(self.__label, 1, wx.BOTTOM | wx.GROW, GAP)
		
		for b in self.__buttons[2:]:
			buttonsSizer.Add(b, 0, wx.LEFT | wx.BOTTOM, GAP)

		self.GetSizer().Add(buttonsSizer, 0, wx.GROW)
		self.GetSizer().Add(self.__calendar, 1, wx.GROW)

		self._updateButtons()

		self.__buttons[0].Bind(wx.EVT_BUTTON, lambda event: self.__calendar.getModel().incMonth(-12))
		self.__buttons[1].Bind(wx.EVT_BUTTON, lambda event: self.__calendar.getModel().incMonth(-1))
		self.__buttons[2].Bind(wx.EVT_BUTTON, lambda event: self.__calendar.getModel().incMonth( 1))
		self.__buttons[3].Bind(wx.EVT_BUTTON, lambda event: self.__calendar.getModel().incMonth( 12))

		self.__calendar.getModel().listeners.bind("propertyChanged", self.__onPropertyChange)


	def getCalendar(self):
		return self.__calendar


	def __onPropertyChange(self, event):
		if event.propertyName == 'dateFirst':
			self._updateButtons()
			

	def _updateButtons(self):
		
		date = self.__calendar.getModel().getDate()
        
		self.__buttons[0].SetLabel("%s <<" % (date.year - 1))
		self.__buttons[3].SetLabel(">> %s" % (date.year + 1))

		self.__label.setText(date.strftime("%B %Y"))

		self.__buttons[1].SetLabel((date - datetime.timedelta(date.day)).strftime("%B <"))
		self.__buttons[2].SetLabel((date + datetime.timedelta(32 - date.day)).strftime("> %B"))


	def __getattr__(self, name):
		return getattr(self.__calendar, name)
Example #43
0
 def onBeginDay(self, tradingDay):
     mappingFileName = os.path.join(self.mappingDirectory, Calendar.dateToString(tradingDay) + '.mapping.csv')
     if not os.path.isfile(mappingFileName):
         raise Exception('can not open mapping file %s' % mappingFileName)
     self.loadFromFile(mappingFileName)
Example #44
0
 def __str__(self):
     return Calendar.__str__(self) + ", " + Clock.__str__(self)
 def _send_ack(self, IP, PORT, accNum, accVal, log_slot):
     """Send ack with given accNum, accVal to given IP, PORT."""
     transmission = ("ack", accNum, Calendar.serialize(accVal), log_slot)
     self._send_UDP_message(transmission, IP, PORT)
 def _send_commit(self, v, log_slot):
     """Send commit message as described in Synod Algorithm."""
     transmission = ("commit", Calendar.serialize(v), log_slot)
     for ID, IP_info in self._ip_table.items():
         IP, UDP_PORT = IP_info[0], IP_info[2]
         self._send_UDP_message(transmission, IP, UDP_PORT)
Example #47
0
 def __init__(self):
     calendar = Calendar()
     self.calendar = calendar
     self.value_history.append(self.initial_value)
Example #48
0
    def onEndDay(self, tradingDay):
        self.feeder.data.LastPrice.plot()

if __name__ == '__main__':
    scriptPath, greenRiver = os.path.split(os.path.abspath(sys.argv[0]))

    parser = argparse.ArgumentParser(prog=greenRiver
        ,description = " generate tailsignal configure")

    parser.add_argument('-m','--mappingRoot',help='directory that contains mapping files')
    parser.add_argument('-d','--dataRoot',help='direcotry that contains data')
    parser.add_argument('-o','--holidayFile',help='holiday file')
    parser.add_argument('-f','--fromDay',help='backtest from this day')
    parser.add_argument('-t','--toDay',help='backtest to this day')
    args = parser.parse_args()


    tradingContext = TradingContext()
    tradingContext.instrumentManager = InstrumentManager(tradingContext,args.mappingRoot)
    tradingContext.feedSource = FeedSource(tradingContext,LocalFeederCreator(args.dataRoot))
    tradingContext.calendar = Calendar(open(args.holidayFile, 'r'))

    tradingContext.initialize(Calendar.dateFromString(args.fromDay),Calendar.dateFromString(args.toDay))

    outSignal = OutputMarket(tradingContext, Symbol('IF_01','CFFEX'))

    tradingContext.run()


Example #49
0
 def __init__(self, url):
     Calendar.__init__(self, url)
     self.url = url
     self.GHelper = GlobalHelper()
     self.reqBuilder = SysUtils.getRequestBuilder()
Example #50
0
    nodeID = 140

    mUser = neo4j.Node("http://localhost:7474/db/data/node/" + str(nodeID))
    mUser2 = neo4j.Node("http://localhost:7474/db/data/node/" + str(nodeID + 1))

    if "User" in mUser.get_labels():
        print(mUser["name"] + " is a User with id of " + str(mUser._id))
    else:
        raise Exception("No User")

        # Get the Times that everything occurs
    event_winterbreak_sTime = datetime(2013, 12, 15)
    event_winterbreak_eTime = datetime(2014, 1, 2)

    # Create the Calendar
    appCalendar = Calendar(Name="Applications Team", Owner=mUser)

    # Create our Break Event
    event_winterbreak = Event(
        Name="Winter Break Development",
        Owner=mUser,
        sTime=dateTimeToMillis(event_winterbreak_sTime),
        eTime=dateTimeToMillis(event_winterbreak_eTime),
    )

    # Create all the tasks that have to be done
    task_develop_calendar = Task(Name="Develop Calendar System", Status=STS_CLOSED)
    task_develop_task_system = Task(Name="Develop Task System", Status=STS_CLOSED)
    task_develop_workspace_system = Task(Name="Develop Workspace System", Status=STS_IN_PROG)
    task_develop_project_system = Task(Name="Develop Project System", Status=STS_OPEN)
Example #51
0
GOOGLE_OUTPUT_FILE_NAME = 'iCal_Google.ics'

DOMAIN = 'http://www.techvibes.com'
URL = DOMAIN + '/event/vancouver'

page = openPage(URL)
html = parse(page)

pageList = html.find(class_ = 'pagination')
try:
	pageIndex = pageList.find(class_ = 'active').a['title']
	numberOfPages = int(findAll('Page 1 of (\d+)', pageIndex)[0])
except AttributeError:
	numberOfPages = 1

calendar = Calendar()

for pageNumber in range(1, numberOfPages + 1):

	print 'Page', pageNumber

	url = URL + '/' + str(pageNumber)
	page = openPage(url)
	html = parse(page)

	content = html.find(id = 'content')
	eventListings = content.find_all(class_ = 'event')

	for listing in eventListings:

		print ' Listing'
Example #52
0
    def load(self, fname):
        try:
            tree = ElementTree.parse(fname)

            for agency_node in tree.getroot().findall('Agency'):
                agency_id = agency_node.get('id', Agency.new_id())
                gtfs_id = agency_node.get('gtfs_id', None)
                name = agency_node.findtext('name')
                url = agency_node.findtext('url')
                timezone = agency_node.findtext('timezone')
                language = agency_node.findtext('language')
                phone = agency_node.findtext('phone')
                fare_url = agency_node.findtext('fare_url')

                a = Agency(name = name, url = url, timezone = timezone, language = language,
                           phone = phone, fare_url = fare_url)
                a.agency_id = int(agency_id)
                a.gtfs_id = gtfs_id
            
            for calendar_node in tree.getroot().findall('Calendar'):
                calendar_id = calendar_node.get('id', Calendar.new_id())
                gtfs_id = calendar_node.get('gtfs_id', None)
                name = calendar_node.findtext('name')
                days = calendar_node.findtext('days')
                start_date = calendar_node.findtext('start_date')
                end_date = calendar_node.findtext('end_date')
                added_excn = calendar_node.findtext('added_excn') or ''
                remov_excn = calendar_node.findtext('remov_excn') or ''

                days = [int(x) for x in days.split()]
                c = Calendar(service_name = name, monday = days[0],
                             tuesday = days[1], wednesday = days[2],
                             thursday = days[3], friday = days[4],
                             saturday = days[5], sunday = days[6],
                             start_date = start_date, end_date = end_date,
                             added_excn = added_excn.split(),
                             remov_excn = remov_excn.split())
                c.calendar_id = int(calendar_id)
                c.gtfs_id = gtfs_id

            for stop_node in tree.getroot().findall('Stop'):
                stop_id = stop_node.get('id', Stop.new_id())
                gtfs_id = stop_node.get('gtfs_id', None)
                code = stop_node.findtext('code')
                name = stop_node.findtext('name')
                description = stop_node.findtext('description')
                latitude = stop_node.findtext('latitude')
                longitude = stop_node.findtext('longitude')
                zone_id = stop_node.findtext('zone_id')
                url = stop_node.findtext('url')
                location_type = stop_node.findtext('location_type')
                parent_station = stop_node.findtext('parent_station')

                try: location_type = int(location_type)
                except: pass

                try:
                    s = Stop(code = code, name = name, description = description,
                             latitude = float(latitude), longitude = float(longitude),
                             zone_id = zone_id, url = url, location_type = location_type,
                             parent_station = parent_station)
                    s.stop_id = int(stop_id)
                    s.gtfs_id = gtfs_id
                except Exception, e:
                    print >> sys.stderr, 'Error loading stop', name, e

            for path_node in tree.getroot().findall('Path'):
                path_id = path_node.get('id', Path.new_id())
                gtfs_id = path_node.get('gtfs_id', None)
                name = path_node.findtext('name')

                coords_node = path_node.find('coordinates')
                coords = []
                for coord_node in coords_node.findall('Coordinate'):
                    try:
                        sequence = int(coord_node.get('sequence', -1))
                        lat = float(coord_node.get('lat', 0.0))
                        lon = float(coord_node.get('lon', 0.0))
                        coords.append((lat, lon))
                    except Exception, e:
                        print >> sys.stderr, 'Invalid coordinate path %s: %s' % (name, e)

                try:
                    p = Path(name = name, coords = coords)
                    p.path_id = int(path_id)
                    p.gtfs_id = gtfs_id
                except Exception, e:
                    print >> sys.stderr, 'Error loading path', name, e