Пример #1
1
def get_build_config(args):
    # Use the platform defaults to populate the values
    if args["toolchain"] is None:
        args["toolchain"] = br_platform.supported["toolchain"][0]

    if args["rtos"] is None:
        args["rtos"] = br_platform.supported["rtos"][0]

    if args["outputDir"] is None:
        pathStr = "%s/output/%s_%s_%s" % (os.getcwd(), args["boardName"], args["rtos"], args["toolchain"])
        args["outputDir"] = os.path.realpath(pathStr)
    else:
        args["outputDir"] = os.path.realpath(args["outputDir"])

    if args["logFile"] is None:
        logFile = "build_%s.log" % datetime.datetime.now().strftime("%b_%d_%Y_%H%M%S")
        args["logFile"] = os.path.join(args["outputDir"], logFile)
    else:
        args["logFile"] = os.path.realpath(args["logFile"])
        if not os.path.isdir(os.path.dirname(args["logFile"])):
            os.makedirs(os.path.dirname(args["logFile"]))

    if args["imageDest"] is None:
        args["imageDest"] = "%s/images" % args["outputDir"]
    else:
        args["imageDest"] = os.path.realpath(args["imageDest"])

    if args["dlDir"] is None:
        args["dlDir"] = os.path.realpath("%s/dl/%s" % (BR_ROOT, args["platformName"]))
    elif not os.path.isabs(args["dlDir"]):
        args["dlDir"] = os.path.realpath("%s/%s" % (os.getcwd(), args["dlDir"]))

    args["catalogFile"] = os.path.realpath(args["catalogFile"])
def transfer_file():
    import os
    import tarfile
    import zipfile

    filename = raw_input("Enter the filename you want to move:")
    object_file = raw_input("Enter the object filename:")

    if filename.split(".")[1] == "zip":
        with zipfile.ZipFile(filename) as f_from:
            file_list = f_from.namelist()
            f_from.extractall()
    else:
        with tarfile.open(filename, "r") as f_from:
            file_list = f_from.getnames()
            f_from.extractall()

    if object_file.split(".")[1] == "zip":
        for file in os.listdir(os.getcwd()):
            if file in file_list:
                with zipfile.ZipFile(filename, "a") as f_to:
                    f_to.write(file)
                os.remove(file)
    else:
        for file in os.listdir(os.getcwd()):
            if file in file_list:
                with tarfile.open(object_file, "a") as f_to:
                    f_to.add(file)
                os.remove(file)
Пример #3
0
def add_post():
    if request.form.has_key("title"):
        photo = request.files.get("photo", None)
        filename = None
        directory = os.getcwd()
        dir_photo = os.getcwd()

        if photo and is_allowed(photo.filename):
            try:
                directory = app.config["UPLOAD_FOLDER"] + "/" + str(current_user.id) + "/"
                dir_photo = os.getcwd() + directory.replace("/", "\\")
                os.makedirs(dir_photo)
            except OSError:
                pass
            filename = secure_filename(photo.filename).split(".")
            filename[0] = filename[0] + str(time.time()).replace(".", "")[-6:-1]
            dir_photo = dir_photo + ".".join(filename)
            filename = directory + ".".join(filename)
            photo.save(dir_photo)

        post = Post(
            title=request.form["title"],
            body=request.form["body"],
            author=current_user.id,
            picture=filename,
            date=datetime.utcnow(),
        )
        db.session.add(post)
        db.session.commit()
    return redirect(url_for("homepage"))
    def test_process_schema_rule_mismatched_table(self):

        test_case_buf = """
SET search_path = bial, pg_catalog

--
-- Name: ab_reporting_beta_match_ins; Type: RULE; Schema: bial; Owner: table_owner
--

CREATE RULE ab_reporting_beta_match_ins AS ON INSERT TO weblog_mart_tbls.ab_reporting_beta_match DO INSTEAD INSERT INTO ab_reporting_beta_match VALUES new.search_session_id;
"""
        expected_out = ""

        in_name = os.path.join(os.getcwd(), "infile")
        out_name = os.path.join(os.getcwd(), "outfile")
        with open(in_name, "w") as fd:
            fd.write(test_case_buf)

        dump_schemas = set(["bial"])
        dump_tables = set([("bial", "ab_reporting_beta_match")])
        with open(out_name, "w") as fdout:
            with open(in_name, "r") as fdin:
                process_schema(dump_schemas, dump_tables, fdin, fdout)

        with open(out_name, "r") as fd:
            results = fd.read()

        self.assertEquals(results, expected_out)
        os.remove(in_name)
        os.remove(out_name)
