コード例 #1
0
 def testParsePropertiesInput(self):
     properties = Properties()
     properties.load(open(self.properties_file))
     self.assertEquals(23, len(properties.items()))
     self.assertEquals('Value00', properties['Key00'])
     self.assertEquals('Value01', properties['Key01'])
     self.assertEquals('Value02', properties['Key02'])
     self.assertEquals('Value03', properties['Key03'])
     self.assertEquals('Value04', properties['Key04'])
     self.assertEquals('Value05a, Value05b, Value05c', properties['Key05'])
     self.assertEquals('Value06a, Value06b, Value06c', properties['Key06'])
     self.assertEquals('Value07b', properties['Key07'])
     self.assertEquals(
         'Value08a, Value08b, Value08c, Value08d, Value08e, Value08f',
         properties['Key08'])
     self.assertEquals(
         'Value09a, Value09b, Value09c, Value09d, Value09e, Value09f',
         properties['Key09'])
     self.assertEquals('Value10', properties['Key10'])
     self.assertEquals('', properties['Key11'])
     self.assertEquals('Value12a, Value12b, Value12c', properties['Key12'])
     self.assertEquals('Value13 With Spaces', properties['Key13'])
     self.assertEquals('Value14 With Spaces', properties['Key14'])
     self.assertEquals('Value15 With Spaces', properties['Key15'])
     self.assertEquals('Value16', properties['Key16 With Spaces'])
     self.assertEquals('Value17', properties['Key17 With Spaces'])
     self.assertEquals('Value18 # Not a comment.', properties['Key18'])
     self.assertEquals('Value19 ! Not a comment.', properties['Key19'])
     self.assertEquals('Value20', properties['Key20=WithEquals'])
     self.assertEquals('Value21', properties['Key21:WithColon'])
     self.assertEquals('Value22', properties['Key22'])
コード例 #2
0
 def load_configuration(self):
     p = Properties()
     p.load(open(CONFIGURATION_PROPERTIES))
     self.producers_point = p['producers.point']
     # FIXME: auto acquire the name according to the machine's ip
     self.cluster_name = socket.gethostname().split('-')[0]
     self.ip = get_public_ip()
コード例 #3
0
 def _testParsePropertiesInput(self, stream):
   properties = Properties()
   properties.load(stream)
   self.assertEquals(23, len(properties.items()))
   self.assertEquals('Value00', properties['Key00'])
   self.assertEquals('Value01', properties['Key01'])
   self.assertEquals('Value02', properties['Key02'])
   self.assertEquals('Value03', properties['Key03'])
   self.assertEquals('Value04', properties['Key04'])
   self.assertEquals('Value05a, Value05b, Value05c', properties['Key05'])
   self.assertEquals('Value06a, Value06b, Value06c', properties['Key06'])
   self.assertEquals('Value07b', properties['Key07'])
   self.assertEquals(
       'Value08a, Value08b, Value08c, Value08d, Value08e, Value08f',
       properties['Key08'])
   self.assertEquals(
       'Value09a, Value09b, Value09c, Value09d, Value09e, Value09f',
       properties['Key09'])
   self.assertEquals('Value10', properties['Key10'])
   self.assertEquals('', properties['Key11'])
   self.assertEquals('Value12a, Value12b, Value12c', properties['Key12'])
   self.assertEquals('Value13 With Spaces', properties['Key13'])
   self.assertEquals('Value14 With Spaces', properties['Key14'])
   self.assertEquals('Value15 With Spaces', properties['Key15'])
   self.assertEquals('Value16', properties['Key16 With Spaces'])
   self.assertEquals('Value17', properties['Key17 With Spaces'])
   self.assertEquals('Value18 # Not a comment.', properties['Key18'])
   self.assertEquals('Value19 ! Not a comment.', properties['Key19'])
   self.assertEquals('Value20', properties['Key20=WithEquals'])
   self.assertEquals('Value21', properties['Key21:WithColon'])
   self.assertEquals('Value22', properties['Key22'])
コード例 #4
0
ファイル: createResourceZip.py プロジェクト: thuskey/wagic
def getFilename():
    p = Properties();
    p.load(open('../../build.number.properties'));
    minor = p['build.minor'];
    major = p['build.major'];
    point = p['build.point'];
    filename = 'core_' + major + minor + point 
    return filename
コード例 #5
0
def getFilename(filename):
    p = Properties()
    p.load(open('../build.number.properties'))
    minor = p['build.minor']
    major = p['build.major']
    point = p['build.point']
    filename = filename + '-' + major + minor + point
    return filename
コード例 #6
0
 def __init__(self):
     self.prop = Properties()
     try:
         propertiesFile = open("../Files/Config.properties", 'r')
         self.prop.load(propertiesFile)
         self.prop.list()
     except FileNotFoundError as e:
         print(e)
コード例 #7
0
    def __init__(self):
        # Open and load the file. For each file property,
        # we assign it as the property of the object instance
        with open(APP_PROP_FILE, "r") as app_property_file:
            app_properties = Properties()
            app_properties.load(app_property_file)

            for property, value in app_properties.items():
                setattr(self, property, value)
コード例 #8
0
ファイル: upload-binaries.py プロジェクト: bjornsnoen/wagic
def suffixFilename(filename, build):
    p = Properties();
    p.load(open('projects/mtg/build.number.properties'));
    minor = p['build.minor'];
    major = p['build.major'];
    point = p['build.point'];
    name, extension = os.path.splitext(filename)
    filename = name + '-' + major + minor + point + '-' + build + extension
    return filename
コード例 #9
0
def suffixFilename(filename, build):
    p = Properties()
    p.load(open('projects/mtg/build.number.properties'))
    minor = p['build.minor']
    major = p['build.major']
    point = p['build.point']
    name, extension = os.path.splitext(filename)
    filename = name + '-' + major + minor + point + '-' + build + extension
    return filename
コード例 #10
0
def load_properties_locally(locale):
    props = Properties()
    props.load(
        open(os.path.abspath(
            os.path.join(os.path.abspath(os.path.join(os.getcwd(), os.pardir)),
                         os.pardir)) + '/main/resources/messages' + locale +
             '.properties',
             mode='r'))
    return props
コード例 #11
0
ファイル: util.py プロジェクト: HuangWenhuan0/email-build
def get_dependency_projects():
    if os.path.exists(project_filename):
        with open(project_filename) as fsock:
            properties = Properties()
            properties.load(fsock)

            project  = re.compile(r'android.library.reference.\d+')
            return (value for key, value in properties.items() if project.match(key))
    else:
        return []
コード例 #12
0
    def isPropertiesFileValid(filePath):
        """Verifies if a given properties file is valid"""

        p = Properties()
        try:
            p.load(open(filePath))
            return True

        except:
            return sys.exc_info()[1]
コード例 #13
0
ファイル: stockconfig.py プロジェクト: tastypotinc/twstock
def load(filename=DEFAULT_CONFIG_FILENAME):
    p = Properties()
    if os.path.isfile(filename):
        p.load(open('stock.properties'))

    if not p['listed.pricePath'].strip():
        p['listed.pricePath'] = DEFAULT_LISTED_PRICE_PATH
    if not p['listed.instPath'].strip():
        p['listed.instPath'] = DEFAULT_LISTED_INST_PATH

    if not p['listed.lastDownload'].strip():
        p['listed.lastDownload'] = DEFAULT_START_DATE
    if p['listed.isDownload'].strip() != 'false':
        p['listed.isDownload'] = 'true'

    if not p['listed.lastUpdateDb'].strip():
        p['listed.lastUpdateDb'] = DEFAULT_START_DATE
    if p['listed.isUpdateDb'].strip() != 'false':
        p['listed.isUpdateDb'] = 'true'

    if not p['listed.lastUpdateIdx'].strip():
        p['listed.lastUpdateIdx'] = DEFAULT_START_DATE
    if p['listed.isUpdateIdx'].strip() != 'false':
        p['listed.isUpdateIdx'] = 'true'

    if not p['otc.pricePath'].strip():
        p['otc.pricePath'] = DEFAULT_OTC_PRICE_PATH
    if not p['otc.instPath'].strip():
        p['otc.instPath'] = DEFAULT_OTC_INST_PATH

    if not p['otc.lastDownload'].strip():
        p['otc.lastDownload'] = DEFAULT_START_DATE
    if p['otc.isDownload'].strip() != 'false':
        p['otc.isDownload'] = 'true'

    if not p['otc.lastUpdateDb'].strip():
        p['otc.lastUpdateDb'] = DEFAULT_START_DATE
    if p['otc.isUpdateDb'].strip() != 'false':
        p['otc.isUpdateDb'] = 'true'

    if not p['otc.lastUpdateIdx'].strip():
        p['otc.lastUpdateIdx'] = DEFAULT_START_DATE
    if p['otc.isUpdateIdx'].strip() != 'false':
        p['otc.isUpdateIdx'] = 'true'

    if not p['db.server'].strip():
        p['db.server'] = 'SERVER_NAME'
    if not p['db.username'].strip():
        p['db.username'] = '******'
    if not p['db.password'].strip():
        p['db.password'] = '******'
    if not p['db.database'].strip():
        p['db.database'] = 'DATABASE_NAME'

    return p
