示例#1
0
def __make_interface_files(command_line, codegen_service):
    sub_path0 = "src"

    # For each interface generate service and client .java Interface files.
    for key in sorted(codegen_service.interfaces):
        i = codegen_service.interfaces[key]
        __make_interface_arg_info(i)

        sub_path1 = __get_interface_subdirectory(i)

        # If client only don't generate the service files.
        if not command_line.client_only:
            temp = Interface()
            temp.interface = i

            service_path = os.path.join("Service", sub_path0, sub_path1)
            filename = "{0}.java".format(i.interface_name)

            full_filename = os.path.join(service_path, filename)
            __make_target_file(temp, full_filename, command_line,
                               codegen_service)

            temp = ServiceImplementation()
            temp.interface = i

            service_path = os.path.join("Service", sub_path0, sub_path1)
            filename = "{0}Impl.java".format(i.interface_name)

            full_filename = os.path.join(service_path, filename)
            __make_target_file(temp, full_filename, command_line,
                               codegen_service)

        temp = Interface()
        temp.interface = i

        client_path = os.path.join("Client", sub_path0, sub_path1)
        filename = "{0}.java".format(i.interface_name)

        full_filename = os.path.join(client_path, filename)
        __make_target_file(temp, full_filename, command_line, codegen_service)

        if i.signals:
            temp = ClientImplementation()
            temp.interface = i

            service_path = os.path.join("Client", sub_path0, sub_path1)
            filename = "{0}Impl.java".format(i.interface_name)

            full_filename = os.path.join(client_path, filename)
            __make_target_file(temp, full_filename, command_line,
                               codegen_service)

    return
    def fetchAndSaveUrl(self, url='', bit=1):
        ok = True
        if len(url) == 0:
            url, ok = QtGui.QInputDialog.getText(self, 'Link',
                                                 'Download Link:',
                                                 QtGui.QLineEdit.Normal, '',
                                                 QtCore.Qt.FramelessWindowHint)
        if ok == True:
            key = self.freeKey()
            if key == -1:
                obj = Interface(self.PARTS)
                key = self.links
                self.links = self.links + 1
            else:
                obj = self.dLoads[key]
                obj.PARTS = self.PARTS
                obj.clear()
                del self.dLoads[key]

            thread.start_new_thread(obj.start_Download,
                                    (url, self.wMutex, bit))
            self.dLoads[key] = obj
        else:
            msg = QtGui.QMessageBox(QtGui.QMessageBox.Warning, 'Oops.',
                                    "Not a valid Url ", QtGui.QMessageBox.Ok,
                                    self, QtCore.Qt.FramelessWindowHint)
            msg.show()
示例#3
0
def main():
    msg = WhatIsMessage()

    # The hidden prepend keyword of the text input also includes
    # double-quotes so that left whitespace is not stripped by the
    # server.
    if msg and msg.startswith("\""):
        msg = msg[1:]

    Logger("CHAT", "Console: {}: {}".format(activator.name, msg))

    console = console_find(activator)

    if msg == "exit()":
        if console:
            console_remove(activator)
            inf = Interface(activator, None)
            inf.dialog_close()

        return

    if not console:
        console = console_create(activator)

    console.push(msg)

    if not msg:
        console.show()
 def __init__(self, parent=None):
     super(MainWindow, self).__init__(parent)
     self.ui = Interface()
     self.ui.UI_Setup(self)
     self.list = []
     self.flag = 0
     self.ui.pushButton.clicked.connect(self.trigger)
示例#5
0
    def __init__(self,
                 port,
                 baud_rate=19200,
                 parity=serial.PARITY_NONE,
                 stop_bits=serial.STOPBITS_ONE,
                 byte_size=serial.EIGHTBITS,
                 timeout=1,
                 write_timeout=5):

        # get logger
        self.log = logging.getLogger('get_UART')

        # get interface
        self.interface = Interface()

        # Get PICom
        self.pic_com = PICom()

        self.serial_com = None

        self.port = port
        self.baud_rate = baud_rate
        self.parity = parity
        self.stop_bits = stop_bits
        self.byte_size = byte_size
        self.timeout = timeout
        self.write_timeout = write_timeout
示例#6
0
    def __init__(self, argv):

        # init, initialization class
        self.init = Init(argv)

        # Get logger from Init class
        self.log = logging.getLogger('get_UART')

        # Serial com variable definition
        self.serial_com = UART(port=self.init.get_serial_port())

        # System class
        self.system = System()

        # Is UART init a program beginning
        self.init_UART_bit = self.init.get_init_UART_bit()

        # Define interface class
        self.interface = Interface()

        # Plot curve class
        self.plot_curve_class = PlotCurve()

        # Temp data
        self.temp_data_tab = []
