Python os.path.normpath() Examples

The following are code examples for showing how to use os.path.normpath(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: CodingDojo   Author: ComputerSocietyUNB   File: templates.py    (license) View Source Project 10 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 2
Project: sublime-text-3-packages   Author: nickjj   File: node_linter.py    (MIT License) View Source Project 6 votes vote down vote up
def rev_parse_manifest_path(self, cwd):
        """
        Search parent directories for package.json.

        Starting at the current working directory. Go up one directory
        at a time checking if that directory contains a package.json
        file. If it does, return that directory.

        """

        name = 'package.json'
        manifest_path = path.normpath(path.join(cwd, name))

        bin_path = path.join(cwd, 'node_modules/.bin/')

        if path.isfile(manifest_path) and path.isdir(bin_path):
            return manifest_path

        parent = path.normpath(path.join(cwd, '../'))

        if parent == '/' or parent == cwd:
            return None

        return self.rev_parse_manifest_path(parent) 
Example 3
Project: sublime-text-3-packages   Author: nickjj   File: node_linter.py    (MIT License) View Source Project 6 votes vote down vote up
def find_local_cmd_path(self, cmd):
        """
        Find a local binary in node_modules/.bin.

        Given package.json filepath and a local binary to find,
        look in node_modules/.bin for that binary.

        """

        cwd = path.dirname(self.manifest_path)

        binary = self.get_pkg_bin_cmd(cmd)

        if binary:
            return path.normpath(path.join(cwd, binary))

        return self.find_ancestor_cmd_path(cmd, cwd) 
Example 4
Project: sublime-text-3-packages   Author: nickjj   File: node_linter.py    (MIT License) View Source Project 6 votes vote down vote up
def find_ancestor_cmd_path(self, cmd, cwd):
        """Recursively check for command binary in ancestors' node_modules/.bin directories."""

        node_modules_bin = path.normpath(path.join(cwd, 'node_modules/.bin/'))

        binary = path.join(node_modules_bin, cmd)

        if sublime.platform() == 'windows' and path.splitext(binary)[1] != '.cmd':
            binary += '.cmd'

        if binary and access(binary, X_OK):
            return binary

        parent = path.normpath(path.join(cwd, '../'))

        if parent == '/' or parent == cwd:
            return None

        return self.find_ancestor_cmd_path(cmd, parent) 
Example 5
Project: sublime-text-3-packages   Author: nickjj   File: gutter_color.py    (MIT License) View Source Project 6 votes vote down vote up
def fix_scheme_in_settings(settings_file,current_scheme, new_scheme, regenerate=False):
  """Change the color scheme in the given Settings to a background-corrected one"""
  from os.path import join, normpath, isfile

  settings = load_settings(settings_file)
  settings_scheme = settings.get("color_scheme")
  if current_scheme == settings_scheme:
    new_scheme_path =  join(packages_path(), normpath(new_scheme[len("Packages/"):]))
    if isfile(new_scheme_path) and not regenerate:
      settings.set("color_scheme", new_scheme)
    else:
      generate_scheme_fix(current_scheme, new_scheme_path)
      settings.set("color_scheme", new_scheme)
    save_settings(settings_file)
    return True
  return False 
Example 6
Project: sublime-text-3-packages   Author: nickjj   File: st_color_scheme_matcher.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.color_scheme = path.normpath(scheme_file)
        self.scheme_file = path.basename(self.color_scheme)
        self.plist_file = color_filter(
            readPlistFromBytes(
                re.sub(
                    br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'',
                    sublime.load_binary_resource(sublime_format_path(self.color_scheme))
                )
            )
        )
        self.scheme_file = scheme_file
        self.matched = {}

        self.parse_scheme() 
Example 7
Project: NarshaTech   Author: KimJangHyeon   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 8
Project: Scrum   Author: prakharchoudhary   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 9
Project: bpy_lambda   Author: bcongdon   File: path.py    (license) View Source Project 6 votes vote down vote up
def is_subdir(path, directory):
    """
    Returns true if *path* in a subdirectory of *directory*.
    Both paths must be absolute.

    :arg path: An absolute path.
    :type path: string or bytes
    """
    from os.path import normpath, normcase, sep
    path = normpath(normcase(path))
    directory = normpath(normcase(directory))
    if len(path) > len(directory):
        sep = sep.encode('ascii') if isinstance(directory, bytes) else sep
        if path.startswith(directory.rstrip(sep) + sep):
            return True
    return False 
Example 10
Project: bpy_lambda   Author: bcongdon   File: path.py    (license) View Source Project 6 votes vote down vote up
def reduce_dirs(dirs):
    """
    Given a sequence of directories, remove duplicates and
    any directories nested in one of the other paths.
    (Useful for recursive path searching).

    :arg dirs: Sequence of directory paths.
    :type dirs: sequence
    :return: A unique list of paths.
    :rtype: list
    """
    dirs = list({_os.path.normpath(_os.path.abspath(d)) for d in dirs})
    dirs.sort(key=lambda d: len(d))
    for i in range(len(dirs) - 1, -1, -1):
        for j in range(i):
            print(i, j)
            if len(dirs[i]) == len(dirs[j]):
                break
            elif is_subdir(dirs[i], dirs[j]):
                del dirs[i]
                break
    return dirs 
Example 11
Project: nzb-monkey   Author: nzblnk   File: nzblnkconfig.py    (license) View Source Project 6 votes vote down vote up
def config_win():

    try:
        import winreg as reg
        key = reg.CreateKey(reg.HKEY_CURRENT_USER, 'SOFTWARE\\Classes\\nzblnk')
        reg.SetValue(key, '', reg.REG_SZ, 'URL:nzblnk')
        reg.SetValueEx(key, 'URL Protocol', 0, reg.REG_SZ, '')
        reg.CloseKey(key)

        key = reg.CreateKey(reg.HKEY_CURRENT_USER, 'SOFTWARE\\Classes\\nzblnk\\shell\\open\\command')
        reg.SetValue(key, '', reg.REG_SZ, '"{0}" "%1"'.format(op.normpath(os.path.abspath(sys.executable))))
        reg.CloseKey(key)

    except (OSError, ImportError):
        print(Col.FAIL + ' FAILED to setup registry link for NZBLNK scheme!' + Col.OFF)
        sleep(wait_time)
        sys.exit(2) 
Example 12
Project: django   Author: alexsukhrin   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 13
Project: Taigabot   Author: FrozenPigs   File: base.py    (license) View Source Project 6 votes vote down vote up
def _get_config_path(self, config_level):
        # we do not support an absolute path of the gitconfig on windows ,
        # use the global config instead
        if is_win and config_level == "system":
            config_level = "global"

        if config_level == "system":
            return "/etc/gitconfig"
        elif config_level == "user":
            config_home = os.environ.get("XDG_CONFIG_HOME") or osp.join(os.environ.get("HOME", '~'), ".config")
            return osp.normpath(osp.expanduser(osp.join(config_home, "git", "config")))
        elif config_level == "global":
            return osp.normpath(osp.expanduser("~/.gitconfig"))
        elif config_level == "repository":
            return osp.normpath(osp.join(self.git_dir, "config"))

        raise ValueError("Invalid configuration level: %r" % config_level) 
Example 14
Project: Taigabot   Author: FrozenPigs   File: util.py    (license) View Source Project 6 votes vote down vote up
def _cygexpath(drive, path):
    if osp.isabs(path) and not drive:
        ## Invoked from `cygpath()` directly with `D:Apps\123`?
        #  It's an error, leave it alone just slashes)
        p = path
    else:
        p = path and osp.normpath(osp.expandvars(osp.expanduser(path)))
        if osp.isabs(p):
            if drive:
                # Confusing, maybe a remote system should expand vars.
                p = path
            else:
                p = cygpath(p)
        elif drive:
            p = '/cygdrive/%s/%s' % (drive.lower(), p)

    return p.replace('\\', '/') 
Example 15
Project: macos-st-packages   Author: zce   File: st_color_scheme_matcher.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.color_scheme = path.normpath(scheme_file)
        self.scheme_file = path.basename(self.color_scheme)
        self.plist_file = color_filter(
            readPlistFromBytes(
                re.sub(
                    br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'',
                    sublime.load_binary_resource(sublime_format_path(self.color_scheme))
                )
            )
        )
        self.scheme_file = scheme_file
        self.matched = {}

        self.parse_scheme() 
Example 16
Project: pymixup   Author: rdevost   File: utilities.py    (license) View Source Project 6 votes vote down vote up
def obfuscate_path(file_path):
    """Create an obfuscated path name.

    Parameters
    ----------
    file_path : str

    Returns
    -------
    obfuscated path : str
    """
    from logic.identifier import get_obfuscated_name

    obf_path = [get_obfuscated_name(p) for
                p in normpath(file_path).split(sep)]

    if obf_path[-1][-3:] in ['.py', '.kv']:
        obf_path[-1] = ''.join([get_obfuscated_name(obf_path[-1][:-3]),
                                obf_path[-1][-3:]])

    return join(*obf_path) 
Example 17
Project: recipe_zs2017_track2   Author: kamperh   File: ksegment.py    (license) View Source Project 6 votes vote down vote up
def main():
    args = check_argv()

    # Complete options
    options_dict = default_options_dict.copy()
    options_dict["data_dir"] = path.normpath(args.data_dir)
    options_dict["model_dir"] = path.join(MODEL_DIR, options_dict["data_dir"].replace("data" + os.sep, ""))
    options_dict["init_am_n_iter"] = args.init_am_n_iter
    options_dict["segment_n_iter"] = args.segment_n_iter
    options_dict["K_max"] = args.K_max
    options_dict["min_duration"] = args.min_duration
    options_dict["n_slices_max"] = args.n_slices_max
    options_dict["p_boundary_init"] = args.p_boundary_init
    options_dict["n_cpus"] = args.n_cpus
    options_dict["n_batches"] = args.n_batches

    ksegment(options_dict) 
Example 18
Project: zippy   Author: securesystemslab   File: test_module_imports.py    (license) View Source Project 6 votes vote down vote up
def test_module_imports_are_direct():
    my_filename = abspath(inspect.getfile(inspect.currentframe()))
    my_dirname = dirname(my_filename)
    diagnose_imports_filename = join(my_dirname, 'diagnose_imports.py')
    diagnose_imports_filename = normpath(diagnose_imports_filename)

    process = subprocess.Popen(
        [
            sys.executable,
            normpath(diagnose_imports_filename),
            '--problems',
            '--by-importer'
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        bufsize=-1)
    output, _ = process.communicate()
    assert output == '', "There are import problems:\n" + output.decode() 
Example 19
Project: Gypsy   Author: benticarlos   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 20
Project: orange3-timeseries   Author: biolab   File: test_doctests.py    (license) View Source Project 6 votes vote down vote up
def suite(package):
    """Assemble test suite for doctests in path (recursively)"""
    from importlib import import_module
    for module in find_modules(package.__file__):
        try:
            module = import_module(module)
            yield DocTestSuite(module,
                               globs=Context(module.__dict__.copy()),
                               optionflags=ELLIPSIS | NORMALIZE_WHITESPACE)
        except ValueError:
            pass  # No doctests in module
        except ImportError:
            import warnings
            warnings.warn('Unimportable module: {}'.format(module))

    # Add documentation tests
    yield DocFileSuite(path.normpath(path.join(path.dirname(__file__), '..', '..', '..', 'doc', 'scripting.rst')),
                       module_relative=False,
                       globs=Context(module.__dict__.copy()),
                       optionflags=ELLIPSIS | NORMALIZE_WHITESPACE
                       ) 
Example 21
Project: DjangoBlog   Author: 0daybug   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 22
Project: Price-Comparator   Author: Thejas-1   File: senna.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, senna_path, operations, encoding='utf-8'):
        self._encoding = encoding
        self._path = path.normpath(senna_path) + sep 
        
        # Verifies the existence of the executable on the self._path first    
        #senna_binary_file_1 = self.executable(self._path)
        exe_file_1 = self.executable(self._path)
        if not path.isfile(exe_file_1):
            # Check for the system environment 
            if 'SENNA' in environ:
                #self._path = path.join(environ['SENNA'],'')  
                self._path = path.normpath(environ['SENNA']) + sep 
                exe_file_2 = self.executable(self._path)
                if not path.isfile(exe_file_2):
                    raise OSError("Senna executable expected at %s or %s but not found" % (exe_file_1,exe_file_2))
        
        self.operations = operations 
Example 23
Project: wanblog   Author: wanzifa   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 24
Project: hookshub   Author: gisce   File: listener.py    (license) View Source Project 6 votes vote down vote up
def start_listening(host_ip=DEFAULT_IP,
                    host_port=DEFAULT_PORT,
                    proc_num=DEFAULT_PROCS):
    global config
    from os.path import isfile
    path = normpath(abspath(dirname(__file__)))
    config_path = join(path, 'config.json')
    if isfile(config_path):
        with open(config_path, 'r') as cfg:
            config = loads(cfg.read())
    else:
        config = {}
    sentry = Sentry(application)
    logging.getLogger(__name__).info(
        'Start Listening on {}:{} with {} procs'.format(
            host_ip, host_port, proc_num
        )
    )
    global pool
    pool = Pool(processes=proc_num, initializer=init_worker)
    try:
        application.run(debug=False, host=host_ip, port=host_port)
    finally:
        pool.terminate()
        pool.close() 
Example 25
Project: chalktalk_docs   Author: loremIpsum1771   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def get_matching_files(dirname, exclude_matchers=()):
    """Get all file names in a directory, recursively.

    Exclude files and dirs matching some matcher in *exclude_matchers*.
    """
    # dirname is a normalized absolute path.
    dirname = path.normpath(path.abspath(dirname))
    dirlen = len(dirname) + 1    # exclude final os.path.sep

    for root, dirs, files in walk(dirname, followlinks=True):
        relativeroot = root[dirlen:]

        qdirs = enumerate(path_stabilize(path.join(relativeroot, dn))
                          for dn in dirs)
        qfiles = enumerate(path_stabilize(path.join(relativeroot, fn))
                           for fn in files)
        for matcher in exclude_matchers:
            qdirs = [entry for entry in qdirs if not matcher(entry[1])]
            qfiles = [entry for entry in qfiles if not matcher(entry[1])]

        dirs[:] = sorted(dirs[i] for (i, _) in qdirs)

        for i, filename in sorted(qfiles):
            yield filename 
Example 26
Project: tabmaster   Author: NicolasMinghetti   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 27
Project: trydjango18   Author: lucifer-yqh   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 28
Project: rapydml_cmp   Author: valq7711   File: rapydml_cmp.py    (license) View Source Project 6 votes vote down vote up
def read_config():
    self_path =  os.path.abspath(os.path.dirname(__file__))
    ml_cmp_conf =  os.path.join(self_path,'ml_cmp.conf')
    if os.path.isfile(ml_cmp_conf):
        with open(ml_cmp_conf, 'r') as f:
            cfg = f.read()
        try:
            cfg = json.loads(cfg)
        except ValueError:
            raise ValueError('Invalid ml_cmp.conf: %s' % ml_cmp_conf)
        # check settings
        missing = set(('node', 'rapydscript', 'rs_options')) - set(cfg.keys())
        if missing:
            raise ValueError('Missing settings in ml_cmp.conf: %s' % missing)

        ret = [
                [   os.path.normpath(cfg['node']),
                    os.path.normpath(cfg['rapydscript'])
                ],
                cfg['rs_options'],
                cfg.get('ugly_template', False) 
        ]
        return ret 
Example 29
Project: rapydml_cmp   Author: valq7711   File: rapydml_cmp.py    (license) View Source Project 6 votes vote down vote up
def make_pyj_js(rs_s, dest_base_fname):
    """
    produce 2 files
        - dest_base_fname.pyj
        - dest_base_fname.js
    rs_s - RapydScript string
    dest_base_fname - 'd:/dfsdf/sdfsdf/out_name' - no ext!
    """
    from os  import path

    pyj_fname =  path.normpath( dest_base_fname+'.pyj')
    js_fname = path.normpath(dest_base_fname+'.js')

    with open(pyj_fname, 'w') as file_pyj:
    	file_pyj.write(rs_s)

    #cmd = RapydRS_cmd
    cmd_lst = RS_CMD + [pyj_fname] + RS_OPT + ['-o', js_fname]
    #compile pyj to js
    result = Popen(cmd_lst,
                    stdout = PIPE, stderr = PIPE, shell = True).communicate()
    if result[1]:
    	raise ShellError("'%s' triggered the following OS error: %s" %
                               ('make_pyj_js', result[1])) 
Example 30
Project: trydjango18   Author: wei0104   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 31
Project: evaluation-toolkit   Author: lightfield-analysis   File: submission_evaluation.py    (license) View Source Project 6 votes vote down vote up
def save_visualization(algo_result, metric_vis, metric, scene, tgt_dir):
    fig = init_figure()

    # algorithm result as background
    plt.imshow(algo_result, **settings.disp_map_args(scene, cmap="gray"))

    # metric visualization on top
    if scene.hidden_gt() and metric.pixelize_results() and settings.PIXELIZE:
        metric_vis = plotting.pixelize(metric_vis, noise_factor=0.05)
    cm = plt.imshow(metric_vis, **settings.metric_args(metric))
    add_colorbar(cm, metric.colorbar_bins)

    # save fig
    relative_fname = get_relative_path(scene, metric.get_id())
    fpath = op.normpath(op.join(tgt_dir, relative_fname))
    plotting.save_tight_figure(fig, fpath, hide_frames=True, pad_inches=0.01)

    return relative_fname 
Example 32
Project: splunk_ta_ps4_f1_2016   Author: jonathanvarley   File: util.py    (license) View Source Project 6 votes vote down vote up
def get_appname_from_path(absolute_path):
    absolute_path = op.normpath(absolute_path)
    parts = absolute_path.split(os.path.sep)
    parts.reverse()
    for key in ("apps", "slave-apps", "master-apps"):
        try:
            idx = parts.index(key)
        except ValueError:
            continue
        else:
            try:
                if parts[idx + 1] == "etc":
                    return parts[idx - 1]
            except IndexError:
                pass
            continue
    #return None
    return "-" 
Example 33
Project: ims   Author: ims-team   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 34
Project: lifesoundtrack   Author: MTG   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 35
Project: EasyClangComplete   Author: niosus   File: utils.py    (license) View Source Project 6 votes vote down vote up
def dir_from_output(output):
        """Get library directory based on the output of clang.

        Args:
            output (str): raw output from clang

        Returns:
            str: path to folder with libclang
        """
        log.debug("real output: %s", output)
        if platform.system() == "Darwin":
            # [HACK] uh... I'm not sure why it happens like this...
            folder_to_search = path.join(output, '..', '..')
            log.debug("folder to search: %s", folder_to_search)
            return folder_to_search
        elif platform.system() == "Windows":
            log.debug("architecture: %s", platform.architecture())
            return path.normpath(output)
        elif platform.system() == "Linux":
            return path.normpath(path.dirname(output))
        return None 
Example 36
Project: EasyClangComplete   Author: niosus   File: test_compilation_db.py    (license) View Source Project 6 votes vote down vote up
def test_persistence(self):
        """Test if compilation db is persistent."""
        include_prefixes = ['-I']
        db = CompilationDb(include_prefixes)

        expected_lib = [Flag('-Dlib_EXPORTS'), Flag('-fPIC')]
        expected_main = [Flag('-I' + path.normpath('/lib_include_dir'))]
        lib_file_path = path.normpath('/home/user/dummy_lib.cpp')
        main_file_path = path.normpath('/home/user/dummy_main.cpp')
        path_to_db = path.join(path.dirname(__file__),
                               'compilation_db_files',
                               'command')
        scope = SearchScope(from_folder=path_to_db)
        self.assertEqual(expected_lib, db.get_flags(lib_file_path, scope))
        self.assertEqual(expected_main, db.get_flags(main_file_path, scope))
        # check persistence
        self.assertGreater(len(db._cache), 2)
        self.assertEqual(path.join(path_to_db, "compile_commands.json"),
                         db._cache[main_file_path])
        self.assertEqual(path.join(path_to_db, "compile_commands.json"),
                         db._cache[lib_file_path]) 
Example 37
Project: EasyClangComplete   Author: niosus   File: test_compilation_db.py    (license) View Source Project 6 votes vote down vote up
def test_get_c_flags(self):
        """Test argument filtering for c language."""
        include_prefixes = ['-I']
        db = CompilationDb(include_prefixes)

        main_file_path = path.normpath('/home/blah.c')
        # also try to test a header
        path_to_db = path.join(path.dirname(__file__),
                               'compilation_db_files',
                               'command_c')
        scope = SearchScope(from_folder=path_to_db)
        flags = db.get_flags(main_file_path, scope)
        self.assertNotIn(Flag('-c'), flags)
        self.assertNotIn(Flag('-o'), flags)
        self.assertIn(Flag('-Wno-poison-system-directories'), flags)
        self.assertIn(Flag('-march=armv7-a'), flags) 
Example 38
Project: TA-SyncKVStore   Author: georgestarcher   File: util.py    (license) View Source Project 6 votes vote down vote up
def get_appname_from_path(absolute_path):
    absolute_path = op.normpath(absolute_path)
    parts = absolute_path.split(os.path.sep)
    parts.reverse()
    for key in ("apps", "slave-apps", "master-apps"):
        try:
            idx = parts.index(key)
        except ValueError:
            continue
        else:
            try:
                if parts[idx + 1] == "etc":
                    return parts[idx - 1]
            except IndexError:
                pass
            continue
    #return None
    return "-" 
Example 39
Project: PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda   Author: SignalMedia   File: senna.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, senna_path, operations, encoding='utf-8'):
        self._encoding = encoding
        self._path = path.normpath(senna_path) + sep 
        
        # Verifies the existence of the executable on the self._path first    
        #senna_binary_file_1 = self.executable(self._path)
        exe_file_1 = self.executable(self._path)
        if not path.isfile(exe_file_1):
            # Check for the system environment 
            if 'SENNA' in environ:
                #self._path = path.join(environ['SENNA'],'')  
                self._path = path.normpath(environ['SENNA']) + sep 
                exe_file_2 = self.executable(self._path)
                if not path.isfile(exe_file_2):
                    raise OSError("Senna executable expected at %s or %s but not found" % (exe_file_1,exe_file_2))
        
        self.operations = operations 