コード例 #14
0
ファイル: stockconfig.py プロジェクト: angusan/twstock
def load(filename=DEFAULT_CONFIG_FILENAME):
    p = Properties()
    if os.path.isfile(filename):
        p.load(open('stock.properties'))

    if not p['listed.pricePath'].strip():
        p['listed.pricePath'] = DEFAULT_LISTED_PRICE_PATH
    if not p['listed.instPath'].strip():
        p['listed.instPath'] = DEFAULT_LISTED_INST_PATH
    
    if not p['listed.lastDownload'].strip():
        p['listed.lastDownload'] = DEFAULT_START_DATE
    if p['listed.isDownload'].strip() != 'false':
        p['listed.isDownload'] = 'true'
    
    if not p['listed.lastUpdateDb'].strip():
        p['listed.lastUpdateDb'] = DEFAULT_START_DATE
    if p['listed.isUpdateDb'].strip() != 'false':
        p['listed.isUpdateDb'] = 'true'
    
    if not p['listed.lastUpdateIdx'].strip():
        p['listed.lastUpdateIdx'] = DEFAULT_START_DATE
    if p['listed.isUpdateIdx'].strip() != 'false':
        p['listed.isUpdateIdx'] = 'true'

    if not p['otc.pricePath'].strip():
        p['otc.pricePath'] = DEFAULT_OTC_PRICE_PATH
    if not p['otc.instPath'].strip():
        p['otc.instPath'] = DEFAULT_OTC_INST_PATH
        
    if not p['otc.lastDownload'].strip():
        p['otc.lastDownload'] = DEFAULT_START_DATE
    if p['otc.isDownload'].strip() != 'false':
        p['otc.isDownload'] = 'true'
    
    if not p['otc.lastUpdateDb'].strip():
        p['otc.lastUpdateDb'] = DEFAULT_START_DATE
    if p['otc.isUpdateDb'].strip() !='false':
        p['otc.isUpdateDb'] = 'true'
    
    if not p['otc.lastUpdateIdx'].strip():
        p['otc.lastUpdateIdx'] = DEFAULT_START_DATE
    if p['otc.isUpdateIdx'].strip() !='false':
        p['otc.isUpdateIdx'] = 'true'

    if not p['db.server'].strip():
        p['db.server'] = 'SERVER_NAME'
    if not p['db.username'].strip():
        p['db.username'] = '******'
    if not p['db.password'].strip():
        p['db.password'] = '******'
    if not p['db.database'].strip():
        p['db.database'] = 'DATABASE_NAME'

    return p
コード例 #15
0
ファイル: common.py プロジェクト: DavidjohnBlodgett/on-tools
def parse_property_file(filename):
    """
    parse java properties file
    :param filename: the path of the properties file
    :return: dictionary loaded from the file
    """
    if not os.path.isfile(filename):
        raise RuntimeError("No file found for parameter at {0}".format(filename))
    p = Properties()
    p.load(open(filename))
    return p
コード例 #16
0
 def __init__(self):
     self.driver = webdriver.Chrome(
         executable_path=
         "/home/easyway/Desktop/selnium jars/chromedriver_linux64/chromedriver"
     )
     self.p = Properties()
     self.p.load(
         open(
             '/home/easyway/Music/github/SeleniumWithPython/config.properties'
         ))
     self.p.list()
コード例 #17
0
    def __init__(self):
        self.propAbhi = Properties()
        try:
            propertiesFile = open("./Files/Config.properties")
            self.propAbhi.load(propertiesFile)
            self.propAbhi.list()        
        except FileNotFoundError as e:
            print(e)

        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)
        self.driver = null
コード例 #18
0
class Config(object):
    def __init__(self, filepath):
        self.filepath = filepath
        self.config = Properties()
        with open(filepath) as file:
            self.config.load(file)

    def get_property(self, key):
        return self.config[key]

    def has_property(self, key):
        return key in self.config.propertyNames()
コード例 #19
0
class Config(object):
    def __init__(self, filepath):
        self.filepath = filepath
        self.config = Properties()
        with open(filepath) as file:
            self.config.load(file)

    def get_property(self, key):
        return self.config[key]

    def has_property(self, key):
        return key in self.config.propertyNames()
コード例 #20
0
def parse_property_file(filename):
    """
    parse java properties file
    :param filename: the path of the properties file
    :return: dictionary loaded from the file
    """
    if not os.path.isfile(filename):
        raise RuntimeError(
            "No file found for parameter at {0}".format(filename))
    p = Properties()
    p.load(open(filename))
    return p
コード例 #21
0
 def __generate_workload_config(self, extraneous_config):
     # Read base workload properties into a dict if we haven't already
     if self.__base_workload_props is None:
         props = Properties()
         with open(self.workload_path) as wf:
             props.load(wf)
         self.__base_workload_props = props.getPropertyDict()
     if extraneous_config is None:
         extraneous_config = {}
     # Merge base workload properties with extraneous options
     workload_config = dict(self.__base_workload_props)
     workload_config.update(extraneous_config)
     # Merge and return the workload config dict
     return workload_config
コード例 #22
0
def updateConfigReport():
    for model in [file for file in glob.glob('./*.model')]:
        print('\tChecking [{0}]'.format(model))
        type, target, spec = readModel(model)
        print('\t\tType: {0}, Target: {1}'.format(type, target))
        if type == 'XML':
            compareXML(target, spec, etree.XML(open(target, "r").read()))
        elif type == 'OS':
            compareOS(target, spec)
        elif type == 'properties':
            p = Properties()
            p.load(open(target, "r"))
            compareProperties(target, spec, p)
        else:
            print('\t{0} is invalid.'.format(model))
コード例 #23
0
def run_servers():
    print "Running Servers..."
    p = Properties()
    p.load(open(property_file_name, 'r'))
    hostname = p[configHostname]
    port = p[configPortname]

    status = ssh(
        server_machines["ConfigServer"][0], server_machines["ConfigServer"][1],
        "cd " + server_folder + " && java -jar " + server_folder +
        "ConfigServer.jar")
    if status != 0:
        print "Error running ConfigServer."
    print "Started ConfigServer on " + server_machines["ConfigServer"][
        0] + "..."
    status = ssh(server_machines["ConfigServer"][0],
                 server_machines["ConfigServer"][1],
                 "cd " + server_folder +
                 " && ps aux | grep '[j]ava -jar /home' | grep " +
                 server_machines["ConfigServer"][1] +
                 " | awk '{print \$2}' > pid",
                 blocking=True,
                 verbose=True)
    if status != 0:
        print "Error saving pid file."

    time.sleep(1)
    for i in server_machines:
        if i == "ConfigServer":
            continue
        status = ssh(
            server_machines[i][0], server_machines[i][1],
            "cd " + server_folder + " && java -jar " + server_folder + i +
            ".jar " + hostname + " " + port)
        if status != 0:
            print "Error running " + i + "."
        else:
            print "Started " + i + " on " + server_machines[i][0] + "..."
        status = ssh(server_machines[i][0],
                     server_machines[i][1],
                     "cd " + server_folder +
                     " && ps aux | grep '[j]ava -jar /home' | grep " +
                     server_machines[i][1] + " | awk '{print \$2}' > pid",
                     blocking=True,
                     verbose=True)
        if status != 0:
            print "Error saving pid file."
    time.sleep(2)