Пример #5
0
def main():
    args_failed = False
    rootdirs = []
    argv = copy.copy(sys.argv)
    argv.__delitem__(0)
    for arg in argv:
        if arg in ("--usage", "--help", "--version"):
            print helptext
            sys.exit()
        elif os.path.isdir(arg):
            rootdirs.append(arg)
            # This is needed because paths may have start
            # in the working dir or in the root dir.
            item = os.path.join(os.getcwd(), arg)
        elif os.path.isdir(item):
            rootdirs.append(item)
        else:
            print ("Invalid argument {}: not a directory." "See '--usage'.".format(sys.argv[i]))
            sys.exit()
    if not rootdirs:
        rootdirs = [os.getcwd()]
        print "Starting search in the ", rootdirs

    for rootdir in rootdirs:
        for root, dirs, files in os.walk(rootdir):
            pass_dir(root)
 def start_monitor(self, event):
     print(os.getcwd())
     os.chdir("../activity_monitor/")
     print(os.getcwd())
     cmd = ["sudo", "python3", "main.py"]
     self.monitor_pro = subprocess.Popen(cmd, preexec_fn=os.setsid)
     os.chdir("../administrator_program")
Пример #7
0
    def __init__(self, app):
        os.environ["SERVER_SOFTWARE"] = SERVER_SOFTWARE

        self._num_workers = None
        self.setup(app)

        self.pidfile = None
        self.worker_age = 0
        self.reexec_pid = 0
        self.master_name = "Master"

        # get current path, try to use PWD env first
        try:
            a = os.stat(os.environ["PWD"])
            b = os.stat(os.getcwd())
            if a.st_ino == b.st_ino and a.st_dev == b.st_dev:
                cwd = os.environ["PWD"]
            else:
                cwd = os.getcwd()
        except:
            cwd = os.getcwd()

        args = sys.argv[:]
        args.insert(0, sys.executable)

        # init start context
        self.START_CTX = {"args": args, "cwd": cwd, 0: sys.executable}
Пример #8
0
def main():
    pwd = os.getcwd()
    s = raw_input("chdir[%s]" % pwd)
    if s:
        os.chdir(s)
        pwd = os.getcwd()
    host = ask("host", "vovrn.cwi.n1")
    port = 4127
    verbose = 1
    mode = ""
    print """\
Mode should be a string of characters,indicating what to do with differences.
r - read different files to local file system 
w - write different files to remote file system 
c - create new files,either remote or local 
d - delete disappearing files,either remote or local 

"""
    s = raw_input("mode [%s]" % mode)
    if s:
        mode = s
    address = (host, port)
    t1 = time.time()
    local = FSProxy.FSProxyLocal()
    remote = FSProxy.FSProxyClient(address, verbose)
    compare(local, remote, mode)
    remote._close()
    local._close()
    t2 = time.time()
    dt = t2 - t1
    mins, secs = divmod(dt, 60)
    print mins, "minutes and", round(secs), "seconds"
    raw_input("[Return to exit]")
Пример #9
0
    def test_compress_deprecated(self):
        tmpdir, tmpdir2, base_name = self._create_files()
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, "dist", compress="compress")
        finally:
            os.chdir(old_dir)

        tarball = base_name + ".tar.Z"
        self.assertTrue(os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1)
        os.remove(tarball)
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, "dist", compress="compress", dry_run=True)
        finally:
            os.chdir(old_dir)

        self.assertFalse(os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1)
