Beispiel #1
0
def test_terminal_quick_exit(mocker, monkeypatch):
    monkeypatch.setattr(terminal.gtff, "ENABLE_QUICK_EXIT", True)
    monkeypatch.setattr(terminal.gtff, "USE_ION", False)
    monkeypatch.setattr(terminal.gtff, "USE_PROMPT_TOOLKIT", True)

    mocker.patch("sys.stdin")

    terminal.terminal()
Beispiel #2
0
def test_terminal_quit(mocker, monkeypatch):
    monkeypatch.setattr(terminal.gtff, "ENABLE_QUICK_EXIT", False)
    monkeypatch.setattr(terminal.gtff, "USE_ION", False)
    monkeypatch.setattr(terminal.gtff, "USE_PROMPT_TOOLKIT", True)

    mocker.patch("sys.stdin")
    mocker.patch("builtins.input", return_value="e")
    mocker.patch("terminal.session")
    mocker.patch("terminal.session.prompt", return_value="e")
    mocker.patch("terminal.print_goodbye")
    spy_print_goodbye = mocker.spy(terminal, "print_goodbye")

    terminal.terminal()

    spy_print_goodbye.assert_called_once()
Beispiel #3
0
def vis(ticker):
	sio = cStringIO.StringIO()
	likCache = tempfile.NamedTemporaryFile()
	data = terminal(ticker, likCache.name, alpha=-3.0)
	parser = qcyk()
	parser.initGrammar(os.path.dirname(os.path.realpath(__file__))+'/test.gr')
	parser.initTerminal(likCache.name)
	lik, tree = parser.parse()
	likCache.close()

	fig = plt.figure(figsize=(12,5))
	ax = fig.add_subplot(111)
	kps = data[data.pivots!=0].Close
	idx = kps.index
	kps.plot(style='--o', ax=ax)
	for t, xmin, xmax in parser.leafs(tree):
		center = idx[(xmin+xmax)/2]
		high = data[idx[xmin]:idx[xmax]].Close.max()
		low = data[idx[xmin]:idx[xmax]].Close.min()
		bottom, top = ax.get_ylim()
		llow = (low-bottom)/float(top-bottom)
		hhigh = (high-bottom)/float(top-bottom)
		if t != 'null':
			ax.axvspan(idx[xmin], idx[xmax],
				ymin=llow, ymax=hhigh, alpha=0.3, color=CS[t])
			ax.annotate("%s"%(t), (center, high))

	plt.savefig(sio, format='png')
	sio.seek(0)
	return sio.getvalue()
Beispiel #4
0
    def __init__(self, ):

        self.terminal = terminal()

        self.matrix = {}

        self.X = -1  # colunas
        self.Y = -1  # linhas
        self.Z = {}  # profundidadde

        self.blank = '  '
        self.brick = u'█' * 2

        self.clockTime = 1

        self.objectsList = {}
        self.colisions = {}

        #inicia o teclado
        self.keys = {}  #
        self.declaredKeys = []  #
        self.keyBoard_key_name = {}  #
        self.keyBoard_name_key = {}  #

        self.prepareKeyboard()
    def _setup_layout(self):
        self.vbox = VBox(False, 0)
        self.vbox.show()

        self.terminal = terminal()
        self.terminal.connect("child-exited", lambda _: self.close_button.show())
        
        self.expander = expander_new_with_mnemonic(_("_Terminal"))
        self.expander.set_expanded(False)
        self.expander.add(self.terminal)
        self.expander.show_all()
        
        self.close_button = Button(stock=STOCK_CLOSE)
        self.close_button.connect("clicked", lambda _: self.destroy())

        scr = ScrolledWindow()
        scr.set_policy ("automatic", "automatic")
        scr.add (self.tree)
        scr.show()

        vpaned = VPaned()
        vpaned.add1(scr)
        vpaned.add2(self.expander)
        vpaned.set_position (260)
        vpaned.show()

        self.vbox.pack_start(vpaned, True, True, 0)
        self.vbox.pack_start(self.close_button, False, False, 0)

        self.add(self.vbox)
        return
    def _setup_layout(self):

        self.hpaned = HPaned()
        self.hpaned.add1(self.inst_tree)
        self.hpaned.add2(self.rem_tree)
        self.hpaned.show_all()

        self.close_button = Button(stock=STOCK_CLOSE)
        self.close_button.connect("clicked", lambda _: self.destroy())

        self.terminal = terminal()
        self.terminal.connect("child-exited", lambda _: self.close_button.show())

        self.expander = Expander(_("Terminal"))
        self.expander.connect("notify::expanded", self._set_size)
        self.expander.show()

        self.vbox = VBox(False, 0)
        self.vbox.show()
        
        self.vbox.pack_start(self.hpaned, False, False, 0)
        self.vbox.pack_start(self.expander, False, False, 0)
        self.vbox.pack_start(self.close_button, False, False, 0)

        
        self.add(self.vbox)
    def __init__(self, icon):

        Window.__init__(self, WINDOW_TOPLEVEL)
        self.set_property("skip-taskbar-hint", True)
        self.set_property("destroy-with-parent", True)
        self.set_modal(True)
        self.set_position(WIN_POS_CENTER)

        self.vbox = VBox(False, 0)
        
        self.terminal = terminal()
        self.terminal.connect("child-exited",
                              lambda _: self.close_button.show())
        self.terminal.show()
        
        self.close_button = Button(stock=STOCK_CLOSE)
        self.close_button.connect("clicked", lambda _: self.destroy())

        self.vbox.pack_start(self.terminal, False, False, 0)
        self.vbox.pack_start(self.close_button, False, False, 0)
        self.vbox.show()

        self.add(self.vbox)

        self.set_icon(pixbuf_new_from_file(icon))