コード例 #24
0
ファイル: gnip_test.py プロジェクト: jvaleski/gnip-python
    def __init__(self,*args):
        unittest.TestCase.__init__(self, *args)
        index = int(__file__.rfind("/"))
        basedir = __file__[0:index]

        p = Properties()
        p.load(open(basedir + '/gnip_account.properties'))
        p.load(open(basedir + '/test.properties'))
        self.gnip = Gnip(p['gnip.username'], p['gnip.password'], p['gnip.server'])
        self.testpublisher = p['gnip.test.publisher']
        self.testpublisherscope = p['gnip.test.publisher.scope']
        self.success = Result('Success')
        self.filterXml = None
        self.rules = None
        self.filterName = None
        self.filterFullData = None
コード例 #25
0
def readModel(modelFile):
    fd = open(modelFile, "r")
    targetline = fd.readline()
    target = re.match("compareTo\((XML|OS|properties)\):\s*(.*)", targetline)
    if target is not None:
        if target.groups()[0] == 'XML': spec = etree.XML(fd.read())
        elif target.groups()[0] == 'OS':
            spec = yaml.load(fd.read(), Loader=yaml.FullLoader)
        elif target.groups()[0] == 'properties':
            p = Properties()
            p.load(fd)
            spec = p
        else:
            spec = None
        return target.groups()[0], target.groups()[1], spec
    else:
        return None, None, None
コード例 #26
0
ファイル: jitsi.py プロジェクト: rostendorf/otrfileconverter
    def parse(settingsdir=None):
        if settingsdir == None:
            settingsdir = JitsiProperties.path
        p = Properties()
        p.load(open(os.path.join(settingsdir, JitsiProperties.propertiesfile)))
        keydict = dict()
        for item in p.items():
            propkey = item[0]
            name = ""
            if re.match("net\.java\.sip\.communicator\.impl\.protocol\.jabber\.acc[0-9]+\.ACCOUNT_UID", propkey):
                name = JitsiProperties._parse_account_uid(item[1])
                if name in keydict:
                    key = keydict[name]
                else:
                    key = dict()
                    key["name"] = name
                    key["protocol"] = "prpl-jabber"
                    keydict[name] = key

                propkey_base = "net.java.sip.communicator.plugin.otr." + re.sub("[^a-zA-Z0-9_]", "_", item[1])
                private_key = p.getProperty(propkey_base + "_privateKey").strip()
                public_key = p.getProperty(propkey_base + "_publicKey").strip()
                numdict = util.ParsePkcs8(private_key)
                key["x"] = numdict["x"]
                numdict = util.ParseX509(public_key)
                for num in ("y", "g", "p", "q"):
                    key[num] = numdict[num]
                key["fingerprint"] = util.fingerprint((key["y"], key["g"], key["p"], key["q"]))
                verifiedkey = (
                    "net.java.sip.communicator.plugin.otr."
                    + re.sub("[^a-zA-Z0-9_]", "_", key["name"])
                    + "_publicKey_verified"
                )
                if p.getProperty(verifiedkey).strip() == "true":
                    key["verification"] = "verified"
            elif re.match("net\.java\.sip\.communicator\.plugin\.otr\..*_publicKey_verified", propkey):
                name, protocol = JitsiProperties._parse_account_from_propkey(settingsdir, propkey)
                if name != None:
                    if name not in keydict:
                        key = dict()
                        key["name"] = name
                        keydict[name] = key
                    if protocol and "protocol" not in keydict[name]:
                        keydict[name]["protocol"] = protocol
                    keydict[name]["verification"] = "verified"
            # if the protocol name is included in the property name, its a local account with private key
            elif re.match("net\.java\.sip\.communicator\.plugin\.otr\..*_publicKey", propkey) and not re.match(
                "net\.java\.sip\.communicator\.plugin\.otr\.(Jabber_|Google_Talk_)", propkey
            ):
                name, ignored = JitsiProperties._parse_account_from_propkey(settingsdir, propkey)
                if name not in keydict:
                    key = dict()
                    key["name"] = name
                    key["protocol"] = "prpl-jabber"
                    keydict[name] = key
                numdict = util.ParseX509(item[1])
                for num in ("y", "g", "p", "q"):
                    key[num] = numdict[num]
                key["fingerprint"] = util.fingerprint((key["y"], key["g"], key["p"], key["q"]))
        return keydict
コード例 #27
0
ファイル: exports.py プロジェクト: pritishmishra/xmake
def write_version_properties(build_cfg):
    p = Properties()
    log.info('version is ' + build_cfg.version())
    log.info('scm_url is ' + str(build_cfg.scm_snapshot_url()))
    p.setProperty('release_version', build_cfg.version())
    p.setProperty('scm_url', str(build_cfg.scm_snapshot_url()))

    #     pairs = [('release_version', build_cfg.version()),
    #              ('scm_url', build_cfg.scm_snapshot_url())]
    #     contents = '\n'.join([key + '=' + str(value) for (key, value) in pairs])
    with open(build_cfg.version_properties_file(), 'w') as f:
        p.store(f)
コード例 #28
0
ファイル: jitsi.py プロジェクト: the-solipsist/keysync
    def parse(settingsdir=None):
        if settingsdir == None:
            settingsdir = JitsiProperties.path
        p = Properties()
        p.load(open(os.path.join(settingsdir, JitsiProperties.propertiesfile)))
        keydict = dict()
        for item in p.items():
            propkey = item[0]
            name = ''
            if re.match('net\.java\.sip\.communicator\.impl\.protocol\.jabber\.acc[0-9]+\.ACCOUNT_UID', propkey):
                name = JitsiProperties._parse_account_uid(item[1])
                if name in keydict:
                    key = keydict[name]
                else:
                    key = dict()
                    key['name'] = name
                    key['protocol'] = 'prpl-jabber'
                    keydict[name] = key

                propkey_base = ('net.java.sip.communicator.plugin.otr.'
                                + re.sub('[^a-zA-Z0-9_]', '_', item[1]))
                private_key = p.getProperty(propkey_base + '_privateKey').strip()
                public_key = p.getProperty(propkey_base + '_publicKey').strip()
                numdict = util.ParsePkcs8(private_key)
                key['x'] = numdict['x']
                numdict = util.ParseX509(public_key)
                for num in ('y', 'g', 'p', 'q'):
                    key[num] = numdict[num]
                key['fingerprint'] = util.fingerprint((key['y'], key['g'], key['p'], key['q']))
                verifiedkey = ('net.java.sip.communicator.plugin.otr.'
                               + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                               + '_publicKey_verified')
                if p.getProperty(verifiedkey).strip() == 'true':
                    key['verification'] = 'verified'
            elif (re.match('net\.java\.sip\.communicator\.plugin\.otr\..*_publicKey_verified', propkey)):
                name, protocol = JitsiProperties._parse_account_from_propkey(settingsdir, propkey)
                if name != None:
                    if name not in keydict:
                        key = dict()
                        key['name'] = name
                        keydict[name] = key
                    if protocol and 'protocol' not in keydict[name]:
                        keydict[name]['protocol'] = protocol
                    keydict[name]['verification'] = 'verified'
            # if the protocol name is included in the property name, its a local account with private key
            elif (re.match('net\.java\.sip\.communicator\.plugin\.otr\..*_publicKey', propkey) and not
                  re.match('net\.java\.sip\.communicator\.plugin\.otr\.(Jabber_|Google_Talk_)', propkey)):
                name, ignored = JitsiProperties._parse_account_from_propkey(settingsdir, propkey)
                if name not in keydict:
                    key = dict()
                    key['name'] = name
                    key['protocol'] = 'prpl-jabber'
                    keydict[name] = key
                numdict = util.ParseX509(item[1])
                for num in ('y', 'g', 'p', 'q'):
                    key[num] = numdict[num]
                key['fingerprint'] = util.fingerprint((key['y'], key['g'], key['p'], key['q']))
        return keydict