Example 40
Project: cb-defense-splunk-app   Author: carbonblack   File: util.py    (license) View Source Project 6 votes vote down vote up
def get_appname_from_path(absolute_path):
    absolute_path = op.normpath(absolute_path)
    parts = absolute_path.split(os.path.sep)
    parts.reverse()
    for key in ("apps", "slave-apps", "master-apps"):
        try:
            idx = parts.index(key)
        except ValueError:
            continue
        else:
            try:
                if parts[idx + 1] == "etc":
                    return parts[idx - 1]
            except IndexError:
                pass
            continue
    #return None
    return "-" 
Example 41
Project: django-open-lecture   Author: DmLitov4   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 42
Project: sublimeTextConfig   Author: luoye-fe   File: node_linter.py    (license) View Source Project 6 votes vote down vote up
def rev_parse_manifest_path(self, cwd):
        """
        Search parent directories for package.json.

        Starting at the current working directory. Go up one directory
        at a time checking if that directory contains a package.json
        file. If it does, return that directory.

        """

        name = 'package.json'
        manifest_path = path.normpath(path.join(cwd, name))

        bin_path = path.join(cwd, 'node_modules/.bin/')

        if path.isfile(manifest_path) and path.isdir(bin_path):
            return manifest_path

        parent = path.normpath(path.join(cwd, '../'))

        if parent == '/' or parent == cwd:
            return None

        return self.rev_parse_manifest_path(parent) 