Beispiel #8
0
def multi_process():
    print "******"
    ter=terminal.terminal(str(random.randrange(100000000000000,999999999999999)),ipaddr, port)
    ter.login()
    print "ssssssss*****"
    ter.flag=False
    while True:
        ter.heartbeat()
        time.sleep(0.5)
    def __init__(self, parent, icon):

        Dialog.__init__(self, None, parent, DIALOG_MODAL | DIALOG_DESTROY_WITH_PARENT)
        self.set_icon(pixbuf_new_from_file(icon))
        
        self.close_button = self.add_button(STOCK_CLOSE, RESPONSE_CLOSE)
        self.close_button.connect("clicked", lambda _: self.destroy())
        
        self.terminal = terminal()
        self.terminal.connect("child-exited", lambda _: self.close_button.show())  
Beispiel #10
0
    def __init__(self, scr, file):
        self.mode = 'edit'
        self.terminal = terminal.terminal()
        self.scr = scr
        height, width = scr.getmaxyx()
        self.scrh = height
        self.scrw = width
        self.edith = height
        self.editw = width
        #caret positioning
        self.cx = 0
        self.cy = 0
        #screen positioning
        self.sx = 0
        self.sy = 0
        self.key = 0
        self.ck = ''
        f = open(file, 'r')
        txt = f.read().replace('\t', ' ' * 4)
        f.close()
        self.filename = file
        self.lines = txt.split('\n')
        self.keystrokes = 0
        self.message = 'Welcome! Press ctrl-q for help'
        self.showkeycodes = False

        helppath = os.path.join(os.path.dirname(__file__), 'help.txt')
        self.helplines = open(helppath).read().split('\n')
        self.ishelpon = False

        self.undoq = [inputfunc.ministate(self.lines, self.cx, self.cy)]
        self.redoq = []

        #handle highlighting
        l = re.findall('(.+?)(\.[^\.]+$|$)', self.filename)
        extension = '' if len(l) == 0 else l[-1][-1][1:]
        highlightpath = os.path.join(os.path.dirname(__file__),
                                  'highlight_{}.txt'.format(extension))
        self.highlight = filetext(highlightpath).split('\n')

        #autocompletion stuff
        self.isautocomp = False
        self.acword = ''
        self.acwordx = 0
        self.acwords = []
        self.linewords = re.findall('[_a-zA-Z][_a-zA-Z0-9]*', (self.lines + [''])[0])
        self.aci = 0 #autocomplete index
        freqmap = {}
        words = re.findall('[_a-zA-Z][_a-zA-Z0-9]*', txt)
        for w in words:
            if w in freqmap.keys() : freqmap[w] += 1
            else : freqmap[w] = 1
        self.freqmap = freqmap
        d = freqmap
        self.lastwords = [pair[0] for pair in sorted(d.items(), key=lambda item: item[1])][::-1]
    def _setup_layout(self):

        self.set_default_size(600,200)
        self.hpaned = HPaned()
        
        inst_scroll = ScrolledWindow()
        inst_scroll.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC)

        rem_scroll = ScrolledWindow()
        rem_scroll.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC)
        
        inst_scroll.add(self.inst_tree)
        rem_scroll.add(self.rem_tree)
        
        self.hpaned.pack1(inst_scroll, False, False)
        self.hpaned.pack2(rem_scroll, False, False)
        self.hpaned.show_all()

        self.close_button = Button(stock=STOCK_CLOSE)
        self.close_button.connect("clicked", lambda _: self.destroy())

        self.terminal = terminal()
        self.terminal.connect("child-exited", lambda _: self.close_button.show())

        self.expander = Expander(_("Terminal"))
        self.expander.connect("notify::expanded", self._set_size)
        self.expander.show()

        self.vbox = VBox(False, 0)
        self.vbox.show()
        
        self.vbox.pack_start(self.hpaned, True, True, 0)
        self.vbox.pack_start(self.expander, False, False, 0)
        self.vbox.pack_start(self.close_button, False, False, 0)

        
        self.add(self.vbox)