コード例 #29
0
class HandlingObjectRepository:
    def __init__(self):
        self.driver = webdriver.Chrome(
            executable_path=
            "/home/easyway/Desktop/selnium jars/chromedriver_linux64/chromedriver"
        )
        self.p = Properties()
        self.p.load(
            open(
                '/home/easyway/Music/github/SeleniumWithPython/config.properties'
            ))
        self.p.list()

    def Handling_Object_Repository(self):
        self.driver.get(self.p["url"])
        print(self.driver.title)
        assert self.driver.title == self.p["title"], "Title is not as expected"

    def teardown(self):
        self.driver.close()
コード例 #30
0
    def gather_dependencies(self):
        log.info('gathering dependencies...')
        self.npm(['shrinkwrap'])
        shrinkwrapFile = join(self.module_dir, 'npm-shrinkwrap.json')
        if is_existing_file(shrinkwrapFile):
            move(shrinkwrapFile, self.shrinkwrap)

        # clean shrinkwrap file see spec on https://wiki.wdf.sap.corp/wiki/display/xs2/Filtering+SAP-internal+metadata+before+release
        cleanedShrinwrap = {}
        with open(self.shrinkwrap, 'r') as f:
            cleanedShrinwrap = json.load(f)

        keystoremove = []
        self._clean_shrinkwrap(cleanedShrinwrap,
                               listofkeytoremove=keystoremove)
        for keys in keystoremove:
            shrinkwrappart = cleanedShrinwrap
            for key in keys[:-1]:
                shrinkwrappart = shrinkwrappart[key]
            shrinkwrappart.pop(keys[-1], None)

        with open(self.shrinkwrap, 'w') as jsonfile:
            json.dump(cleanedShrinwrap, jsonfile, indent=2)

        dep = self.module_dir
        p = Properties()
        for (m, v) in self.list_deps(join(dep), ''):
            p.setProperty(m, v)
        with open(self.deps, 'w') as f:
            p.store(f)
        copyfile(self.deps, join(dep, 'dependencies'))
コード例 #31
0
    def __init__(self, username, password, gnip_server=None, properties_file=None):
        """Initialize the class.

        @type username string
        @param username Your Gnip account username
        @type password string
        @param password Your Gnip account password
        @type gnip_server string
        @param gnip_server The Gnip server to connect to

        Initializes a Gnip class by setting up authentication
        information, used to log into the Gnip service.

        """

        p = Properties()
        if properties_file is not None:
            p.load(open(properties_file))
        else:
            index = int(__file__.rfind("/"))
            basedir = __file__[0:index]
            p.load(open(basedir + '/gnip.properties'))
        
        # Determine base Gnip URL
        if (gnip_server is None):
            self.base_url = p['gnip.server']
        else:
            self.base_url = gnip_server
        
        self.tunnel_over_post = bool(p['gnip.tunnel.over.post=false'])

        # Configure authentication
        self.client = httplib2.Http(timeout = int(p['gnip.http.timeout']))
        self.client.add_credentials(username, password)

        self.headers = {}
        self.headers['Accept'] = 'gzip, application/xml'
        self.headers['User-Agent'] = 'Gnip-Client-Python/2.1.0'
        self.headers['Content-Encoding'] = 'gzip'
        self.headers['Content-Type'] = 'application/xml'
コード例 #32
0
    def __setattr__(self, name, value):
        # For each property assigned to the instance object, we write it to the
        #file, If it doesn't exist we add it.
        app_properties = Properties()
        with open(APP_PROP_FILE, "r") as app_property_file:
            app_properties.load(app_property_file)
            current_properties = app_properties.propertyNames()

        if name not in current_properties or value != app_properties.get(name):
            with open(APP_PROP_FILE, "w") as app_property_file:
                app_properties[name] = value
                app_properties.store(app_property_file)

        super(MyAppProperties, self).__setattr__(name, value)
コード例 #33
0
ファイル: sendbirdy.py プロジェクト: tcbutler320/SendBirdy
def main():
    p = Properties()
    p.load(open('res/proj.properties'))

    print(c.sendBirdyHeader)
    ts = time.gmtime()
    ts2 = time.asctime(ts)

    if (len(sys.argv)
        ) <= 1:  # if no arguments are provided, print usage and exit
        print(c.errorMsg + c.askForHelp)
        print("{!}-----[Settings]--- Workspace: " + p['WORKSPACE'])
        print("{!}-----[Settings]--- hinge-id: " + p['HINGE-ID'])
        print("{!}-----[Settings]--- hinge-token: " + p['HINGE-TOKEN'])
        sys.exit(0)
    else:

        # Get Options

        options, remainder = getopt.getopt(sys.argv[1:], 'o:v', [
            'help',
            'app=',
            'put=',
            'interactive=',
            'version',
        ])
        for opt, arg in options:
            if opt in ('-h', '--help'):
                print_help()
            elif opt in ('-a', '--app'):
                c.app = arg
            elif opt in ('-i', '--interactive'):
                if arg == "yes":
                    interactive_mode = True
            elif opt == ('-i', '--interactive'):
                if arg != "yes":
                    print("interactive")
            start_sendbirdy()
            sys.exit(0)
コード例 #34
0
def change_dbms_config(db):
    from pyjavaproperties import Properties
    p = Properties()
    p.load(open('config/database.properties'))
    print p['dbms']
    print db
    p['dbms'] = db
    p.store(open('config/database.properties', 'w'))
コード例 #35
0
 def get_data_from_property_file(self, file_name):
     """| Usage |
         Gets data from .property file and returns dictionary.
         For more information on dictionary: https://github.com/robotframework/robotframework/blob/master/atest/testdata/standard_libraries/collections/dictionary.robot
         | Arguents |
         'file_name' = .property file location
             Example:
                 |***TestCases*** |
                 ${dict} | Get Data From Property File | ${filename}
                 ${value} | Get From Dictionary | ${dict} | ${key}
     """
     if not os.path.exists(file_name):
         raise AssertionError("File not found error :" + file_name +
                              " doesn't exist")
     else:
         try:
             p = Properties()
             p.load(open(file_name))
             return p
         except:
             raise AssertionError(
                 "Error in Properties file. Please pass standard properties files"
             )
コード例 #36
0
def update_properties_file(properties_file, new_properties):
    p = Properties()
    logging.debug('Opening file %s', properties_file)
    p.load(open(properties_file))
    for name, value in new_properties:
        logging.info('Setting new value of %s to %s', name, value)
        p[name] = value
    logging.debug('Saving file %s with new values', properties_file)
    p.store(open(properties_file, 'w'))
コード例 #37
0
def format(file):

    p = Properties()
    p.load(open('res/proj.properties'))

    dt = datetime.datetime.now().strftime("%Y%m%d%H%M")

    try:
        for line in open(file, 'r'):
            parsed = json.loads(line)
            formatted_outfile = str(p.getProperty('FORMATTEDOUTFILE')) + "sendbirdy-" + dt + ".json"
            try:
                f = open(formatted_outfile, "a")
                f.write(json.dumps(parsed, indent=4, sort_keys=True))
                f.close()
            except IOError as io:
                print("{!}----- I/O error({0}): {1}"+ format(io.errno))
    except Exception as e:
        print(c.indent_msg + c.indent_err + e)

    print(c.indent_msg + c.indent_info + " Output Located : [" + formatted_outfile)


    return
コード例 #38
0
ファイル: LibDriver.py プロジェクト: biswajit-713/STAF
def get_property_value(property_name):

    cur_path = os.getcwd()
    ui_map_file = os.path.join(cur_path, '..' + os.sep,
                               'STAF_Config' + os.sep + 'ui_map.properties')
    ui_map_file = os.path.abspath(ui_map_file)

    prop = Properties()
    prop.load(open(ui_map_file))

    if prop.getProperty(property_name).strip() == "":
        return "Property not found"
    else:
        return prop.getProperty(property_name)
コード例 #39
0
def createResult(path):
    all_dir=getDirList(path)

    varss=['project.dir','outputFile']
    vars2=['outputFile','project.dir']
    for x in all_dir:
        print x
        p = Properties()
        p.load(open('rouge.properties'))

        for name, value in [('project.dir', x), ('outputFile', str(x+'_results.csv'))]:
            p[name] = value
            
        p.store(open('rouge.properties', 'w'))
        
        #time.sleep(30)
        runJar(path)
