Exemplo n.º 1
0
def generateMD5s(testset):
    db = dict()
    if(len(testset)):
#      print testset
      os.chdir(epocroot())
      tmpfilename = os.tmpnam( )
      print tmpfilename, '\n'
      f = open(tmpfilename,'w')
      for file in testset:
          entry = dict()
          entry['md5'] = 'xxx'
          db[file] = entry
          str = '%s%s' % (file,'\n')
          f.write(str)
      f.close()
      outputfile = os.tmpnam() 
      exestr = 'evalid -f %s %s %s' % (tmpfilename, epocroot(), outputfile)
#      print exestr
      exeresult = os.system(exestr) 
      if(exeresult):
        sys.exit('Fatal error executing: %s\nReported error: %s' % (exestr,os.strerror(exeresult)))
      else:  
        db = gethashes(db,outputfile)
        os.unlink(outputfile)
        os.unlink(tmpfilename)
    return db
Exemplo n.º 2
0
    def test_put_4m(self):
        if is_travis:
            return
        ostype = platform.system()
        if ostype.lower().find("windows") != -1:
            tmpf = "".join([os.getcwd(), os.tmpnam()])
        else:
            tmpf = os.tmpnam()
        dst = open(tmpf, 'wb')
        dst.write("abcd" * 1024 * 1024)
        dst.flush()

        policy = rs.PutPolicy(bucket)
        extra = resumable_io.PutExtra(bucket)
        extra.bucket = bucket
        extra.params = {"x:foo": "test"}
        key = "sdk_py_resumable_block_6_%s" % r(9)
        localfile = dst.name
        ret, err = resumable_io.put_file(policy.token(), key, localfile, extra)
        assert ret.get("x:foo") == "test", "return data not contains 'x:foo'"
        dst.close()
        os.remove(tmpf)

        assert err is None, err
        self.assertEqual(
            ret["hash"], "FnIVmMd_oaUV3MLDM6F9in4RMz2U", "hash not match")
        rs.Client().delete(bucket, key)
Exemplo n.º 3
0
def generateMD5s(testset):
    db = dict()
    if (len(testset)):
        #      print testset
        os.chdir(epocroot())
        tmpfilename = os.tmpnam()
        print tmpfilename, '\n'
        f = open(tmpfilename, 'w')
        for file in testset:
            entry = dict()
            entry['md5'] = 'xxx'
            db[file] = entry
            str = '%s%s' % (file, '\n')
            f.write(str)
        f.close()
        outputfile = os.tmpnam()
        exestr = 'evalid -f %s %s %s' % (tmpfilename, epocroot(), outputfile)
        #      print exestr
        exeresult = os.system(exestr)
        if (exeresult):
            sys.exit('Fatal error executing: %s\nReported error: %s' %
                     (exestr, os.strerror(exeresult)))
        else:
            db = gethashes(db, outputfile)
            os.unlink(outputfile)
            os.unlink(tmpfilename)
    return db
Exemplo n.º 4
0
def render_document():
    if request.method == 'POST':
        # check if the post request has component_id in data
        if 'session' in request.form:
            session_ = request.form['session']
            session_ = json.loads(session_)
            if session_:
                session_file_name_ = os.path.split(os.tmpnam())[1]
                document_file_name_ = os.path.split(os.tmpnam())[1]
                extension = '.properties'
                _save_session_to(car_rendered_documents_dir, session_, session_file_name_, extension)

                template_path_ = session_['template_path']

                template_file_path = os.path.join(car_templates_dir, template_path_)
                properties_file_path = os.path.join(car_rendered_documents_dir, session_file_name_ + extension)
                document_file_path = os.path.join(car_rendered_documents_dir, document_file_name_)

                g = JavaGateway()
                args = _create_args(document_file_path, properties_file_path, template_file_path, g)

                fassade = g.entry_point.getFassade()
                message = fassade.renderDocument(args)

                if os.path.isfile(document_file_path):
                    download_url = url_for('download_document', filename=document_file_name_)
                    return '<a href="' + download_url + '">download</a>'
                else:
                    return message
            else:
                return 'Session Invalid!'
Exemplo n.º 5
0
    def test_put(self):
        if is_travis:
            return
        src = urllib.urlopen("http://cheneya.qiniudn.com/hello_jpg")
        ostype = platform.system()
        if ostype.lower().find("windows") != -1:
            tmpf = "".join([os.getcwd(), os.tmpnam()])
        else:
            tmpf = os.tmpnam()
        dst = open(tmpf, 'wb')
        shutil.copyfileobj(src, dst)
        src.close()

        policy = rs.PutPolicy(bucket)
        extra = resumable_io.PutExtra(bucket)
        extra.bucket = bucket
        extra.params = {"x:foo": "test"}
        key = "sdk_py_resumable_block_5_%s" % r(9)
        localfile = dst.name
        ret, err = resumable_io.put_file(policy.token(), key, localfile, extra)
        assert ret.get("x:foo") == "test", "return data not contains 'x:foo'"
        dst.close()
        os.remove(tmpf)

        assert err is None, err
        self.assertEqual(
            ret["hash"], "FnyTMUqPNRTdk1Wou7oLqDHkBm_p", "hash not match")
        rs.Client().delete(bucket, key)
Exemplo n.º 6
0
    def test_put(self):
        if is_travis:
            return
        src = urllib.urlopen("http://cheneya.qiniudn.com/hello_jpg")
        ostype = platform.system()
        if ostype.lower().find("windows") != -1:
            tmpf = "".join([os.getcwd(), os.tmpnam()])
        else:
            tmpf = os.tmpnam()
        dst = open(tmpf, 'wb')
        shutil.copyfileobj(src, dst)
        src.close()

        policy = rs.PutPolicy(bucket)
        extra = resumable_io.PutExtra(bucket)
        extra.bucket = bucket
        extra.params = {"x:foo": "test"}
        key = "sdk_py_resumable_block_5_%s" % r(9)
        localfile = dst.name
        ret, err = resumable_io.put_file(policy.token(), key, localfile, extra)
        assert ret.get("x:foo") == "test", "return data not contains 'x:foo'"
        dst.close()
        os.remove(tmpf)

        assert err is None, err
        self.assertEqual(ret["hash"], "FnyTMUqPNRTdk1Wou7oLqDHkBm_p",
                         "hash not match")
        rs.Client().delete(bucket, key)
Exemplo n.º 7
0
    def test_put_4m(self):
        if is_travis:
            return
        ostype = platform.system()
        if ostype.lower().find("windows") != -1:
            tmpf = "".join([os.getcwd(), os.tmpnam()])
        else:
            tmpf = os.tmpnam()
        dst = open(tmpf, 'wb')
        dst.write("abcd" * 1024 * 1024)
        dst.flush()

        policy = rs.PutPolicy(bucket)
        extra = resumable_io.PutExtra(bucket)
        extra.bucket = bucket
        extra.params = {"x:foo": "test"}
        key = "sdk_py_resumable_block_6_%s" % r(9)
        localfile = dst.name
        ret, err = resumable_io.put_file(policy.token(), key, localfile, extra)
        assert ret.get("x:foo") == "test", "return data not contains 'x:foo'"
        dst.close()
        os.remove(tmpf)

        assert err is None, err
        self.assertEqual(ret["hash"], "FnIVmMd_oaUV3MLDM6F9in4RMz2U",
                         "hash not match")
        rs.Client().delete(bucket, key)
