Esempio n. 1
0
def set_thread_count(thread_count):
    try:
        ConfigFile.set_property("gnip.cfg", "HPT", "threadcount", thread_count)
        return {"result": "success"}
    except Exception as ex:
        handle_error(ex)
    return {"result": "failed"}
Esempio n. 2
0
def set_account_name(account_name):
    try:
        ConfigFile.set_property("gnip.cfg", "basic", "account", account_name)
        return {"result": "success"}
    except Exception as ex:
        handle_error(ex)
        return {"result": "failed"}
Esempio n. 3
0
def set_download_location(location):
    try:
        ConfigFile.set_property("gnip.cfg", "HPT", "destination", location)
        return {"result": "success"}
    except Exception as ex:
        handle_error(ex)
    return {"result": "failed"}
Esempio n. 4
0
 def setupBut(self, event):
   dlg=SetupDialog.SetupDialog(self, self.calcTime)
   dlg.ShowModal()
   self.calcTime=dlg.getData()
   cfgfile.setCalcTime(self.calcTime)
   dlg.Destroy()
   self.fillComboBoxes()
Esempio n. 5
0
def set_password(password):
    try:
        ConfigFile.set_property("gnip.cfg", "basic", "password", password)
        return {"result": "success"}
    except Exception as ex:
        handle_error(ex)
    return {"result": "failed"}
Esempio n. 6
0
def set_username(username):
    try:
        ConfigFile.set_property("gnip.cfg", "basic", "username", username)
        return {"result": "success"}
    except Exception as ex:
        handle_error(ex)
    return {"result": "failed"}
Esempio n. 7
0
 def onColResize(self, event):
   if self.ctrl_nr==1:
     visibleCols=(1, 2, 3, 4)
   elif self.ctrl_nr==2:
     visibleCols=(2, 3)
   else:
     return
   lst=[]
   for c in visibleCols:
     lst.append(self.list_ctrl.GetColumnWidth(c))
   cfgfile.setColWidth(self.ctrl_nr, lst)
Esempio n. 8
0
def checkConfigFile(conf):

    mail = ConfigFile.mail
    pwd = ConfigFile.pwd
    duration = ConfigFile.duration
    minDist = ConfigFile.mindist
    maxDist = ConfigFile.maxdist
    blackList = ConfigFile.blacklist

    keyList = [mail, pwd, duration, minDist, maxDist]
    ConfigFile.checkKeys(conf, keyList)

    keyList = [blackList]
    ConfigFile.checkKeys(conf, keyList, optional=True)
Esempio n. 9
0
def validate_files(url_list, uuid):
    try:
        file_count = 0
        valid_info = []
        error_status = []
        hpt_preferences = ConfigFile.get_settings("gnip.cfg", "HPT")
        validate_status = True
        print("Validating files in: " + hpt_preferences["destination"])
        activities_count = 0
        for url in url_list:
            file_count += 1
            # print ("#" + str(file_count), end=": ")
            print(".", end="")
            validate_status = validate_file(url, uuid,
                                            hpt_preferences["destination"])
            if "info" in validate_status:
                valid_info.append(validate_status)
                activities_count += validate_status["info"]["activity_count"]
            else:
                error_status.append(validate_status)
        print("")
        print("Done!")

        hpt_preferences = ConfigFile.get_settings("gnip.cfg", "HPT")
        directory = hpt_preferences["destination"]
        output = open(directory + uuid + "-validation.json", 'wb')
        output.write(json.dumps({"results": valid_info}))
        output.close()

        if len(error_status) > 0:
            output = open(directory + uuid + "-errors.json", 'wb')
            output.write(json.dumps({"results": error_status}))
            output.close()
        else:
            if os.path.isfile(directory + uuid + "-errors.json"):
                os.remove(directory + uuid + "-errors.json")

        return {
            "results": {
                "activities": activities_count,
                "errors": error_status
            }
        }

    except Exception as e:
        print("")
        handle_error(e)
        return {"results": {"errors": "Abnormally ended", "Message": str(e)}}
Esempio n. 10
0
def read_excel(file_name):

    data_path = cf.get_user_data()
    data_folder_path = join(data_path, 'data_1')

    data_files = listdir(data_folder_path)

    data = []

    if file_name is 'all':
        print('Read all')
        for i in range(len(data_files)):
            if splitext(data_files[i])[1] == '.xlsx':
                data.append(pd.read_excel(join(data_folder_path, data_files[i])))
                # data.append(pd.read_excel(join(data_folder_path, data_files[i]), index_col=0))

    elif type(file_name) is list:
        print('Read list')
        # read only the specified files (multiple)
        return
    elif type(file_name) is str:
        print('Read one')
        # read only the specified file (one)
        return

    return data
Esempio n. 11
0
    def __Decode_Command_Line(self, argv = [], definitions = {}, defaults = {}):
        result = {}
        line_opts, rest = getopt.getopt(argv, SHORT_OPTIONS, LONG_OPTIONS)

        for item in line_opts:
            opt, value = item

            # First trying "opt" value against options that use an argument.            
            if opt in ['-a', '--bind_adress']:
                opt = 'bind_adress'
            elif opt in ['-p', '--bind_port']:
                opt = 'bind_port'
            elif opt in ['-i', '--use_ident']:
                opt = 'use_ident'
                value = 1
            elif opt in ['-r', '--req_buf_size']:
                opt = 'req_buf_size'
            elif opt in ['-d', '--data_buf_size']:
                opt = 'data_buf_size'
            elif opt in ['-d', '--inactivity_timeout']:
                opt = 'inactivity_timeout'
            elif opt in ['-b', '--bind_timeout']:
                opt = 'bind_timeout'

            result[opt] = value

        return ConfigFile.evaluate(definitions, result, defaults)