コード例 #40
0
 def testParsePropertiesInput(self):
     properties = Properties()
     properties.load(open(self.properties_file))
     self.assertEqual(25, len(properties.items()))
     self.assertEqual('Value00', properties['Key00'])
     self.assertEqual('Value01', properties['Key01'])
     self.assertEqual('Value02', properties['Key02'])
     self.assertEqual('Value03', properties['Key03'])
     self.assertEqual('Value04', properties['Key04'])
     self.assertEqual('Value05a, Value05b, Value05c', properties['Key05'])
     self.assertEqual('Value06a, Value06b, Value06c', properties['Key06'])
     self.assertEqual('Value07b', properties['Key07'])
     self.assertEqual(
         'Value08a, Value08b, Value08c, Value08d, Value08e, Value08f',
         properties['Key08'])
     self.assertEqual(
         'Value09a, Value09b, Value09c, Value09d, Value09e, Value09f',
         properties['Key09'])
     self.assertEqual('Value10', properties['Key10'])
     self.assertEqual('', properties['Key11'])
     self.assertEqual('Value12a, Value12b, Value12c', properties['Key12'])
     self.assertEqual('Value13 With Spaces', properties['Key13'])
     self.assertEqual('Value14 With Spaces', properties['Key14'])
     self.assertEqual('Value15 With Spaces', properties['Key15'])
     self.assertEqual('Value16', properties['Key16 With Spaces'])
     self.assertEqual('Value17', properties['Key17 With Spaces'])
     self.assertEqual('Value18 # Not a comment.', properties['Key18'])
     self.assertEqual('Value19 ! Not a comment.', properties['Key19'])
     # Single referenced property
     self.assertEqual('Value19 ! Not a comment.Value20',
                      properties['Key20'])
     self.assertEqual('Value21', properties['Key21=WithEquals'])
     self.assertEqual('Value22', properties['Key22:WithColon'])
     self.assertEqual('Value23', properties['Key23'])
     # Multiple referenced properties with separator
     self.assertEqual(
         'Value18 # Not a comment.-separator-Value19 ! Not a comment.',
         properties['Key24'])
     properties.store(open('saved.properties', 'w'))
コード例 #41
0
def connect_to_s3():
    boto_kwargs = {}
    try:
        with open(CONFIG_FILE, 'r') as f:
            p = Properties()
            p.load(f)

            access_key = p.get('accessKey')
            if access_key:
                logger.debug('Reading access key from {0}'.format(CONFIG_FILE))
                boto_kwargs['aws_access_key_id'] = access_key

            secret_key = p.get('secretKey')
            if secret_key:
                logger.debug('Reading access key from {0}'.format(CONFIG_FILE))
                boto_kwargs['aws_secret_access_key'] = secret_key
    except IOError:
        logger.debug('Could not load {0}, using ENV vars'.format(CONFIG_FILE))

    config = Config(connect_timeout=4, read_timeout=4)
    return boto3.resource('s3', config=config, **boto_kwargs)
コード例 #42
0
ファイル: toGraphML.py プロジェクト: sidney-shaw/BlueBench
# Convert an edgelist to graphML
# author Sidney Shaw

from igraph import *
from pyjavaproperties import Properties
from random import *

p = Properties()
p.load(open('../java/com/tinkerpop/bench/bench.properties'))

g = Graph.Read_Edgelist("")  # here specify the file to be converted

for v in g.vs:
    g.vs[v.index][p['bench.graph.property.id']] = "node:n" + str(v.index)
for e in g.es:
    g.es[e.index][p['bench.graph.property.id']] = "e" + str(e.index)
for e in g.es:
    g.es[e.index][p['bench.graph.label']] = p['bench.graph.label.friend']

g.write_graphml('../../' + p['bench.datasets.directory'] +
                '/amazon.graphml')
コード例 #43
0
ファイル: gen-mapping.py プロジェクト: mraad/spark-csv-es
def main():
    if len(sys.argv) == 1:
        sys.exit('Usage: {} <file.properties>'.format(sys.argv[0]))

    if not os.path.exists(sys.argv[1]):
        sys.exit('Error: {} does not exist !'.format(sys.argv[1]))

    p = Properties()
    p.load(open(sys.argv[1]))

    hex_sizes = p['hex.sizes'].split(';')
    hex_sizes = [hs.split(',')[0] for hs in hex_sizes]
    mappings = p['index.mapping'].split('/')[1]

    properties = {}

    fields = p['fields']
    for field in fields.split(';'):
        tokens = field.split(',')
        if tokens[0] == 'geo':
            name = tokens[1]
            properties[name] = {"type": "geo_point"}
            properties[name + "_xm"] = {"type": "float", "index": "no"}
            properties[name + "_ym"] = {"type": "float", "index": "no"}
            for hs in hex_sizes:
                properties[name + "_" + hs] = {"type": "string", "index": "not_analyzed"}
        elif tokens[0] == 'grid':
            name = tokens[1]
            properties[name] = {"type": "geo_point"}
            properties[name + "_xm"] = {"type": "float", "index": "no"}
            properties[name + "_ym"] = {"type": "float", "index": "no"}
            properties[name + "_g"] = {"type": "string", "index": "not_analyzed"}
        elif tokens[0] == 'int':
            properties[tokens[1]] = {"type": "integer"}
        elif tokens[0] == 'long':
            properties[tokens[1]] = {"type": "long"}
        elif tokens[0] == 'float':
            properties[tokens[1]] = {"type": "float"}
        elif tokens[0] == 'double':
            properties[tokens[1]] = {"type": "float"}
        elif tokens[0] == 'date' or tokens[0] == 'date-time':
            name = tokens[1]
            date_format = tokens[3] if len(tokens) == 4 else "YYYY-MM-dd HH:mm:ss"
            properties[name] = {"type": "date", "format": date_format}
            properties[name + "_yy"] = {"type": "integer"}
            properties[name + "_mm"] = {"type": "integer"}
            properties[name + "_dd"] = {"type": "integer"}
            properties[name + "_hh"] = {"type": "integer"}
            properties[name + "_dow"] = {"type": "integer"}
        elif tokens[0] == 'date-iso':
            name = tokens[1]
            date_format = tokens[3] if len(tokens) == 4 else "date_optional_time"
            properties[name] = {"type": "date", "format": date_format}
            properties[name + "_yy"] = {"type": "integer"}
            properties[name + "_mm"] = {"type": "integer"}
            properties[name + "_dd"] = {"type": "integer"}
            properties[name + "_hh"] = {"type": "integer"}
            properties[name + "_dow"] = {"type": "integer"}
        elif tokens[0] == 'date-only':
            name = tokens[1]
            date_format = tokens[3] if len(tokens) == 4 else "YYYY-MM-dd HH:mm:ss"
            properties[name] = {"type": "date", "format": date_format}
        else:
            name = tokens[1]
            properties[name] = {"type": "string", "index": "not_analyzed"}

    doc = {
        "settings": {
            "number_of_shards": 1,
            "number_of_replicas": 0,
            "refresh_interval": "-1",
            "auto_expand_replicas": "false"
        },
        "mappings": {mappings: {
            "_all": {
                "enabled": False
            },
            "_source": {
                "enabled": True
            },
            "properties": properties
        }}
    }

    basename, extension = os.path.splitext(sys.argv[1])
    with open(basename + ".json", "wb") as fw:
        fw.write(json.dumps(doc, ensure_ascii=False, indent=2))

    base = os.path.basename(sys.argv[1])
    name = os.path.splitext(base)[0]
    print("Post Example: curl -XPOST localhost:9200/{}?pretty -d @{}.json".format(name.lower(), basename))