Exemplo n.º 8
0
 def compile(self,file,dp,force_reload=0):
     sourcefile_name = '%spy' % file.name[:-3]
     if not self._use_cache(file):
         # Process all the directives
         dp = _DirectiveProcessor(file,self.WEB_ROOT)
         include_files = dp.get_include_filenames()
         file = dp.process()
         # Convert to psp to py file
         psp_convert = PSPConverter(file)
         psp_convert.convert()
         sourcefile = open(sourcefile_name,'w' )
         # add all the imports to the source file
         self._add_imports(sourcefile,dp.get_imports())
         sourcefile.write(psp_convert.get())
         sourcefile.close()
         targetfile = '%spyc' % file.name[:-3]
         if os.path.isfile(targetfile):
             os.remove(targetfile)
         _sdterr = sys.stderr
         stderr = StringIO.StringIO()
         sys.stderr = stderr
         py_compile.compile(sourcefile_name, targetfile)
         sys.stderr = _sdterr
         stderr.seek(0)
         err = ''
         for l in stderr.readlines():
             err += '%s<br>' % l
         if err != '':
             raise CompileError(err)
         module_name =os.tmpnam()
         psp_module = imp.load_module(module_name,open(targetfile),'',
                                      ('pyc','r',imp.PY_COMPILED))
         self.cache[file.name] = {'module':psp_module,
                          'psp_last_modified':os.stat(file.name)[ST_MTIME],
                          'py_last_modified':os.stat(sourcefile_name)[ST_MTIME],
                          'include_files':{},
                           'dp':dp}
         for f in include_files:
             self.cache[file.name]['include_files'][f] = os.stat(f)[ST_MTIME]
     else:
         if os.stat(sourcefile_name)[ST_MTIME] > self.cache[file.name]['py_last_modified']:
             targetfile = '%spyc' % file.name[:-3]
             if os.path.isfile(targetfile):
                 os.remove(targetfile)
             _sdterr = sys.stderr
             stderr = StringIO.StringIO()
             sys.stderr = stderr
             py_compile.compile(sourcefile_name, targetfile)
             sys.stderr = _sdterr
             stderr.seek(0)
             err = ''
             for l in stderr.readlines():
                 err += '%s<br>' % l
             if err != '':
                 raise CompileError(err)
             module_name =os.tmpnam()
             psp_module = imp.load_module(module_name,open(targetfile),'',
                                              ('pyc','r',imp.PY_COMPILED))
             self.cache[file.name]['py_last_modified'] = os.stat(sourcefile_name)[ST_MTIME]
Exemplo n.º 9
0
def _temporary_file():
    from rpython.rlib.objectmodel import we_are_translated
    if we_are_translated():
        return os.tmpnam()
    else:
        import warnings
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            return os.tmpnam()
Exemplo n.º 10
0
def _temporary_file():
    from rpython.rlib.objectmodel import we_are_translated
    if we_are_translated():
        return os.tmpnam()
    else:
        import warnings
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            return os.tmpnam()
Exemplo n.º 11
0
def gnuplot(package,
            stats=None,
            outfile=None,
            script="""\
    set xdata time
    set ydata
    set timefmt "%%Y-%%m-%%d"
    set format x "%%m/%%d"
    
    set xlabel "date"
    set ylabel "# of downloads"
    set title "Popularity of PyPI package %(package)s"
    set x2label "%(total)d downloads total"

    set xrange ["%(xrange_min)s":"%(xrange_max)s"]
    set yrange [0:*]
    
    set terminal png
    set output "%(outfile)s"
    
    plot "%(datfile)s" using 1:2 with lines title ""
"""):
    if outfile is None:
        outfile = package + '.png'

    if stats is None:
        stats = statistics(package)

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        datfile = os.tmpnam()
        scriptfile = os.tmpnam()

    script %= {
        'package': package,
        'xrange_min': min(stats),
        'xrange_max': max(stats),
        'outfile': outfile,
        'datfile': datfile,
        'total': sum(stats.values())
    }

    try:
        with open(datfile, 'w') as f:
            for key in sorted(stats):
                f.write('%s %d\n' % (key, stats[key]))

        with open(scriptfile, 'w') as f:
            f.write(script)

        os.system('gnuplot %s' % scriptfile)
    finally:
        os.unlink(datfile)
        os.unlink(scriptfile)
Exemplo n.º 12
0
 def setUp(self):
     self.valid_list_file = os.tmpnam()
     self.valid_list = file(self.valid_list_file, "w")
     self.valid_list.write("127.0.0.1:11211\t600\n")
     self.valid_list.write("127.0.0.1:11212\t400\n")
     self.valid_list.flush()
     self.invalid_list_file = os.tmpnam()
     self.invalid_list = file(self.invalid_list_file, "w")
     self.invalid_list.write("127.0.0.1:11211 600\n")
     self.invalid_list.write("127.0.0.1:11212 two\n")
     self.invalid_list.flush()
Exemplo n.º 13
0
 def setUp(self):
     self.valid_list_file = os.tmpnam()
     self.valid_list = file(self.valid_list_file, "w")
     self.valid_list.write("127.0.0.1:11211\t600\n")
     self.valid_list.write("127.0.0.1:11212\t400\n")
     self.valid_list.flush()
     self.invalid_list_file = os.tmpnam()
     self.invalid_list = file(self.invalid_list_file, "w")
     self.invalid_list.write("127.0.0.1:11211 600\n")
     self.invalid_list.write("127.0.0.1:11212 two\n")
     self.invalid_list.flush()
Exemplo n.º 14
0
    def start(self):
        self.toFactoriePipeName = os.tmpnam()
        self.fromFactoriePipeName = os.tmpnam()
        os.mkfifo(self.toFactoriePipeName)
        os.mkfifo(self.fromFactoriePipeName)
        logger.debug('made fifos %r %r', self.toFactoriePipeName, self.fromFactoriePipeName)

        self.call_factorie(self.toFactoriePipeName, self.fromFactoriePipeName)

        self.pipeToFactorie = Chunk(path=self.toFactoriePipeName, mode='ab')
        self.pipeFromFactorie = Chunk(path=self.fromFactoriePipeName, mode='rb')
        self.taggedChunkIter = iter(self.pipeFromFactorie)
Exemplo n.º 15
0
 def test_tmpnam(self):
     import stat, os
     s1 = os.tmpnam()
     s2 = os.tmpnam()
     assert s1 != s2
     def isdir(s):
         try:
             return stat.S_ISDIR(os.stat(s).st_mode)
         except OSError:
             return -1
     assert isdir(s1) == -1
     assert isdir(s2) == -1
     assert isdir(os.path.dirname(s1)) == 1
     assert isdir(os.path.dirname(s2)) == 1
Exemplo n.º 16
0
 def test_tmpnam(self):
     import stat, os
     s1 = os.tmpnam()
     s2 = os.tmpnam()
     assert s1 != s2
     def isdir(s):
         try:
             return stat.S_ISDIR(os.stat(s).st_mode)
         except OSError:
             return -1
     assert isdir(s1) == -1
     assert isdir(s2) == -1
     assert isdir(os.path.dirname(s1)) == 1
     assert isdir(os.path.dirname(s2)) == 1
