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
    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)
Exemple #3
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))
Exemple #4
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()
Exemple #5
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))
Exemple #6
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
        }
Exemple #7
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())
Exemple #8
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_())
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)
Exemple #10
0
 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 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())
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)
Exemple #13
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))))
Exemple #14
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 __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 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()
Exemple #17
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
Exemple #18
0



tk.Label(bookAppointment,text="Attendace Sheet date",font=("Courier", 30),bg='black').grid(row=1,column=1,columnspan=5)
tk.Label(bookAppointment,text="Select a Date: ",font=("Courier", 22),bg='black').grid(row=2,column=1)
tk.Label(bookAppointment,text="Select Hour: ",font=("Courier", 22),bg='black').grid(row=3,column=1)

#Buttons

tk.Button(bookAppointment,font=("Courier", 22),bg='grey',text="view sheet",command=lambda :makeAppointment()).grid(row=5,column=2)
tk.Button(bookAppointment,font=("Courier", 22),bg='grey',text="Back").grid(row=5,column=1)


#Time Selector
timeSelectFrame = tk.Frame(bookAppointment,borderwidth=5,bg="black")
timeSelectFrame.grid(row=3,column=2)

tk.Spinbox(timeSelectFrame,from_=1, to=24,bg="grey",width=2,textvariable=hours).grid(row=1,column=1)

tk.Label(timeSelectFrame,text=":00",bg="grey").grid(row=1,column=2)


calendarFrame = tk.Frame(bookAppointment, borderwidth=5, bg="black")
calendarFrame.grid(row=2, column=2, columnspan=5)

datePickercalendar = Calendar(calendarFrame, {})
#Raise Initial Frame
bookAppointment.tkraise(bookAppointment)
root.mainloop()
Exemple #19
0
    def __init__(self):
        Gtk.Window.__init__(self, title="Magic Mirror")

        self.state_list = [
            "HOME", "WEATHER", "TIME", "QUOTE", "CALENDAR", "HELP", "INFO",
            "MIRROR"
        ]
        self.state = ""

        # Data classes which update from subscriber
        input_data = InputData()
        weather_data = WeatherData()
        quote_data = QuoteData()
        calendar_data = EventData()
        message_data = MessageData()
        home_data = HomeData()
        self.auth_data = AuthData()
        pin_data = PinData()

        # Screen objects that are cycled in the window
        self.home_screen = Home(weather_data, calendar_data, home_data,
                                self.auth_data)
        self.auth_screen = Auth(self.auth_data, pin_data)
        self.weather_screen = Weather(weather_data)
        self.time_screen = TimeDate()
        self.message_screen = Messages(message_data)
        self.quote_screen = Quote(quote_data)
        self.calendar_screen = Calendar(calendar_data)
        self.help_screen = Help()
        self.info_screen = Info()
        self.mirror_screen = Mirror()

        # Starts the MQTT subscriber
        self.data_thread = threading.Thread(target=subscriber.run,
                                            args=([
                                                input_data, weather_data,
                                                quote_data, calendar_data,
                                                home_data, self.auth_data,
                                                pin_data
                                            ], ))
        self.data_thread.daemon = True
        self.data_thread.start()

        # Updates the value on the screens in separate threads
        GObject.timeout_add(1000, self.auth_screen.update)
        GObject.timeout_add(1000, self.weather_screen.update_weather)
        GObject.timeout_add(1000, self.time_screen.update_clock)
        GObject.timeout_add(1000, self.quote_screen.update)
        GObject.timeout_add(1000, self.calendar_screen.update_events)
        GObject.timeout_add(1000, self.message_screen.update_screen)
        GObject.timeout_add(1000, self.home_screen.update_home)

        self.app_stack = Gtk.Stack()
        self.app_stack.set_transition_type(
            Gtk.StackTransitionType.SLIDE_LEFT_RIGHT)
        self.app_stack.set_transition_duration(500)

        self.app_stack.add_named(self.auth_screen, "Auth")
        self.app_stack.add_named(self.home_screen, "Home")
        self.app_stack.add_named(self.weather_screen, "Weather")
        self.app_stack.add_named(self.time_screen, "Time")
        self.app_stack.add_named(self.message_screen, "Message")
        self.app_stack.add_named(self.quote_screen, "Quote")
        self.app_stack.add_named(self.calendar_screen, "Calendar")
        self.app_stack.add_named(self.help_screen, "Help")
        self.app_stack.add_named(self.info_screen, "Info")
        self.app_stack.add_named(self.mirror_screen, "Mirror")

        # Meant to add the default screen
        self.add(self.app_stack)

        self.fullscreen()
        self.modify_bg(Gtk.StateType.NORMAL, Gdk.Color(255, 0, 255))
        self.set_icon(IMG.iconpix)