Пример #10
0
    def set_total_costs_matrix(self, i, j, def_param=None):
        def_param = total_costs_matrix_base
        curve_name_i = all_curves[i][0]
        curve_type_i = all_curves[i][1]
        curve_file_i = fits.open(
            os.getcwd() + "/memoria/" + "inputs/" + curve_type_i + "/" + curve_name_i + ".fits", memmap=False
        )

        curve_data_i = Extractor.get_values(curve_file_i)

        curve_file_i.close()

        curve_name_j = all_curves[j][0]
        curve_type_j = all_curves[j][1]
        curve_file_j = fits.open(
            os.getcwd() + "/memoria/" + "inputs/" + curve_type_j + "/" + curve_name_j + ".fits", memmap=False
        )

        curve_data_j = Extractor.get_values(curve_file_j)

        curve_file_j.close()

        x, y = curve_data_i, curve_data_j

        dtw = DTW(x, y)
        cost_matrix = dtw.compute_cost_matrix(DTW.euclidean_distance)
        acc_cost_matrix, cost = dtw.compute_acc_cost_matrix(cost_matrix)

        self.total_costs_matrix[i, j] = cost
Пример #11
0
    def run_filediff(self):
        print "==================== Start Test: %s ====================" % self.tag
        passed = True
        timed_out = False

        # Adjust the number of iterations in the config file
        self.adjust_iter()

        # Assemble the shell command to run
        logfilename = "%s.log" % os.path.splitext(self.cfg_file)[0]
        command = "%s -f %s > %s" % (self.su2_exec, self.cfg_file, logfilename)

        # Run SU2
        workdir = os.getcwd()
        os.chdir(self.cfg_dir)
        print os.getcwd()
        start = datetime.datetime.now()
        process = subprocess.Popen(command, shell=True)  # This line launches SU2

        # check for timeout
        while process.poll() is None:
            time.sleep(0.1)
            now = datetime.datetime.now()
            running_time = (now - start).seconds
            if running_time > self.timeout:
                try:
                    process.kill()
                    os.system("killall %s" % self.su2_exec)  # In case of parallel execution
                except AttributeError:  # popen.kill apparently fails on some versions of subprocess... the killall command should take care of things!
                    pass
                timed_out = True
                passed = False

        if not timed_out:
            # Compare files
            fromfile = self.reference_file
            tofile = self.test_file

            fromdate = time.ctime(os.stat(fromfile).st_mtime)
            todate = time.ctime(os.stat(tofile).st_mtime)
            fromlines = open(fromfile, "U").readlines()
            tolines = open(tofile, "U").readlines()

            diff = list(difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate))

            if diff == []:
                passed = True
            else:
                for line in diff:
                    print line[:-1]
                passed = False

        else:
            passed = False

        print "test duration: %.2f min" % (running_time / 60.0)
        print "==================== End Test: %s ====================\n" % self.tag

        os.chdir(workdir)
        return passed
Пример #12
0
    def test_known_scaffold_multiple_rendered(self):
        import os

        cmd = self._makeOne("-s", "dummy1", "-s", "dummy2", "Distro")
        scaffold1 = DummyScaffold("dummy1")
        scaffold2 = DummyScaffold("dummy2")
        cmd.scaffolds = [scaffold1, scaffold2]
        cmd.pyramid_dist = DummyDist("0.1")
        result = cmd.run()
        self.assertEqual(result, 0)
        self.assertEqual(scaffold1.output_dir, os.path.normpath(os.path.join(os.getcwd(), "Distro")))
        self.assertEqual(
            scaffold1.vars,
            {
                "project": "Distro",
                "egg": "Distro",
                "package": "distro",
                "pyramid_version": "0.1",
                "pyramid_docs_branch": "0.1-branch",
            },
        )
        self.assertEqual(scaffold2.output_dir, os.path.normpath(os.path.join(os.getcwd(), "Distro")))
        self.assertEqual(
            scaffold2.vars,
            {
                "project": "Distro",
                "egg": "Distro",
                "package": "distro",
                "pyramid_version": "0.1",
                "pyramid_docs_branch": "0.1-branch",
            },
        )
