Example #1
0
 def test_typical(self):
     """
     Test a non-broken, typical setup
     """
     from ConfigParser import ConfigParser
     from velouria.config import VelouriaConfigKeyboard
     from gi.repository import Gdk
     
     config = ConfigParser()
     config.add_section("keyboard")
     config.set("keyboard", "quit", "META_MASK+KEY_q\nKEY_x")
     config.set("keyboard", "fullscreen", "CONTROL_MASK+KEY_r")
     config.set("keyboard", "pause", "")
     
     keyconfig = VelouriaConfigKeyboard(config)
     
     expected = self._defaults()
     
     # override quit and fullscreen actions
     expected['pause'] = None
     expected['quit'] = [
         {'key': Gdk.KEY_x, 'modifiers': 0},
         {'key': Gdk.KEY_q, 'modifiers': Gdk.ModifierType.META_MASK},
     ]
     expected['fullscreen'] = [
         {'key': Gdk.KEY_r, 'modifiers': Gdk.ModifierType.CONTROL_MASK},
     ]
     
     self.assertItemsEqual(expected['quit'], keyconfig.quit)
     self.assertItemsEqual(expected['fullscreen'], keyconfig.fullscreen)
     self.assertIsNone(keyconfig.pause)
Example #2
0
def config_parser(role='agent'):
    config_parser = ConfigParser()
    config_parser.add_section(role)
    config_parser.set(role, 'APP_ID', '1')
    config_parser.set(role, 'IPOP_BASE_NAMESPACE', 'http://example.org:443')
    config_parser.set(role, 'CONPAAS_HOME', IPOP_CONF_DIR)
    return config_parser
Example #3
0
class UserConfig:

    def __init__(self, filename=default_user_config_file):
        self.parser = ConfigParser()
        self.parser.read(filename)
        self.filename = filename
        if not isfile(self.filename):
            self.parser.add_section('diaspora')
            self.set_activated(False)
            self.__save()
        else:
            self.parser.read(self.filename)

        if not self.parser.has_section('diaspora'):
            self.parser.add_section('diaspora')

    def is_installed(self):
        return self.parser.getboolean('diaspora', 'activated')

    def set_activated(self, value):
        self.parser.set('diaspora', 'activated', str(value))
        self.__save()

    def __save(self):
        with open(self.filename, 'wb') as f:
            self.parser.write(f)