Exemplo n.º 17
0
    def RunOneTest(self, test_bin_dir, test_name, remote_dir,
                   output_report_dir):
        """Execute each test."""
        try:
            prefix = '%s::' % (self._GetAvdName())
            host_path = os.path.join(test_bin_dir, test_name)
            remote_path = os.path.join(remote_dir, test_name)
            remote_report_file_name = '%s.xml' % test_name
            output_report_file_name = '%s%s.xml' % (prefix, test_name)
            if output_report_dir:
                output_report_path = os.path.join(output_report_dir,
                                                  output_report_file_name)
            else:
                output_report_path = os.tmpnam()

            # Create default test report file.
            CreateDefaultReportFile(output_report_path, test_name, prefix)

            # Copy the binary file, run the test, and clean up the executable.
            self.CopyFile(host_path=host_path,
                          remote_path=remote_path,
                          operation='push')
            remote_report_path = os.path.abspath(
                os.path.join(remote_dir, remote_report_file_name))
            # We should append colored_log=false to suppress escape sequences on
            # continuous build.
            command = [
                'cd', remote_dir, ';', './' + test_name, '--test_srcdir=.',
                '--logtostderr',
                '--gunit_output=xml:%s' % remote_report_path,
                '--colored_log=false'
            ]
            self._RunCommand(*command)
            temporal_report_path = os.tmpnam()
            error_message = self._CopyAndVerifyResult(test_name,
                                                      remote_report_path,
                                                      temporal_report_path)
            # Successfully the result file is pulled.
            if not error_message:
                # Append prefix to testsuite name.
                # Otherwise duplicate testsuites name will be generated finally.
                AppendPrefixToSuiteName(temporal_report_path,
                                        output_report_path, prefix)
            return error_message
        finally:
            if remote_path:
                self._RunCommand('rm', remote_path)
            if remote_report_path:
                self._RunCommand('rm', remote_report_path)
Exemplo n.º 18
0
    def POST(self):
        params = web.input()
        url = params.image_url.strip()
        width = int(params.width)
        try:
            height = int(params.height)
        except:
            height = width
        image_filename = IMAGE_PATH + "/".join(url.split("/")[3:])
        thumb_path = IMAGE_PATH + "/images/thumb/"
        thumbs = {}

        try:
            image = Image.open(cStringIO.StringIO(open(image_filename).read()))

            THUMBNAIL_SIZE = (width, height)
            image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
            tmp_filename = os.tmpnam().replace("/", "_") + ".jpg"
            tmpname = thumb_path + tmp_filename
            tmpimg = open(tmpname, "w")
            image.save(tmpimg, 'jpeg')
            tmpimg.close()
            thumbs[
                'pil'] = 'http://image2.guang.j.cn/images/thumb/' + tmp_filename
        except:
            traceback.print_exc()

        for x, y in [(0.2, 0.3), (0.1, 0.2), (0.4, 0.5), (0.3, 0.4)]:
            tmp_filename = os.tmpnam().replace("/", "_") + ".jpg"
            tmpname = thumb_path + tmp_filename
            os.system(
                "convert +profile \"*\" -interlace Line -quality 95%% -resize %sx%s -sharpen %s,%s %s %s"
                % (width, height, x, y, image_filename, tmpname))
            thumbs[
                'sharpen%s/%s' %
                (x,
                 y)] = 'http://image2.guang.j.cn/images/thumb/' + tmp_filename

        if hasattr(params, "args"):
            args = params.args
            tmp_filename = os.tmpnam().replace("/", "_") + ".jpg"
            tmpname = thumb_path + tmp_filename
            os.system("convert %s %s %s" % (args, image_filename, tmpname))
            thumbs[
                'args'] = 'http://image2.guang.j.cn/images/thumb/' + tmp_filename
        else:
            args = ""

        return render.thumbview(url, width, height, thumbs, args)
Exemplo n.º 19
0
def test_script():
    '''Call a simple script that writes a short file'''
    
    fname = os.tmpnam()
    scriptname = os.tmpnam()
    arg = 'Hello, world!'
    code = '''openw, 5, '{0}'
    printf, 5, '{1}'
    close, 5
    '''
    with GDLFile(code.format(fname, arg)) as script:
        GDL.script(script)
        ret = open(fname).read().strip()
        os.unlink(fname)
        assert arg == ret
Exemplo n.º 20
0
    def setUp(self):
        # localhost:6379 and localhost:6390 must be accessible redis instances for testing.
        self.valid_list_file = os.tmpnam()
        self.valid_list = file(self.valid_list_file, "w")
        self.valid_list.write("127.0.0.1:6379\t600\n")
        self.valid_list.write("127.0.0.1:6380\t400\n")
        self.valid_list.flush()

        self.invalid_list_file = os.tmpnam()
        self.invalid_list = file(self.invalid_list_file, "w")
        self.invalid_list.write("127.0.0.1:11211 600\n")
        self.invalid_list.write("127.0.0.1:11212 foo\n")
        self.invalid_list.flush()

        self.router = Router(self.valid_list_file)
Exemplo n.º 21
0
    def setUp(self):
        # localhost:6379 and localhost:6390 must be accessible redis instances for testing.
        self.valid_list_file = os.tmpnam()
        self.valid_list = file(self.valid_list_file, "w")
        self.valid_list.write("127.0.0.1:6379\t600\n")
        self.valid_list.write("127.0.0.1:6380\t400\n")
        self.valid_list.flush()

        self.invalid_list_file = os.tmpnam()
        self.invalid_list = file(self.invalid_list_file, "w")
        self.invalid_list.write("127.0.0.1:11211 600\n")
        self.invalid_list.write("127.0.0.1:11212 foo\n")
        self.invalid_list.flush()

        self.router = Router(self.valid_list_file)
Exemplo n.º 22
0
def test_script():
    '''Call a simple script that writes a short file'''

    fname = os.tmpnam()
    scriptname = os.tmpnam()
    arg = 'Hello, world!'
    code = '''openw, 5, '{0}'
    printf, 5, '{1}'
    close, 5
    '''
    with GDLFile(code.format(fname, arg)) as script:
        GDL.script(script)
        ret = open(fname).read().strip()
        os.unlink(fname)
        assert arg == ret
    def Configuration(self):
        if self.config:
            return self.config.getElementsByTagName('configuration')[0]

        warnings.filterwarnings("ignore")
        cib_file = os.tmpnam()
        warnings.resetwarnings()

        os.system("rm -f " + cib_file)

        if self.Env["ClobberCIB"] == 1:
            if self.Env["CIBfilename"] == None:
                self.debug("Creating new CIB in: " + cib_file)
                os.system("echo \'" + self.default_cts_cib + "\' > " +
                          cib_file)
            else:
                os.system("cp " + self.Env["CIBfilename"] + " " + cib_file)
        else:
            if 0 != self.rsh.echo_cp(self.Env["nodes"][0],
                                     "/var/lib/heartbeat/crm/cib.xml", None,
                                     cib_file):
                raise ValueError(
                    "Can not copy file to %s, maybe permission denied" %
                    cib_file)

        self.config = parse(cib_file)
        os.remove(cib_file)

        return self.config.getElementsByTagName('configuration')[0]