Beispiel #12
0
    def __init__(self, scr, file):
        self.mode = 'edit'
        self.terminal = terminal.terminal()
        self.terminal.filename = file
        self.scr = scr
        height, width = scr.getmaxyx()
        self.scrh = height
        self.scrw = width
        self.edith = height
        self.editw = width
        #caret positioning
        self.cx = 0
        self.cy = 0
        #screen positioning
        self.sx = 0
        self.sy = 0
        #restore previous positions of screen and caret
        if file in posmems.keys():
            p = posmems[file]
            self.cx = p.cx
            self.cy = p.cy
            self.sx = p.sx
            self.sy = p.sy
        self.key = 0
        self.ck = ''
        f = open(file, 'r')
        txt = f.read().replace('\t', ' ' * 4)
        f.close()
        self.filename = file
        self.lines = txt.split('\n')
        #move current working file to top of filelist
        if self.filename in filelist: filelist.remove(self.filename)
        filelist.insert(0, self.filename)

        self.filelist = filelist
        self.filecol = []
        self.fi = 0
        self.newfname = ''
        self.keystrokes = 0
        self.message = 'Welcome! Press ctrl-q for help'
        self.showkeycodes = False

        helppath = os.path.join(os.path.dirname(__file__), 'help.txt')
        self.helplines = open(helppath).read().split('\n')
        self.ishelpon = False

        #set up undo queue and redo queue
        self.undoq = [inputfunc.ministate(self.lines, self.cx, self.cy)]
        self.redoq = []

        #handle highlighting
        l = re.findall('(.+?)(\.[^\.]+$|$)', self.filename)
        extension = '' if len(l) == 0 else l[-1][-1][1:]
        highlightpath = os.path.join(os.path.dirname(__file__),
                                     'highlight_{}.txt'.format(extension))
        self.highlight = filetext(highlightpath).split('\n')

        #autocompletion stuff
        self.isautocomp = False
        self.acword = ''
        self.acwordx = 0
        self.acwords = []
        self.linewords = re.findall('[_a-zA-Z][_a-zA-Z0-9]*',
                                    (self.lines + [''])[0])
        self.aci = 0  #autocomplete index
        freqmap = {}
        words = re.findall('[_a-zA-Z][_a-zA-Z0-9]*', txt)

        #load autocomplete suggestions file
        try:
            suggestedpath = os.path.join(os.path.dirname(__file__),
                                         'suggest_{}.txt'.format(extension))
            suggested = open(suggestedpath).read().split('\n')
        except:
            suggested = []

        for w in words + self.highlight + suggested:
            if w in freqmap.keys(): freqmap[w] += 1
            else: freqmap[w] = 1
        self.freqmap = freqmap
        d = freqmap
        self.lastwords = [
            pair[0] for pair in sorted(d.items(), key=lambda item: item[1])
        ][::-1]

        self.localcpy = ''
        self.foreigncpy = ''

        self.adjustcoords()
Beispiel #13
0
                written / t * 8 / 1000,
            )
        print "\nLeaving..."
        if args.flash_mode == "dio":
            esp.flash_unlock_dio()
        else:
            esp.flash_begin(0, 0)
            esp.flash_finish(False)

    elif args.operation == "run":
        esp.run()
        if args.terminal:
            from terminal import terminal

            print "Press ^C twice to exit"
            terminal(esp._port)

    elif args.operation == "image_info":
        image = ESPFirmwareImage(args.filename)
        print ("Entry point: %08x" % image.entrypoint) if image.entrypoint != 0 else "Entry point not set"
        print "%d segments" % len(image.segments)
        print
        checksum = ESPROM.ESP_CHECKSUM_MAGIC
        for (idx, (offset, size, data)) in enumerate(image.segments):
            print "Segment %d: %5d bytes at %08x" % (idx + 1, size, offset)
            checksum = ESPROM.checksum(data, checksum)
        print
        print "Checksum: %02x (%s)" % (image.checksum, "valid" if image.checksum == checksum else "invalid!")

    elif args.operation == "make_image":
        image = ESPFirmwareImage()