def set_auto_rsvp_groups():
    '''Generates a group config file from user input. The config file is saved
    to CONFIG_FILENAME specified above.

    All groups of the current member are printed to the config file. However,
    any groups the user doesn't want to auto RSVP will be commented out with a
    '#'.
    '''
    groups = get_groups()

    config_groups = []
    for group in groups:
        ans = raw_input(
            'Automatically RSVP yes for %s? [y/n]: ' % group['name']
        ).lower()

        while ans not in ['y', 'n']:
            print 'Please enter a \'y\' or \'n\'.'
            ans = raw_input(
                'Automatically RSVP yes for %s? [y/n]: ' % group['name']
            ).lower()
        
        if ans == 'y':
            # We want to auto-rsvp for this group
            config_groups.append((str(group['id']), group['name']))
        else:
            # Don't auto RSVP. We'll write add this group with a comment
            # preceding the line.
            config_groups.append(('#%s' % str(group['id']), group['name']))

    config = ConfigParser()
    config.add_section('rsvp_groups')
    [config.set('rsvp_groups', group_id, group_name) for group_id, group_name
        in config_groups]
    write_config(config)
    def initConfig(self):
        kate.debug("initConfig()")
        config_path = kate.pate.pluginDirectories[1] + "/%s/%s.conf" % (__name__, __name__)
        config_file = QFileInfo(config_path)

        if not config_file.exists():
            open(config_path, "w").close()

        config = ConfigParser()
        config.read(config_path)

        # init the DEFAULT options if they don't exist
        # the DEFAULT section is special and doesn't need to be created: if not config.has_section('DEFAULT'): config.add_section('DEFAULT')
        if not config.has_option("DEFAULT", "ignore"):
            config.set("DEFAULT", "ignore", "")
        if not config.has_option("DEFAULT", "filter"):
            config.set("DEFAULT", "filter", "*")
        if not config.has_option("DEFAULT", "finder_size"):
            config.set("DEFAULT", "finder_size", "400x450")
        if not config.has_option("DEFAULT", "config_size"):
            config.set("DEFAULT", "config_size", "300x350")
        if not config.has_option("DEFAULT", "search_type"):
            config.set("DEFAULT", "search_type", "word")

        # create the general section if it doesn't exist
        if not config.has_section("general"):
            config.add_section("general")

        # flush the config file
        config.write(open(config_path, "w"))

        # save the config object and config path as instance vars for use later
        self.config = config
        self.config_path = config_path
    def startCompetitorDialog(self):
        pbText = str(self.startStopPB.text())

        if pbText == "Start":
            self.newCompetitorDialog.show()
        if pbText == "Stop":
            self.timer.stop()
            self.updateStartStop("Start")

            log = ConfigParser()
            log.add_section("Scoreboard")
            log.set("Scoreboard","MinesDetected",self.mineDetectedLB.text())
            log.set("Scoreboard","WrongMinesDetected",self.wrongMinesDetectedLB.text())
            log.set("Scoreboard","ExplodedMines",len(self.minesExploded))
            log.set("Scoreboard","ExplodedMinesDetected",len(self.minesExplodedDetected))
            log.set("Scoreboard","Time",self.timeLB.text())

            undetected = undetectedCovered = 0
            mWidth, mHeight = self.width/self.cellXSize,self.height/self.cellYSize
            for m in self.mines:
                if not self.minesDetected.has_key(tuple(m)):
                    x, y = m[0]/self.cellXSize+mWidth/2., mHeight/2. - m[1]/self.cellYSize
                    if (x<0) or (y<0) or (y >self.Map.shape[0]) or (x >self.Map.shape[1]):
                        undetected += 1
                        continue
                    if self.actionCoilsSignal.isChecked():
                        if self.Map[y,x] != 220:
                            undetectedCovered += 1
                        else:
                            undetected += 1
                    else:
                        if self.Map[y,x] == 183:
                            undetectedCovered += 1
                        else:
                            undetected += 1

            log.set("Scoreboard","Undetected", undetected)
            log.set("Scoreboard","UndetectedCovered", undetectedCovered)


            percent = 0.0
            if self.actionCoilsSignal.isChecked():
                percent = self.Map[self.Map != 220].size/float(self.Map.size)
            else:
                percent = self.Map[self.Map == 183].size/float(self.Map.size)
            log.set("Scoreboard","Covered Area",percent)

            path = os.path.expanduser("~/HRATC 2014 Simulator/")
            if not os.path.exists(path):
                os.mkdir(path)

            path += "logs/"
            if not os.path.exists(path):
                os.mkdir(path)

            cfile = open(path+"/log_{}.log".format(self.competitorName),"w")  
            log.write(cfile)
            cfile.close()

            self.competitorName = None