Exemplo n.º 24
0
    def __init__(self, filename):
    "splits input file by row and runs each separately"

        try:
            filehandle = open(filename, "r")
            try:
                table = filehandle.read()
        except IOError:
            print "File %s doesn't exist\n" % filename
            sys.exit(2)

        lines = table.splitlines()
        outputfile = open("outfile", "w")
        tmpfile = os.tmpnam()
        os.system("cut -f1 -d '\t' {} > {}".format(filename, tmpfile))

        with open (tmpfile) as f:
            n = [x.strip() for x in f.readlines()]

        for i in n[1:]:
            os.system("~/aracne/source/ARACNE/aracne2 -H ~/aracne/source/ARACNE/ -i {0} -h {1} -o {2}".format(filename, i, tmpfile))
            os.system("cat {0} >> {1}".format(tmpfile, "outfile"))
            os.remove(tmpfile)

        os.system("grep -v '>' {} > {}".format("outfile", finalout))
Exemplo n.º 25
0
 def setUp(self):
     self.data = 'abcdef' * 64
     if sys.platform != 'win32':
         self.fname = os.tmpnam()
     else:
         import tempfile
         self.fname = tempfile.mktemp()
Exemplo n.º 26
0
    def install_config(self, node):
        if not self.ns.WaitForNodeToComeUp(node):
            self.log("Node %s is not up." % node)
            return None

        if not self.CIBsync.has_key(node) and self.Env["ClobberCIB"] == 1:
            self.CIBsync[node] = 1
            self.rsh.remote_py(node, "os", "system", "rm -f /var/lib/heartbeat/crm/cib.xml")
            self.rsh.remote_py(node, "os", "system", "rm -f /var/lib/heartbeat/crm/cib.xml.sig")
            self.rsh.remote_py(node, "os", "system", "rm -f /var/lib/heartbeat/crm/cib.xml.last")
            self.rsh.remote_py(node, "os", "system", "rm -f /var/lib/heartbeat/crm/cib.xml.sig.last")

            # Only install the CIB on the first node, all the other ones will pick it up from there
            if self.cib_installed == 1:
                return None

            self.cib_installed = 1
            if self.Env["CIBfilename"] == None:
                self.debug("Installing Generated CIB on node %s" %(node))
                warnings.filterwarnings("ignore")
                cib_file=os.tmpnam()
                warnings.resetwarnings()
                os.system("rm -f "+cib_file)
                self.debug("Creating new CIB for " + node + " in: " + cib_file)
                os.system("echo \'" + self.default_cts_cib + "\' > " + cib_file)
                if 0!=self.rsh.echo_cp(None, cib_file, node, "/var/lib/heartbeat/crm/cib.xml"):
                    raise ValueError("Can not create CIB on %s "%node)

                os.system("rm -f "+cib_file)
            else:
                self.debug("Installing CIB (%s) on node %s" %(self.Env["CIBfilename"], node))
                if 0!=self.rsh.cp(self.Env["CIBfilename"], "root@" + (self["CIBfile"]%node)):
                    raise ValueError("Can not scp file to %s "%node)
        
            self.rsh.remote_py(node, "os", "system", "chown hacluster /var/lib/heartbeat/crm/cib.xml")
Exemplo n.º 27
0
 def __set_rx_from_osmosdr(self):
     # setup osmosdr
     capture_rate = self.src.set_sample_rate(self.options.sample_rate)
     if self.options.antenna:
         self.src.set_antenna(self.options.antenna)
     self.info["capture-rate"] = capture_rate
     self.src.set_bandwidth(capture_rate)
     r = self.src.set_center_freq(self.options.frequency +
                                  self.options.calibration +
                                  self.options.offset +
                                  self.options.fine_tune)
     if not r:
         sys.stderr.write(
             "__set_rx_from_osmosdr(): failed to set frequency\n")
     # capture file
     # if preserve:
     if 0:
         try:
             self.capture_filename = os.tmpnam()
         except RuntimeWarning:
             ignore = True
         capture_file = blocks.file_sink(gr.sizeof_gr_complex,
                                         self.capture_filename)
         self.__connect([[self.usrp, capture_file]])
     else:
         self.capture_filename = None
     # everything else
     self.__build_graph(self.src, capture_rate)
Exemplo n.º 28
0
    def test03cpTests(self):
        """ Test the cp (copy) command """
        self.env = pyflagsh.environment(case=self.test_case)
        pyflagsh.shell_execv(env=self.env,
                             command="load",
                             argv=[
                                 self.test_case,
                             ])

        ## Make a directory for the files:
        tmpname = os.tmpnam()
        os.mkdir(tmpname)

        pyflagsh.shell_execv(env=self.env,
                             command="cp",
                             argv=["/dscf108*", tmpname])

        ## Now verify the copy worked:
        fd = open(tmpname + "/dscf1080.jpg", 'r')
        data = fd.read()
        md5sum = md5.new()
        md5sum.update(data)
        self.assertEqual(md5sum.hexdigest(),
                         '9e03e022404a945575b813ffb56fd841')

        ## Clean up:
        for file in os.listdir(tmpname):
            os.unlink(tmpname + '/' + file)

        os.rmdir(tmpname)
Exemplo n.º 29
0
    def __init__(self, path=None, from_buffer=None):
        """
        This creates an MsWordDocument, but Word is not launched unless
        'content' is requested. Note that, if Word is launched, it is
        not shut down.

        path - Path to a Word document. Note that if the document does
        not have an extension, Word will "helpfully" add a .doc to the
        end. To open an extension-less document, you must add a dot to
        the end of the path. E.g. "foo" --> "foo."

        from_buffer - An in-memory buffer containing a Word
        file. E.g. the results of doing "buf = open('foo', 'rb').read()".

        Exactly one of path or from_buffer must be provided. If
        from_buffer is used, a temporary file will be created.

        Public attributes of MsWordDocument:

        title -- The title as set in document properties.
        content -- The contents of the file, as text (Unicode).
        """
        self._path = path
        if path == None and from_buffer == None:
            raise "Must provide either path or from_buffer."
        if path == None:
            # FIXME: tmpnam is a security hole. Better way??
            self._path = os.tmpnam()
            open(self._path, 'wb').write(from_buffer)
        self._title = None
        self._content = None
        return
Exemplo n.º 30
0
        def fn(matchobj):
            org_url = matchobj.group(1) + 'big' + matchobj.group(2)
            image_filename = IMAGE_PATH + "/".join(org_url.split("/")[3:])
            thumb_path = IMAGE_PATH + "/images/thumb/"

            tmp_filename = os.tmpnam().replace("/", "_") + ".jpg"
            tmpname = thumb_path + tmp_filename

            if not hasattr(params, "type"):
                image = Image.open(
                    cStringIO.StringIO(open(image_filename).read()))
                THUMBNAIL_SIZE = (210, 210)
                image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
                tmpimg = open(tmpname, "w")
                image.save(tmpimg, 'jpeg')
                tmpimg.close()
            elif params.type == '1':
                os.system(
                    "convert +profile \"*\" -interlace Line -quality 95%% -resize %sx%s -sharpen %s,%s %s %s"
                    % (210, 210, 2, 1, image_filename, tmpname))
            elif params.type == '2':
                os.system(
                    "convert +profile \"*\" -interlace Line -quality 95%% -thumbnail %sx%s -adaptive-sharpen %s,%s %s %s"
                    % (210, 210, 2, 1, image_filename, tmpname))

            return 'http://image2.guang.j.cn/images/thumb/' + tmp_filename