示例#7
0
    def insert_dicionarios(self, myJson):  #myJson == []
        # dic {}
        # list []
        insercoes = []
        atualizacoes = []
        delete_list = []
        #myJson is a list
        sendAlert = EnviarNotificacao()
        myJson = json.loads(myJson)
        for dicio in myJson:
            if str(dicio["type_log"]) == 'INSERT':
                insercoes.append(dicio)
            elif str(dicio["type_log"]) == 'DELETE':  #Só id
                delete_list.append(str(dicio["id_produto"]))  #lista de ids
            else:
                atualizacoes.append(dicio)

        print(insercoes)
        print(atualizacoes)
        print(delete_list)
        MyInterface = Interface()
        error = MyInterface.realiza_operacoes_atualizacao_bd(
            insercoes, atualizacoes, delete_list)
        if error is not None:
            print(error)
            pass
            #sendAlert.enviarEmail(error)

        #saving the last value read at or json
        if len(myJson) == 0:
            return
        last_dicio = myJson[-1]
        with open("the_last_logid.txt", "w", encoding='utf-8') as f:

            f.write(str(last_dicio["id_log"]))
    def addLoadedDevice(self, deviceLoad):
        if deviceLoad.deviceType == 'router':
            device = Device('router.jpg', deviceLoad.deviceName, 'router',
                            self)
        else:
            device = Device('computer.jpg', deviceLoad.deviceName, 'computer',
                            self)
        device.move(deviceLoad.position)
        device.show()
        device.deviceType = deviceLoad.deviceType
        device.routageTable = deviceLoad.routageTable
        device.interfaceList = []
        for interfaceLoad in deviceLoad.interfaceList:
            interface = Interface('point.png', interfaceLoad.interfaceName,
                                  self, device)
            interface.ip = interfaceLoad.ip
            interface.network = interfaceLoad.network
            device.interfaceList.append(interface)
        device.drawInterface()
        self.deviceList.append(device)

        try:
            self.detailsWindow.updateDetails()
        except Exception as e:
            pass
示例#9
0
 def __init__(self, argv):
     self.markets = []
     marketFileDefined = 0
     try:
         opts, args = getopt.getopt(argv, "hv", ["help", "verbose", "markets=", "testmode="])
     except getopt.GetoptError:
         self.ExitUsage(1, "Bad arguments.")
     for opt, arg in opts:
         if opt in ("-h", "--help"):
             self.ExitUsage()
         elif opt in ("-v", "--verbose"):
             Globales.verbose = 1
         elif opt == "--markets":
             marketFileDefined = 1
             self.marketFile = arg
             try:
                 f = open(self.marketFile, "r")
                 for line in f:
                     infos = line.split()
                     if infos[0][0] != '#':
                         self.markets.append(Market(self, infos[0], infos[1], infos[2]))
             except IOError as e:
                 self.ExitUsage(1, "Bad arguments. Failed to open the markets description file.")
         elif opt == "--testmode":
             Globales.testMode = 1
             Globales.testModeFile = arg
     if marketFileDefined == 0:
         self.ExitUsage(1, "Bad arguments. Please define a markets description file.")
     self.interface = Interface(self)