class NightscoutConfig(object):
    FILENAME = 'config'
    SECTION = 'NightscoutMenubar'
    HOST = 'nightscout_host'
    USE_MMOL = 'use_mmol'

    def __init__(self, app_name):
        self.config_path = os.path.join(rumps.application_support(app_name), self.FILENAME)
        self.config = ConfigParser()
        self.config.read([self.config_path])
        if not self.config.has_section(self.SECTION):
            self.config.add_section(self.SECTION)
        if not self.config.has_option(self.SECTION, self.HOST):
            self.set_host('')
        if not self.config.has_option(self.SECTION, self.USE_MMOL):
            self.set_use_mmol(False)

    def get_host(self):
        return self.config.get(self.SECTION, self.HOST)

    def set_host(self, host):
        self.config.set(self.SECTION, self.HOST, host)
        with open(self.config_path, 'w') as f:
            self.config.write(f)

    def get_use_mmol(self):
        return bool(self.config.get(self.SECTION, self.USE_MMOL))

    def set_use_mmol(self, mmol):
        self.config.set(self.SECTION, self.USE_MMOL, 'true' if mmol else '')
        with open(self.config_path, 'w') as f:
            self.config.write(f)
	def addRegra(self, ipORrede, nome, banda_liberada, banda_down, prio, delimitado, isolado):
		#system("tc qdisc del dev %s root"%self.device)
		arquivo = ConfigParser()
		arquivo.read( '/var/lib/netcontrol/plugins/limite_banda/etc/config_server' )
		
		if not arquivo.has_section("contador_regras"):
			arquivo.add_section("contador_regras")
			arquivo.set("contador_regras","contador",1)
			arquivo.write( open('/var/lib/netcontrol/plugins/limite_banda/etc/config_server','w') )
			cont = "1"
		else:
			cont = int(arquivo.get("contador_regras", "contador")) + 1
			arquivo.set("contador_regras","contador", cont)
			arquivo.write( open('/var/lib/netcontrol/plugins/limite_banda/etc/config_server','w') )
			cont = str(cont)
		cont = "000%s"%(cont)
		ip   = ipORrede.replace('.','_').replace('/','_')
		user = nome.replace(' ','_')
		nome = "cbq-%s.%s%s-in"%(cont[-4:],ip,user)
		regra = "DEVICE=%s,%s,%s\n" \
				"RATE=%sKbit\n"   \
				"WEIGHT=%sKbit\n" \
				"PRIO=%s\n"       \
				"RULE=%s\n"       \
				"BOUNDED=%s\n"    \
				"ISOLATED=%s"%(self.device, self.banda_total, self.banda_total_down, banda_liberada, banda_down, prio, ipORrede, delimitado, isolado)
		open('%s%s'%(self.etc,nome),'w').write(regra)
Example #9
0
def createNodeInfoFile(dirPath, toKeep):
	"""
	Creates the .nodeInfo file in the directory specified by dirPath.
	The Node:Type must be set by concrete nodes
	@precondition: dirPath is a valid directory
	@postcondition: All sections/tags are created and set except "Type".
		"Type" must be set by concrete nodes.
	"""
	username = getUsername()
	timestamp = time.strftime("%a, %d %b %Y %I:%M:%S %p", time.localtime())
	
	nodeInfo = ConfigParser()
	nodeInfo.add_section('Node')
	nodeInfo.set('Node', 'Type', '')
	
	nodeInfo.add_section('Versioning')
	nodeInfo.set('Versioning', 'LatestVersion', '0')
	nodeInfo.set('Versioning', 'VersionsToKeep', str(toKeep))
	nodeInfo.set('Versioning', 'Locked', 'False')
	nodeInfo.set('Versioning', 'LastCheckoutTime', timestamp)
	nodeInfo.set('Versioning', 'LastCheckoutUser', username)
	nodeInfo.set('Versioning', 'LastCheckinTime', timestamp)
	nodeInfo.set('Versioning', 'LastCheckinUser', username)
	
	_writeConfigFile(os.path.join(dirPath, ".nodeInfo"), nodeInfo)
Example #10
0
def set_config_to_path(configPath, section, option, value):

    read = False

    #check if config file exists
    if ( os.path.isfile(configPath)):
        configPath = os.path.realpath(configPath);
        config = ConfigParser();
        #try to read the value from ini file
        try:
            config.read(configPath)
            if config.has_section(section) :
                    #Update the new values
                config.set(section, option, value)
                read = True
        except: #read failed due currupted ini file that can happen due to suddent power of during update
            print "except"
    if( read == False): #file not exist and needs to be creatred
        config = ConfigParser();
        config.add_section(section)
        config.set(section, option, value)
        read = True

    fo=open(configPath, "w+")
    config.write(fo) # Write update config

    return read