Beispiel #14
0
 def onterminal(self, event, shell):
     from terminal import terminal
     ter = terminal(event, shell)
     ter.ShowModal()
     ter.Destroy()
Beispiel #15
0
    def add_custom(self, arg):
        """Add a custom entry to database.

        Examples:
            add name, tag,...,tag: trait,value,unit ...
            add name: trait,value trait,value,unit ...
            add name, tag,...,tag
            add name
            add
        """

        name = None
        tags = None
        attributes = None

        if len(arg.strip()) != 0:
            arg = arg.split(":")
            if len(arg) == 1:
                name_tags, attributes = arg[0], None
            elif len(arg) == 2:
                arg[1] = arg[1].strip()
                if len(arg[1].split()) == 0:
                    arg[1] = None
                name_tags, attributes = arg[0], arg[1]
            else:
                print("Malformed command 1")
                return

            name_tags = name_tags.split(",", 1)
            if len(name_tags) == 1:
                name = name_tags[0]
                tags = None
            else:
                name = name_tags[0]
                tags = [
                    tag.strip() for tag in name_tags[1].split(",")
                    if len(tag.strip()) != 0
                ]
                if len(tags) == 0:
                    tags = None

            if attributes is not None:
                attributes = attributes.split(" ")
                for i, attribute in enumerate(attributes):
                    attribute = [
                        trait.strip() for trait in attribute.split(",")
                        if len(trait.strip()) != 0
                    ]
                    if len(attribute) == 2:
                        attributes[i] = (attribute[0],
                                         self._float_eval(attribute[1]), None)
                    elif len(attribute) == 3:
                        if len(attribute[2].strip()) == 0:
                            attribute[2] = None
                        attributes[i] = (attribute[0],
                                         self._float_eval(attribute[1]),
                                         attribute[2])
                    else:
                        print("Malformed command 3")
                        return

        with terminal.terminal() as term:
            while name is None:
                name = str(
                    term.input("Enter entry name: ",
                               self._tabcomplete_name())).strip()
                if len(name) == 0:
                    name = None

            if tags is None:
                tags = str(
                    term.input("Enter tags(comma separated): ",
                               self._tabcomplete_tag(name))).strip()
                tags = [
                    tag.strip() for tag in tags.split(",")
                    if len(tag.strip()) != 0
                ]

            if attributes is None:
                attributes = []
                while True:
                    attribute = str(
                        term.input(
                            "Enter attribute, leave blank if finished. format 'Name,value,[unit]'\nattribute: "
                        ))
                    attribute = [
                        trait.strip() for trait in attribute.split(",")
                        if len(trait.strip()) != 0
                    ]

                    if len(attribute) == 0:
                        break
                    elif len(attribute) == 2:
                        attributes.append(
                            (attribute[0], self._float_eval(attribute[1]),
                             None))
                    elif len(attribute) == 3:
                        if len(attribute[2].strip()) == 0:
                            attribute[2] = None
                        attributes.append(
                            (attribute[0], self._float_eval(attribute[1]),
                             attribute[2]))
                    else:
                        term.print("Malformed command 4")
                        return

        new_entry = groceryDatabase.entry(name, tags)
        for name, value, unit in attributes:
            new_attribute = groceryDatabase.attribute(name, value, unit)
            new_entry.add_attribute(new_attribute)

        self.database.add_entry(new_entry)
        self.database.update()