コード例 #44
0
ファイル: jitsi.py プロジェクト: the-solipsist/keysync
    def write(keydict, savedir):
        if not os.path.exists(savedir):
            raise Exception('"' + savedir + '" does not exist!')

        loadfile = os.path.join(savedir, JitsiProperties.propertiesfile)
        savefile = loadfile
        if not os.path.exists(loadfile) and os.path.exists(JitsiProperties.path):
            print('Jitsi NOTICE: "' + loadfile + '" does not exist! Reading from:')
            loadfile = os.path.join(JitsiProperties.path, JitsiProperties.propertiesfile)
            print('\t"' + loadfile + '"')

        propkey_base = 'net.java.sip.communicator.plugin.otr.'
        p = Properties()
        p.load(open(loadfile))
        for name, key in keydict.items():
            if 'verification' in key and key['verification'] != '':
                verifiedkey = (propkey_base + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                               + '_publicKey_verified')
                p[verifiedkey] = 'true'
            if 'y' in key:
                pubkey = (propkey_base + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                          + '_publicKey')
                p.setProperty(pubkey, util.ExportDsaX509(key))
            if 'x' in key:
                protocol_id = 'UNKNOWN_'
                domain_id = 'unknown'
                servername = None
                if '@' in key['name']:
                    domainname = key['name'].split('@')[1]
                    domain_id = re.sub('[^a-zA-Z0-9_]', '_', domainname)
                    if domainname == 'chat.facebook.com':
                        protocol_id = 'Facebook_'
                    elif domainname == 'gmail.com' \
                            or domainname == 'google.com' \
                            or domainname == 'googlemail.com':
                        protocol_id = 'Google_Talk_'
                        servername = 'talk_google_com'
                    else:
                        protocol_id = 'Jabber_'
                else:
                    if key['protocol'] == 'prpl-icq':
                        protocol_id = 'ICQ_'
                        domain_id = 'icq_com'
                    elif key['protocol'] == 'prpl-yahoo':
                        protocol_id = 'Yahoo__'
                        domain_id = 'yahoo_com'
                # Writing
                pubkey = (propkey_base + protocol_id + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                          + '_' + domain_id + '_publicKey')
                p.setProperty(pubkey, util.ExportDsaX509(key))
                privkey = (propkey_base + protocol_id + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                           + '_' + domain_id + '_privateKey')
                p.setProperty(privkey, util.ExportDsaPkcs8(key))
		   
                if servername:
                    pubkey = (propkey_base + protocol_id + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                              + '_' + servername + '_publicKey')
                    p.setProperty(pubkey, util.ExportDsaX509(key))
                    privkey = (propkey_base + protocol_id + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                               + '_' + servername + '_privateKey')
                    p.setProperty(privkey, util.ExportDsaPkcs8(key))	
		   		
        p.store(open(savefile, 'w'))
コード例 #45
0
from flaskext.babel import Babel

app = Flask(__name__)

db = SQLAlchemy(app)

app.config.update(
	SECRET_KEY = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT',
	SQLALCHEMY_DATABASE_URI = 'sqlite:///db/app.sqlite',
	SQLALCHEMY_ECHO = True
)

babel = Babel(app)

#Open properties file
p = Properties()
p.load(open('properties/application.properties'))

#Logging
logging.basicConfig(level=logging.DEBUG)

#File
file = TimedRotatingFileHandler("log/dondeEstaciono.log", when="midnight", backupCount=10)
file.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s')

file.setFormatter(formatter)