Example #11
0
def start_config(config_file_name):
    config = ConfigParser()
    config.add_section("global")

    value = raw_input("Enter the JSON root folder to write the json files too : ")
    if len(value) == 0:
        value = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/www/JSON'
    elif value[-1] != "/":
        value += "/"
    config.set("global", "json_root", value)

    modules_config = []

    module_list = os.listdir(os.path.dirname(os.path.abspath(__file__)))
    for module in module_list:
        if module == "__init__.py" or module[-3:] != ".py" or module[:4] == 'main':
            continue
        loaded_module = __import__("pygamescanner." + module[:-3], fromlist=["*"])
        module_config = loaded_module.start_config(config)
        modules_config.append(module_config)

    modules_config_dict = dict()
    modules_config_dict["module_list"] = modules_config
    config_string = json.dumps(modules_config_dict)
    modules_file = open(config.get("global", "json_root") + "modules.json", "w")
    modules_file.write(config_string)
    modules_file.close()

    config_file = open(config_file_name, "w")
    config.write(config_file)
    config_file.close()
 def CreateConfig(self, ):
     config=ConfigParser()
     config.add_section('SMTP')
     config.add_section('SEND')
     config.add_section('MAIL')
     config.set('SMTP','Server','smtp.163.com')
     config.set('SMTP','Port','25')
     config.set('SMTP','SSL','0')
     config.set('SEND','Thread','1')
     config.set('SEND','Per_Sender','4')
     config.set('SEND','per_email_sleep','10')
     config.set('SEND','fail_times','4')
     config.set('SEND','Sender','Sender.txt')
     config.set('SEND','Receiver','Receiver.txt')
     config.set('MAIL','PlainOrHtml','html')
     config.set('MAIL','Subject','Join My Network On Linkedin')
     config.set('MAIL','DisplayName','Rich Park{%MAILFROM%}')
     config.set('MAIL','ForgeSource','false')
     config.set('MAIL','Content','mail.html')
     config.set('MAIL','Attachment','None')
     
     
     config.write(open(gConfigFileStr,'w'))
     #config.write(codecs.open(gConfigFileStr,'w'))
     if not exists('Sender.txt'):open('Sender.txt','a')
     if not exists('Receiver.txt'):open('Receiver.txt','a')
     self.__init__()
def build_config():
    config = ConfigParser()
    config.add_section('Modbus Tcp')
    config.add_section('Modbus Protocol')
    config.add_section('Modbus Serial')
    config.set('Modbus Tcp', "ip", '127.0.0.1')
    config.set('Modbus Protocol', "block start", "0")
    config.set('Modbus Protocol', "block size", "100")
    config.set('Modbus Protocol', "bin min", "0")
    config.set('Modbus Protocol', "bin max", "1")
    config.set('Modbus Protocol', "reg min", "0")
    config.set('Modbus Protocol', "reg max", "65535")
    config.set('Modbus Serial', "baudrate", "9600")
    config.set('Modbus Serial', "bytesize", "8")
    config.set('Modbus Serial', "parity", 'N')
    config.set('Modbus Serial', "stopbits", "1")
    config.set('Modbus Serial', "xonxoff", "0")
    config.set('Modbus Serial', "rtscts", "0")
    config.set('Modbus Serial', "dsrdtr", "0")
    config.set('Modbus Serial', "writetimeout", "2")
    config.set('Modbus Serial', "timeout", "2")

    config.add_section('Logging')
    # config.set('Logging', "log file", os.path.join(self.user_data_dir,
    #                                                'modbus.log'))

    config.set('Logging', "logging", "1")
    config.set('Logging', "console logging", "1")
    config.set('Logging', "console log level", "DEBUG")
    config.set('Logging', "file log level", "DEBUG")
    config.set('Logging', "file logging", "1")

    config.add_section('Simulation')
    config.set('Simulation', 'time interval', "1")
    return config