Exemple #20
0
from Monitor import Monitor
from Gui import Gui
from Calendar import Calendar
import Ribbon

from pathlib import Path
import datetime

if __name__ == '__main__':

    # unpickle queue from known file location
    if Path(Ribbon.save_location).is_file():
        file = open(Ribbon.save_location, 'rb')
        Ribbon.calendar = pickle.load(file)
    else:
        Ribbon.calendar = Calendar()

    # create GUI
    Ribbon.gui = Gui()

    # create monitor
    Ribbon.monitor = Monitor()

    # start monitor
    Ribbon.monitor.start()

    # init to today's date
    Ribbon.setSelectedDate(datetime.datetime.now().date())

    # start gui
    Ribbon.gui.mainloop()
Exemple #21
0
def showCalendar(year, month, day):
    cal = Calendar(year, month, day)
    return cal.render()
Exemple #22
0
 def test_optimize(self):
     test_list = [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]
     calendar = Calendar(test_list)
     calendar.optimize()
     self.assertEqual(calendar.output_list, [(0, 1), (3, 8), (9, 12)])
Exemple #23
0
def tabUi(self,showLists=True):
        self.horizontalLayout = QtGui.QHBoxLayout(self)
        """Każdą zakładkę dzielimy jak na razie na 3 obszary: opcje,
        listy , wykresy """
        
        """Ramka przechowujaca listy"""
        if showLists:
                self.listsFrame = QtGui.QFrame(self)
                sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
                QtGui.QSizePolicy.Preferred)
                sizePolicy.setHorizontalStretch(0)
                sizePolicy.setVerticalStretch(0)
                sizePolicy.setHeightForWidth(self.listsFrame.sizePolicy().hasHeightForWidth())
                self.listsFrame.setSizePolicy(sizePolicy)
                # ustawimy maksymalna szerokosc kolumny na 350
                self.listsFrame.setMaximumSize(QtCore.QSize(600, 16777215))
                self.listsFrame.setMinimumSize(QtCore.QSize(550, 0))
                self.listsFrame.setFrameShape(QtGui.QFrame.StyledPanel)
                self.listsFrame.setFrameShadow(QtGui.QFrame.Raised)
                self.listsFrame.setLineWidth(3)
        

                #ustawiamy zarządce rozkładu vertical
                self.listsLayout = QtGui.QVBoxLayout(self.listsFrame)
                # textline
                self.filterLineEdit = QtGui.QLineEdit(self.listsFrame)
                self.listsLayout.addWidget(self.filterLineEdit)
                # Tool Box przechowujący listy
                self.listsToolBox = QtGui.QToolBox(self.listsFrame)

                #Index
                self.indexPage = QtGui.QWidget(self.listsFrame)
                self.indexPageLayout = QtGui.QHBoxLayout(self.indexPage)
                self.listsToolBox.addItem(self.indexPage, "Index")
                self.indexListView = QtGui.QTableView(self.listsFrame)
                self.indexListView.setAlternatingRowColors(True)
                self.indexListView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
                self.indexListView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
                tableStyle(self,self.indexListView) #ustawiamy styl tabeli
                self.indexPageLayout.addWidget(self.indexListView)

                #Stock
                self.stockPage = QtGui.QWidget(self.listsFrame)
                self.stockPageLayout = QtGui.QGridLayout(self.stockPage)
                self.stockPageLayout.setSpacing(0)
                self.listsToolBox.addItem(self.stockPage , "Stock")

                self.nasdaqButton = QtGui.QPushButton("NASDAQ",self.listsFrame)
                self.nasdaqButton.setCheckable(True)
                self.nasdaqButton.setAutoExclusive(True)
                self.stockPageLayout.addWidget(self.nasdaqButton, 0, 0, 1, 1)
                self.nyseButton = QtGui.QPushButton("NYSE",self.listsFrame)
                self.nyseButton.setCheckable(True)
                self.nyseButton.setAutoExclusive(True)
                self.stockPageLayout.addWidget(self.nyseButton, 0, 1, 1, 1)
                self.amexButton = QtGui.QPushButton("AMEX",self.listsFrame)
                self.amexButton.setCheckable(True)
                self.amexButton.setAutoExclusive(True)
                self.stockPageLayout.addWidget(self.amexButton, 1, 0, 1, 1)
                self.wigButton = QtGui.QPushButton("WIG",self.listsFrame)
                self.wigButton.setCheckable(True)
                self.wigButton.setAutoExclusive(True)
                self.stockPageLayout.addWidget(self.wigButton, 1, 1, 1, 1)
                self.wig20Button = QtGui.QPushButton("WIG20",self.listsFrame)
                self.wig20Button.setCheckable(True)
                self.wig20Button.setAutoExclusive(True)
                self.stockPageLayout.addWidget(self.wig20Button, 0, 2, 1, 1)
                self.allButton = QtGui.QPushButton("ALL",self.listsFrame)
                self.allButton.setCheckable(True)
                self.allButton.setChecked(True)
                self.allButton.setAutoExclusive(True)
                self.stockPageLayout.addWidget(self.allButton, 1, 2, 1, 1)
               
                self.stockListView = QtGui.QTableView(self.listsFrame)
                self.stockListView.setAlternatingRowColors(True)
                self.stockListView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
                #self.stockListView.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
                tableStyle(self,self.stockListView)#ustawiamy styl tabeli
                self.stockPageLayout.addWidget(self.stockListView,2,0,1,3)

                #forex
                self.forexPage = QtGui.QWidget(self.listsFrame)
                self.forexPageLayout = QtGui.QHBoxLayout(self.forexPage)
                self.listsToolBox.addItem(self.forexPage, "Forex")
                self.forexListView = QtGui.QTableView(self.listsFrame)
                self.forexListView.setAlternatingRowColors(True)
                self.forexListView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
                #self.forexListView.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
                tableStyle(self,self.forexListView)#ustawiamy styl tabeli
                self.forexPageLayout.addWidget(self.forexListView)

                #Bond
                self.bondPage = QtGui.QWidget(self.listsFrame)
                self.bondPageLayout = QtGui.QHBoxLayout(self.bondPage)
                self.listsToolBox.addItem(self.bondPage, "Bond")
                self.bondListView = QtGui.QTableView(self.listsFrame)
                self.bondListView.setAlternatingRowColors(True)
                self.bondListView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
                #self.bondListView.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
                tableStyle(self,self.bondListView)
                self.bondPageLayout.addWidget(self.bondListView)

                #Resource
                self.resourcePage = QtGui.QWidget(self.listsFrame)
                self.resourcePageLayout = QtGui.QHBoxLayout(self.resourcePage)
                self.listsToolBox.addItem(self.resourcePage, "Resource")
                self.resourceListView = QtGui.QTableView(self.listsFrame)
                self.resourceListView.setAlternatingRowColors(True)
                self.resourceListView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
                #self.resourceListView.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
                tableStyle(self,self.resourceListView)
                self.resourcePageLayout.addWidget(self.resourceListView)


                #Futures contract
                self.futuresContractPage = QtGui.QWidget(self.listsFrame)
                self.futuresContractPageLayout = QtGui.QHBoxLayout(self.futuresContractPage)
                self.listsToolBox.addItem(self.futuresContractPage, "Futures Contract")
                self.futuresListView = QtGui.QTableView(self.listsFrame)
                self.futuresListView.setAlternatingRowColors(True)
                self.futuresListView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
                #self.futuresListView.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
                tableStyle(self,self.futuresListView)
                self.futuresContractPageLayout.addWidget(self.futuresListView)
        
                self.listsLayout.addWidget(self.listsToolBox)
                # koniec Tool Box

                #compare
                self.compareWidget = QtGui.QWidget(self.listsFrame)
                self.compareLayout = QtGui.QHBoxLayout(self.compareWidget)
                self.compareCheckBox = QtGui.QCheckBox("Enable Compare",self.listsFrame)
                self.compareLayout.addWidget(self.compareCheckBox)
                self.compareLineEdit = QtGui.QLineEdit(self.listsFrame)
                self.compareLineEdit.setEnabled(False)
                self.compareLineEdit.setToolTip("e.g. ^DJI vs FLWS vs ...")
                self.compareLayout.addWidget(self.compareLineEdit)
                self.compareButton = QtGui.QPushButton("Compare",self.listsFrame)
                self.compareButton.setEnabled(False)
                self.compareButton.setToolTip("Click to Compare")
                self.compareLayout.addWidget(self.compareButton)
                self.listsLayout.addWidget(self.compareWidget)

                self.horizontalLayout.addWidget(self.listsFrame)
        # koniec ramki przechowywyjącej listy
        

        """Ramka przechowujaca opcjie i wykres"""
        self.optionsAndChartsFrame = QtGui.QFrame(self)
        # ustawimy maksymalna szerokosc kolumny na 350
        #self.optionsAndChartsFrame.setMaximumSize(QtCore.QSize(1600, 16777215))
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(0)
        #sizePolicy.setHeightForWidth(self.optionsAndChartsFrame.sizePolicy().hasHeightForWidth())
        self.optionsAndChartsFrame.setSizePolicy(sizePolicy)
        self.optionsAndChartsFrame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.optionsAndChartsFrame.setFrameShadow(QtGui.QFrame.Raised)
        self.verticalLayout = QtGui.QVBoxLayout(self.optionsAndChartsFrame)

        """Ramka przechowujaca wykresy"""
        self.chartsFrame = QtGui.QFrame(self)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(self.chartsFrame.sizePolicy().hasHeightForWidth())
        self.chartsFrame.setSizePolicy(sizePolicy)
        self.chartsFrame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.chartsFrame.setFrameShadow(QtGui.QFrame.Raised)
        self.chartsFrame.setLineWidth(3)
        #ustawiamy zarządce rozkładu vertical
        self.chartsLayout = QtGui.QVBoxLayout(self.chartsFrame)
        self.verticalLayout.addWidget(self.chartsFrame)

        """Ramka przechowujaca opcje"""
        self.optionsFrame = QtGui.QFrame(self)
        # ustawimy maksymalna wysokosc na 120

        self.optionsFrame.setMaximumSize(QtCore.QSize(16777215, 150))
        self.optionsFrame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.optionsFrame.setFrameShadow(QtGui.QFrame.Raised)
        self.optionsFrame.setLineWidth(3)
        #ustawiamy zarządce rozkładu Grid
        self.optionsLayout = QtGui.QGridLayout(self.optionsFrame)
        
        #pola do wprowadzania okresu
        self.label = QtGui.QLabel('Range:',self.optionsFrame) 
        self.optionsLayout.addWidget(self.label,0,0,1,1)
        self.startDateEdit = QtGui.QDateEdit(self.optionsFrame)
        self.startDateEdit.setCalendarPopup(True)
        self.startDateEdit.setCalendarWidget(Calendar())
        self.startDateEdit.setDate(QtCore.QDate.currentDate().addDays(-18))
        self.startDateEdit.setMaximumDate(QtCore.QDate.currentDate().addDays(-1))
        self.optionsLayout.addWidget(self.startDateEdit,1,0,1,1)
        self.endDateEdit = QtGui.QDateEdit(self.optionsFrame)
        self.endDateEdit.setCalendarPopup(True)
        self.endDateEdit.setCalendarWidget(Calendar())
        self.endDateEdit.setDate(QtCore.QDate.currentDate().addDays(-5))
        self.endDateEdit.setMaximumDate(QtCore.QDate.currentDate().addDays(-1))
        self.optionsLayout.addWidget(self.endDateEdit,2,0,1,1)
        self.dateButton = QtGui.QPushButton('Ok',self.optionsFrame)
        self.optionsLayout.addWidget(self.dateButton,3,0,1,1)
        #koniec pola do wprowadzania okresu
	self.verticalLayout.addWidget(self.optionsFrame)
        
        #dodajemy ramke zawierajaca wykres i opcje do tab
        self.horizontalLayout.addWidget(self.optionsAndChartsFrame)