Esempio n. 12
0
    def __init__(self, driver, stringDict={}, conf=None):
        "CONFIG"
        if conf == None:
            logging.info("%s Config file is None" %
                         driver.capabilities['deviceName'])
            conf = ConfigFile.Config()

        self._assertionDebug = conf.ASSERTION_DEBUG
        self.PACKAGE_NAME = conf.PACKAGE_NAME
        self.DEVICE_NAME = driver.capabilities['deviceName']
        self.driver = driver
        self.stringDict = stringDict
        self.midX = driver.get_window_size()['width'] // 2
        self.midY = driver.get_window_size()['height'] // 2
        self._content = 'android:id/content'
        self._alertTitle = 'android:id/alertTitle'
        self._message = 'android:id/message'
        self._button1 = 'android:id/button1'
        self._button2 = 'android:id/button2'
        self.webkit_class = 'android.webkit.WebView'
        self.n_test_cases = 0
        self.n_test_pass = 0
        self.n_test_fail = 0
        self.l_test_fail = list()
        self.tls = TestLink(conf.DEVKEY, conf.TESTLINK_URL,
                            str(conf.TESTPLANID), str(conf.BUILDID),
                            str(conf.PLATFORMID), conf.RESULTASSIGNMENT,
                            self.DEVICE_NAME)
        self.conf = conf
Esempio n. 13
0
def init():
	global initialized
	if (initialized):
		return
	for size in SIZES:
		parts[size] = {}
		configPath = os.path.join(os.path.dirname(__file__), "data", "parts_%s.cfg" % TYPE_ABBRS[size])
		configDict = ConfigFile.readFile(configPath)
		allReactors = []
		allThrusters = []
		allGyros = []
		for partName in configDict.keys():
			if (type(configDict[partName]) != type({})):
				continue
			parts[size][partName] = Part(configDict[partName])
			if (parts[size][partName].mass != 0):
				if (parts[size][partName].power < 0):
					allReactors.append((parts[size][partName], -parts[size][partName].power, parts[size][partName].mass))
				if (parts[size][partName].thrust > 0):
					allThrusters.append((parts[size][partName], parts[size][partName].thrust, parts[size][partName].mass))
				if (parts[size][partName].turn > 0):
					allGyros.append((parts[size][partName], parts[size][partName].turn, parts[size][partName].mass))
		reactors[size] = prioritizeByEfficiency(allReactors)
		thrusters[size] = prioritizeByEfficiency(allThrusters)
		gyros[size] = prioritizeByEfficiency(allGyros)
	initialized = True
Esempio n. 14
0
def checkConfigFile(conf):

    mail = ConfigFile.mail
    pwd = ConfigFile.pwd
    keyfilefolder = ConfigFile.keyfilefolder

    keyList = [mail, pwd, keyfilefolder]
    return ConfigFile.checkKeys(conf, keyList)
Esempio n. 15
0
def checkConfigFile(conf):

    mail = ConfigFile.mail
    pwd = ConfigFile.pwd
    keyfilefolder = ConfigFile.keyfilefolder
    duration = ConfigFile.duration

    keyList = [mail, pwd, keyfilefolder, duration]
    return ConfigFile.checkKeys(conf, keyList)
Esempio n. 16
0
  def __init__(self, parent, ctrl_nr=1):
    wx.Panel.__init__(self, parent, wx.ID_ANY, style=wx.WANTS_CHARS)
    self.parent=parent
    self.ctrl_nr=ctrl_nr

    self.lastSortOrder=cfgfile.getColSort(ctrl_nr)
    self.list_ctrl=MyListCtrl(self, style=wx.LC_REPORT|wx.BORDER_SUNKEN|wx.LC_SORT_ASCENDING)

    self.il=wx.ImageList(16, 16)
    self.c1iinfo= self.il.Add(wx.ArtProvider.GetBitmap(wx.ART_REPORT_VIEW,  wx.ART_OTHER, (16, 16)))
    self.empty=   self.il.Add(wx.EmptyBitmap(0, 0))
    self.c1ifile= self.il.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE,  wx.ART_OTHER, (16, 16)))
    self.c1ifldr= self.il.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER,       wx.ART_OTHER, (16, 16)))
    self.sm_up=   self.il.Add(wx.ArtProvider.GetBitmap(wx.ART_GO_UP,        wx.ART_OTHER, (16, 16)))
    self.sm_dn=   self.il.Add(wx.ArtProvider.GetBitmap(wx.ART_GO_DOWN,      wx.ART_OTHER, (16, 16)))
    self.errico=  self.il.Add(wx.ArtProvider.GetBitmap(wx.ART_ERROR,        wx.ART_OTHER, (16, 16)))

    colWidthList=cfgfile.getColWidth(self.ctrl_nr)
    # leere/unsichtbare Spalte anlegen, weil die Spalte0 Probleme mit der BMP-Darstellung hat
    self.list_ctrl.InsertColumn(0, '',                                    width=0)
    if self.ctrl_nr==1:
      self.list_ctrl.InsertColumn(1, 'path',                              width=colWidthList[0])
      self.list_ctrl.InsertColumn(2, 'name',                              width=colWidthList[1])
    elif self.ctrl_nr==2:
      self.list_ctrl.InsertColumn(1, '',                                  width=0)
      self.list_ctrl.InsertColumn(2, 'name',                              width=colWidthList[0])

    if self.ctrl_nr==1:
      self.list_ctrl.InsertColumn(3, 'size(real)',  wx.LIST_FORMAT_RIGHT, width=colWidthList[2])
      self.list_ctrl.InsertColumn(4, 'size(dest)',  wx.LIST_FORMAT_RIGHT, width=colWidthList[3])
      listmix.ColumnSorterMixin.__init__(self, 5)
    elif self.ctrl_nr==2:
      self.list_ctrl.InsertColumn(3, 'size(dest)',  wx.LIST_FORMAT_RIGHT, width=colWidthList[1])
      listmix.ColumnSorterMixin.__init__(self, 4)

    self.list_ctrl.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)
    self.list_ctrl.Bind(wx.EVT_LIST_COL_END_DRAG, self.onColResize)

    self.list_ctrl.SetImageList(self.il, wx.IMAGE_LIST_SMALL)

    sizer=wx.BoxSizer(wx.VERTICAL)
    sizer.Add(self.list_ctrl, 1, wx.EXPAND)
    self.SetSizer(sizer)
    self.SortListItems(self.lastSortOrder[0], self.lastSortOrder[1])