Example #14
0
class Playlist(object):
  def __init__(self, location):
    dir = os.path.expanduser(os.path.dirname(location))
    if not os.path.exists(dir):
      os.makedirs(dir)

    self._config = ConfigParser()
    self._config.optionxform = str

    self._file = os.path.expanduser(location)
    if os.path.exists(self._file):
      self._config.read(self._file)
    else:
      self._config.add_section('Playlist')
      self.save()

  def save(self):
    self._config.write(open(self._file, 'wb'))

  def append(self, item):
    self._config.set('Playlist', *item)
    self.save()

  def remove(self, option):
    self._config.remove_option('Playlist', option)
    self.save()

  def __getitem__(self, item):
    return self._config.items('Playlist')[item]

  def __iter__(self):
    return iter(self._config.items('Playlist'))
Example #15
0
 def save_action_to_file(action, f):
     parser = ConfigParser()
     parser.add_section('action')
     for action_k, action_v in action.items():
         parser.set('action', action_k, action_v)
     parser.write(f)
     f.seek(0)
def configure_manager(manager_config_path,
                      manager_config):
    '''Sets config defaults and creates the config file'''
    _, temp_config = tempfile.mkstemp()
    config = ConfigParser()

    config.add_section('Credentials')
    config.set('Credentials', 'subscription_id',
               manager_config['subscription_id'])
    config.set('Credentials', 'tenant_id',
               manager_config['tenant_id'])
    config.set('Credentials', 'client_id',
               manager_config['client_id'])
    config.set('Credentials', 'client_secret',
               manager_config['client_secret'])

    config.add_section('Azure')
    config.set('Azure', 'location',
               manager_config['location'])

    with open(temp_config, 'w') as temp_config_file:
        config.write(temp_config_file)

    fabric.api.sudo('mkdir -p {0}'.
                    format(os.path.dirname(manager_config_path)))
    fabric.api.put(temp_config,
                   manager_config_path,
                   use_sudo=True)
Example #17
0
def setup_pypi(pypi, extras=None, strict=False):
    # setup distutils.cfg
    import distutils
    location = os.path.dirname(distutils.__file__)
    cfg = os.path.join(location, 'distutils.cfg')
    if os.path.exists(cfg):
        os.remove(cfg)

    parser = ConfigParser()
    parser.read(cfg)

    if 'easy_install' not in parser.sections():
        parser.add_section('easy_install')

    parser.set('easy_install', 'index_url', pypi)
    allowed_hosts = [urlparse(pypi)[1]]

    if extras:
        parser.set('easy_install', 'find_links', extras)
        allowed_hosts.append(urlparse(extras)[1])

    if strict:
        parser.set('easy_install', 'allow_hosts', ','.join(allowed_hosts))

    with open(cfg, 'w') as cfg:
        parser.write(cfg)
Example #18
0
class RedirectConfig:
    def __init__(self, filename):
        self.parser = ConfigParser()
        self.parser.read(filename)
        self.filename = filename
        self.logger = logger.get_logger('insider.RedirectConfig')

    def update(self, domain, api_url):
        self.logger.info('settig domain={0}, api_url={1}'.format(domain, api_url))
        if not self.parser.has_section('redirect'):
            self.parser.add_section('redirect')

        self.parser.set('redirect', 'domain', domain)
        self.parser.set('redirect', 'api_url', api_url)
        self._save()

    def get_domain(self):
        return self.parser.get('redirect', 'domain')

    def get_api_url(self):
        return self.parser.get('redirect', 'api_url')

    def _save(self):
        self.logger.info('saving config={0}'.format(self.filename))
        with open(self.filename, 'wb') as file:
            self.parser.write(file)
 def set_config(self, config):
     cp = ConfigParser()
     cp.add_section(self.DEFAULT_INI_SECTION)
     for k, v in config.items():
         cp.set(self.DEFAULT_INI_SECTION, k, v)
     with open(self.ini_file_name, "w") as f:
         cp.write(f)