示例#10
0
文件: Main.py 项目: wuyx/mms
def main():

    # Print the usage
    if not 3 <= len(sys.argv) <= 4:
        print("Usage: python Main.py <WIDTH> <HEIGHT> [<SEED>]")
        return

    # Read the width and height args
    width = int(sys.argv[1])
    height = int(sys.argv[2])
    if width <= 0 or height <= 0:
        print("Error: <WIDTH> and <HEIGHT> must be positive integers")
        return

    # Read the seed arg
    if len(sys.argv) == 4:
        seed = int(sys.argv[3])
        if seed < 0:
            print("Error: <SEED> must be a non-negative integer")
            return
        random.seed(seed)

    # Generate an empty maze
    maze = [[{c: False
              for c in 'nesw'} for j in range(height)] for i in range(width)]

    interface = Interface(maze)
    Algo().generate(interface)

    if interface.success:
        Printer.print_to_stderr(maze)
    def __init__(self):
        self.clock = 0.0  # Reloj de la simulacion
        self.number_of_runs = 0  # Cantidad de veces a ejecutar la simulacion
        self.simulation_time = 0.0  # Tiempo de simulacion por corrida
        self.max = 0.0  # Valor utilizado como infinito (se cambia a 4 * Tiempo de simulacion)
        self.x1_probability = 0.0  # Probabilidad de X1
        self.x2_probability = 0.0  # Probabilidad de X2
        self.x3_probability = 0.0  # Probabilidad de X3

        self.distribution_list = {}  # Contiene D1, D2, D3, D4, D5 y D6
        self.event_list = {}  # Contiene la lista de eventos para programar
        self.message_list = [
        ]  # Contiene todos los mensajes que se crean en una corrida
        self.processor_list = [
        ]  # Contiene todos los procesadores utilizados en la simulacion
        self.LMC1_list = [
        ]  # Lista ordenada de mensajes que deben llegar a la computadora 1
        self.LMC2_list = [
        ]  # Lista ordenada de mensajes que deben llegar a la computadora 2
        self.LMC3_list = [
        ]  # Lista ordenada de mensajes que deben llegar a la computadora 3

        self.results = Results(
        )  # Objeto que contiene los resultados de cada corrida

        self.interface = Interface(
        )  # Instancia para utilizar la interfaz de consola
        self.computer_1 = None  # Instancia de la Computadora 1 de la Simulación
        self.computer_2 = None  # Instancia de la Computadora 2 de la Simulación
        self.computer_3 = None  # Instancia de la Computadora 3 de la Simulación
    def YoutubeLinkDownload(self):
        txt, ok = QtGui.QInputDialog.getText(self, 'YouTube Link',
                                             'YTube Link:',
                                             QtGui.QLineEdit.Normal, '',
                                             QtCore.Qt.FramelessWindowHint)
        if ok == True:
            if txt.startsWith('https://www.youtube.com'):
                key = self.freeKey()
                if key == -1:
                    obj = Interface(self.PARTS)
                else:
                    obj = self.dLoads[key]
                    obj.PARTS = self.PARTS
                    obj.clear()
                    del self.dLoads[key]

                thread.start_new_thread(obj.start_Download, (txt, self.wMutex))
                self.dLoads[self.links] = obj
                self.links = self.links + 1
            else:
                msg = QtGui.QMessageBox(QtGui.QMessageBox.Warning, 'Oops.',
                                        "Not a valid YTube Url ",
                                        QtGui.QMessageBox.Ok, self,
                                        QtCore.Qt.FramelessWindowHint)
                msg.show()
示例#13
0
 def __init__(self):
     self.interface = Interface()
     self.config = Config()
     self.images = Images(self.config.get('Images', 'dir'), self.interface)
     self.imageList = self.images.getFileList()
     if len(self.imageList) == 0:
         raise Exception('There are no images to scythe')
示例#14
0
 def __init__(self):
     '''Инициализация модуля
     
     Выполняется инициализация интерфейса, логгера и статуса соединения
     Определяется операционная система и задаются соответствующие пути 
     '''
     self.view = Interface(self)
     self.logger = logging.getLogger('RocketOne.Connector')
     self.connected = False
     # Пути до OpenVPN
     if os.name == "nt":
         #Windows paths
         self.ovpnpath = 'C:\\Program Files (x86)\\OpenVPN'
         self.path = getBasePath() + '/'
         self.ovpnconfigpath = self.ovpnpath + '\\config\\'
         self.configfile = 'config.ini'  # self.ovpnconfigpath +
         self.ovpnexe = self.ovpnpath + '\\bin\\openvpnserv.exe'
         self.traymsg = 'OpenVPN Connection Manager'
         self.logger.debug("Started on Windows")
     elif os.name == "posix":
         #Linux Paths
         self.ovpnpath = ''
         self.path = getBasePath() + '/'
         self.ovpnconfigpath = self.ovpnpath + '//home//alexei//SOLOWAY//'
         self.ovpnexe = self.ovpnpath + 'openvpn'
         self.configfile = 'config.ini'
         self.traymsg = 'OpenVPN Connection Manager'
         self.logger.debug("Started on Linux")
示例#15
0
def generate_RPC_functions(className):
    interface_obj = Interface()
    members_list = inspect.getmembers(interface_obj, predicate=inspect.ismethod)

    for i in range(len(members_list)):
        func_name = members_list[i][0]
        func_parameters = inspect.getargspec(members_list[i][1]).args
        func_parameters = func_parameters[1:len(func_parameters)]

        def innerFunc(self, *param_list):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            try:
                s.connect((ip, port))
                bundle_data = {}
                stack = traceback.extract_stack()
                filename, codeline, funName, text = stack[-2]
                func_name = text.split('(')[0].split('.')[1]
                bundle_data["function_name"] = func_name
                bundle_data["function_params"] = list(param_list)
                bytes_data = pickle.dumps(bundle_data)
                s.sendall(bytes_data)
                data_rcv = s.recv(1024*1024)
                loaded_data = pickle.loads(data_rcv)
                s.close()
                return loaded_data["response"]
            except:
                return "Error in Connection with the server!"


        innerFunc.__doc__ = "docstring for innerfunctions"
        innerFunc.__name__ = func_name
        setattr(className, innerFunc.__name__, innerFunc)
        func_parameters.clear()