Esempio n. 17
0
def init():
	global initialized
	if (initialized):
		return
	Classes.init()
	configPath = os.path.join(os.path.dirname(__file__), "data", "profiles.cfg")
	configDict = ConfigFile.readFile(configPath)
	for profName in configDict.keys():
		if (type(configDict[profName]) != type({})):
			continue
		profiles[profName] = Profile(configDict[profName])
	initialized = True
Esempio n. 18
0
  def choose_destBut(self, event=0):
    lastProfile=cfgfile.getLastSelectedDestProfile()  # merken, um es bei NO im Folgedialog ggf. zurücksetzen zu können
    dlg=DestProfileCustomizationDialog.DestProfileCustomizationDialog(self, 
                                        self.targetFolder, self.size, self.blockSize, self.addblock)
    if dlg.ShowModal()!=wx.ID_OK:
      dlg.Destroy()
      return

    targetFolder, size, blockSize, addblock=dlg.getData()
    dlg.Destroy()
    if (self.blockSize>0 and self.blockSize!=blockSize) or (self.addblock!=None and self.addblock!=addblock):
      # Blocksize wurde verändert!!!
      if len(self.list_panel1.list_ctrl.data.obj)>0 or len(self.list_panel2.list_ctrl.data.obj)>0:
        # es befinden sich schon Objekte in mind. einem der ListCtrls
        rc=wx.MessageBox("Blocksize or filesystems changed!\nRemove all files from both lists?",
                          "Confirm", wx.YES_NO, self)
        if rc!=wx.YES:
          cfgfile.setLastSelectedDestProfile(lastProfile)
          return
        self.deleteAllFromListCtrl1(0)
        self.deleteAllFromListCtrl2(0)
        self.base_profile.SetValue("")

    self.targetFolder=targetFolder
    self.size=size
    self.blockSize=blockSize
    self.addblock=addblock
    self.__updateSum(self.list_panel1.list_ctrl, 1)
    self.__updateSum(self.list_panel2.list_ctrl, 2)

    self.blksize.SetValue(hlp.intToStringWithCommas(self.blockSize))
    self.targtFldr.SetValue(targetFolder)
    if self.isEmptyFolder(targetFolder)!=True:
      self.targtFldr.SetBackgroundColour("YELLOW")
      self.targtFldr.SetToolTip(wx.ToolTip("Folder not empty!"))
    else:
      self.targtFldr.SetBackgroundColour(wx.NullColor)
      self.targtFldr.SetToolTip(wx.ToolTip.Enable(False))

    self.enableListCtrl1()
Esempio n. 19
0
def init():
	global initialized
	if (initialized):
		return
	Parts.init()
	configPath = os.path.join(os.path.dirname(__file__), "data", "rooms.cfg")
	configDict = ConfigFile.readFile(configPath)
	rooms[EXTERIOR] = Room(EXTERIOR_CONFIG)
	for roomName in configDict.keys():
		if (type(configDict[roomName]) != type({})):
			continue
		rooms[roomName] = Room(configDict)
	initialized = True
Esempio n. 20
0
def init():
	global initialized
	if (initialized):
		return
	configPath = os.path.join(os.path.dirname(__file__), "data", "materials.cfg")
	configDict = ConfigFile.readFile(configPath)
	materials[EXTERIOR_DEFAULT] = Material(EXTERIOR_DEFAULT, EXTERIOR_CONFIG)
	materials[INTERIOR_DEFAULT] = Material(INTERIOR_DEFAULT, INTERIOR_CONFIG)
	for materialName in configDict.keys():
		if (type(configDict[materialName]) != type({})):
			continue
		materials[materialName] = Material(materialName, configDict[materialName])
	initialized = True
Esempio n. 21
0
def init():
	global initialized
	if (initialized):
		return
	configPath = os.path.join(os.path.dirname(__file__), "data", "dists.cfg")
	configDict = ConfigFile.readFile(configPath)
	for distName in configDict.keys():
		if (type(configDict[distName]) != type("")):
			continue
		probs = [float(x) for x in configDict[distName].split() if x]
		if (not probs):
			continue
		dists[distName] = Distribution(probs)
	initialized = True
Esempio n. 22
0
 def get_login_data(self):
     login_request_mode = "post"
     api = "%s/api/member/login" % ConfigFile().host()
     users_number = len(GetUsers().get_users())
     data = []
     for id in range(users_number):
         login = Login().login(GetUsers().get_mobile(id),
                               GetUsers().get_password(id))
         data.append([
             id + 1, login["description"], login_request_mode, api,
             login["mobile"], login["time"], login["status_code"],
             login["msg"]
         ])
     return data