Пример #13
0
    def _upload_preview_image(self):
        os.makedirs(os.path.join(os.getcwd(), "preview_images"), 0755)
        raw_image = os.path.join(os.getcwd(), "preview_images", self.channel + "_" + self._ip)
        thumbnail = os.path.join(os.getcwd(), "preview_images", self.channel + "_" + self._ip)
        upload_client = UploadClient(
            self._upload_server, self._project_name, self._ivt.id, self._ivt.login_passwd, self.channel
        )
        while True:
            try:
                if self._is_online != self.STATE_OFFLINE:
                    res = requests.get("http://{0}/snapshot_ch=1".format(self._ip), stream=True)
                    res.raise_for_status()
                    for data in res.iter_content(1024):
                        with open(raw_image, "wb") as f:
                            f.write(data)
                    # TODO scale image down

                    # upload image to IVC
                    with open(thumbnail, "rb") as f:
                        upload_client.upload(f)
            except Exception:
                try:
                    res.close()
                except Exception:
                    pass
                log.exception("Failed to fetch or upload preview image of {0}".format(self))
            finally:
                gevent.sleep(self._upload_interval)
def ADAMS_setup_INP(myAsm, key, jointsMBDXML, instRef, instAssemblyRef, myModel, parallelCores, ramAllocated):
    logger = logging.getLogger()
    try:
        lodFileID = instRef[key]["ComponentID"]
    except KeyError:
        try:
            lodFileID = instAssemblyRef[key]["ComponentID"]
        except KeyError:
            logger.error("LOD file not found for " + str(key))
            raise Exception("LOD file not found. Please check log.")
    lodFileName = "LT_" + lodFileID + ".lod"
    lodFilePath = os.path.join(os.getcwd(), lodFileName)

    constrainWithSoftSprings(
        key, myAsm
    )  # Constrain every vertice of the part in x, y and z directions with soft-springs
    refPointRef = readAndDefineMarkers(
        key, os.getcwd(), myAsm, lodFilePath
    )  # Read the markers from the LOD files and define them in the Abaqus assembly as reference points

    (refPntOtherComp, sortedOtherComp) = getBoundingNodes(
        jointsMBDXML, key, instRef, myModel, myAsm
    )  # Get the nodes inside the bounding box of the part which is connected to the current part

    defineMPCs(
        sortedOtherComp, refPntOtherComp, refPointRef, instRef, myAsm, myModel, key
    )  # Define MPCs between the reference points (markers) and the corresponding surfaces on the part

    inpName = createINP(myAsm, key, myModel, parallelCores, ramAllocated)  # Create an INP file of the current part

    cleanModel(
        myModel, myAsm
    )  # Clean the current model of the Abaqus/CAE from the previous part itself and its constraints

    inpTempFileName = (
        inpName + ".inp"
    )  # Define the previously created INP file of the current part as the temporary INP file
    inpTempFilePath = os.path.join(
        os.getcwd(), inpTempFileName
    )  # Define the location of the temporary INP file and store it
    with open(inpTempFilePath, "r") as inpTempFile:
        stopLine = parseInpTemp(
            inpTempFile
        )  # Determine upto which point the temporary INP file needs to be merged with the final INP file
        with open(lodFilePath, "r") as lodFile:
            startLine = parseLOD(lodFile)  # Determine from which point the LOD file generated by Adams needs...
            # ...to be merged with the final INP file
    with open(inpTempFilePath, "r") as inpTempFile:
        with open(lodFilePath, "r") as lodFile:
            inpFileName = key + ".inp"  # Define the name of the final INP file by using the name of the current part
            inpFilePath = os.path.join(
                os.getcwd(), inpFileName
            )  # Define the location of the final INP file and store it
            open(inpFilePath, "a").close()  # Create the final INP file by opening and closing it

            createFinalInp(
                inpFilePath, inpTempFile, lodFile, stopLine, startLine
            )  # Merge temporary INP file and LOD file to create the final INP file

    os.remove(inpTempFilePath)