Beispiel #16
0
    def add(self, arg):
        """Add a food entry to database.

        Examples:
            add name, tag,...,tag
            add name
            add
        """

        name = None
        tags = None
        attributes = []

        if len(arg.strip()) != 0:
            arg = arg.split(",", 1)
            if len(arg) == 1:
                name = arg[0]
                tags = None
            else:
                name = arg[0]
                tags = [
                    tag.strip() for tag in arg[1].split(",")
                    if len(tag.strip()) != 0
                ]
                if len(tags) == 0:
                    tags = None

        with terminal.terminal() as term:
            while name is None:
                name = str(
                    term.input("Enter entry name: ",
                               self._tabcomplete_name())).strip()
                if len(name) == 0:
                    name = None

            if tags is None:
                tags = str(
                    term.input("Enter tags(comma separated): ",
                               self._tabcomplete_tag(name))).strip()
                tags = [
                    tag.strip() for tag in tags.split(",")
                    if len(tag.strip()) != 0
                ]

            attributes.append(
                ("price",
                 self._float_eval(
                     term.input(
                         "Enter price: ",
                         self._tabcomplete_attribute(name, tags,
                                                     "price"))), "dollars"))

            while True:
                reply = str(
                    term.input("Did you buy more than one[y/n]: ")).lower()
                if reply.startswith("y"):
                    attributes.append(("quantity",
                                       self._float_eval(
                                           term.input(
                                               "Enter quantity: ",
                                               self._tabcomplete_attribute(
                                                   name, tags,
                                                   "quantity"))), None))
                    break
                elif reply.startswith("n"):
                    break

            while True:
                reply = str(
                    term.input("Mesure by mass or volume[m/v]: ")).lower()
                if reply.startswith("m"):
                    attributes.append(("mass",
                                       self._float_eval(
                                           term.input(
                                               "Enter mass in grams: ",
                                               self._tabcomplete_attribute(
                                                   name, tags, "mass"))), "g"))
                    break
                elif reply.startswith("v"):
                    attributes.append(("volume",
                                       self._float_eval(
                                           term.input(
                                               "Enter volume in milliliters: ",
                                               self._tabcomplete_attribute(
                                                   name, tags,
                                                   "volume"))), "ml"))
                    break
                elif reply.strip() == "":
                    # skip if empty
                    break

            try:
                attributes.append(
                    ("calories",
                     self._float_eval(
                         term.input(
                             "Enter calories in calories per 100 grams: ",
                             self._tabcomplete_attribute(
                                 name, tags, "calories"))), "calories/100g"))
            except:
                pass  # skip if empty

            try:
                attributes.append(
                    ("fat",
                     self._float_eval(
                         term.input(
                             "Enter fat in grams per 100 grams: ",
                             self._tabcomplete_attribute(name, tags,
                                                         "fat"))), "g/100g"))
            except:
                pass

            try:
                attributes.append(
                    ("carbohydrates",
                     self._float_eval(
                         term.input(
                             "Enter carbohydrates in grams per 100 grams: ",
                             self._tabcomplete_attribute(
                                 name, tags, "carbohydrates"))), "g/100g"))
            except:
                pass

            try:
                attributes.append(
                    ("protein",
                     self._float_eval(
                         term.input(
                             "Enter protein in grams per 100 grams: ",
                             self._tabcomplete_attribute(
                                 name, tags, "protein"))), "g/100g"))
            except:
                pass

        new_entry = groceryDatabase.entry(name, tags)
        for name, value, unit in attributes:
            new_attribute = groceryDatabase.attribute(name, value, unit)
            new_entry.add_attribute(new_attribute)

        self.database.add_entry(new_entry)
        self.database.update()
Beispiel #17
0
import pygame
import fractal as frc
import terminal as trm

pygame.init()
disp = pygame.display.set_mode([400, 400])
pygame.display.set_caption("Fractal")

fractal = frc.frac(disp, 200, 200, 150, (0, 0, 0), 6)

terminal = trm.terminal("fractal")

while True:
    fractal.generate_batch()
    disp.fill((255, 255, 255))
    fractal.draw_batch()
    pygame.display.update()
Beispiel #18
0
def reset(args):
    fractal.Xfractal = [[fractal.x]]
    fractal.Yfractal = [[fractal.y]]
    fractal.colors = [[fractal.color]]
    fractal.Xfrac = [fractal.Xfractal[-1][-1]]
    fractal.Yfrac = [fractal.Yfractal[-1][-1]]
    fractal.colr = [fractal.color]


def set_window_size(args):
    x = int(args[0])
    y = int(args[1])
    pygame.display.set_mode([x, y])