Esempio n. 23
0
	def clickConnectButton(self):
		self.setup["host"]=self.host_le.text()
		self.setup["database"]=self.database_le.text()
		self.setup["user"]=self.user_le.text()
		self.setup["password"]=self.password_le.text()
		try:
			conn=DB.connect(self.setup)
			answer=messageDialog(title="Подключение завершено",\
				text="Подключение завершено. Сохранить настройки?",\
				yes="Да", no="Нет")
			if answer==1:
				b=True
				while b:
					if ConfigFile.write("config.json",self.setup):
						b=False
					else:
						answer=messageDialog(title="Ошибка",\
						text="Не удалось записать файл настроек. Повторить?",\
						yes="Да", no="Нет")
						if answer in (-1, 0):
							b=False 
			if self.main_win:
				self.main_win.editConnection(conn)
				self.main_win.editSetup(self.setup)
			else:
				self.main_win=MainWindow(conn,self.setup)
			self.close()
			self.main_win.show()
		except DB.ConnectToDBError:
			answer=0
			if self.main_win:
				answer=messageDialog(title="Неудачная попытка", text=\
					"Не удалось подключится к базе данных. Продолжить?",\
					yes="Да", no="Нет, повторить ещё раз",\
					cancel="Выйти из программы")
				if answer==1:
					self.main_win.editSetup(self.setup)
					self.close()
					self.main_win.show()
				elif answer==0:
					exit(0)
			else:
				answer=messageDialog(title="Неудачная попытка", text=\
					"Не удалось подключится к базе данных. Войти в программу без подключения?",\
					yes="Да", no="Нет, повторить ещё раз")
				if answer in (0, 1):
					self.main_win=MainWindow(setup=self.setup)
					self.close()
					self.main_win.show()
Esempio n. 24
0
def init():
	global initialized
	if (initialized):
		return
	Dists.init()
	Parts.init()
	Rooms.init()
	for (shipType, typeAbbr) in TYPE_ABBRS.items():
		classes[shipType] = {}
		configPath = os.path.join(os.path.dirname(__file__), "data", "classes_%s.cfg" % typeAbbr)
		configDict = ConfigFile.readFile(configPath)
		for className in configDict.keys():
			if (type(configDict[className]) != type({})):
				continue
			classes[shipType][className] = ShipClass(shipType, configDict[className])
	initialized = True
Esempio n. 25
0
def init(configFileName=None):

    global EventDir, ProtFileDir, ConfigDict, isDebug

    ProtFileDir = os.path.join(EventDir(), 'tmp1')

    if True:  # not isClient:
        ConfigDict = ConfigFile.readGlobalConf(configFileName)

        if ConfigDict == None: return False
    key = 'DEBUG_FLAG'

    if not isClient:
        if isDebug: Logfile.add('Debugging is on')

    return True
Esempio n. 26
0
    def __init__(self, driver, stringDict={}, conf=None):
        if conf == None:
            conf = ConfigFile.Config()
        self.conf = conf
        self.PACKAGE_NAME = self.conf.PACKAGE_NAME
        self.DEVICE_NAME = driver.capabilities['deviceName']

        self._ramSSCounter = 0
        if 'RAMDUMP' not in os.listdir():
            os.mkdir('RAMDUMP')

        self._gfxSSCounter = 0
        if 'GFXDUMP' not in os.listdir():
            os.mkdir('GFXDUMP')
        self.driver = driver
        self.stringDict = stringDict
Esempio n. 27
0
def download_files(url_list, uuid, start_file=0):

    global job_processors
    global download_job_info
    global queue

    try:
        hpt_preferences = ConfigFile.get_settings("gnip.cfg", "HPT")
        download_job_info["uuid"] = uuid
        download_job_info["start_file"] = start_file
        download_job_info["directory"] = hpt_preferences["destination"]

        thread_count = hpt_preferences["threadcount"]

        file_count = 0
        print("Queuing files.")
        for item in url_list:
            file_count += 1
            queue.put({"url": item, "number": file_count})
        print("Queueing complete.")

        print("Starting worker threads")
        try:
            for i in range(int(thread_count)):
                job_processors.append(
                    multiprocessing.Process(target=worker, args=(queue, )))
                job_processors[-1].daemon = True
                job_processors[-1].name = str(i)
                job_processors[-1].start()
                print("Thread " + str(i) + " created.")
        except Exception as ex:
            print("Process interrupted: " + str(ex))
            sys.exit()

        try:
            # wait for workers to finish processing queue
            queue.join()
            return True
        except KeyboardInterrupt:
            print("Ctrl-C pressed.  Terminating application.")
            cleanup()
            return False

    except Exception as e:
        print("")
        handle_error(e)
        return False
Esempio n. 28
0
def get_response(method, endpoint, data=None):
    headers = {'Content-Type': 'application/json'}
    auth_info = ConfigFile.get_settings("gnip.cfg", "basic")
    username = auth_info["username"]
    password = auth_info["password"]
    account = auth_info["account"]
    base_url = 'https://gnip-api.gnip.com/historical/powertrack/accounts/' + account + '/publishers/twitter/jobs'

    # print ("url:" + base_url + endpoint)
    response = None
    try:
        if method.lower() == "get":
            response = requests.request("GET",
                                        base_url + endpoint,
                                        headers=headers,
                                        auth=(username, password))
        elif method.lower() in ['post', 'put']:
            response = requests.request(method.upper(),
                                        base_url + endpoint,
                                        headers=headers,
                                        json=data,
                                        auth=(username, password))

        if response is not None and response.ok:
            if "json" in str(response.headers["Content-Type"]):
                return response.json()
            else:
                return response.text
        else:
            if response is not None:
                # print("status code:" + str(response.status_code))
                if response.status_code in [400, 404]:
                    return response.text
                else:
                    raise Exception("Error: in get_response " +
                                    str(response.status_code) + ": " +
                                    response.text + " url:" + base_url +
                                    endpoint)
            else:
                raise Exception("Error: in get_response " + base_url +
                                endpoint)

    except Exception as ex:
        handle_error(ex)
    return None