Example 43
Project: sublimeTextConfig   Author: luoye-fe   File: node_linter.py    (license) View Source Project 6 votes vote down vote up
def find_local_cmd_path(self, cmd):
        """
        Find a local binary in node_modules/.bin.

        Given package.json filepath and a local binary to find,
        look in node_modules/.bin for that binary.

        """

        cwd = path.dirname(self.manifest_path)

        binary = self.get_pkg_bin_cmd(cmd)

        if binary:
            return path.normpath(path.join(cwd, binary))

        return self.find_ancestor_cmd_path(cmd, cwd) 
Example 44
Project: sublimeTextConfig   Author: luoye-fe   File: node_linter.py    (license) View Source Project 6 votes vote down vote up
def find_ancestor_cmd_path(self, cmd, cwd):
        """Recursively check for command binary in ancestors' node_modules/.bin directories."""

        node_modules_bin = path.normpath(path.join(cwd, 'node_modules/.bin/'))

        binary = path.join(node_modules_bin, cmd)

        if sublime.platform() == 'windows' and path.splitext(binary)[1] != '.cmd':
            binary += '.cmd'

        if binary and access(binary, X_OK):
            return binary

        parent = path.normpath(path.join(cwd, '../'))

        if parent == '/' or parent == cwd:
            return None

        return self.find_ancestor_cmd_path(cmd, parent) 