terminal = term.terminal("fractal-console")
terminal.add_command("add", term.add)
terminal.add_command("sub", term.sub)
terminal.add_command("keys", keys)
terminal.add_command("radius", set_radius)
terminal.add_command("setxy", set_xy)
terminal.add_command("points", set_points)
terminal.add_command("frpoints", set_fractal_points)
terminal.add_command("color", set_color)
terminal.add_command("addp", add_points)
terminal.add_command("undo", undo)
terminal.add_command("list", lis)
terminal.add_command("drawp", draw_points)
terminal.add_command("draw", draw)
terminal.add_command("bgcol", set_bg)
terminal.add_command("gen", gen_points)
Beispiel #19
0
    def __init__(self, parent):
        self.parent = parent
        self.parent.module_treeview = modules.treeview(self.parent)
        self.parent.workflow_treeview = workflows.treeview(self.parent)
        self.parent.workflow_list = self.parent.workflow_treeview.lis
        self.parent.tabs = self.parent.module_treeview.notebook_manager.tabs

        self.parent.console = self.parent.builder.get_object("ConsoleNotebook")
        self.parent.notebook = self.parent.builder.get_object("ModuleNotebook")

        self.parent.message_tree_class = general_tree.treeview(self.parent)
        self.parent.message_tree = self.parent.message_tree_class.treeview
        self.parent.message_box = self.parent.builder.get_object("message_box")
        self.parent.message_box.pack_start(self.parent.message_tree, True,
                                           True, 0)
        self.parent.message_tree_class.store.append(
            None, ['sudoSU started normally \U0001f60A'])

        self.parent.module_box = self.parent.builder.get_object("module_box")
        self.parent.module_box.pack_start(self.parent.module_treeview.vbox,
                                          True, True, 0)

        self.parent.workflow_box = self.parent.builder.get_object(
            "workflow_box")
        self.parent.workflow_box.pack_start(self.parent.workflow_treeview.vbox,
                                            True, True, 0)
        # self.parent.workflow_box.pack_start(Gtk.Label(label="Cool Stuff coming up... \U0001f60A"),True,True,0)

        self.parent.commands_tree_class = general_tree.treeview(self.parent)
        self.parent.commands_tree = self.parent.commands_tree_class.treeview
        self.parent.commands_box = self.parent.builder.get_object(
            "commands_box")
        self.parent.commands_box.pack_start(self.parent.commands_tree, True,
                                            True, 0)

        self.parent.terminal = terminal.terminal(self.parent)
        self.parent.terminal_box = self.parent.builder.get_object(
            "terminal_tab")
        self.parent.terminal_box.pack_start(self.parent.terminal.main_box,
                                            True, True, 0)

        self.parent.target = self.parent.builder.get_object("selected_files")
        self.parent.target.drag_dest_set(Gtk.DestDefaults.ALL, [], DRAG_ACTION)
        self.parent.target.connect("drag-data-received",
                                   self.parent.on_drag_data_received)
        self.parent.iconview = draganddrop.DragSourceIconView()
        self.parent.iconview.refresh(home + "/sudoSU/Projects/")

        self.parent.dest = self.parent.builder.get_object("dest")
        self.parent.source = self.parent.builder.get_object("source")
        self.parent.vbox = self.parent.builder.get_object("vbox")

        self.parent.source.pack_start(self.parent.iconview, True, True, 0)
        self.parent.add_image_targets()
        self.parent.add_text_targets()
        """to add the treview file exporer)"""
        # self.fex = file_explorer.treeview(self)
        # self.parent.source.pack_start(self.fex.vbox, True, True,0)

        self.parent.selected_files = self.parent.builder.get_object(
            "selected_files")
        self.parent.file_label = Gtk.Label()
        self.parent.file_label.set_xalign(0)
        self.parent.selected_files.pack_start(self.parent.file_label, False,
                                              False, 0)