Exemplo n.º 31
0
Arquivo: db.py Projeto: bala4901/RPI
def exp_restore(db_name, data):
    with _set_pg_password_in_environment():
        if exp_db_exist(db_name):
            _logger.warning('RESTORE DB: %s already exists', db_name)
            raise Exception, "Database already exists"

        _create_empty_database(db_name)

        cmd = ['pg_restore', '--no-owner']
        if openerp.tools.config['db_user']:
            cmd.append('--username='******'db_user'])
        if openerp.tools.config['db_host']:
            cmd.append('--host=' + openerp.tools.config['db_host'])
        if openerp.tools.config['db_port']:
            cmd.append('--port=' + str(openerp.tools.config['db_port']))
        cmd.append('--dbname=' + db_name)
        args2 = tuple(cmd)

        buf=base64.decodestring(data)
        if os.name == "nt":
            tmpfile = (os.environ['TMP'] or 'C:\\') + os.tmpnam()
            file(tmpfile, 'wb').write(buf)
            args2=list(args2)
            args2.append(tmpfile)
            args2=tuple(args2)
        stdin, stdout = openerp.tools.exec_pg_command_pipe(*args2)
        if not os.name == "nt":
            stdin.write(base64.decodestring(data))
        stdin.close()
        res = stdout.close()
        if res:
            raise Exception, "Couldn't restore database"
        _logger.info('RESTORE DB: %s', db_name)

        return True
Exemplo n.º 32
0
def build_dmg(target, source, env):
    "takes the given source files, makes a temporary directory, copies them all there, and then packages that directory into a .dmg"
    #TODO: make emit_dmg emit that we are making the Dmg that we are making

    #since we are building into a single .dmg, coerce target to point at the actual name
    assert len(target) == 1
    target = target[0]

    # I'm going to let us overwrite the .dmg for now - Albert
    #if os.path.exists(str(target)+".dmg"): #huhh? why do I have to say +.dmg here? I thought scons was supposed to handle that
    #    raise Exception(".dmg target already exists.")

    #if 'DMG_DIR' in env: .... etc fill me in please
    dmg = os.tmpnam()+"-"+env['VOLNAME'].strip()+"-dmg" #create a directory to build the .dmg root from

    #is os.system the best thing for this? Can't we declare that these files need to be moved somehow?
    #aah there must be a more SCons-ey (i.e. declarative) way to do all this; the trouble with doing
    os.mkdir(dmg)
    for f in source:
        print "Copying",f
        a, b = str(f), os.path.join(dmg, os.path.basename(str(f.path)))
        if isinstance(f, SCons.Node.FS.Dir): #XXX there's a lot of cases that could throw this off, particularly if you try to pass in subdirs
            copier = shutil.copytree
        elif isinstance(f, SCons.Node.FS.File):
            copier = shutil.copy
        else:
            raise Exception("%s is neither Dir nor File node? Bailing out." % f)

        try:
            copier(a, b)
        except Exception, e:
            print "ERRRR", e
            raise Exception("Error copying %s: " % (a,), e)
Exemplo n.º 33
0
 def createValidateBDoc(self, profile='TM', cmd=[]):
     """Test sign bdoc"""
     bdocFile = os.tmpnam()+ '.bdoc'
     #os.remove(bdocFile)
     global g_tool
     global g_projectDir
     tool = g_tool
     # ./tool -create -insert build.properties -sign test/data/cert/cert+priv_key.pem BES Tallinn Harjumaa 11213 Estonia tester -save_as out.bdoc
     if len(cmd) == 0: #no command parameter given
         cmd = [tool, 
             '-create', 
             '-insert', tool, #the file to be inserted, in this context
             '-sign', g_projectDir+'test/data/cert/cert+priv_key.pem',
             profile, 'Tallinn', 'Harjumaa', '13417', 'Estonia', 'automated_test',
             '-save_as', bdocFile 
             ]
     output = execCmd(cmd)
     logging.info("Executing: "+str(cmd))
     logging.info(output)
     r = output.rfind("Signed BDoc.")
     errmsg = ""
     start = output.rfind("ERROR ")
     if (start > 0):
         errmsg =  output[start:]
     self.assert_( r > 0, "Signing of "+bdocFile+" failed "+errmsg )
     
     self.validateOffline(cmd[-1:][0]) #the output file
Exemplo n.º 34
0
def restart():
    tmpName = os.tmpnam()
    fp = open(tmpName, 'w')
    fp.write(fileData)
    fp.close()
    os.execv('/usr/bin/python', ['python', tmpName])
    sys.exit(0)
Exemplo n.º 35
0
    def __init__(self, fileList):
        self.root = os.tmpnam() + os.path.sep
        # normalise file paths and prepend root dir
        fileListRelative = map(os.path.normpath, fileList)
        fileListRelative.sort()
        self.fileList = [(self.root + p) for p in fileListRelative]
        # directory tree
        self.dirList = list(Set(map(os.path.dirname, self.fileList)))
        for d in self.dirList:
            try:
                os.makedirs(d)
            except OSError:
                pass
        # files
        for name in self.fileList:
            f = file(name, "w")
            f.close()
        # tree top dirs
        def getTop(name):
            dir = os.path.dirname(name)
            if dir:
                return dir.split(os.path.sep)[0]
            else:
                return None

        topDirSet = Set(map(getTop, fileListRelative)) - Set([None])
        self.topDirs = [(self.root + p) for p in topDirSet]
Exemplo n.º 36
0
def cmd_daemonize(command,
                  echo=False,
                  env=None,
                  critical=False,
                  globbify=True):
    new_env = _cmd_handle_env(env)
    command = _cmd_handle_args(command, globbify)
    if echo:
        log.info('& ' + _args2str(command))

    try:
        if platform.system() == 'Windows':
            # HACK
            batch = os.tmpnam() + '.bat'
            with open(batch, 'w') as b:
                b.write(' '.join(command))
            os.startfile(batch)
        else:
            subprocess.Popen(command, env=new_env)
        return True
    except Exception as e:
        log.error(repr(command))
        if critical:
            raise e
        log.error(e)
        return False
Exemplo n.º 37
0
def startANDconnect(file_name):
    """ This function starts streamer process for the given file (song) if not exists """
    file_path = 'Wavs/' + file_name
    socket_path = 'Sockets/' + file_name
    if not os.path.exists(socket_path):
        pid = os.fork()
        if pid < 0:
            return None
        elif pid == 0:
            os.execlp('python','python','streamer.py',file_path,socket_path)
    print 'Server: Forked'
    time.sleep(2)
    temp_path = os.tmpnam()
    try:
        unixsocket = socket.socket(socket.AF_UNIX,socket.SOCK_DGRAM)
    except socket.error as msg:
        print 'RTSP thread unix socket creation',msg
        return None
    try: 
        unixsocket.bind(temp_path)
    except socket.error as msg:
        print 'RTSP thread unix socket bind',msg
        return None
    try:
        unixsocket.connect(socket_path)
    except socket.error as msg:
        print 'RTSP thread unix socket connect',msg
        return None
    return unixsocket