Пример #15
0
def main(allowed_options=None, description=None, usage=None):
    from os import getcwd
    from sys import argv
    from optparse import OptionParser
    from rabbitvcs.util.helper import get_common_directory

    parser = OptionParser(usage=usage, description=description)

    if allowed_options:
        for (option_args, option_kwargs) in allowed_options:
            parser.add_option(*option_args, **option_kwargs)

    (options, args) = parser.parse_args(argv)

    # Convert "." to current working directory
    paths = args[1:]
    for i in range(0, len(paths)):
        if paths[i] == ".":
            paths[i] = getcwd()

    if not paths:
        paths = [getcwd()]

    if parser.has_option("--base-dir") and not options.base_dir:
        options.base_dir = get_common_directory(paths)

    return (options, paths)
Пример #16
0
def prep(first, last, which, max_depth=100):
    output = {"first": first, "last": last, "matches": [], "misspelled": defaultdict(int)}

    if which == "first":
        options = {
            "query": last,
            "regex": r"\b(" + first[0] + "[a-z']+)\s" + last,
            "correct": [first],
            "max_depth": max_depth,
        }
    else:
        options = {
            "query": first,
            "regex": first + "\s(" + last[0] + "[a-z']+)",
            "correct": [last, last + "'s"],
            "max_depth": max_depth,
        }
    search(options, output)

    if which == "first":
        f = open(
            os.getcwd() + "/data/matches-%s-%s.json" % (output["first"], datetime.now().strftime("%Y-%m-%d-%H-%M-%S")),
            "w",
        )
        f.write(json.dumps(output, indent=2))
        f.close()
    else:
        f = open(
            os.getcwd() + "/data/matches-%s-%s.json" % (output["last"], datetime.now().strftime("%Y-%m-%d-%H-%M-%S")),
            "w",
        )
        f.write(json.dumps(output, indent=2))
        f.close()
Пример #17
0
def rm_sub_dir(dir_name):
    os.chdir(os.getcwd() + "/" + dir_name)
    dir_list = os.listdir(os.getcwd())
    for i in dir_list:
        os.remove(i)
    os.chdir("..")
    os.removedirs(dir_name)
Пример #18
0
    def postprocessMolrep(self):
        """
    Sort Molrep data.
    """
        if self.verbose:
            self.logger.debug("AutoStats::postprocessMolrep")
        try:
            if os.path.exists("molrep_rf.ps"):
                Utils.convertImage(self, "molrep_rf.ps", "molrep_rf.jpg")
                # self.molrep_log = open('molrep.doc','r').readlines()
                # data = Parse.ParseOutputMolrep(self,self.molrep_log)
                data = Parse.ParseOutputMolrep(self, open("molrep.doc", "r").readlines())
            else:
                data = Parse.setMolrepFailed(self)
                self.failed = True
                self.clean = False
            data.update(
                {
                    "Molrep log": os.path.join(os.getcwd(), "molrep.doc"),
                    "Molrep jpg": os.path.join(os.getcwd(), "molrep_rf.jpg"),
                }
            )
            self.molrep_results = {"Molrep results": data}

        except:
            self.logger.exception("**ERROR in AutoStats.postprocessMolrep**")
Пример #19
0
    def _make_tarball(self, target_name):
        tmpdir = self.mkdtemp()
        self.write_file([tmpdir, "file1"], "xxx")
        self.write_file([tmpdir, "file2"], "xxx")
        os.mkdir(os.path.join(tmpdir, "sub"))
        self.write_file([tmpdir, "sub", "file3"], "xxx")
        tmpdir2 = self.mkdtemp()
        unittest.skipUnless(
            splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0], "source and target should be on same drive"
        )
        base_name = os.path.join(tmpdir2, target_name)
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            make_tarball(splitdrive(base_name)[1], ".")
        finally:
            os.chdir(old_dir)

        tarball = base_name + ".tar.gz"
        self.assertTrue(os.path.exists(tarball))
        base_name = os.path.join(tmpdir2, target_name)
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            make_tarball(splitdrive(base_name)[1], ".", compress=None)
        finally:
            os.chdir(old_dir)

        tarball = base_name + ".tar"
        self.assertTrue(os.path.exists(tarball))
        return