Example #20
0
class InsiderConfig:

    def __init__(self, filename):
        self.parser = ConfigParser()
        self.parser.read(filename)
        self.filename = filename
        self.redirect_config = RedirectConfig(join(dirname(filename), 'redirect.cfg'))
        self.logger = logger.get_logger('insider.InsiderConfig')

    def _save(self):
        self.logger.info('saving config={0}'.format(self.filename))
        with open(self.filename, 'wb') as file:
            self.parser.write(file)

    def update(self, domain, api_url):
        self.redirect_config.update(domain, api_url)

    def get_redirect_api_url(self):
        return self.redirect_config.get_api_url()

    def get_redirect_main_domain(self):
        return self.redirect_config.get_domain()

    def get_cron_period_mins(self):
        return self.parser.getint('cron', 'period_mins')

    def is_upnpc_mock(self):
        return self.parser.getboolean('upnpc', 'mock')

    def set_upnpc_mock(self, enable):
        if not self.parser.has_section('upnpc'):
            self.parser.add_section('upnpc')
        self.parser.set('upnpc', 'mock', enable)
        self._save()
Example #21
0
    def _hg_hook(self):
        # In hg, hooks can be set in config
        hgrc = "%s/.hg/hgrc" % self.vcs_path
        parser = ConfigParser()
        files = parser.read(hgrc)

        if not files:
            conf.log.warning("Failed to find mercurial config: {0}".format(hgrc))
            return False

        try:
            # Set hook
            path = os.path.join(conf.version_control_hooks_dir, "hg-incoming")
            if 'hooks' not in parser.sections():
                parser.add_section('hooks')
            parser.set('hooks', 'incoming', path)

            # Write hook in config
            with open(hgrc, "w") as hgrc_file:
                parser.write(hgrc_file)

        except Exception:
            conf.log.exception("Failed to hook with mercurial repository")
            return False

        return True
Example #22
0
	def buttonExportSensors_clicked_cb(self, widget):
		treemodel, treeiter = self.treeviewSensors.get_selection().get_selected()
		if treeiter:
			sensorNumber = int(treemodel.get_path(treeiter)[0])
			
			dialog = gtk.FileChooserDialog("Salvar..", None, gtk.FILE_CHOOSER_ACTION_SAVE,
			(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))		
			dialog.set_default_response(gtk.RESPONSE_OK)
			dialog.set_current_folder(dialog.get_current_folder() + "/sensors/")
			dialog.set_current_name(self.sensorTypes[sensorNumber].name + ".sensor")
			response = dialog.run()
			if response == gtk.RESPONSE_OK:
				filename = dialog.get_filename()
				FILE = open(filename, "w")
			
				c = ConfigParser()
				
				
				for i in  range(len(self.sensorTypes[sensorNumber].points) - 1, -1, -1):
					c.add_section("POINT " + str(i))
					c.set("POINT " + str(i), "x", self.sensorTypes[sensorNumber].points[i][0])
					c.set("POINT " + str(i), "y", self.sensorTypes[sensorNumber].points[i][1])
					
					
				c.add_section("SENSOR")
				c.set("SENSOR", "name", self.sensorTypes[sensorNumber].name)
				c.set("SENSOR", "unit", self.sensorTypes[sensorNumber].unit)
				c.set("SENSOR", "description", self.sensorTypes[sensorNumber].description)
				
				c.write(FILE)
				FILE.close()
			dialog.destroy()
Example #23
0
def install_mercurial_hook():
    """
    Installs the mercurial precommit hook by adding a hook to the hgrc
    file in the .hg directory of the repository.
    """

    repo_dir = get_repo_dir()

    config_file = os.path.join(repo_dir, '.hg', 'hgrc')
    config_parser = ConfigParser()
    config_parser.read(config_file)

    precommit_abs_file = os.path.join(repo_dir, 'scripts',
            'codestyleprecommit.py')

    section = 'hooks'
    key = 'pretxncommit.precommit'
    value = 'python:%s:mercurial_hook' % precommit_abs_file

    if not config_parser.has_section(section):
        config_parser.add_section(section)

    config_parser.set(section, key, value)

    with open(config_file, 'w') as config:
        config_parser.write(config)