Esempio n. 29
0
    def __init__(self, driver, stringDict={}, conf=None):
        "CONFIG"
        if conf == None:
            conf = ConfigFile.Config()

        self._assertionDebug = conf.ASSERTION_DEBUG
        self.driver = driver
        self.stringDict = stringDict
        self.n_test_cases = 0
        self.n_test_pass = 0
        self.n_test_fail = 0
        self.l_test_fail = list()
        self.DEVICE_NAME = driver.name
        self.tls = TestLink(conf.DEVKEY, conf.TESTLINK_URL,
                            str(conf.TESTPLANID), str(conf.BUILDID),
                            str(conf.PLATFORMID), conf.RESULTASSIGNMENT,
                            self.DEVICE_NAME)
        self.conf = conf
Esempio n. 30
0
  def okBut(self, event):
    sel=self.todo.GetSelection()

    if self.toClipboard.GetValue()==True:
      if sel==0:  cmd='cp -rp "%s" "%s"\n'
      if sel==1:  cmd='mv "%s" "%s"\n'
      txt=""
      for fn in sorted(self.fileDict):
        txt+=cmd%(fn, self.targetFolder)
      self.copyToClipboard(txt)
    else:
      if sel in (0, 1):     # copy / move files to target folder
        dlg=ExecutionProgressDialog(self, self.targetFolder, self.fileDict, sel)
        dlg.ShowModal()
        dlg.Destroy()
      elif sel==2:          # genisoimage
        volID=cfgfile.getLastVolumeID()
        imgNam=cfgfile.getLastImageName()
        dlg=VolIdImageNameDialog(self, imgNam, volID)
        if dlg.ShowModal()!=wx.ID_OK:
          dlg.Destroy()
          return
        imgNam, volID=dlg.getData()
        dlg.Destroy()
        cfgfile.setLastVolumeID(volID)
        cfgfile.setLastImageName(imgNam)

        # Inputfile für genisoimage mit den zu schreibenden Dateien unter /tmp anlegen
        tmpfile=os.path.join(tempfile.gettempdir(), "__fillBD2.tmp")
        with open(tmpfile, "w") as tmpObj:
          for fn, data in self.fileDict.items():
            if data.isFolder==True:
              tmpObj.write('%s=%s\n'%(data.filename.encode('utf8'), fn.encode('utf8')))
            elif data.isFile==True:
              tmpObj.write('%s\n'%fn.encode('utf8'))

        # das Kommando zum genisoimage-Aufruf ebenfalls unter /tmp ablegen, weil es einfacher
        # an den subprocess.Popen() übergeben werden kann.
        cmd='genisoimage -o "%s" %s -graft-points -V "%s" -path-list %s'%( \
             os.path.join(self.targetFolder, imgNam), self.getGenisoimageParm(), volID, tmpfile)
        cmdfile=os.path.join(tempfile.gettempdir(), "__fillBD2.sh")
        with open(cmdfile, "w") as cmdObj:
          cmdObj.write(cmd)
        dlg=ExecutionProgressDialog(self, self.targetFolder, self.fileDict, sel, ["sh", cmdfile])
        dlg.ShowModal()
        dlg.Destroy()
    self.EndModal(wx.ID_OK)
Esempio n. 31
0
def init(configFileName=None):

    global EventDir, ProtFileDir, ConfigDict, isDebug

    ProtFileDir = os.path.join(EventDir(), 'tmp1')

    if True:  # not isClient :
        ConfigDict = ConfigFile.readGlobalConf(configFileName)

        if ConfigDict == None: return False

    #obj     = ConfigFile.GlobCfg()
    #isDebug = obj.Bool ('debug', '0')
    key = 'DEBUG_FLAG'

    if not os.environ.has_key(key): isDebug = False
    else: isDebug = (os.environ[key].strip() == '1')

    if not isClient:
        if isDebug: Logfile.add('Debugging is on')

    return True
Esempio n. 32
0
    def __init__(self, RequestHandlerClass, argv = []):
        """Constructor of the server."""
        
        # Declaration of class members        

        # Here will come the command-line parameters and configuration file
        # processing

        self.Options = ConfigFile.decode_configfile(
            DEFAULT_OPTIONS['configfile'],
            OPTION_TYPE,
            DEFAULT_OPTIONS)

        self.Options = self.__Decode_Command_Line(argv, OPTION_TYPE, self.Options)

        print "Server starting with following options:"
        for i in self.Options.keys(): print i, ':', self.Options[i]

        # All that follows is temporary and bogus. We always wait for incoming
        # connections ("bind" requests) on an interface that has a routable IP
        # address. This means no support for multi-homed servers and no way to
        # connect to hosts on local networks.
        # Getting info on the physical interface of the server.
        hostname, aliaslist, ipaddrlist = socket.gethostbyaddr('')

        # Finding the internet address of the server. If none is found, the first ip is choosed
        self.external_ip = None
        for ip in ipaddrlist:
            if IPv4_Tools.is_routable(ip):
                self.external_ip = ip
                break
        if self.external_ip == '':
            self.external_ip = ipaddrlist[0]

        print 'The choosen ip adress is', self.external_ip
        SocketServer2.ThreadingTCPServer.__init__(
            self,
            (self.Options['bind_address'], self.Options['bind_port']),
            RequestHandlerClass)
Esempio n. 33
0
def set_access_token(a_token):
    ConfigFile.set_property("gnip.cfg", "oauth", "token", a_token)
    return
Esempio n. 34
0
def set_access_token_secret(a_secret):
    ConfigFile.set_property("gnip.cfg", "oauth", "tokensecret", a_secret)
    return
Esempio n. 35
0
def set_consumer_key(a_key):
    ConfigFile.set_property("gnip.cfg", "oauth", "consumerkey", a_key)
    return