Exemple #24
0
 def test_empty(self):
     calendar = Calendar([])
     calendar.optimize()
     self.assertEqual(calendar.output_list, [])
def main():
    """
	Samuraiz Calendar App

	Usage:
		calendar -h| --help
		calendar --version

	Options:
		-h --help
		--version

	Examples:
		calendar create

	"""

    print("\n\n")
    print("Welcome to your Personal Calendar\n\n")
    count = 0

    while True:
        now = datetime.datetime.now()
        if count <= 1:  # Checks if there are more than one calendar created.
            print(
                " 1. Create calendar\n 2. Add Event\n 3. View Events \n 4. View Last Entry \n 5. Exit \n \n"
            )
        else:
            print(
                " 1. Create calendar\n 2. Add Event\n 3. View Events \n 4. View Last Entry \n 4.5. View other calendar's events \n 5. Exit \n\n"
            )
        action = input('Enter your choice: ')
        if action == '1':
            month = input("Enter month (e.g 7 for 'July') : ")
            try:
                if int(month) in range(1, 13):
                    year = input('Enter year (e.g 2016) : ')
                    if int(year) >= now.year:
                        calendar_name = input('Enter your calendar name: ')
                        name = calendar_name
                        calendar_name = Calendar()
                        calendar_name.create_calendar(int(year), int(month))
                        count += 1  #increments every time a new calendar is created.
                        print('\n')
                        print('Calendar created.')
                        print('\n')
                    else:
                        print('You can only create events for future dates')
                else:
                    print('Sorry month entered should be between 1 to 12')
                    print('\n')
            except:
                print('Please key in month in numbers.')
                print('\n')
        elif action == '2':
            try:
                if calendar_name._days:
                    event_day = int(input("Add Event day: "))
                    if event_day in calendar_name._days:
                        event_name = input("Add Event name: ")
                        event_desc = input("Add Event description: ")
                        print(
                            calendar_name.add_event(event_day, event_name,
                                                    event_desc))
                        save(
                            name, calendar_name
                        )  # calls the save function in Calendar.py. This creates a json file.
                        print('\n')
                    else:
                        print('No such day in the {} month'.format(
                            calendar_name.calendar_month))
                        print('\n')
            except UnboundLocalError:
                print('No calendars created yet, Create a Calendar first')
                print("\n")
        elif action == '3':
            try:
                if calendar_name._days:
                    print(calendar_name.view_events())
            except UnboundLocalError:
                print('No calendars created yet, Create a Calendar first')
                print("\n")
        elif action == '4':
            try:
                if calendar_name._days:
                    print(calendar_name.view_last_event())
            except UnboundLocalError:
                print('No calendars created yet, Create a Calendar first')
                print("\n")
        elif action == '4.5':
            """
            Prints all the events in all the calendars created.
            Option only available if more than one calendar created.
            Calls except when no event has been added to any calendar thus no json file was created.
            """
            try:
                open_file()
                print("\n \n")
            except:
                print('No event added to any calendar')
                print('\n')
        elif action == '5':
            break
        else:
            print("Invalid choice: select again")