Example 45
Project: sublimeTextConfig   Author: luoye-fe   File: st_color_scheme_matcher.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.color_scheme = path.normpath(scheme_file)
        self.scheme_file = path.basename(self.color_scheme)
        self.plist_file = color_filter(
            readPlistFromBytes(
                re.sub(
                    br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'',
                    sublime.load_binary_resource(sublime_format_path(self.color_scheme))
                )
            )
        )
        self.scheme_file = scheme_file
        self.matched = {}

        self.parse_scheme() 
Example 46
Project: travlr   Author: gauravkulkarni96   File: templates.py    (license) View Source Project 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 47
Project: ansible-container   Author: ansible   File: config.py    (license) View Source Project 6 votes vote down vote up
def _update_service_config(self, env, service_config):
        if isinstance(service_config, dict):
            dev_overrides = service_config.pop('dev_overrides', {})
            if env == 'dev':
                service_config.update(dev_overrides)
        if 'volumes' in service_config:
            # Expand ~, ${HOME}, ${PWD}, etc. found in the volume src path
            updated_volumes = []
            for volume in service_config['volumes']:
                vol_pieces = volume.split(':')
                vol_pieces[0] = path.normpath(path.expandvars(path.expanduser(vol_pieces[0])))
                updated_volumes.append(':'.join(vol_pieces))
            service_config['volumes'] = updated_volumes

        for engine_name in self.remove_engines:
            if engine_name in service_config:
                del service_config[engine_name] 