示例#16
0
def main():

    app = wx.App()

    ui = Interface()
    ui.initialize()

    app.MainLoop()
示例#17
0
 def run(self):
     zip(self.words, self.weights, self.sentiments)
     self.interface = Interface(self.words, self.weights, self.sentiments)
     self.query = self.interface.get_query(self.words)
     self.interface.search(self.query, self.args)
     self.interface.score()
     self.interface.db.close()
     time.sleep(1)
示例#18
0
def threadJob(con):
    myInterface = Interface()
    recebe = con.recv(1024)
    entradas_da_url = recebe.decode()
    dicio_de_entradas = parsear(entradas_da_url)
    lista_de_id = myInterface.devolveNprodutosRecomendados(
        dicio_de_entradas[0], dicio_de_entradas[1])  #idusuario idproduto
    string_de_ids = str(lista_de_id)
    con.send((string_de_ids + "\n").encode())
示例#19
0
def main():
    match = re.match(r"((?:\")(.+)(?:\")|([^ ]+))"
            "( (removeall|(add|remove) ([^ ]+)|add))?", msg)

    if not match:
        activator.Controller().DrawInfo(
                "Usage: /cmd_permission <[]\"]player name[]\"]>",
                color = COLOR_WHITE)
        return

    player = match.group(2) or match.group(3)
    action = match.group(6) or match.group(5)
    cmd_permission = match.group(7)

    pl = FindPlayer(player)

    if not pl:
        activator.Controller().DrawInfo("No such player.", color = COLOR_RED)
        return

    inf = Interface(activator, pl)

    if cmd_permission:
        cmd_permission = markup_unescape(cmd_permission)

    if action == "add":
        if cmd_permission:
            if not cmd_permission in pl.Controller().cmd_permissions:
                pl.Controller().cmd_permissions.append(cmd_permission)
            else:
                inf.add_msg("{pl.name} already has that permission.",
                        color = COLOR_RED, pl = pl)
        else:
            inf.set_text_input(prepend = "/cmd_permission {} add ".format(
                    pl.name))
    elif action == "remove":
        try:
            pl.Controller().cmd_permissions.remove(cmd_permission)
        except ValueError:
            inf.add_msg("{pl.name} does not have that permission.",
                    color = COLOR_RED, pl = pl)
    elif action == "removeall":
        pl.Controller().cmd_permissions.clear()

    inf.add_msg("{pl.name} has the following permissions:\n", pl = pl)

    for tmp in pl.Controller().cmd_permissions:
        if tmp:
            inf.add_msg("\n    {perm} [y=-2][a=:/cmd_permission "
                    "{pl.name} remove {perm}]x[/a]",
                    perm = markup_escape(tmp), newline = False, pl = pl)

    inf.add_link("Add permission",
            dest = "/cmd_permission {} add".format(pl.name))
    inf.add_link("Remove all permissions",
            dest = "/cmd_permission {} removeall".format(pl.name))
    inf.send()
示例#20
0
def threadJob(con):
    myInterface = Interface()
    recebe = con.recv(1024)
    stringincomleta = recebe.decode('latin_1')
    print("sugestão solicitada:" + stringincomleta)
    resposta = myInterface.retorne_sugestoes(stringincomleta)
    print("orignal do wesley:" + str(resposta))
    respostaFinal = str(resposta)
    con.send((respostaFinal + "\n").encode())
示例#21
0
def threadJob(con):
    myInterface = Interface()
    recebe = con.recv(1024)
    numero_de_resultados = recebe.decode()
    print("numero de resultados:" + numero_de_resultados)
    lista_de_id = myInterface.devolveRecomendacaoPaginaInicial(
        int(numero_de_resultados))
    print("orignal do wesley:" + str(lista_de_id))
    string_de_ids = str(lista_de_id)
    print("respota:" + string_de_ids)
    con.send((string_de_ids + "\n").encode())
示例#22
0
    def __init__(self):

        self._config    = Configuration()
        self._config.size_puzzle = 7 # Configuration to show a correctly tablet

        self._interface = Interface()
        self._state     = State()

        self._IA        = IA()

        #self._interface.printJungle(self._state.matrix)
        print self._state.statusHash()