Пример #20
0
    def set_libdir_variables(self):
        for varname in ("SAPPORO_LIBDIRS", "GRAPE6_LIBDIRS"):
            if varname in self.environment:
                continue

            if varname in os.environ:
                self.environment[varname] = os.environ[varname]
            else:
                self.environment_notset[varname] = "-L<directory>"

        if "SAPPORO_LIBDIRS" in self.environment:
            self.environment["SAPPORO_LIBS"] = "-L{0} -lsapporo".format(self.environment["SAPPORO_LIBDIRS"])
        else:
            if is_configured and hasattr(config.cuda, "sapporo_version"):
                if config.cuda.sapporo_version == "2":
                    self.environment["SAPPORO_LIBS"] = "-L{0}/lib/sapporo-2 -lsapporo {1}".format(
                        os.path.abspath(os.getcwd()), config.openmp.cflags
                    )
                else:
                    self.environment["SAPPORO_LIBS"] = "-L{0}/lib/sapporo_light -lsapporo".format(
                        os.path.abspath(os.getcwd())
                    )
            else:
                self.environment["SAPPORO_LIBS"] = "-L{0}/lib/sapporo_light -lsapporo".format(
                    os.path.abspath(os.getcwd())
                )
            self.environment["BOOSTLIBS"] = ""
Пример #21
0
def copy_rails_config_file(directory, filename, flag=0):
    """
    Description:

    Vars:
        1. f_dst: source file name
        2. f_src: dst file name
        3. flag
            1 => copy ".project"
            2 => copy "do_heroku.bat"
        4. content: content of ".project"
        5. fin: file object
        6. fout: file object
        7. directory: full directory path
    """
    f_dst = os.path.join(os.getcwd(), filename)
    f_src = os.path.join(os.path.dirname(inspect.currentframe().f_code.co_filename), directory, filename)
    if flag == 1:
        fin = open(f_src, "r")
        #        content = f.read()
        content = fin.read()
        content = content.replace("@project_name@", os.path.basename(os.getcwd()))
        #                    os.path.basename(f_dst))
        fout = open(f_dst, "w")
        fout.write(content)

        fin.close()
        fout.close()

    else:
        shutil.copyfile(f_src, f_dst)
    print "File copied"
    print "\t", "From: %s" % f_src
    print "\t", "To: %s" % f_dst
Пример #22
0
def temp_cwd(name="tempcwd", quiet=False):
    """
    Context manager that creates a temporary directory and set it as CWD.

    The new CWD is created in the current directory and it's named *name*.
    If *quiet* is False (default) and it's not possible to create or change
    the CWD, an error is raised.  If it's True, only a warning is raised
    and the original CWD is used.
    """
    if isinstance(name, unicode):
        try:
            name = name.encode(sys.getfilesystemencoding() or "ascii")
        except UnicodeEncodeError:
            if not quiet:
                raise unittest.SkipTest("unable to encode the cwd name with " "the filesystem encoding.")
    saved_dir = os.getcwd()
    is_temporary = False
    try:
        os.mkdir(name)
        os.chdir(name)
        is_temporary = True
    except OSError:
        if not quiet:
            raise
        warnings.warn("tests may fail, unable to change the CWD to " + name, RuntimeWarning, stacklevel=3)
    try:
        yield os.getcwd()
    finally:
        os.chdir(saved_dir)
        if is_temporary:
            rmtree(name)
Пример #23
0
def unzip_input(file):
    print "* Unzipping" + file
    zfile = zipfile.ZipFile(os.getcwd() + "/input/" + file + ".zip")
    for name in zfile.namelist():
        (dirname, filename) = os.path.split(name)
        zfile.extract(name, os.getcwd() + "/input/")
    zfile.close()
Пример #24
0
def get_path(root, number):
    """
    再帰的にパスを取り出します。
    探査するディレクトリとそこからの深さを指定します。
    """
    pre_dir = os.getcwd()
    os.chdir(root)
    if not root.startswith("/"):
        root = os.getcwd()
    # import ipdb; ipdb.set_trace()
    def g(dir):
        l = len(root)
        if dir.startswith(root):
            return dir[l + 1 :]
        else:
            return dir

    def _(ret, num):
        if num == 0:
            return g(os.getcwd())
        dirs = os.listdir("./")
        dirs = [d for d in dirs if os.path.isdir(d)]
        for dir in dirs:
            os.chdir(dir)
            ret[dir] = _({}, num - 1)
            os.chdir("..")
        return ret

    r = _({}, number)
    os.chdir(pre_dir)
    return r