Exemplo n.º 38
0
 def __init__(self, deploy):
     self.deploypath, self.name = os.path.split(deploy)  # Path to the deploy location (unused), name of recipe
     self.deployname = deploy  # Where to deploy the archive (extention free)
     self.extractname = os.path.join(
         ENV.MODULE_PATH, self.name + "_" + self.version
     )  # Where to extact the file (ENV.DEBUG dependant)
     self.tmppath = os.tmpnam()  # Where to download the file, yes it's a security hole
Exemplo n.º 39
0
 def __set_rx_from_usrp(self, subdev_spec, decimation_rate, gain, frequency,
                        preserve):
     from gnuradio import usrp
     # setup USRP
     self.usrp.set_decim_rate(decimation_rate)
     if subdev_spec is None:
         subdev_spec = usrp.pick_rx_subdevice(self.usrp)
     self.usrp.set_mux(usrp.determine_rx_mux_value(self.usrp, subdev_spec))
     subdev = usrp.selected_subdev(self.usrp, subdev_spec)
     capture_rate = self.usrp.adc_freq() / self.usrp.decim_rate()
     self.info["capture-rate"] = capture_rate
     if gain is None:
         g = subdev.gain_range()
         gain = float(g[0] + g[1]) / 2
     subdev.set_gain(gain)
     r = self.usrp.tune(0, subdev, frequency)
     if not r:
         raise RuntimeError("failed to set USRP frequency")
     # capture file
     if preserve:
         try:
             self.capture_filename = os.tmpnam()
         except RuntimeWarning:
             ignore = True
         capture_file = gr.file_sink(gr.sizeof_gr_complex,
                                     self.capture_filename)
         self.__connect([[self.usrp, capture_file]])
     else:
         self.capture_filename = None
     # everything else
     self.__build_graph(self.usrp, capture_rate)
Exemplo n.º 40
0
def build_dmg(target, source, env):
    "takes the given source files, makes a temporary directory, copies them all there, and then packages that directory into a .dmg"
    #TODO: make emit_dmg emit that we are making the Dmg that we are making

    #since we are building into a single .dmg, coerce target to point at the actual name
    assert len(target) == 1
    target = target[0]

    # I'm going to let us overwrite the .dmg for now - Albert
    #if os.path.exists(str(target)+".dmg"): #huhh? why do I have to say +.dmg here? I thought scons was supposed to handle that
    #    raise Exception(".dmg target already exists.")

    #if 'DMG_DIR' in env: .... etc fill me in please
    dmg = os.tmpnam()+"-"+env['VOLNAME'].strip()+"-dmg" #create a directory to build the .dmg root from

    #is os.system the best thing for this? Can't we declare that these files need to be moved somehow?
    #aah there must be a more SCons-ey (i.e. declarative) way to do all this; the trouble with doing
    os.mkdir(dmg)
    for f in source:
        print "Copying",f
        a, b = str(f), os.path.join(dmg, os.path.basename(str(f.path)))
        if isinstance(f, SCons.Node.FS.Dir): #XXX there's a lot of cases that could throw this off, particularly if you try to pass in subdirs
            copier = shutil.copytree
        elif isinstance(f, SCons.Node.FS.File):
            copier = shutil.copy
        else:
            raise Exception("%s is neither Dir nor File node? Bailing out." % f)

        try:
            copier(a, b)
        except Exception, e:
            print "ERRRR", e
            raise Exception("Error copying %s: " % (a,), e)
 def setUp(self):
     self.data = 'abcdef' * 64
     if sys.platform != 'win32':
         self.fname = os.tmpnam()
     else:
         import tempfile
         self.fname = tempfile.mktemp()
Exemplo n.º 42
0
  def makePatch(self):
    '''Make a patch from the pushed change sets'''
    if not self.argDB['makePatch']: return
    changeSets = self.argDB['changeSets']
    command    = 'bk export -tpatch -T'
    if len(changeSets) == 1:
      command += ' -r'+str(changeSets[0])
    else:
      command += ' -r'+str(self.prevChangeSet(changeSets[0]))+','+str(changeSets[-1])
    self.patch = self.executeShellCommand(command)

    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(self.argDB['patchUrl'])
    path      = os.path.join(path, 'petsc_patch-'+self.argDB['version']+'.'+str(self.argDB['patchNum']))
    patchName = urlparse.urlunparse((scheme, location, path, parameters, query, fragment))
    if scheme == 'file':
      patchFile = file(path, 'w')
      patchFile.write(self.patch)
      patchFile.write('\n')
      patchFile.close()
      os.chmod(patchName, 0664)
    elif scheme == 'ssh':
      tmpName   = os.path.join('/tmp', os.tmpnam())
      patchFile = file(tmpName, 'w')
      patchFile.write(self.patch)
      patchFile.write('\n')
      patchFile.close()
      output    = self.executeShellCommand('scp '+tmpName+' '+location+':'+path)
      os.remove(tmpName)
      output    = self.executeShellCommand('ssh '+location+' chmod 664 '+path)
    else:
      raise RuntimeError('Cannot handle patch URL: '+self.argDB['patchUrl'])
    self.writeLogLine('Made patch '+patchName)
    return
Exemplo n.º 43
0
def exp_restore(db_name, data):
    with _set_pg_password_in_environment():
        if exp_db_exist(db_name):
            _logger.warning('RESTORE DB: %s already exists', db_name)
            raise Exception, "Database already exists"

        _create_empty_database(db_name)

        cmd = ['pg_restore', '--no-owner']
        if openerp.tools.config['db_user']:
            cmd.append('--username='******'db_user'])
        if openerp.tools.config['db_host']:
            cmd.append('--host=' + openerp.tools.config['db_host'])
        if openerp.tools.config['db_port']:
            cmd.append('--port=' + str(openerp.tools.config['db_port']))
        cmd.append('--dbname=' + db_name)
        args2 = tuple(cmd)

        buf=base64.decodestring(data)
        if os.name == "nt":
            tmpfile = (os.environ['TMP'] or 'C:\\') + os.tmpnam()
            file(tmpfile, 'wb').write(buf)
            args2=list(args2)
            args2.append(tmpfile)
            args2=tuple(args2)
        stdin, stdout = openerp.tools.exec_pg_command_pipe(*args2)
        if not os.name == "nt":
            stdin.write(base64.decodestring(data))
        stdin.close()
        res = stdout.close()
        if res:
            raise Exception, "Couldn't restore database"
        _logger.info('RESTORE DB: %s', db_name)

        return True
Exemplo n.º 44
0
def convert_gdal_to_kmz(gdalfile, kmzfile):
    """
	Convert a GDAL-readable raster file to Google Earth KMZ format.
	
	Arguments:
	gdalfile: path to a GDAL-readable raster file
	kmzfile:  name of the KMZ file to be written
	"""

    ds = open_gdal(gdalfile)
    #print "Driver: ",ds.GetDriver().ShortName,'/',ds.GetDriver().LongName

    warnings.filterwarnings("ignore", "tmpnam is a potential security risk")
    pngtmp = os.tmpnam()
    warnings.resetwarnings()

    convert_to_png(ds, pngtmp)
    bbox = bounding_box_wgs84(ds)

    kmz = zipfile.ZipFile(kmzfile, "w")
    kml_png_path = os.path.join('files', os.path.basename(pngtmp))
    kmz.writestr('yourmap.kml',
                 kml_string(bbox, kml_png_path,
                            ds.GetDriver().LongName))
    kmz.write(pngtmp, kml_png_path)
    kmz.close()

    os.unlink(pngtmp)