Esempio n. 36
0
 def onClose(self, event):
   pos=self.GetScreenPosition()
   size=self.GetSizeTuple()
   cfgfile.setWindowSize(pos, size)
   event.Skip()
Esempio n. 37
0
 def OnSortOrderChanged(self):
   self.lastSortOrder=self.GetSortState()
   cfgfile.setColSort(self.ctrl_nr, self.lastSortOrder)
Esempio n. 38
0
            self.owner = LookupStoreHacker(owner, email)

    @classmethod
    def parse(cls, line):
        split = line.split()
        return cls(split[0], split[1], split[2], split[3:])

#
# Here starts the real program.
#
ParseOpts ()

#
# Read the config files.
#
ConfigFile.ConfigFile (CFName, DirName)

bugs = [Bug.parse(l) for l in sys.stdin]

for bug in bugs:
    bug.owner.addbugfixed(bug)
    empl = bug.owner.emailemployer(bug.owner.email[0], ConfigFile.ParseDate(bug.date))
    empl.AddBug(bug)

if DumpDB:
    database.DumpDB ()
database.MixVirtuals ()

#
# Say something
#
Esempio n. 39
0
import ConfigFile as cf
from os import listdir
from os.path import join, splitext

import tensorflow as tf

from keras.models import Sequential
from keras.layers import Dense, LSTM
from keras.optimizers import Adam
from keras.callbacks import EarlyStopping

from matplotlib import pyplot as plt


data_path = cf.get_user_data()
data_path = join(data_path, 'output.xlsx')

data_excel = pd.read_excel(data_path)

length = len(data_excel)

fromIndex = 18000
toIndex = length
steps = 1

lon = data_excel['lon_rad'][fromIndex:toIndex:steps].to_numpy()
lat = data_excel['lat_rad'][fromIndex:toIndex:steps].to_numpy()
date_time = data_excel['datetime'][fromIndex:toIndex:steps].to_numpy()

lon_min = 2
Esempio n. 40
0
            sys.stderr.write('(W) detected a commit on a svn tag: %s\n' %
                             (m.group(0), ))
            return True

    return False


#
# Here starts the real program.
#
ParseOpts()

#
# Read the config files.
#
ConfigFile.ConfigFile(CFName, DirName)

TotalChanged = TotalAdded = TotalRemoved = 0

#
# Snarf changesets.
#
print >> sys.stderr, str(DateFrom) + ' - ' + str(DateTo) + '\r'
print >> sys.stderr, 'Grabbing changesets...\r'

patches = logparser.LogPatchSplitter(InputData, DateFrom, DateTo)
printcount = CSCount = 0

for logpatch in patches:
    if (printcount % 10) == 0:
        print >> sys.stderr, 'Grabbing changesets...%d\r' % printcount,
Esempio n. 41
0
def set_consumer_key():
    ConfigFile.set_property("gnip.cfg", "oauth", "consumerkey", sys.argv[2])
    return
Esempio n. 42
0
def get_audience_object():
    oauth = ConfigFile.get_settings("gnip.cfg", "oauth")
    audience = insights.Audience(oauth["consumerkey"], oauth["consumersecret"], oauth["token"], oauth["tokensecret"])
    return audience
Esempio n. 43
0
def set_consumer_secret(c_secret):
    ConfigFile.set_property("gnip.cfg", "oauth", "consumersecret", c_secret)
    return
Esempio n. 44
0
def set_consumer_secret():
    ConfigFile.set_property("gnip.cfg", "oauth", "consumersecret", sys.argv[2])
    return
Esempio n. 45
0
def set_access_token(a_token):
    ConfigFile.set_property("gnip.cfg", "oauth", "token", a_token)
    return
Esempio n. 46
0
    self.restoreSort(self.list_panel2, topItem2)

  # ###########################################################
  # Löscht alles Sätze aus "self.list_panel2.list_ctrl.data".
  def deleteAllFromListCtrl2(self, event):
    self.list_panel2.list_ctrl.data.clear()
    self.list_panel2.list_ctrl.DeleteAllItems()
    self.__updateSum(self.list_panel2.list_ctrl, 2)
    self.base_profile.SetValue("")

  # ###########################################################
  # Liefert eine Liste mit den Indices der selektierten Sätze
  # in "ctrl".
  def getSelectedItems(self, ctrl):
    lst=[]
    idx=ctrl.GetFirstSelected()
    while idx!=-1:
      lst.append(idx)
      idx=ctrl.GetNextSelected(idx)
    return(lst)



if __name__=='__main__':
  app=wx.App()
  pos, size=cfgfile.getWindowSize()
  frame=FillBD2Frame(pos, size)
  frame.Show()
  app.MainLoop()

Esempio n. 47
0
def set_access_token_secret():
    ConfigFile.set_property("gnip.cfg", "oauth", "tokensecret", sys.argv[2])
    return
Esempio n. 48
0
#! /bin/usr/env python3.4

# Подключение модулей
import ConfigFile, DB, GUI

win=None # Окно

# 1 шаг - инициализация
app=GUI.init() # Приложение

# 2 шаг - предварительная загрузка настроек
configs=None
try:
	configs=ConfigFile.read("config.json")
except ConfigFile.ConfigFileOpenError:
	answer=GUI.messageDialog(title="Приветствие",\
		text="Хотите настроить подключение к базе данных?", yes="Да",\
		no="Нет, продолжить без подключения", cancel="Нет, выйти")
	if answer==-1:
		win=GUI.MainWindow()
		win.show()
	elif answer==0:
		exit(0)
	else:
		win=GUI.SetupDatabaseWindow()
		win.show()