Пример #25
0
    def completechdir(self, text, line, begidx, endidx):
        """ complete directories """
        toreturn = []
        tocomplete = line.split()[-1]
        # replace "~" with home path
        tocomplete = re.sub("^~", self.conf["home_path"], tocomplete)
        try:
            directory = os.path.realpath(tocomplete)
        except:
            directory = os.getcwd()

        if not os.path.isdir(directory):
            directory = directory.rsplit("/", 1)[0]
            if directory == "":
                directory = "/"
            if not os.path.isdir(directory):
                directory = os.getcwd()

        ret_check_path, self.conf = sec.check_path(directory, self.conf, completion=1)
        if ret_check_path == 0:
            for instance in os.listdir(directory):
                if os.path.isdir(os.path.join(directory, instance)):
                    instance = instance + "/"
                else:
                    instance = instance + " "
                if instance.startswith("."):
                    if text.startswith("."):
                        toreturn.append(instance)
                    else:
                        pass
                else:
                    toreturn.append(instance)
            return [a for a in toreturn if a.startswith(text)]
        else:
            return None
Пример #26
0
def hardcoded_reg(anatomical_brain, reference_brain, anatomical_skull, reference_skull):  # , wait=""):

    import os

    os.system(
        "antsRegistration --collapse-output-transforms 0 --dimensionality 3 --initial-moving-transform [ %s, %s, 0 ] --interpolation Linear --output [ transform, transform_Warped.nii.gz ] --transform Rigid[ 0.1 ] --metric MI[ %s, %s, 1, 32, Regular, 0.25 ] --convergence [ 1000x500x250x100, 1e-08, 10 ] --smoothing-sigmas 3.0x2.0x1.0x0.0 --shrink-factors 8x4x2x1 --use-histogram-matching 1 --transform Affine[ 0.1 ] --metric MI[ %s, %s, 1, 32, Regular, 0.25 ] --convergence [ 1000x500x250x100, 1e-08, 10 ] --smoothing-sigmas 3.0x2.0x1.0x0.0 --shrink-factors 8x4x2x1 --use-histogram-matching 1 --transform SyN[ 0.1, 3.0, 0.0 ] --metric CC[ %s, %s, 1, 4 ] --convergence [ 100x100x70x20, 1e-09, 15 ] --smoothing-sigmas 3.0x2.0x1.0x0.0 --shrink-factors 6x4x2x1 --use-histogram-matching 1 --winsorize-image-intensities [ 0.01, 0.99 ]"
        % (
            reference_brain,
            anatomical_brain,
            reference_brain,
            anatomical_brain,
            reference_brain,
            anatomical_brain,
            reference_skull,
            anatomical_skull,
        )
    )

    warp_list = []

    files = [f for f in os.listdir(".") if os.path.isfile(f)]

    for f in files:

        if ("transform" in f) and ("Warped" not in f):
            warp_list.append(os.getcwd() + "/" + f)

        if "Warped" in f:
            warped_image = os.getcwd() + "/" + f

    # print wait

    return warp_list, warped_image
Пример #27
0
    def _WarnIfMissingTernProject(self):
        # The Tern server will operate without a .tern-project file. However, it
        # does not operate optimally, and will likely lead to issues reported that
        # JavaScript completion is not working properly. So we raise a warning if we
        # aren't able to detect some semblance of manual Tern configuration.

        # We do this check after the server has started because the server does
        # have nonzero use without a project file, however limited. We only do this
        # check once, though because the server can only handle one project at a
        # time. This doesn't catch opening a file which is not part of the project
        # or any of those things, but we can only do so much. We'd like to enhance
        # ycmd to handle this better, but that is a FIXME for now.
        if self._ServerIsRunning() and self._do_tern_project_check:
            self._do_tern_project_check = False

            tern_project = FindTernProjectFile(os.getcwd())
            if not tern_project:
                _logger.warning("No .tern-project file detected: " + os.getcwd())
                raise RuntimeError(
                    "Warning: Unable to detect a .tern-project file "
                    "in the hierarchy before " + os.getcwd() + " and no global .tern-config file was found. "
                    "This is required for accurate JavaScript "
                    "completion. Please see the User Guide for "
                    "details."
                )
            else:
                _logger.info("Detected .tern-project file at: " + tern_project)