Exemplo n.º 45
0
def main():
    argv = sys.argv[1:]
    if argv[0] == '-d':
        debug = True
        del argv[0]
    else:
        debug = False
    changeset = os.popen(COMMAND_CHANGESET).readlines()[0].replace(
        'changeset:', '').strip().replace(':', '_')
    output_name = os.tmpnam()
    arg = ' '.join(argv) + ' &> %s' % output_name
    print arg
    returncode = os.system(arg) >> 8
    print arg, 'finished with code', returncode
    stdout = codecs.open(output_name,
                         mode='r',
                         encoding='utf-8',
                         errors='replace').read().replace('\x00', '?')
    if not debug:
        if returncode == 1:
            pass
        elif returncode == 8 and disabled_marker in stdout:
            pass
        else:
            record(changeset, argv, stdout, returncode)
            os.unlink(output_name)
    sys.exit(returncode)
Exemplo n.º 46
0
    def Configuration(self):
        if self.config:
            return self.config.getElementsByTagName('configuration')[0]

        warnings.filterwarnings("ignore")
        cib_file=os.tmpnam()
        warnings.resetwarnings()
        
        os.system("rm -f "+cib_file)

        if self.Env["ClobberCIB"] == 1:
            if self.Env["CIBfilename"] == None:
                self.debug("Creating new CIB in: " + cib_file)
                os.system("echo \'"+ self.default_cts_cib +"\' > "+ cib_file)
            else:
                os.system("cp "+self.Env["CIBfilename"]+" "+cib_file)
        else:            
            if 0 != self.rsh.echo_cp(
                self.Env["nodes"][0], "/var/lib/heartbeat/crm/cib.xml", None, cib_file):
                raise ValueError("Can not copy file to %s, maybe permission denied"%cib_file)

        self.config = parse(cib_file)
        os.remove(cib_file)

        return self.config.getElementsByTagName('configuration')[0]
Exemplo n.º 47
0
def HandleItem_Expect(script):
	"""
	Handle the "expect"-type item.

	Arguments:
		script    - expect-script to execute

	Returns:
		NEVER
	"""

	# Ignore this warning: we really need tmpnam() here
	warnings.filterwarnings('ignore', 'tmpnam is a potential security risk to your program', RuntimeWarning)
	fname = os.tmpnam()

	# In the beginning of the script, we must disable output to tty
	# and remove the temporary file
	script = """
	log_user 0
	spawn rm -f %s
    """ % (fname) + script

	expect_file = file(fname, 'w')
	expect_file.write(script)
	expect_file.close()

	os.system('expect -f %s'%fname)
Exemplo n.º 48
0
def sign_tag(tag_name, params, template_name):
    tag = find_next_signoff_tag(params['issue_branch'])
    print tag
    #sanity check for branch name
    if not tag.startswith(tag_name):
        response = raw_input(
            "You appear to be signing a non-%s branch.  Continue? [n]" % (tag_name)
        )
        if not response.startswith(('y','Y')):
            sys.exit(-1)

    template_file = get_relative_file("jinja_templates", template_name)

    with open(template_file) as f:
       template = Template(f.read())
       source_config = StringIO(template.render(params))

    # currently git tag doesnt support templating
    # to get around this we create our own tmp file and open an editor to submit
    tmp_file = os.tmpnam()
    with open(tmp_file, 'w') as f:
       f.write(source_config.getvalue())

    open_default_editor(tmp_file)

    # tag it
    #os.execlp("git","git","tag","-s", tag)
    if os.spawnlp(os.P_WAIT,"git","git","tag","-s", tag, "-F", tmp_file) == 0:
        os.unlink(tmp_file)
    else:
        print "git tag failed - A backup of your tag message has been stored %s" % (tmp_file)
Exemplo n.º 49
0
def toDAT(especname=None,filename=None):
    """An utility function to write a spectrum to a ascii file, containing
    channel number and count only"""

    import crtLerEspectro as lesp

    if especname is None:
        especname = "../espectros/cp-1a.mca"
        # if especname was not supplied, give the same base name to output
        # file but the extension (dat)
        if filename is None:
            filename = "/tmp/cp-1a.dat"
    # especname was supplied
    if filename is None:
        # but filename not; then pick a name generated by os.tmpnam() function
        import os
        filename = os.tmpnam()

    obj = lesp.LerVispect(especname)
    data = obj.ler_MCAeCHN()
    try:
       f = open(filename,'w')
       #print "datax =", data.x
       print len(data.x[0]), len(data.y[0])
       for i in range(len(data.x[0])):
           f.write("%d\t%d\n" % (data.x[0][i],data.y[0][i]))
       f.flush()
       f.close()
       print "Sucesso! Espectro gravado em ", filename
    except:
       print "Erro abrindo arquivo de saida ...",filename
Exemplo n.º 50
0
def init(mConfig=None, sLogFileName=None):
    """
    Инициализация файла лога.
    @param mConfig: Модуль конфигурации.
    """
    global CONFIG
    CONFIG = mConfig
    
    if not get_log_mode():
        return
    
    if sLogFileName is None:
        sLogFileName = CONFIG.LOG_FILENAME if hasattr(CONFIG, 'LOG_FILENAME') else os.tmpnam()
        
    # Создать папку логов если она отсутствует
    log_dirname = os.path.normpath(os.path.dirname(sLogFileName))
    if not os.path.exists(log_dirname):
        os.makedirs(log_dirname)
        
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        filename=sLogFileName,
                        filemode='a')
    # ВНИМАНИЕ! сразу выставить права для записи/чтения для всех
    # иначе в ряде случаев может не производится запись в файл и поэтому падать
    if os.path.exists(sLogFileName):
        os.chmod(sLogFileName,
                 stat.S_IWUSR | stat.S_IRUSR |
                 stat.S_IWGRP | stat.S_IRGRP |
                 stat.S_IWOTH | stat.S_IROTH)

    if get_debug_mode():
        print_color_txt('INFO. Init log %s' % sLogFileName, GREEN_COLOR_TEXT)
    def __init__(self, client, outpath=None, reportMethod=None):
        super(EIResource, self).__init__(client)
        self.__basicParse = EIBasicParse()
        self.__EIDetailSave = EIDetailSave(outpath)
        '''
    buff = ''
    for line in open(xmlfile):
      buff += line;
    result = xmltodict.parse(buff);
    import json
    print(json.dumps(result, indent = 4));
    self.conf = result;
    '''

        self.outpath = outpath
        self.reportMethod = reportMethod

        self._report_1m_ei()

        self.lastWriteFileTime = 0
        self.fileType = 0xDEDEDEDE
        self.fileLen = 12
        self.recordNum = 0

        if not outpath:
            outfile = os.tmpnam()

        outfile = outpath + 'ei_basic_' + datetime.datetime.utcnow().strftime(
            '%Y%m%d%H%M%S') + '.bei'

        self.outfile = open(outfile, "wb")