示例#23
0
def terminal(request):
    i = Interface.Interface()
    u = HuntUser.objects.get(name=request.POST["huntUser"])
    c = HuntCommand(text=request.POST["command"],
                    user=u,
                    timestamp=timezone.now())
    c.save()
    if request.POST["command"] == "logout":
        return render(request, "index.html")
    output = i.process(request.POST["command"], request.POST["huntUser"])
    context = {"huntUser": request.POST["huntUser"], "output": output}
    return render(request, "terminal.html", context)
示例#24
0
    def ImportNewInterface(self):

        dataset = csv.reader(open(self.__file, 'r'))

        for data in dataset:

            nip = data[1]
            host = data[0]

            h = Host(self.__zapi, host, host_group_id=None)
            upd = Interface(self.__zapi, h.getHostID())
            upd.setInterface(nip)
示例#25
0
    def addInterface(self):
        name, ok = QInputDialog().getText(self, 'Add Interface',
                                          'Interface name:')
        if ok:
            interface = Interface('point.png', name, self.parent, self)
            self.interfaceList.append(interface)
            self.addInterfaceImage(interface)

        try:
            self.parent.detailsWindow.updateDetails()
        except Exception as e:
            pass
示例#26
0
    def processdata(self):
        dict1 = {}
        list1 = []

        CO2 = Interface("Co2.html")
        co2 = CO2.filtercarbondata()

        TEMP = Interface("Temperature.html")
        temp = TEMP.filterAnnualtemperature()
        for item, value in co2.items():
            if item not in dict1:
                for key, pair in value.items():
                    dict1[item] = {'year': item, 'Average': pair}
                    list1.append([int(item), int(pair)])

        for item, value in temp.items():
            # ======= Compreshension =======
            res1 = any(int(item) in sublist for sublist in list1)
            for key in value:
                if res1 == True:
                    dict1[item]['change'] = key[2]

        return dict1
示例#27
0
def terminal(request):
    i = Interface.Interface()
    u = User.objects.get(name='admin')
    #u = User.objects.get(name=(request.POST.get("User", 'admin'))) !!!!!!!!!!!!!!Don't supply with default value 'admin', needs rework
    strin = request.POST.get('prefix').split()
    j=1
    while request.POST.get(str(j)) != None:
        strin.append(request.POST.get(str(j)))
        j += 1
    print(strin)
    try:
        i.process(strin, u)
    except IntegrityError:
        pass
    context = {"User": u, "Games": Game.objects.all()}
    return render(request, "terminal.html", context)
示例#28
0
    def initScene(self):
        #Scene initialization
        self.scene = Scene(self)

        self.earth = self.scene.sys.earth.mod
        self.moon = self.scene.sys.moon.mod
        self.sun = self.scene.sys.sun.mod
        self.home = self.scene.home
        self.focus = self.scene.focus

        #camera manip and mode
        self.Camera = Camera(self)
        #mouse and keyboard inputs
        self.InputHandler = InputHandler(self)
        #Interface
        self.Interface = Interface(self)
示例#29
0
def addlandmark(request):
    command = request.POST["command"] + " " + request.POST["landmarkName"] + ", " + \
        request.POST["landmarkClue"] + ", " + request.POST["landmarkQuestion"] + \
        ", " + request.POST["landmarkAnswer"]
    print(command)
    i = Interface.Interface()
    u = HuntUser.objects.get(name=request.POST["huntUser"])
    c = HuntCommand(text=command, user=u, timestamp=timezone.now())
    c.save()
    i.process(command, request.POST["huntUser"])
    context = {
        "huntUser": request.POST["huntUser"],
        "landmarks": Landmark.objects.exclude(name="dummy"),
        "teams": HuntUser.objects.exclude(name="maker")
    }
    return render(request, "gamemaker.html", context)
示例#30
0
    def show (self, ac = None, append = None):
        inf = Interface(self.activator, self.activator)

        if ac is None:
            inf.set_title(self.activator.name + "'s Python Console")
            msg = markup_escape("\n".join(self.inf_data))
            inf.add_msg("[font=mono 12]{}[/font]".format(msg))
        else:
            inf.restore()

        inf.set_text_input(prepend = "/console \"", allow_tab = True,
                allow_empty = True, cleanup_text = False, scroll_bottom = True,
                autocomplete = "noinf::ac::",
                text = ac if ac else "")

        if append:
            inf.set_append_text("[font=mono 12]\n{}[/font]".format(append))

        inf.send()