Пример #28
0
 def command(self):
     config_spec = self.args[0]
     section = self.options.section_name
     if section is None:
         if "#" in config_spec:
             config_spec, section = config_spec.split("#", 1)
         else:
             section = "main"
     if not ":" in section:
         plain_section = section
         section = "app:" + section
     else:
         plain_section = section.split(":", 1)[0]
     if not config_spec.startswith("config:"):
         config_spec = "config:" + config_spec
     if plain_section != "main":
         config_spec += "#" + plain_section
     config_file = config_spec[len("config:") :].split("#", 1)[0]
     config_file = os.path.join(os.getcwd(), config_file)
     self.logging_file_config(config_file)
     conf = appconfig(config_spec, relative_to=os.getcwd())
     ep_name = conf.context.entry_point_name
     ep_group = conf.context.protocol
     dist = conf.context.distribution
     if dist is None:
         raise BadCommand(
             "The section %r is not the application (probably a filter).  "
             "You should add #section_name, where section_name is the "
             "section that configures your application" % plain_section
         )
     installer = self.get_installer(dist, ep_group, ep_name)
     installer.setup_config(self, config_file, section, self.sysconfig_install_vars(installer))
     self.call_sysconfig_functions("post_setup_hook", installer, config_file)
Пример #29
0
def main(purl):
    apiurl = "http://flvgo.com/download?url=%s" % urllib.quote(purl)
    ss.get("http://flvgo.com")
    cn = ss.get(apiurl).content
    infos = flvxz_parser(cn)
    title = infos["title"]
    quality = pickup(infos)
    durls = infos["data"][quality]["durls"]

    yes = True if len(durls) > 1 else False
    dir_ = os.path.join(os.getcwd(), infos["title"]) if yes else os.getcwd()

    n = args.from_ - 1
    amount = len(durls)

    for i in xrange(n, amount):
        info = {
            "title": title,
            "filename": os.path.join(dir_, str(i + 1) + getext(durls[i])),
            "durl": durls[i],
            "dir_": dir_,
            "amount": amount,
            "n": n,
        }
        if args.play:
            play(info)
        else:
            download(info)
        n += 1
Пример #30
0
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)

        self.title("libuseful")

        old_dir = os.getcwd()
        os.chdir(os.path.dirname(sys.argv[0]))  # Change to root package directory needed for __import__
        # Add buttons
        for name in os.listdir("."):
            button_name = ""
            if os.path.isdir(name) and os.path.isfile(name + "/__init__.py"):  # if this directory is a package
                mod = __import__(  # this means import name as mod
                    name,  # Name of the module
                    globals(),
                    locals(),  # Context for the module (all the globlas and locals it can use)
                    [],  # the from part
                    0,  # 0 = absalute import only
                )
                if "_gui" in mod.__dict__ and mod._gui == True and "main" in mod.__dict__:
                    if "_gui_name" in mod.__dict__:
                        button_name = mod._gui_name
                    else:
                        button_name = name
                    Button(self, text=button_name, command=mod.main).pack()
        docPathPy = os.getcwd() + "/docs/index.html"
        docPathPy = "file://" + docPathPy.replace("\\", "/")
        Button(self, text="Open Python style docuemtation/API", command=lambda: webbrowser.open(docPathPy)).pack()

        docPathJava = os.getcwd() + "/docs-epydoc/index.html"
        docPathJava = "file://" + docPathJava.replace("\\", "/")
        Button(self, text="Open Java style docuemtation/API", command=lambda: webbrowser.open(docPathJava)).pack()
        os.chdir(old_dir)  # Change to where we were

        self.mainloop()