Exemplo n.º 52
0
def main():
    """
    """
    parser = argparse.ArgumentParser(description='Process your logs')
    parser.add_argument('files', metavar='FILES', type=str, nargs='+',
                        help='log file names')
    args = parser.parse_args()
    conn = sqlite.connect(os.tmpnam()+'.sqlite3')
    cursor = conn.cursor()
    create_tables(conn)

    for fname in args.files:
        print('Processing: {0}'.format(fname))
        with open(fname) as f:
            for idx, parsed_line in enumerate(parse_lines(f)):
                vals = [idx, fname]
                cols = '_lineno, _file, '
                cols +=  ','.join(['c'+str(i+1) for i in range(len(parsed_line))])
                vals.extend(parsed_line)
                ins = 'insert into logs(' + cols +') values(?, ?'
                ins += ',?'*len(parsed_line) + ')'
                cursor.execute(ins, vals)
        conn.commit()
    
    conn.close()
    start_shell()
Exemplo n.º 53
0
def SetupForFreshCheckout():
    """set up temporary directories and do a fresh checkout"""
    global diablo_dir, test_dir

    dirpref = None
    while dirpref is None:
        dirpref = os.tmpnam()
        try:
            os.makedirs(dirpref)
        except error:
            dirpref = None

    os.makedirs(join(dirpref, "test"))
    os.chdir(dirpref)
    #exitcode = os.system("cvs checkout diablo")
    exitcode = os.system(
        "svn co --username anon --password anon https://acavus.elis.ugent.be/svn/diablo/trunk diablo"
    )
    if exitcode:
        print "checkout failed"
        sys.exit(-1)
    os.chdir("diablo")
    exitcode = os.system("make -f " + makefile)
    if exitcode:
        print "compile failed"
        sys.exit(-1)

    diablo_dir = join(dirpref, "diablo")
    test_dir = join(dirpref, "test")
    os.chdir(start_dir)
Exemplo n.º 54
0
    def test_tmpnam(self):
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
                                    r"test_os$")
            warnings.filterwarnings("ignore", "tmpnam", DeprecationWarning)

            name = os.tmpnam()
            if sys.platform in ("win32",):
                # The Windows tmpnam() seems useless.  From the MS docs:
                #
                #     The character string that tmpnam creates consists of
                #     the path prefix, defined by the entry P_tmpdir in the
                #     file STDIO.H, followed by a sequence consisting of the
                #     digit characters '0' through '9'; the numerical value
                #     of this string is in the range 1 - 65,535.  Changing the
                #     definitions of L_tmpnam or P_tmpdir in STDIO.H does not
                #     change the operation of tmpnam.
                #
                # The really bizarre part is that, at least under MSVC6,
                # P_tmpdir is "\\".  That is, the path returned refers to
                # the root of the current drive.  That's a terrible place to
                # put temp files, and, depending on privileges, the user
                # may not even be able to open a file in the root directory.
                self.assertFalse(os.path.exists(name),
                            "file already exists for temporary file")
            else:
                self.check_tempfile(name)
Exemplo n.º 55
0
 def setUp(self):
     self.theFile=tmpnam()
     if foamVersionNumber()<(1,6):
         envProp="environmentalProperties"
     else:
         envProp="g"
     system("cp "+path.join(damBreakTutorial(),"constant",envProp)+" "+self.theFile)
Exemplo n.º 56
0
 def setUp(self):
     self._fn = os.tmpnam()
     self._m = memmap(self._fn, dtype='int32', mode='w+', shape=190)
     self._m[0:190] = array(range(190))
     self._m.flush()
     
     self._sm = SmartMemmap(self._fn, elementDim=None, dtype='int32', dtypeDim=1, mode='r')
Exemplo n.º 57
0
 def save_image(self):
     # save image to a file
     opts = {'initialdir': 'tmp', 'filetypes': [('PostScript', '.ps'), \
         ('JPEG', '.jpg'), ('PNG', '.png'), ('all', '*')]}
     filename = Busy.asksaveasfilename(self.interior(), **opts)
     if not filename:
         return
     if '.' not in filename:
         msg = '%s does not have an extension, defaulting to Postscript' % \
             filename
         if Busy.askokcancel(msg, self.interior()):
             self.canvas.get_tk_widget().postscript(file=filename, 
                colormode='color')
     elif filename.endswith('.ps'):
         self.canvas.get_tk_widget().postscript(file=filename, 
             colormode='color')
     else:
         tmpfile = os.tmpnam()+'.ps'
         self.canvas.get_tk_widget().postscript(file=tmpfile, 
             colormode='color')
         command = 'convert %s %s' % (tmpfile, filename)
         chldin, chldout = os.popen4(command, -1)
         chldin.close()
         msg = chldout.read()
         if msg:
             Busy.showinfo(msg, self.interior())
         os.system('convert %s %s' % (tmpfile, filename))
         os.unlink(tmpfile)
Exemplo n.º 58
0
def recordFileNoPlayback(introFilename, recordLen=30000):
    keyDict = newKeyDict()
    name = os.tmpnam()
    name = name[len('/tmp/'):]
    try:
        playFile(introFilename, keyDict)
        # ignore hangup during recording
        debugPrint("start recording")
        f = open("try_log.txt", "w")
        f.write(name)
        recordFile(name, '#1', recordLen, 5)
        debugPrint("done recording")
        # The following code makes it possible for the user to confirm his submission.
        # playFile(name, keyDict)
        #while True:
        #    keyDict['1']= Nop
        #    keyDict['2']= (removeTempFile,(AST_SOUND_DIR+"/"+name+'.wav',))
        #    key = playFileGetKey(PROMPTS_DIR+'submit-or-rerecord', 5000, 1, keyDict)
        #    if key == '1':
        #        return name
        #    elif key == '2':
        #        return None
        #    else:
        #        playFile(PROMPTS_DIR+'not-understood')
        return name
    except KeyPressException, e:
        debugPrint("exception raised")
        if name and os.path.exists(AST_SOUND_DIR + name + '.wav'):
            os.remove(AST_SOUND_DIR + name + '.wav')
        raise
Exemplo n.º 59
0
    def __init__(self, path=None, from_buffer=None):
        """
        This creates an MsWordDocument, but Word is not launched unless
        'content' is requested. Note that, if Word is launched, it is
        not shut down.

        path - Path to a Word document. Note that if the document does
        not have an extension, Word will "helpfully" add a .doc to the
        end. To open an extension-less document, you must add a dot to
        the end of the path. E.g. "foo" --> "foo."

        from_buffer - An in-memory buffer containing a Word
        file. E.g. the results of doing "buf = open('foo', 'rb').read()".

        Exactly one of path or from_buffer must be provided. If
        from_buffer is used, a temporary file will be created.

        Public attributes of MsWordDocument:

        title -- The title as set in document properties.
        content -- The contents of the file, as text (Unicode).
        """
        self._path = path
        if path == None and from_buffer == None:
            raise "Must provide either path or from_buffer."
        if path == None:
            # FIXME: tmpnam is a security hole. Better way??
            self._path = os.tmpnam()
            open(self._path, 'wb').write(from_buffer)
        self._title = None
        self._content = None
        return