Example 48
Project: neighborhood_mood_aws   Author: jarrellmark   File: senna.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, senna_path, operations, encoding='utf-8'):
        self._encoding = encoding
        self._path = path.normpath(senna_path) + sep 
        
        # Verifies the existence of the executable on the self._path first    
        #senna_binary_file_1 = self.executable(self._path)
        exe_file_1 = self.executable(self._path)
        if not path.isfile(exe_file_1):
            # Check for the system environment 
            if 'SENNA' in environ:
                #self._path = path.join(environ['SENNA'],'')  
                self._path = path.normpath(environ['SENNA']) + sep 
                exe_file_2 = self.executable(self._path)
                if not path.isfile(exe_file_2):
                    raise OSError("Senna executable expected at %s or %s but not found" % (exe_file_1,exe_file_2))
        
        self.operations = operations 
Example 49
Project: Chromium_DepotTools   Author: p07r0457   File: pytest.py    (license) View Source Project 6 votes vote down vote up
def project_root(parser, projdir=os.getcwd()):
    """try to find project's root and add it to sys.path"""
    previousdir = curdir = osp.abspath(projdir)
    testercls = PyTester
    conf_file_path = osp.join(curdir, CONF_FILE)
    if osp.isfile(conf_file_path):
        testercls = load_pytest_conf(conf_file_path, parser)
    while this_is_a_testdir(curdir) or \
              osp.isfile(osp.join(curdir, '__init__.py')):
        newdir = osp.normpath(osp.join(curdir, os.pardir))
        if newdir == curdir:
            break
        previousdir = curdir
        curdir = newdir
        conf_file_path = osp.join(curdir, CONF_FILE)
        if osp.isfile(conf_file_path):
            testercls = load_pytest_conf(conf_file_path, parser)
    return previousdir, testercls 
Example 50
Project: Chromium_DepotTools   Author: p07r0457   File: pytest.py    (license) View Source Project 6 votes vote down vote up
def load_django_settings(self, dirname):
        """try to find project's setting and load it"""
        curdir = osp.abspath(dirname)
        previousdir = curdir
        while not osp.isfile(osp.join(curdir, 'settings.py')) and \
                  osp.isfile(osp.join(curdir, '__init__.py')):
            newdir = osp.normpath(osp.join(curdir, os.pardir))
            if newdir == curdir:
                raise AssertionError('could not find settings.py')
            previousdir = curdir
            curdir = newdir
        # late django initialization
        settings = load_module_from_modpath(modpath_from_file(osp.join(curdir, 'settings.py')))
        from django.core.management import setup_environ
        setup_environ(settings)
        settings.DEBUG = False
        self.settings = settings
        # add settings dir to pythonpath since it's the project's root
        if curdir not in sys.path:
            sys.path.insert(1, curdir)