Beispiel #20
0
def tzara(string):
    """
    Searches the input string for keywords, or commands.
    If keywords are found, it calls appropriate function.
    List of functions:
    (1) Open (website, pdf, folder, terminal, reminder)
    (2) Play (movies, songs)
    (3) Tell the time.
    (4) Google, or search for a string online.
    (5) Close (tab, song, movie, pdf)
    (6) Mail (read, send)
    (7) Shutdown
    (8) Reminder
    """
    #Splitting each sentence in a list of words.
    word_list = word_tokenize(string)

    #Setting up stop_words: words that are redundant.
    stop_words = set(stopwords.words('english'))

    #Creating space for a list of sentences without stop_words.
    if "search" not in word_list and "google" not in word_list:
        filtered_sentence = [w for w in word_list if not w in stop_words]
    else:
		filtered_sentence = [w for w in word_list]
   
    if 'open' in filtered_sentence:
        #OPEN WEBSITE
        if 'site' in filtered_sentence:
            print "in function"
            filtered_sentence = [w for w in filtered_sentence \
                if w != "called" and w != "named"]
            firefox.fn_open_site( \
                filtered_sentence[filtered_sentence.index('site') + 1])
        elif 'website' in filtered_sentence and \
            filtered_sentence.index('open') \
                < filtered_sentence.index('website'):
            firefox.fn_open_site( \
                filtered_sentence[filtered_sentence.index('website') + 1])

        #OPEN PDF
        elif 'pdf' in filtered_sentence and \
            filtered_sentence.index('open') \
                < filtered_sentence.index('pdf'):
            filtered_sentence = \
                [w for w in filtered_sentence \
                    if w != "called" and w != "named"]
            fn_open_pdf(filtered_sentence[filtered_sentence.index('pdf') + 1])

        #OPEN FOLDER
        elif 'folder' in filtered_sentence and \
            filtered_sentence.index('open') \
                < filtered_sentence.index('folder'):
            if "called" in string:
                pos = string.index("called") + 7
                string = string[pos:]
            elif "named" in string:
                pos = string.index("named") + 6
                string = string[pos:]
            else:
                pos = string.index("folder")+7
                string = string[pos:]
            open_folder(string)

       #OPEN TERMINAL
        elif 'terminal' in filtered_sentence and \
            filtered_sentence.index('open') \
            < filtered_sentence.index('terminal'):
            terminal.terminal()

        #OPEN REMINDER
        elif 'reminder' in filtered_sentence:
            reminder.reminder()

        elif len(filtered_sentence) > 1:
            sites_path = os.getcwd() + "/Text_Files/comn_sites.txt"
            f_sites = open(sites_path, "r")     
            for line in f_sites:
                name_list = line.strip().split("-")
                #if (n.lower()==''.join(name_list[0:1]).lower()):
                #    counter=1
                #    email_id=''.join(name_list[1:2])
                pos = filtered_sentence.index('open')+1
                if ''.join(filtered_sentence[pos]).lower() \
                    in ''.join(name_list[0:1]).lower():
                    print ''.join(name_list[1:2])
                    firefox.fn_open_site(''.join(name_list[1:2]))
            f_sites.close()

        else:
            speak("You want me to open something,"
                "but I'm not sure what. Could you please repeat?")

    elif 'terminal' in filtered_sentence:
        speak("Would you like me to open the terminal for you?")
        reply = raw_input('\033[1m'+'Username: '******'\033[0m') #modify
        if confirm(reply) == 1:
            terminal.terminal()
        else:
            speak("As you wish.")

    elif 'movie' in filtered_sentence:
        #PLAY MOVIE
        filtered_sentence = [w for w in filtered_sentence \
            if w != "called" and w != "named" and w != "titled"]
        pos = filtered_sentence.index('movie') + 1
        fn_movie(filtered_sentence[pos])

        #PLAY SONG
    elif 'song' in filtered_sentence and filtered_sentence.index('play') \
        < filtered_sentence.index('song'):
        filtered_sentence = [w for w in filtered_sentence \
            if w != "called" and w != "named" and w != "titled"]
        pos = filtered_sentence.index('song') + 1
        fn_play_song(filtered_sentence[pos])

    elif 'time' in filtered_sentence:
        speak(time.strftime("%A") + " " \
            + str(datetime.datetime.now())[:16])

    elif 'google' in filtered_sentence:
        if len(filtered_sentence) > 1:
            pos = filtered_sentence.index('google') + 1
            if 'word' in filtered_sentence \
                and filtered_sentence[-1] != 'word':
                filtered_sentence = \
                    [w for w in filtered_sentence if w != "word"]

            search_string = ''.join(filtered_sentence[pos:])
            firefox.fn_search(search_string)
        else:
            speak("If you want me to open google, say 'open google'")
            speak("If you want me to search for a word,"
                "say 'google <word>'")

    elif 'search' in filtered_sentence:
        if filtered_sentence[-1] == "search":
            speak("Enter the word you would like me to search.")
            search_string = raw_input('\033[1m' + 'Username: '******'\033[0m')     #modify
            firefox.fn_search(search_string)
            return
        pos = filtered_sentence.index('search') + 1
        search_string = " ".join(filtered_sentence[pos:])
        firefox.fn_search(search_string)

    elif 'reminder' in filtered_sentence:
        speak("Opening reminder")
        reminder.reminder()

    elif 'close' in filtered_sentence:
        if 'tab' in filtered_sentence:
            firefox.fn_close_tab()
            speak('There you go!')
        if 'song' in filtered_sentence:
            fn_close_song()
        if 'movie' in filtered_sentence:
            fn_close_movie()
        if 'pdf' in filtered_sentence:
            fn_close_pdf()
        else:
            speak("I figure you want me to close something,"
                "but I'm not sure what!")

    elif 'ping' in filtered_sentence:
        firefox.ping()

    elif 'mail' in filtered_sentence:
        if 'read' in filtered_sentence or \
            'unread' in filtered_sentence or \
            'check' in filtered_sentence or \
            'see' in filtered_sentence:
            firefox.fn_read_mail()
        elif filtered_sentence[-1] != 'mail':
            pos = filtered_sentence.index('mail') + 1
            firefox.fn_write_mail(filtered_sentence[pos])
        elif filtered_sentence[-1] == 'mail':
            speak("Whom would you like to mail?")
            reply = raw_input('\033[1m' + 'Username: '******'\033[0m') #modify
            firefox.fn_write_mail(reply)
        else:
            speak("Do you want to mail somebody?"
                " Then type: 'mail person's_name'")
            speak("Or do you want to read your emails?"
                "Then simply type: 'read mail'")

    elif 'shutdown' in filtered_sentence:
        speak("Would you like me to shutdown the system?")
        reply = raw_input('\033[1m' + 'Username: '******'\033[0m')     #modify
        if confirm(reply) == 1:
            speak("Shutting down system now. Goodbye!")
            os.system("sudo shutdown -h now")
        else:
            speak("As you wish.")

    else:
        speak(converse(string))
    return None