Example #24
0
class RepoConfig(object):
    '''
    This class provides an abstraction around repository configuration files
    '''

    def __init__(self, path):
        '''
        :param path:    Plumbum path to the repository
        '''
        self._config = ConfigParser()
        self._path = path / '.hg' / 'hgrc'
        if self._path.exists():
            self._config.readfp(self._path.open())
        else:
            self._config.add_section('paths')

    def AddRemote(self, name, destination):
        '''
        Adds a remote to the config, or overwrites if it already exists

        :param name:        The name of the remote
        :param destination: The destination path of the remote
        '''
        self._config.set('paths', name, destination)
        self._config.write(self._path.open('w'))

    @property
    def remotes(self):
        '''
        Property to get a dictionary of remotes
        '''
        return dict(self._config.items('paths'))
Example #25
0
def auth_springpad_client(config_file=None):
    """
    Auth the application to make to be allowed to access to user's springpad
    account. If not a valid config file is provided it will prompt the user to
    visit an url in order to allow the application to access to its account
    and it will store authentication details in `config_file`.
    args:
        config_file: the configuration file path to be used. If it is not
            provided, '~/.springpad' will be used instead.
    returns: SpringpadClient instance to interact with the authenticated
        account.
    """
    config_file = config_file or os.path.expanduser("~/.springpad")
    config = ConfigParser()
    config.read([config_file])
    token = config.get("access", "token") if config.has_option("access", "token") else None
    if token:
        token = oauth.OAuthToken.from_string(token)

    client = SpringpadClient(SPRINGPAD_CONSUMER_KEY, SPRINGPAD_CONSUMER_PRIVATE, token)

    if not client.access_token:
        req_token = client.get_request_token()
        print "Please grant access to your springpad account in the following url:\n"
        print "http://springpad.com/api/oauth-authorize?{0}\n".format(req_token)
        print "Once authorized, press intro to continue:",
        raw_input()
        client.access_token = client.get_access_token(req_token)
        config.add_section("access")
        config.set("access", "token", str(client.access_token))
        with open(os.path.expanduser(config_file), "w") as cf:
            config.write(cf)
    return client
Example #26
0
def build_root_cfg(root, timeout, keys):
	# construct the configuration file parser (hint: .ini)
	cp = ConfigParser()
	# handle the expiration data
	cp.add_section("expiration")
	cp.set("expiration", "days", timeout)
	cp.set("expiration", "years", 0)
	cp.set("expiration", "minutes", 0)
	cp.set("expiration", "hours", 0)
	cp.set("expiration", "seconds", 0)
	# build the role data
	for role in keys:
		cp.add_section(role)
		# each role has an associated list of key id's and a threshold
		key_ids, threshold = keys[role]
		# convert the key_ids stuff into a list it can read
		id_list = ",".join(key_ids)
		# and add that data to the appropriate section
		cp.set(role, "keyids", id_list)
		cp.set(role, "threshold", threshold)
	# we want to write this to <root>/root.cfg
	path = root + pathsep + "root.cfg"
	f = open(path, "w")
	cp.write(f)
	f.close()
	return path
Example #27
0
def startSetup():
    config = ConfigParser()
    moduleList = listdir("modules")

    config.add_section("global")
    value = raw_input("Enter the JSON root folder to write the json files too : ")
    if value[-1] != "/":
        value += "/"
    config.set("global", "jsonRoot", value)

    modulesConfig = []

    for module in moduleList:
        if module == "__init__.py" or module[-3:] != ".py":
            continue
        loadedModule = __import__("modules." + module[:-3], fromlist=["*"])
        moduleConfig = loadedModule.startConfig(config)
        modulesConfig.append(moduleConfig)

    modulesConfigDict = {}
    modulesConfigDict["moduleList"] = modulesConfig
    configString = json.dumps(modulesConfigDict)
    modulesFile = open(config.get("global", "jsonRoot") + "modules.json", "w")
    modulesFile.write(configString)
    modulesFile.close()

    configFile = open("server.cfg", "w")
    config.write(configFile)
    configFile.close()