logging.getLogger('').addHandler(file)
コード例 #46
0
def main():
    
    properties = Properties()
    properties.load(open("/home/khepry/home/distributions/PyDataGenerator/PyDataGenerator.properties"))
    properties.list()

    maxRows = 100
    maxXlsRows = 10000
    
    globalPath = '/home/khepry/home/distributions/PyDataGenerator/temp/'
    targetName = 'dataGenerator.csv'

    maxRows = int(properties.getProperty('maxRows', maxRows))
    maxXlsRows = int(properties.getProperty('maxXlsRows', maxXlsRows))

    globalPath = properties.getProperty('globalPath', globalPath)
    targetName = properties.getProperty('targetName', targetName)
    
    print("-- operating system --")
    print(platform.system())
    
    print("-- processing messages --")
    
    if platform.system() == 'Windows':
        xlsPgmPath = '"/Program Files/Microsoft Office 15/root/office15/EXCEL.EXE"'
        txtPgmPath = '"/Program Files (x86)/Notepad++/notepad++.exe"'
    else:
        xlsPgmPath = "libreoffice"
        txtPgmPath = "gedit"
    
    tgtFileFullPath = os.path.abspath(globalPath + targetName)
    tgtFile = open(tgtFileFullPath, 'w', newline='')

    bgnTime = tyme.time()

    rows = 0
    
    try:
        writer = csv.writer(tgtFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

        for i in range(0, maxRows):
            rows += 1
            
            record = Record()
            record.addField("UUID4", "UUID4").random()
            record.addField("Alpha", "Alpha").random(20, 25)
            record.addField("AlphaNumeric", "AlphaNumeric").random()
            record.addField("Numeric", "Numeric").random()
            record.addField("String", "String").random()
            record.addField("Range", "Range").random(12, 24)
            record.addField("Date", "Date").random(date(1980,1,1), date(2000,12,31))
            record.addField("DateTime", "DateTime").random(date(1980,1,1), date(2000,12,31))
            record.addField("AgeInYears","Numeric").years(date.today(), record.getField("Date").value)
            record.addField("AgeInMonths","Numeric").months(date.today(), record.getField("Date").value)
            record.addField("AgeInDays","Numeric").days(date.today(), record.getField("Date").value)
                
            if (i == 0):
                writer.writerow([key for key in record.fields.keys()])
            writer.writerow([field.text for field in record.fields.values()])
            
    finally:
        tgtFile.close()


    endTime = tyme.time()

    elapsedTime = endTime - bgnTime

    print("{:,}".format(rows) + ' records processed in ' + "{:,.4f}".format(elapsedTime) + ' seconds at ' + "{:,.4f}".format(rows / elapsedTime) + ' rows/second.')

    if (platform.system() == 'Windows'):
        if (rows < maxXlsRows):
            subprocess.call(xlsPgmPath + ' "' + tgtFileFullPath + '"')
        else:
            subprocess.call(txtPgmPath + ' "' + tgtFileFullPath + '"')
    else:
        if (rows < maxXlsRows):
            subprocess.call([xlsPgmPath, tgtFileFullPath])
        else:
            subprocess.call([txtPgmPath, tgtFileFullPath])
コード例 #47
0
ファイル: graph-creator.py プロジェクト: MLnick/tinkubator
# Generate Artificial Graphs
# Alex Averbuch ([email protected])

from igraph import *
from pyjavaproperties import Properties
from random import *

p = Properties()
p.load(open('../resources/com/tinkerpop/bench/bench.properties'))

degree = int(p['bench.graph.barabasi.degree'])
vertices = int(p['bench.graph.barabasi.vertices'])

g = Graph.Barabasi(n=vertices, m=degree, power=1, directed=False, zero_appeal=8)

for v in g.vs:
    g.vs[v.index][p['bench.graph.property.id']] = "v" + str(v.index)
for e in g.es:
    g.es[e.index][p['bench.graph.property.id']] = "e" + str(e.index)
for e in g.es:
    if random() < 0.5:
        g.es[e.index][p['bench.graph.label']] = p['bench.graph.label.friend']
    else:
        g.es[e.index][p['bench.graph.label']] = p['bench.graph.label.family']
g.write_graphml('../../../' + p['bench.datasets.directory'] + 
                '/' + p['bench.graph.barabasi.file'])
コード例 #48
0
 def _testParsePropertiesOutput(self, stream):
   properties = Properties()
   properties.setProperty('Key00', 'Value00')
   properties.setProperty('Key01', 'Value01')
   properties.setProperty('Key02', 'Value02')
   properties.setProperty('Key03', 'Value03')
   properties.setProperty('Key04', 'Value04')
   properties.setProperty('Key05', 'Value05a, Value05b, Value05c')
   properties.setProperty('Key06', 'Value06a, Value06b, Value06c',)
   properties.setProperty('Key07', 'Value07b')
   properties.setProperty('Key08',
       'Value08a, Value08b, Value08c, Value08d, Value08e, Value08f')
   properties.setProperty('Key09',
       'Value09a, Value09b, Value09c, Value09d, Value09e, Value09f')
   properties.setProperty('Key10', 'Value10')
   properties.setProperty('Key11', '')
   properties.setProperty('Key12', 'Value12a, Value12b, Value12c')
   properties.setProperty('Key13', 'Value13 With Spaces')
   properties.setProperty('Key14', 'Value14 With Spaces')
   properties.setProperty('Key15', 'Value15 With Spaces')
   properties.setProperty('Key16 With Spaces', 'Value16')
   properties.setProperty('Key17 With Spaces', 'Value17')
   properties.setProperty('Key18', 'Value18 # Not a comment.')
   properties.setProperty('Key19', 'Value19 ! Not a comment.')
   properties.setProperty('Key20=WithEquals', 'Value20')
   properties.setProperty('Key21:WithColon', 'Value21')
   properties.setProperty('Key22', 'Value22')
   properties.store(stream)
コード例 #49
0
    sys.stderr.write("Unspecified graph generation model (please use --help for help)\n")
    sys.exit(1)

if output_filename is None:
    # output_filename = os.path.join(script_dir, '../../../' + p['bench.datasets.directory'] + '/' + p['bench.graph.barabasi.file'])
    sys.stderr.write("The output file name is not specified (please use --help for help)\n")
    sys.exit(1)

model = string.lower(model)


#
# Load the properties
#

p = Properties()
p.load(open(os.path.join(script_dir, '../resources/com/tinkerpop/bench/bench.properties')))


#
# Model "Barabasi"
#

if model == "barabasi":
    
    if param_m is None:
        param_m = int(p['bench.graph.barabasi.degree'])
    if param_n is None:
        param_n = int(p['bench.graph.barabasi.vertices'])

    sys.stderr.write("Generating a Barabasi graph with n=%d, m=%d\n" % (param_n, param_m))
コード例 #50
0
def check_for_lib_diffs(war_path, temp_portlet_path):
    '''
    Checks whether the jars in a war and on a deployed path are the same
    '''
    jars = {}
    # Calculate crc32 for all deployed jars
    webinf_lib_dir = os.path.join(temp_portlet_path, 'WEB-INF/lib/')
    if os.path.exists(webinf_lib_dir):
        for lib in os.listdir(webinf_lib_dir):
            path = os.path.join(temp_portlet_path, 'WEB-INF/lib/', lib)
            if os.path.isfile(path):
                with open(os.path.join(temp_portlet_path, 'WEB-INF/lib/', lib)) as jar:
                    jars['WEB-INF/lib/'+lib] = binascii.crc32(jar.read())
            else:
                jars['WEB-INF/lib/'+lib] = None  # directory assume changed

    # Process the war to be deployed
    with ZipFile(war_path, 'r') as war:
        # Process liferay dependencies
        dep_jars = ['util-taglib.jar', 'util-java.jar', 'util-bridges.jar']
        try:
            with war.open('WEB-INF/liferay-plugin-package.properties') as prop:
                p = Properties()
                # p.load(prop) does not work
                p._Properties__parse(prop.readlines())

                dep_jars.extend(p['portal-dependency-jars'].split(','))
        except KeyError:
            pass
        for jar in dep_jars:
            jars['WEB-INF/lib/'+jar] = 'LR_DEP'

        # Calculate crc32 for jars in war
        for info in war.infolist():
            if info.filename.startswith('WEB-INF/lib/') and not info.filename == 'WEB-INF/lib/':
                    crc = jars.get(info.filename, None)
                    if crc:
                        with war.open(info.filename) as lib:
                            crco = binascii.crc32(lib.read())  # info.CRC
                        jars[info.filename] = crco == crc
                    else:
                        jars[info.filename] = None

    # Iterate the file listing to check for missing/outdated/lingering
    # files
    needs_undeploy = False
    for filename, crc in jars.items():
        if crc == 'LR_DEP':
            pass
        elif crc is True:
            pass
        elif crc is None:
            LOG.info('{0} is missing'.format(filename))
        elif crc is False:
            LOG.info('{0} is out of date'.format(filename))
            needs_undeploy = True
        else:
            LOG.info('{0} is lingering'.format(filename))
            needs_undeploy = True

    return needs_undeploy
コード例 #51
0
    def get_file_items(self, window, files):        
        #les variables sont ici pour le dynamisme du dossier
        #variables
        
        if len(files) <= 0:
            return
        
        
        listFile=[]
        for i in range(0,len(files)):
            if "video" in files[i].get_mime_type() :
                listFile.append(files[i])
            
        if len(listFile)<=0:
            return
        
        
        menu = Nautilus.Menu()

        mainItem=Nautilus.MenuItem(
            name="MenuExtension::JMita2_Menu",
            label="Lire sur ...",
            tip=""
        )
        
        mainItem.set_submenu(menu)
        
        itemJMita2 = Nautilus.MenuItem(
            name="MenuExtension::JMita2_Item",
            label="Rechercher un appareil...",
            tip=""
        )
        
        itemAbout= Nautilus.MenuItem(
            name="MenuExtencion::JMita2_About",
            label="about JMita 2",
            tip=""
        )
        
        menu.append_item(itemJMita2)
        
        
        itemJMita2.connect('activate', self.menu_activate_cb, listFile)
        count=1
        
        if (os.path.exists(self.favoris)):
        
            allFavoris=os.listdir(self.favoris)
            for file in allFavoris:
                p=Properties()
                p.load(open(self.favoris+file))
                
                item=Nautilus.MenuItem(
                    name="MenuExtension::JMita2_Item_"+str(count),
                    label=p["name"],
                    tip=""
                )
                
                item.connect('activate',self.menu_activate_cb_favoris,listFile,p["identifier"])
                
                menu.append_item(item)
                count=count+1
                
        menu.append_item(itemAbout)
        
        return [mainItem]
コード例 #52
0
"""
Commandline parameter(s):

    first parameter must be the ARFF file

"""

# check commandline parameters
if (not (len(sys.argv) == 3)):
    print "Usage: supervised.py <ARFF-file> <Validation>"
    sys.exit()
crossvalidate = sys.argv[2]
rand = Random()              # seed from the system time

# load properties
p = Properties()
p.load(open('./ml.properties'))

# load data file
print "Loading data..."
trainfile = FileReader(sys.argv[1] + "-train.arff")
print "Loading " + sys.argv[1] + "-train.arff"
testfile = FileReader(sys.argv[1] + "-test.arff")
print "Loading " + sys.argv[1] + "-test.arff"
fulltrainset = Instances(trainfile)
fulltrainset.setClassIndex(fulltrainset.numAttributes() - 1)
testset = Instances(testfile)
testset.setClassIndex(testset.numAttributes() - 1)

# open output files
bufsize=0
コード例 #53
0
 def __init__(self, filepath):
     self.filepath = filepath
     self.config = Properties()
     with open(filepath) as file:
         self.config.load(file)
コード例 #54
0
ファイル: jitsi.py プロジェクト: abeluck/keysync
    def write(keydict, savedir):
        if not os.path.exists(savedir):
            raise Exception('"' + savedir + '" does not exist!')

        loadfile = os.path.join(savedir, JitsiProperties.propertiesfile)
        savefile = loadfile
        if not os.path.exists(loadfile) and os.path.exists(JitsiProperties.path):
            print('Jitsi NOTICE: "' + loadfile + '" does not exist! Reading from:')
            loadfile = os.path.join(JitsiProperties.path, JitsiProperties.propertiesfile)
            print('\t"' + loadfile + '"')

        propkey_base = "net.java.sip.communicator.plugin.otr."
        p = Properties()
        p.load(open(loadfile))
        for name, key in keydict.items():
            if "verification" in key and key["verification"] != "":
                verifiedkey = propkey_base + re.sub("[^a-zA-Z0-9_]", "_", key["name"]) + "_publicKey_verified"
                p[verifiedkey] = "true"
            if "y" in key:
                pubkey = propkey_base + re.sub("[^a-zA-Z0-9_]", "_", key["name"]) + "_publicKey"
                p.setProperty(pubkey, otrapps.util.ExportDsaX509(key))
            if "x" in key:
                protocol_id = "UNKNOWN_"
                domain_id = "unknown"
                servername = None
                if "@" in key["name"]:
                    domainname = key["name"].split("@")[1]
                    domain_id = re.sub("[^a-zA-Z0-9_]", "_", domainname)
                    if domainname == "chat.facebook.com":
                        protocol_id = "Facebook_"
                    elif domainname == "gmail.com" or domainname == "google.com" or domainname == "googlemail.com":
                        protocol_id = "Google_Talk_"
                        servername = "talk_google_com"
                    else:
                        protocol_id = "Jabber_"
                else:
                    if key["protocol"] == "prpl-icq":
                        protocol_id = "ICQ_"
                        domain_id = "icq_com"
                    elif key["protocol"] == "prpl-yahoo":
                        protocol_id = "Yahoo__"
                        domain_id = "yahoo_com"
                # Writing
                pubkey = (
                    propkey_base
                    + protocol_id
                    + re.sub("[^a-zA-Z0-9_]", "_", key["name"])
                    + "_"
                    + domain_id
                    + "_publicKey"
                )
                p.setProperty(pubkey, otrapps.util.ExportDsaX509(key))
                privkey = (
                    propkey_base
                    + protocol_id
                    + re.sub("[^a-zA-Z0-9_]", "_", key["name"])
                    + "_"
                    + domain_id
                    + "_privateKey"
                )
                p.setProperty(privkey, otrapps.util.ExportDsaPkcs8(key))

                if servername:
                    pubkey = (
                        propkey_base
                        + protocol_id
                        + re.sub("[^a-zA-Z0-9_]", "_", key["name"])
                        + "_"
                        + servername
                        + "_publicKey"
                    )
                    p.setProperty(pubkey, otrapps.util.ExportDsaX509(key))
                    privkey = (
                        propkey_base
                        + protocol_id
                        + re.sub("[^a-zA-Z0-9_]", "_", key["name"])
                        + "_"
                        + servername
                        + "_privateKey"
                    )
                    p.setProperty(privkey, otrapps.util.ExportDsaPkcs8(key))

        p.store(open(savefile, "w"))
コード例 #55
0
from pyjavaproperties import Properties
import sys
import os

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print "Usage: python prop_util.py <path to runtime.properties> <mydomain replacement>"
        sys.exit(1)
    runtime_filepath = sys.argv[1]
    print "Updating %s" % runtime_filepath
    p = Properties()
    p.load(open(runtime_filepath))
    print "****Properties before****"
    p.list()
    #Add/replace environment variables that begin with v_
    for key, value in [(key[2:], os.environ[key]) for key in os.environ if key.startswith("v_")]:
        print "Adding key %s: %s" % (key, value)
        p[key] = value
    #Replace mydomain in any values
    newdomain = sys.argv[2]
    for key, value in [(key, value) for (key, value) in p.iteritems() if "mydomain.edu" in value]:
        new_value = value.replace("mydomain.edu", newdomain)
        print "Changing key %s from %s to %s" % (key, value, new_value)
        p[key] = new_value
    #Set DB values based on docker-provided environment variables
    p['VitroConnection.DataSource.url'] = "http://db:8111/v1/graphs/sparql"
    p['VitroConnection.DataSource.username'] = '******'
    p['VitroConnection.DataSource.password'] = '******'
    print "****Properties after****"
    p.list()
    p.store(open(runtime_filepath,'w'))
コード例 #56
0
ファイル: jitsi.py プロジェクト: rostendorf/otrfileconverter
    def write(keydict, savedir):
        if not os.path.exists(savedir):
            raise Exception('"' + savedir + '" does not exist!')

        loadfile = os.path.join(savedir, JitsiProperties.propertiesfile)
        savefile = loadfile
        if not os.path.exists(loadfile) and os.path.exists(JitsiProperties.path):
            print 'Adium WARNING: "' + loadfile + '" does not exist! Reading from:'
            loadfile = os.path.join(JitsiProperties.path, JitsiProperties.propertiesfile)
            print '\t"' + loadfile + '"'

        propkey_base = "net.java.sip.communicator.plugin.otr."
        p = Properties()
        p.load(open(loadfile))
        for name, key in keydict.iteritems():
            if "verification" in key and key["verification"] != "":
                verifiedkey = propkey_base + re.sub("[^a-zA-Z0-9_]", "_", key["name"]) + "_publicKey_verified"
                p[verifiedkey] = "true"
            if "y" in key:
                pubkey = propkey_base + re.sub("[^a-zA-Z0-9_]", "_", key["name"]) + "_publicKey"
                p.setProperty(pubkey, util.ExportDsaX509(key))
            if "x" in key and "@" in key["name"]:
                pubkey = (
                    propkey_base
                    + "Jabber_"
                    + re.sub("[^a-zA-Z0-9_]", "_", key["name"])
                    + "_"
                    + re.sub("[^a-zA-Z0-9_]", "_", key["name"].split("@")[1])
                    + "_publicKey"
                )
                p.setProperty(pubkey, util.ExportDsaX509(key))
                privkey = (
                    propkey_base
                    + "Jabber_"
                    + re.sub("[^a-zA-Z0-9_]", "_", key["name"])
                    + "_"
                    + re.sub("[^a-zA-Z0-9_]", "_", key["name"].split("@")[1])
                    + "_privateKey"
                )
                p.setProperty(privkey, util.ExportDsaPkcs8(key))
        p.store(open(savefile, "w"))
コード例 #57
0
ファイル: jitsi.py プロジェクト: gitter-badger/keysync
    def write(keydict, savedir):
        if not os.path.exists(savedir):
            raise Exception('"' + savedir + '" does not exist!')

        loadfile = os.path.join(savedir, JitsiProperties.propertiesfile)
        savefile = loadfile
        if not os.path.exists(loadfile) and os.path.exists(JitsiProperties.path):
            print 'Adium WARNING: "' + loadfile + '" does not exist! Reading from:'
            loadfile = os.path.join(JitsiProperties.path, JitsiProperties.propertiesfile)
            print '\t"' + loadfile + '"'

        propkey_base = 'net.java.sip.communicator.plugin.otr.'
        p = Properties()
        p.load(open(loadfile))
        for name, key in keydict.iteritems():
            if 'verification' in key and key['verification'] != '':
                verifiedkey = (propkey_base + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                               + '_publicKey_verified')
                p[verifiedkey] = 'true'
            if 'y' in key:
                pubkey = (propkey_base + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                          + '_publicKey')
                p.setProperty(pubkey, util.ExportDsaX509(key))
            if 'x' in key:
                suffix2 = ''
                if '@' in key['name']:
                    suffix = re.sub('[^a-zA-Z0-9_]', '_', key['name'].split('@')[1])
                    if 'facebook' in key['name'].split('@')[1]:
                        protocolAcc = 'Facebook_'
                    elif 'gmail' in key['name'].split('@')[1]:
                        protocolAcc = 'Google_Talk_'
                        suffix2 = 'talk_google_com'
                    else:
                        protocolAcc = 'Jabber_'
                elif '@' not in key['name']:
                    if 'icq' in key['protocol']:
                        protocolAcc = 'ICQ_'
                        suffix = 'icq_com'
                    elif 'yahoo' in key['protocol']:
                        protocolAcc = 'Yahoo__'
                        suffix = 'yahoo_com'
                # Writing
                pubkey = (propkey_base + protocolAcc + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                          + '_' + suffix + '_publicKey')
                p.setProperty(pubkey, util.ExportDsaX509(key))
                privkey = (propkey_base + protocolAcc + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                           + '_' + suffix + '_privateKey')
                p.setProperty(privkey, util.ExportDsaPkcs8(key))
		   
                if suffix2 != '':
                    pubkey = (propkey_base + protocolAcc + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                              + '_' + suffix2 + '_publicKey')
                    p.setProperty(pubkey, util.ExportDsaX509(key))
                    privkey = (propkey_base + protocolAcc + re.sub('[^a-zA-Z0-9_]', '_', key['name'])
                               + '_' + suffix2 + '_privateKey')
                    p.setProperty(privkey, util.ExportDsaPkcs8(key))	
		   		
        p.store(open(savefile, 'w'))
コード例 #58
0
import string
from django.shortcuts import render_to_response
from pyjavaproperties import Properties
import urllib2
import json

import logging

# Get an instance of a logger
from ForsquareSampleApp.response_parser import parse_checkins, parse_places

logger = logging.getLogger(__name__)

p = Properties()
p.load(open('app.properties'))
client_id = p['client.id']
client_secret = p['client.secret']
redirect_uri = p['redirect.uri']

access_token = None

def access_page(request):
    return render_to_response("access_page.html", {'redirect_uri': redirect_uri,
                                                   'client_id': client_id})


def parse_code(request):
    code = request.GET['code']

    response = urllib2.urlopen(string.Template('https://foursquare.com/oauth2/access_token?client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&grant_type=authorization_code&redirect_uri=$REDIRECT_URI&code=$CODE')
                    .substitute({'CLIENT_ID': client_id,