Beispiel #21
0
    "BUR": "#009933",
    "BUT": "#009933",
    "IHS": "#009933",
    "BBOT": "#009933",
    "FW": "#009933",
    "BER": "#CC3300",
    "BET": "#CC3300",
    "BTOP": "#CC3300",
    "FC": "#CC3300",
    "HS": "#CC3300",
    "RW": "#CC3300",
}

if __name__ == "__main__":
    likCache = tempfile.NamedTemporaryFile()
    data = terminal("aapl", likCache.name, alpha=-3.0)
    parser = qcyk()
    parser.initGrammar("test.gr")
    parser.initTerminal(likCache.name)
    lik, tree = parser.parse()
    likCache.close()

    print parser.pretty_print_tree(tree)
    print lik

    fig = plt.figure(figsize=(12, 5))
    ax = fig.add_subplot(111)
    kps = data[data.pivots != 0].Close
    idx = kps.index
    kps.plot(style="--o", ax=ax)
    for t, xmin, xmax in parser.leafs(tree):
Beispiel #22
0
                        metavar="terminal_id")
    args = vars(parser.parse_args())
    input_id = args['terminal_id']

    # Iterate over id list
    for get_id in input_id:
        # Request to get terminal data
        response = requests.get(
            'https://api.tport.online/v2/public-stations/%s' % get_id)
        json_response = response.json()
        response_code = response.status_code
        # If response code is not 200, skip this if with an error
        if response_code != 200:
            print(
                "Could not get terminal info by id. Id is: %s. Response code: %s"
                % (str(get_id), str(response_code)))
            continue
        # Initialise terminal object with json data
        current_terminal = terminal(json_response)
        status = current_terminal.get_status()
        print("Current terminal id is %s. Current terminal status is %s" %
              (str(get_id), str(status)))
        # Check if terminal is working right now
        is_working = current_terminal.is_working()
        if is_working == 1:
            print("Current terminal is working at this hours")
        elif is_working == 0:
            print("Current terminal is not working at this hours")
        else:
            print("Working hours data is not find for current terminal")
Beispiel #23
0
 def __init__(self):
     
     self.X=20
     self.Y=20
     
     self.px = 0
     self.py = 0
     self.pt = ''
     self.ps = ''
     
     self.bg = {}
     self.pc = {}
     
     self.P = 0
     
     self.originalClockTime = .6
     self.clockTime = .6
     
     self.terminal = terminal()
     
     self.brick  = u'█'*2 
     
     self.wall  = self.terminal.setColor(self.brick, 'Cyan'  ) 
     self.blank = self.terminal.setColor(self.brick, 'Black' ) 
     
     self.pices = {
         'O' : {
             'up':{
                 0:[0,1],
                 1:[0,1]
             },
             'color':"Red"
         }, 
         'I' : {
             'up':{
                 0:[0],
                 1:[0],
                 2:[0],
                 3:[0]
             },
             'right':{
                 1:[-1, 0, 1, 2]
             },
             'down':{
                 0:[0],
                 1:[0],
                 2:[0],
                 3:[0]
             },
             'left':{
                 1:[-1, 0, 1, 2]
             },
             'color':"Green"
         },
         'L' : {
             'up':{
                 0:[0],
                 1:[0],
                 2:[0,1],
             },
             'color':"Yellow"
         },
         'Z' : {
             'up':{
                 0:[0,1],
                 1:[1,2]
             },
             'color':"Blue"
         },
         'S' : {
             'up':{
                 0:[2,3],
                 1:[1,2]
             },
             'color':"Magenta"
         },
         'T' : {
             'up':{
                 0:[1,2,3],
                 1:[2]
             },
             'color':"White"
         }
     }
     
     _thread.start_new_thread( self.teclado, () )
     
     self.startCene()
     self.novaPeca()