except (ConfigFile.ConfigFileNotJSONError,\
	ConfigFile.ConfigFileInterruptError):
	answer=GUI.messageDialog(title="Ошибка",\
		text="Конфигурационный файл повреждён. Настроить заново?",\
		yes="Да", no="Нет, продолжить без настройки",\
Esempio n. 49
0
__author__="felsamps"
__date__ ="$16/07/2010 15:27:49$"

import sys

from Cache import *
from ConfigFile import *
from MMU import *
from TraceFile import *
from SearchEngine import *


if __name__ == "__main__":
	configFile = ConfigFile(sys.argv[1])
	configFile.parseFile()
	traceFile = TraceFile(sys.argv[2])
	me = SearchEngine(traceFile, configFile)
	me.process()
Esempio n. 50
0
  def __init__(self, parent):
    wx.Panel.__init__(self, parent, wx.ID_ANY, style=wx.WANTS_CHARS)

    self.db=Database.Database()

    self.targetFolder=""                # Zielverzeichnis
    self.size=0                         # Größe des Zieldatenträgers
    self.blockSize=0                    # Blockgröße auf dem Zieldatenträger
    self.addblock=None
    self.calcTime=cfgfile.getCalcTime() # maximale Rechendauer für SelectFiles() [Sekunden]

    self.parent=parent

    # Quasi-Toolbar anlegen
    self.setup=wx.Button(self, wx.ID_ANY, "&Setup Profiles")
    self.setup.Bind(wx.EVT_BUTTON, self.setupBut)

    self.choose_dest=wx.Button(self, wx.ID_ANY, "Choose &Target")
    self.choose_dest.Bind(wx.EVT_BUTTON, self.choose_destBut)

    base_profile_txt=wx.StaticText(self, label="Source &Profile:")
    self.base_profile=wx.ComboBox(self, size=(150, -1), style=wx.CB_DROPDOWN|wx.CB_READONLY)
    self.base_profile.Disable()
    self.base_profile.Bind(wx.EVT_COMBOBOX, self.base_profileChanged)
    self.fillComboBoxes()

    self.fillTarget=wx.Button(self, wx.ID_ANY, "&Fill Target",  (-1, -1), wx.DefaultSize)
    self.fillTarget.Bind(wx.EVT_BUTTON, self.fillTargetBut)

    self.export=wx.Button(self, wx.ID_ANY, "&Export",  (-1, -1), wx.DefaultSize)
    self.export.Bind(wx.EVT_BUTTON, self.exportBut)

    bmp=wx.ArtProvider.GetBitmap(wx.ART_HELP_PAGE, wx.ART_OTHER, (16,16))
    self.info=wx.BitmapButton(self, wx.ID_ANY, bmp)
    self.info.Bind(wx.EVT_BUTTON, self.aboutDialog)

    blksize_txt=wx.StaticText(self, label="Blocksize:")
    self.blksize=wx.TextCtrl(self, wx.ID_ANY, "", size=(70, -1), style=wx.TE_READONLY|wx.TE_RIGHT)
    targtFldr_txt=wx.StaticText(self, label="Target Folder:")
    self.targtFldr=wx.TextCtrl(self, wx.ID_ANY, "", size=(250, -1), style=wx.TE_READONLY)

    # die beiden Haupt-ListCtrls anlegen
    self.list_panel1=FillDB2ListCtrl(self, 1)
    self.list_panel2=FillDB2ListCtrl(self, 2)
    self.list_panel1.list_ctrl.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnRightClick1)
    self.list_panel2.list_ctrl.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnRightClick2)

    # die Summen-Zeile anlegen
    s=wx.TE_READONLY|wx.TE_RIGHT
    self.lp1_size   =wx.TextCtrl(self, wx.ID_ANY, "", size=(120, -1), style=s)
    self.lp1_sizeAdj=wx.TextCtrl(self, wx.ID_ANY, "", size=(120, -1), style=s)
    self.lp2_sizeAdj=wx.TextCtrl(self, wx.ID_ANY, "", size=(120, -1), style=s)
    self.lp2_sizeRem=wx.TextCtrl(self, wx.ID_ANY, "", size=(120, -1), style=s)
    txt_lp1_size    =wx.StaticText(self, label="sum(size(real)):")
    txt_lp1_sizeAdj =wx.StaticText(self, label="sum(size(dest)):")
    txt_lp2_sizeAdj =wx.StaticText(self, label="sum(size(dest)):")
    txt_lp2_sizeRem =wx.StaticText(self, label="size(remain):")

    vsizer=wx.BoxSizer(wx.VERTICAL)     # der oberste Sizer
    bsizer=wx.BoxSizer(wx.HORIZONTAL)   # der Sizer für die Quasi-Toolbar
    hsizer=wx.BoxSizer(wx.HORIZONTAL)   # der Sizer für die beiden ListCtrls

    h1sizer=wx.BoxSizer(wx.HORIZONTAL)  # der Sizer für die Summen unter ListCtrl1
    h2sizer=wx.BoxSizer(wx.HORIZONTAL)  # der Sizer für die Summen unter ListCtrl2
    h3sizer=wx.BoxSizer(wx.HORIZONTAL)  # der Sizer für h1sizer und h2sizer

    bsizer.Add(self.setup,        0, wx.ALL, 2)
    bsizer.Add(self.choose_dest,  0, wx.ALL, 2)
    bsizer.Add(base_profile_txt,  0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 2)
    bsizer.Add(self.base_profile, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 2)
    bsizer.Add(self.fillTarget,   0, wx.ALL, 2)
    bsizer.Add(self.export,       0, wx.ALL, 2)
    bsizer.AddStretchSpacer()
    bsizer.Add(self.info,         0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 2)
    bsizer.Add(blksize_txt,       0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 10)
    bsizer.Add(self.blksize,      0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 2)
    bsizer.Add(targtFldr_txt,     0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 10)
    bsizer.Add(self.targtFldr,    0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 2)

    hsizer.Add(self.list_panel1, 20, wx.ALL|wx.EXPAND, 1)
    hsizer.Add(self.list_panel2, 11, wx.ALL|wx.EXPAND, 1)

    h1sizer.AddStretchSpacer()
    h1sizer.Add(txt_lp1_size,     0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 1)
    h1sizer.Add(self.lp1_size,    0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 1)
    h1sizer.Add(txt_lp1_sizeAdj,  0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 30)
    h1sizer.Add(self.lp1_sizeAdj, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 1)

    h2sizer.AddStretchSpacer()
    h2sizer.Add(txt_lp2_sizeAdj,  0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 1)
    h2sizer.Add(self.lp2_sizeAdj, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 1)
    h2sizer.Add(txt_lp2_sizeRem,  0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 30)
    h2sizer.Add(self.lp2_sizeRem, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 1)

    h3sizer.Add(h1sizer, 10, wx.ALL|wx.EXPAND|wx.ALIGN_RIGHT, 1)
    h3sizer.Add(h2sizer,  8, wx.ALL|wx.EXPAND|wx.ALIGN_RIGHT, 1)

    vsizer.Add(bsizer,  0, wx.ALL|wx.EXPAND, 1)
    vsizer.Add(hsizer,  1, wx.ALL|wx.EXPAND, 1)
    vsizer.Add(h3sizer, 0, wx.ALL|wx.EXPAND, 1)

    self.SetSizer(vsizer)
    vsizer.Fit(self)
    self.choose_dest.SetFocus()
    wx.CallLater(100, self.choose_destBut)