Exemple #26
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)
Exemple #27
0
 def __init__(self):
     calendar = Calendar()
     self.calendar = calendar
     self.value_history.append(self.initial_value)
Exemple #28
0
 def __init__(self):
     self.NewCalendar = Calendar(
     )  # Initialise a new instance of the calendar object
Exemple #29
0
import plotly
import plotly.graph_objs as go

from Investor import Investor
from Calendar import Calendar
from PropertyObj import PropertyObj

MONTHS_IN_PERIOD = 600
Y_RANGE = [0, 1000000]
DOWN_PAYMENT_PERCENTAGE = 20

calendar = Calendar()
investor = Investor(DOWN_PAYMENT_PERCENTAGE)
property_obj = PropertyObj()

# every month, money comes in and money goes out
for month in range(0, MONTHS_IN_PERIOD):
    calendar.nextMonth()
    property_obj.updateValue()
    investor.earnIncome()
    investor.payPropertyPayments(property_obj)
    investor.updateNetWorth(property_obj)
    if (investor.canAffordProperty(property_obj) and len(investor.loans) < 1):
        investor.buyProperty(property_obj)


# function which takes the raw data and makes traces for the chart
# TODO: this function is too large. break it up, it smells
def mapTraces(investor):
    down_payment_percentage = investor.down_payment_percentage
    x_axis_months = [0]
 def setUp(self) -> None:
     self.mock_api = MagicMock()
     self.Calendar = Calendar(self.mock_api)