def _upload_credentials(aws_config, manager_config_path):

    temp_config = tempfile.mktemp()
    credentials = ConfigParser()

    credentials.add_section('Credentials')
    credentials.set('Credentials', 'aws_access_key_id',
                    aws_config['aws_access_key_id'])
    credentials.set('Credentials', 'aws_secret_access_key',
                    aws_config['aws_secret_access_key'])

    if aws_config.get('ec2_region_name'):
        region = get_region(aws_config['ec2_region_name'])
        credentials.add_section('Boto')
        credentials.set('Boto', 'ec2_region_name',
                        aws_config['ec2_region_name'])
        credentials.set('Boto', 'ec2_region_endpoint',
                        region.endpoint)

    credentials_string = StringIO()
    credentials.write(credentials_string)

    with open(temp_config, 'w') as temp_config_file:
        temp_config_file.write(credentials_string.getvalue())

    make_default_lower = \
        'sed -i "s/\[DEFAULT\]/\[default\]/g" {0}'.format(
            constants.AWS_DEFAULT_CONFIG_PATH)

    fabric.api.put(temp_config, manager_config_path)
    fabric.api.run(make_default_lower)
Example #29
0
    def write_last_synced(self, _value, _job, _new, _smb_connection=None):
        """
        Write _value to the last_synced property of the destination status file
        :param _value: The value to write
        :param _job: A SyncJob instance
        :param _new: If there isn't already a history-section
        :param _smb_connection: An SMB connection.
        :return:
        """
        if _new is None:
            if _smb_connection is not None:
                _file_obj = read_string_file_smb(_smb_connection, os.path.join(_job.destination_folder, 'ofs_status.txt'))
            else:
                try:
                    _file_obj = open(os.path.join(_job.destination_folder, 'ofs_status.txt'), "r")
                except IOError:
                    pass
        else:
            _file_obj = StringIO.StringIO()

        _cfg = ConfigParser()
        _cfg.readfp(_file_obj)
        if _new is not None:
            _cfg.add_section("history")

        _cfg.set("history", "last_synced", _value)
        _cfg.write(_file_obj)

        if _smb_connection is not None:
            write_string_file_smb(_smb_connection, os.path.join(_job.destination_folder, 'ofs_status.txt'), _file_obj)
        else:
            try:
                _file = open(os.path.join(_job.destination_folder, 'ofs_status.txt'), "r")
            except IOError:
                pass
def exportChannel(geo, channel):
	# Set the template for the file name
	fileName = '$ENTITY_$CHANNEL_$UDIM'
	fileExt = '.png'

	# Check for the project info file 
	cp = ConfigParser()
	projPath = mari.current.project().info().projectPath()[:-11]
	cp.read(os.path.join(projPath, ".projectInfo")) 
	exportPath = ""

	try:
		# Try and pull the last export path
		exportPath = cp.get("FilePaths", "Export")
	except:
		# If there was none, Prompt user for destination directory
		exportPath = mari.utils.getExistingDirectory(None, 'Select Map Export Path for \"' + channel.name() + '\"')
		if(len(exportPath) == 0):
			return
		else:
			# Save it to a project info file
			projInfo = ConfigParser()
			projInfo.add_section("FilePaths")
			projInfo.set("FilePaths", "Export", exportPath)
			projInfoFile = open(os.path.join(projPath, ".projectInfo"), "wb")
			projInfo.write(projInfoFile)

	# Save all images as PNG
	fullFilePath = exportPath + '/' + fileName + fileExt
	print fullFilePath
	channel.exportImagesFlattened(fullFilePath, mari.Image.DISABLE_SMALL_UNIFORMS)

	# Convert to RAT
	convertToRat(geo, exportPath + '/' + geo.name() + '_' + channel.name())