Esempio n. 51
0
#!/usr/bin/env python2
import sys


sys.path[0] = ".."
from ConfigFile import *

# Start of test code:
print "Performing tests..."
print "Testing Shell Mode..."

try:
	shell = ConfigFile("config.sh")
except SyntaxError.ExecNotAllowed:
	print "\tExecution Checking(disallowed)...ok"
else:
	print "\tExecution Checking(disallowed)...failed"


try:
	shell = ConfigFile("config.sh", allowExec=1)
except SyntaxError.ExecNotAllowed:
	print "\tExecution Checking(allowed)...failed"		
else:
	print "\tExecution Checking(allowed)...ok"


print "Dump:"
print "-" * 30
for key in shell.keys():
	print "%s=%s" %(key, shell[key])
Esempio n. 52
0
            Log('Search RECORD_COUNT_PATTERN Fail')
        return False

    def FillSheetWork(self):
        if self.IsWorkSheetFilled():
            Log('Been Filled Task')
            return
        task = self.GetFirstOngoingTask()
        if task != None:
            Log('Commit Task')
            task.Commit()


reload(sys)
#print sys.getdefaultencoding()
sys.setdefaultencoding('utf8')
Log('Application Start')
username = ConfigFile.Read(GetConfigFile(), CONFIG_FIELD_USER, 'username')
password = ConfigFile.Read(GetConfigFile(), CONFIG_FIELD_USER, 'password')
employeeName = ConfigFile.Read(GetConfigFile(), CONFIG_FIELD_USER,
                               'employeeName')
url_base = ConfigFile.Read(GetConfigFile(), CONFIG_FIELD_URL, 'url_base')
url_ongoingTasks = ConfigFile.Read(GetConfigFile(), CONFIG_FIELD_URL,
                                   'url_ongoingTasks')
url_dailyWorks = ConfigFile.Read(GetConfigFile(), CONFIG_FIELD_URL,
                                 'url_dailyWorks')

crm = CRM(username, password, employeeName)
crm.FillSheetWork()
Log('Application Closed')
Esempio n. 53
0
def set_consumer_key(a_key):
    ConfigFile.set_property("gnip.cfg", "oauth", "consumerkey", a_key)
    return
Esempio n. 54
0
def set_consumer_secret(c_secret):
    ConfigFile.set_property("gnip.cfg", "oauth", "consumersecret", c_secret)
    return
Esempio n. 55
0
def set_access_token_secret(a_secret):
    ConfigFile.set_property("gnip.cfg", "oauth", "tokensecret", a_secret)
    return
Esempio n. 56
0
orders = [0,1,2]
bmas = [["diamond","/home/felsamps/Tcc/cache-mvc/inDiamondTZ.txt"], ["square", "/home/felsamps/Tcc/cache-mvc/inSquareTZ.txt"]]
sets = [1, 2, 3, 4, 5, 6, 7, 8]
blocks = [[16,16], [20,20], [40,40], [32,24], [40, 30]]
caches = [[2,2], [3,3], [4,4], [5,5], [6,6], [7,7], [8,8], [9,9], [10,10], [3,4], [4,5], [5,6], [3,5]]

stats = []

if __name__ == "__main__":
	i = 1
	total = len(orders) * len(bmas) * len(sets) * len(blocks) * len(caches)
	for order in orders:
		for bma in bmas:
			for set in sets:
				for block in blocks:
					for cache in caches:
						config = ConfigFile("fake")
						config.initConfigs(w, h, block[0], block[1], set, cache[0]*cache[1], cache[0], cache[1], order, bma[0])
						trace = TraceFile(bma[1])
						print "Executando configuracao " , i, "de", total
						engine = SearchEngine(trace, config)
						engine.process()
						stats.append(engine.getStats())
						i += 1

	fp = open("/home/felsamps/Tcc/cache-mvc/results/results.csv","w")
	stats[0].printHeader(fp)
	for result in stats:
		# @type result Stats
		result.reportFile(fp)
Esempio n. 57
0
def get_audience_object():
    oauth = ConfigFile.get_settings("gnip.cfg", "oauth")
    audience = insights.Audience(oauth["consumerkey"], oauth["consumersecret"],
                                 oauth["token"], oauth["tokensecret"])
    return audience