Python os.path.abspath() Examples

The following are code examples for showing how to use os.path.abspath(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: hydrus   Author: HTTP-APIs   File: test_pep8.py    MIT License 6 votes vote down vote up
def test_pep8(self):
        """Test method to check PEP8 compliance over the entire project."""
        self.file_structure = dirname(dirname(abspath(__file__)))
        print("Testing for PEP8 compliance of python files in {}".format(
            self.file_structure))
        style = pep8.StyleGuide()
        style.options.max_line_length = 100  # Set this to desired maximum line length
        filenames = []
        # Set this to desired folder location
        for root, _, files in os.walk(self.file_structure):
            python_files = [f for f in files if f.endswith(
                '.py') and "examples" not in root]
            for file in python_files:
                if len(root.split('samples')) != 2:     # Ignore samples directory
                    filename = '{0}/{1}'.format(root, file)
                    filenames.append(filename)
        check = style.check_files(filenames)
        self.assertEqual(check.total_errors, 0, 'PEP8 style errors: %d' %
                         check.total_errors) 
Example 2
Project: FCOS_GluonCV   Author: DetectionTeamUCAS   File: coco_instance.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, dataset, save_prefix, use_time=True, cleanup=False, score_thresh=1e-3):
        super(COCOInstanceMetric, self).__init__('COCOInstance')
        self.dataset = dataset
        self._img_ids = sorted(dataset.coco.getImgIds())
        self._current_id = 0
        self._cleanup = cleanup
        self._results = []
        self._score_thresh = score_thresh

        try_import_pycocotools()
        import pycocotools.mask as cocomask
        self._cocomask = cocomask

        if use_time:
            import datetime
            t = datetime.datetime.now().strftime('_%Y_%m_%d_%H_%M_%S')
        else:
            t = ''
        self._filename = osp.abspath(osp.expanduser(save_prefix) + t + '.json')
        try:
            f = open(self._filename, 'w')
        except IOError as e:
            raise RuntimeError("Unable to open json file to dump. What(): {}".format(str(e)))
        else:
            f.close() 
Example 3
Project: CodeDog   Author: BruceDLong   File: libraryMngr.py    GNU General Public License v2.0 6 votes vote down vote up
def replaceFileName(fileMatch):
    global currentFilesPath
    fileName = fileMatch.group(1)
    currentWD = os.getcwd()
    pathName = abspath(currentWD) +"/"+fileName
    if not os.path.isfile(pathName):
        dirname, filename = os.path.split(abspath(getsourcefile(lambda:0)))
        pathName = dirname +"/"+fileName
        if not os.path.isfile(pathName):
            pathName = currentFilesPath +"/"+fileName
            if not os.path.isfile(pathName):
                cdErr("Cannot find include file '"+fileName+"'")

    includedStr = progSpec.stringFromFile(pathName)
    includedStr = processIncludedFiles(includedStr, pathName)
    return includedStr 
Example 4
Project: praktipy   Author: The-Ludwig   File: praktiplot.py    MIT License 6 votes vote down vote up
def pretty():  
    try:
        locale.setlocale(locale.LC_ALL, locale_strings[platform.system()])
    except locale.Error:
        print("Could not set the language settings! 3.5 will not be written as 3,5! SO SAD!")

    matplotlib.rcParams.update({
        'font.family': 'serif',
        'text.usetex': True,
        'pgf.rcfonts': False,
        'pgf.texsystem': 'lualatex',
        'pgf.preamble': r'\input{'+dirname(abspath(__file__)).replace(" ", r"\ ")+r'//matplotlib_header.tex'+r'}',
        'axes.formatter.use_locale' : True,
    })

# Currently not working
# if platform.system() == "Windows":
#     plt.style.use('file:\\' + os.path.dirname(os.path.abspath(__file__)) + os.sep + 'praktipy.mplstyle')
# else:
#     plt.style.use('file://' + os.path.dirname(os.path.abspath(__file__)) + os.sep + 'praktipy.mplstyle')

# print('file://' + os.path.dirname(os.path.abspath(__file__)) + os.sep + 'praktipy.mplstyle')
# convenience functions 
Example 5
Project: openhatch   Author: campbe13   File: patch.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_file_idx(self, filename, source=None):
    """ Detect index of given filename within patch.

        :param filename:
        :param source: search filename among sources (True),
                       targets (False), or both (None)
        :returns: int or None
    """
    filename = abspath(filename)
    if source == True or source == None:
      for i,fnm in enumerate(self.source):
        if filename == abspath(fnm):
          return i  
    if source == False or source == None:
      for i,fnm in enumerate(self.target):
        if filename == abspath(fnm):
          return i 
Example 6
Project: openhatch   Author: campbe13   File: test_commands.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def test_runspider(self):
        tmpdir = self.mktemp()
        os.mkdir(tmpdir)
        fname = abspath(join(tmpdir, 'myspider.py'))
        with open(fname, 'w') as f:
            f.write("""
from scrapy import log
from scrapy.spider import BaseSpider

class MySpider(BaseSpider):
    name = 'myspider'

    def start_requests(self):
        self.log("It Works!")
        return []
""")
        p = self.proc('runspider', fname)
        log = p.stderr.read()
        self.assert_("[myspider] DEBUG: It Works!" in log)
        self.assert_("[myspider] INFO: Spider opened" in log)
        self.assert_("[myspider] INFO: Closing spider (finished)" in log)
        self.assert_("[myspider] INFO: Spider closed (finished)" in log) 
Example 7
Project: Repobot   Author: Desgard   File: test_path.py    MIT License 6 votes vote down vote up
def test_get_home_dir_8():
    """Using registry hack for 'My Documents', os=='nt'

    HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
    """
    os.name = 'nt'
    # Remove from stub environment all keys that may be set
    for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
        env.pop(key, None)

    class key:
        def Close(self):
            pass

    with patch.object(wreg, 'OpenKey', return_value=key()), \
         patch.object(wreg, 'QueryValueEx', return_value=[abspath(HOME_TEST_DIR)]):
        home_dir = path.get_home_dir()
    nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) 
Example 8
Project: ConvLab   Author: ConvLab   File: mdbt.py    MIT License 6 votes vote down vote up
def cached_path(file_path, cached_dir=None):
    if not cached_dir:
        cached_dir = str(Path(Path.home() / '.tatk') / "cache")

    return allennlp_cached_path(file_path, cached_dir)

# DATA_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))), 'data/mdbt')
# VALIDATION_URL = os.path.join(DATA_PATH, "data/validate.json")
# WORD_VECTORS_URL = os.path.join(DATA_PATH, "word-vectors/paragram_300_sl999.txt")
# TRAINING_URL = os.path.join(DATA_PATH, "data/train.json")
# ONTOLOGY_URL = os.path.join(DATA_PATH, "data/ontology.json")
# TESTING_URL = os.path.join(DATA_PATH, "data/test.json")
# MODEL_URL = os.path.join(DATA_PATH, "models/model-1")
# GRAPH_URL = os.path.join(DATA_PATH, "graphs/graph-1")
# RESULTS_URL = os.path.join(DATA_PATH, "results/log-1.txt")
# KB_URL = os.path.join(DATA_PATH, "data/")  # TODO: yaoqin
# TRAIN_MODEL_URL = os.path.join(DATA_PATH, "train_models/model-1")
# TRAIN_GRAPH_URL = os.path.join(DATA_PATH, "train_graph/graph-1") 
Example 9
Project: godot-mono-builds   Author: godotengine   File: options.py    MIT License 5 votes vote down vote up
def base_opts_from_args(args):
    from os.path import abspath
    return BaseOpts(
        verbose_make = args.verbose_make,
        configure_dir = abspath(args.configure_dir),
        install_dir = abspath(args.install_dir),
        mono_source_root = abspath(args.mono_sources),
        mxe_prefix = args.mxe_prefix
    ) 
Example 10
Project: godot-mono-builds   Author: godotengine   File: options.py    MIT License 5 votes vote down vote up
def android_opts_from_args(args):
    return AndroidOpts(
        **vars(runtime_opts_from_args(args)),
        android_toolchains_prefix = abspath(args.toolchains_prefix),
        android_sdk_root = abspath(args.android_sdk),
        android_ndk_root = abspath(args.android_ndk),
        with_monodroid = args.with_monodroid,
        android_api_version = args.android_api_version,
        android_cmake_version = args.android_cmake_version
    ) 
Example 11
Project: pyblish-win   Author: pyblish   File: test_email_torture.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def openfile(filename):
    from os.path import join, dirname, abspath
    path = abspath(join(dirname(testfile), os.pardir, 'moredata', filename))
    return open(path, 'r')

# Prevent this test from running in the Python distro 
Example 12
Project: pyblish-win   Author: pyblish   File: shutil.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _samefile(src, dst):
    # Macintosh, Unix.
    if hasattr(os.path, 'samefile'):
        try:
            return os.path.samefile(src, dst)
        except OSError:
            return False

    # All other platforms: check for same pathname.
    return (os.path.normcase(os.path.abspath(src)) ==
            os.path.normcase(os.path.abspath(dst))) 
Example 13
Project: pyblish-win   Author: pyblish   File: shutil.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _destinsrc(src, dst):
    src = abspath(src)
    dst = abspath(dst)
    if not src.endswith(os.path.sep):
        src += os.path.sep
    if not dst.endswith(os.path.sep):
        dst += os.path.sep
    return dst.startswith(src) 
Example 14
Project: Collaborative-Learning-for-Weakly-Supervised-Object-Detection   Author: Sunarker   File: config.py    MIT License 5 votes vote down vote up
def get_output_dir(imdb, weights_filename):
  """Return the directory where experimental artifacts are placed.
  If the directory does not exist, it is created.

  A canonical path is built using the name from an imdb and a network
  (if not None).
  """
  outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name))
  if weights_filename is None:
    weights_filename = 'default'
  outdir = osp.join(outdir, weights_filename)
  if not os.path.exists(outdir):
    os.makedirs(outdir)
  return outdir 
Example 15
Project: Collaborative-Learning-for-Weakly-Supervised-Object-Detection   Author: Sunarker   File: config.py    MIT License 5 votes vote down vote up
def get_output_tb_dir(imdb, weights_filename):
  """Return the directory where tensorflow summaries are placed.
  If the directory does not exist, it is created.

  A canonical path is built using the name from an imdb and a network
  (if not None).
  """
  outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'tensorboard', __C.EXP_DIR, imdb.name))
  if weights_filename is None:
    weights_filename = 'default'
  outdir = osp.join(outdir, weights_filename)
  if not os.path.exists(outdir):
    os.makedirs(outdir)
  return outdir 
Example 16
Project: Collaborative-Learning-for-Weakly-Supervised-Object-Detection   Author: Sunarker   File: imdb.py    MIT License 5 votes vote down vote up
def cache_path(self):
    cache_path = osp.abspath(osp.join(cfg.DATA_DIR, 'cache'))
    if not os.path.exists(cache_path):
      os.makedirs(cache_path)
    return cache_path 
Example 17
Project: FasterRCNN_TF_Py3   Author: upojzsb   File: config.py    MIT License 5 votes vote down vote up
def get_output_dir(imdb, weights_filename):
    """Return the directory where experimental artifacts are placed.
    If the directory does not exist, it is created.

    A canonical path is built using the name from an imdb and a network
    (if not None).
    """
    outdir = osp.abspath(osp.join(FLAGS2["root_dir"], FLAGS2["root_dir"] , 'default', imdb.name))
    if weights_filename is None:
        weights_filename = 'default'
    outdir = osp.join(outdir, weights_filename)
    if not os.path.exists(outdir):
        os.makedirs(outdir)
    return outdir 
Example 18
Project: FasterRCNN_TF_Py3   Author: upojzsb   File: imdb.py    MIT License 5 votes vote down vote up
def cache_path(self):
        cache_path = osp.abspath(osp.join(cfg.FLAGS2["data_dir"], 'cache'))
        if not os.path.exists(cache_path):
            os.makedirs(cache_path)
        return cache_path 
Example 19
Project: reroils-data-legacy   Author: rero   File: test_examples_app.py    GNU General Public License v2.0 5 votes vote down vote up
def example_app():
    """Example app fixture."""
    current_dir = os.getcwd()

    # Go to example directory
    project_dir = dirname(dirname(abspath(__file__)))
    exampleapp_dir = join(project_dir, 'examples')
    os.chdir(exampleapp_dir)

    # Setup application
    assert subprocess.call('./app-setup.sh', shell=True) == 0

    # Setup fixtures
    assert subprocess.call('./app-fixtures.sh', shell=True) == 0

    # Start example app
    webapp = subprocess.Popen(
        'FLASK_APP=app.py flask run --debugger -p 5001',
        stdout=subprocess.PIPE, preexec_fn=os.setsid, shell=True)
    time.sleep(10)
    yield webapp

    # Stop server
    os.killpg(webapp.pid, signal.SIGTERM)

    # Tear down example app
    subprocess.call('./app-teardown.sh', shell=True)

    # Return to the original directory
    os.chdir(current_dir)


# def test_example_app_role_admin(example_app):
#     """Test example app."""
#     cmd = 'curl http://0.0.0.0:5001/'
#     output = subprocess.check_output(cmd, shell=True)
#     assert b'Welcome to REROILS-DATA' in output 
Example 20
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: shutil.py    MIT License 5 votes vote down vote up
def _samefile(src, dst):
    # Macintosh, Unix.
    if hasattr(os.path, 'samefile'):
        try:
            return os.path.samefile(src, dst)
        except OSError:
            return False

    # All other platforms: check for same pathname.
    return (os.path.normcase(os.path.abspath(src)) ==
            os.path.normcase(os.path.abspath(dst))) 
Example 21
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: shutil.py    MIT License 5 votes vote down vote up
def _destinsrc(src, dst):
    src = abspath(src)
    dst = abspath(dst)
    if not src.endswith(os.path.sep):
        src += os.path.sep
    if not dst.endswith(os.path.sep):
        dst += os.path.sep
    return dst.startswith(src) 
Example 22
Project: NiBetaSeries   Author: HBClab   File: create_long_description.py    MIT License 5 votes vote down vote up
def read(*names, **kwargs):
    return io.open(
        join(abspath(*names)),
        encoding=kwargs.get('encoding', 'utf8')
    ).read() 
Example 23
Project: flasky   Author: RoseOu   File: shutil.py    MIT License 5 votes vote down vote up
def _samefile(src, dst):
    # Macintosh, Unix.
    if hasattr(os.path, 'samefile'):
        try:
            return os.path.samefile(src, dst)
        except OSError:
            return False

    # All other platforms: check for same pathname.
    return (os.path.normcase(os.path.abspath(src)) ==
            os.path.normcase(os.path.abspath(dst))) 
Example 24
Project: flasky   Author: RoseOu   File: shutil.py    MIT License 5 votes vote down vote up
def _destinsrc(src, dst):
    src = abspath(src)
    dst = abspath(dst)
    if not src.endswith(os.path.sep):
        src += os.path.sep
    if not dst.endswith(os.path.sep):
        dst += os.path.sep
    return dst.startswith(src) 
Example 25
Project: FCOS_GluonCV   Author: DetectionTeamUCAS   File: coco_keypoints.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, dataset, save_prefix, use_time=True, cleanup=False, in_vis_thresh=0.2,
                 data_shape=None):
        super(COCOKeyPointsMetric, self).__init__('COCOMeanAP')
        self.dataset = dataset
        self._img_ids = sorted(dataset.coco.getImgIds())
        self._current_id = 0
        self._cleanup = cleanup
        self._results = []
        self._in_vis_thresh = in_vis_thresh
        if isinstance(data_shape, (tuple, list)):
            assert len(data_shape) == 2, "Data shape must be (height, width)"
        elif not data_shape:
            data_shape = None
        else:
            raise ValueError("data_shape must be None or tuple of int as (height, width)")
        self._data_shape = data_shape

        if use_time:
            import datetime
            t = datetime.datetime.now().strftime('_%Y_%m_%d_%H_%M_%S')
        else:
            t = ''
        self._filename = osp.abspath(osp.expanduser(save_prefix) + t + '.json')
        try:
            f = open(self._filename, 'w')
        except IOError as e:
            raise RuntimeError("Unable to open json file to dump. What(): {}".format(str(e)))
        else:
            f.close() 
Example 26
Project: FCOS_GluonCV   Author: DetectionTeamUCAS   File: coco_detection.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, dataset, save_prefix, use_time=True, cleanup=False, score_thresh=0.05,
                 data_shape=None):
        super(COCODetectionMetric, self).__init__('COCOMeanAP')
        self.dataset = dataset
        self._img_ids = sorted(dataset.coco.getImgIds())
        self._current_id = 0
        self._cleanup = cleanup
        self._results = []
        self._score_thresh = score_thresh
        if isinstance(data_shape, (tuple, list)):
            assert len(data_shape) == 2, "Data shape must be (height, width)"
        elif not data_shape:
            data_shape = None
        else:
            raise ValueError("data_shape must be None or tuple of int as (height, width)")
        self._data_shape = data_shape

        if use_time:
            import datetime
            t = datetime.datetime.now().strftime('_%Y_%m_%d_%H_%M_%S')
        else:
            t = ''
        self._filename = osp.abspath(osp.expanduser(save_prefix) + t + '.json')
        try:
            f = open(self._filename, 'w')
        except IOError as e:
            raise RuntimeError("Unable to open json file to dump. What(): {}".format(str(e)))
        else:
            f.close() 
Example 27
Project: CodeDog   Author: BruceDLong   File: libraryMngr.py    GNU General Public License v2.0 5 votes vote down vote up
def processIncludedFiles(fileString, fileName):
    global currentFilesPath
    dirname, filename = os.path.split(abspath(fileName))
    currentFilesPath = dirname
    pattern = re.compile(r'#include +([\w -\.\/\\]+)')
    return pattern.sub(replaceFileName, fileString) 
Example 28
Project: sic   Author: Yanixos   File: shutil.py    GNU General Public License v3.0 5 votes vote down vote up
def _samefile(src, dst):
    # Macintosh, Unix.
    if hasattr(os.path, 'samefile'):
        try:
            return os.path.samefile(src, dst)
        except OSError:
            return False

    # All other platforms: check for same pathname.
    return (os.path.normcase(os.path.abspath(src)) ==
            os.path.normcase(os.path.abspath(dst))) 
Example 29
Project: sic   Author: Yanixos   File: shutil.py    GNU General Public License v3.0 5 votes vote down vote up
def _destinsrc(src, dst):
    src = abspath(src)
    dst = abspath(dst)
    if not src.endswith(os.path.sep):
        src += os.path.sep
    if not dst.endswith(os.path.sep):
        dst += os.path.sep
    return dst.startswith(src) 
Example 30
Project: Manga-colorization---cycle-gan   Author: OValery16   File: get_data.py    Mozilla Public License 2.0 5 votes vote down vote up
def get(self, save_path, dataset=None):
        """

        Download a dataset.

        Args:
            save_path : str
                A directory to save the data to.
            dataset : str, optional
                A specific dataset to download.
                Note: this must include the file extension.
                If None, options will be presented for you
                to choose from.

        Returns:
            save_path_full : str
                The absolute path to the downloaded data.

        """
        if dataset is None:
            selected_dataset = self._present_options()
        else:
            selected_dataset = dataset

        save_path_full = join(save_path, selected_dataset.split('.')[0])

        if isdir(save_path_full):
            warn("\n'{0}' already exists. Voiding Download.".format(
                save_path_full))
        else:
            self._print('Downloading Data...')
            url = "{0}/{1}".format(self.url, selected_dataset)
            self._download_data(url, save_path=save_path)

        return abspath(save_path_full) 
Example 31
Project: AshsSDK   Author: thehappydinoa   File: shutil.py    MIT License 5 votes vote down vote up
def _samefile(src, dst):
    # Macintosh, Unix.
    if hasattr(os.path, 'samefile'):
        try:
            return os.path.samefile(src, dst)
        except OSError:
            return False

    # All other platforms: check for same pathname.
    return (os.path.normcase(os.path.abspath(src)) ==
            os.path.normcase(os.path.abspath(dst))) 
Example 32
Project: AshsSDK   Author: thehappydinoa   File: shutil.py    MIT License 5 votes vote down vote up
def _destinsrc(src, dst):
    src = abspath(src)
    dst = abspath(dst)
    if not src.endswith(os.path.sep):
        src += os.path.sep
    if not dst.endswith(os.path.sep):
        dst += os.path.sep
    return dst.startswith(src) 
Example 33
Project: reportengine   Author: NNPDF   File: report.py    GNU General Public License v2.0 5 votes vote down vote up
def parse_template(self, template:str, config_rel_path, output_path=None):
        """Filename specifying a template for a report."""

        import reportengine.templates


        finder = filefinder.FallbackFinder([
                     '.',
                     config_rel_path,
                     filefinder.ModuleFinder(reportengine.templates),
                 ])

        try:
            folder, name = finder.find(template)
        #Ridiculous error message
        except FileNotFoundError as e:
            raise configparser.ConfigError("Could not find template '%s': %s" %
                                           (template, e), template,
                                           finder.hint_files()) from e



        abspath = folder / name
        if not abspath.is_file():
            raise Config("The template (%s) must refer to a file." % template)
        if output_path:
            destpath = output_path / 'input' / name
            parpath = destpath.parent
            parpath.mkdir(exist_ok=True, parents=True)
            try:
                shutil.copy2(abspath, destpath)
            except shutil.SameFileError:
                pass

        return abspath 
Example 34
Project: find_forks   Author: frost-nzcr4   File: run.py    MIT License 5 votes vote down vote up
def main():
    """Main function to run as shell script."""
    loader = unittest.TestLoader()
    suite = loader.discover(path.abspath(path.dirname(__file__)), pattern='test_*.py')
    runner = unittest.TextTestRunner(buffer=True)
    runner.run(suite) 
Example 35
Project: praktipy   Author: The-Ludwig   File: praktiplot.py    MIT License 5 votes vote down vote up
def fast():
    matplotlib.rcParams.update({
        'font.family': 'serif',
        'text.usetex': True,
        'pgf.rcfonts': False,
        'pgf.texsystem': 'pdflatex',
        'pgf.preamble': r'\input{'+dirname(abspath(__file__)).replace(" ", r"\ ")+r'//matplotlib_header_minimal.tex'+r'}'
    }) 
Example 36
Project: cascade-rcnn_Pytorch   Author: guoruoqian   File: config.py    MIT License 5 votes vote down vote up
def get_output_dir(imdb, weights_filename):
  """Return the directory where experimental artifacts are placed.
  If the directory does not exist, it is created.

  A canonical path is built using the name from an imdb and a network
  (if not None).
  """
  outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name))
  if weights_filename is None:
    weights_filename = 'default'
  outdir = osp.join(outdir, weights_filename)
  if not os.path.exists(outdir):
    os.makedirs(outdir)
  return outdir 
Example 37
Project: cascade-rcnn_Pytorch   Author: guoruoqian   File: config.py    MIT License 5 votes vote down vote up
def get_output_tb_dir(imdb, weights_filename):
  """Return the directory where tensorflow summaries are placed.
  If the directory does not exist, it is created.

  A canonical path is built using the name from an imdb and a network
  (if not None).
  """
  outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'tensorboard', __C.EXP_DIR, imdb.name))
  if weights_filename is None:
    weights_filename = 'default'
  outdir = osp.join(outdir, weights_filename)
  if not os.path.exists(outdir):
    os.makedirs(outdir)
  return outdir 
Example 38
Project: cascade-rcnn_Pytorch   Author: guoruoqian   File: imdb.py    MIT License 5 votes vote down vote up
def cache_path(self):
    cache_path = osp.abspath(osp.join(cfg.DATA_DIR, 'cache'))
    if not os.path.exists(cache_path):
      os.makedirs(cache_path)
    return cache_path 
Example 39
Project: tri.form   Author: TriOptima   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def style(request):
    return HttpResponse(open(join(dirname(dirname(dirname(abspath(__file__)))), 'form.css')).read()) 
Example 40
Project: rowgenerators   Author: Metatab   File: zip.py    MIT License 5 votes vote down vote up
def zip_dir(self):
        """Directory that files will be extracted to"""

        from os.path import abspath

        cache_dir = self.downloader.cache.getsyspath('/')
        target_path = abspath(self.fspath)

        if target_path.startswith(cache_dir):  # Case when file is already in cache
            return str(self.fspath) + '_d'
        else:  # file is not in cache; it may exist elsewhere.
            return self.downloader.cache.getsyspath(target_path.lstrip('/'))+'_d' 
Example 41
Project: mx   Author: graalvm   File: select_jdk.py    GNU General Public License v2.0 5 votes vote down vote up
def get_suite_env_file(suite_dir=None):
    for n in os.listdir(suite_dir or '.'):
        if n.startswith('mx.'):
            suite_py = join('.', n, 'suite.py')
            if exists(suite_py):
                return abspath(join(suite_dir or '.', n, 'env'))
    return None 
Example 42
Project: openhatch   Author: campbe13   File: patch.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _match_file_hunks(self, filepath, hunks):
    matched = True
    fp = open(abspath(filepath))

    class NoMatch(Exception):
      pass

    lineno = 1
    line = fp.readline()
    hno = None
    try:
      for hno, h in enumerate(hunks):
        # skip to first line of the hunk
        while lineno < h.starttgt:
          if not len(line): # eof
            debug("check failed - premature eof before hunk: %d" % (hno+1))
            raise NoMatch
          line = fp.readline()
          lineno += 1
        for hline in h.text:
          if hline.startswith("+"):
            continue
          if not len(line):
            debug("check failed - premature eof on hunk: %d" % (hno+1))
            # todo: \ No newline at the end of file
            raise NoMatch
          if line.rstrip("\r\n") != hline[1:].rstrip("\r\n"):
            debug("file is not patched - failed hunk: %d" % (hno+1))
            raise NoMatch
          line = fp.readline()
          lineno += 1

    except NoMatch:
      matched = False
      # todo: display failed hunk, i.e. expected/found

    fp.close()
    return matched 
Example 43
Project: openhatch   Author: campbe13   File: genspider.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _genspider(self, module, name, domain, template_name, template_file):
        """Generate the spider module, based on the given template"""
        tvars = {
            'project_name': settings.get('BOT_NAME'),
            'ProjectName': string_camelcase(settings.get('BOT_NAME')),
            'module': module,
            'name': name,
            'domain': domain,
            'classname': '%sSpider' % ''.join([s.capitalize() \
                for s in module.split('_')])
        }
        spiders_module = __import__(settings['NEWSPIDER_MODULE'], {}, {}, [''])
        spiders_dir = abspath(dirname(spiders_module.__file__))
        spider_file = "%s.py" % join(spiders_dir, module)
        shutil.copyfile(template_file, spider_file)
        render_templatefile(spider_file, **tvars)
        print "Created spider %r using template %r in module:" % (name, \
            template_name)
        print "  %s.%s" % (spiders_module.__name__, module) 
Example 44
Project: openhatch   Author: campbe13   File: project.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def project_data_dir(project='default'):
    """Return the current project data dir, creating it if it doesn't exist"""
    if not inside_project():
        raise NotConfigured("Not inside a project")
    cfg = get_config()
    if cfg.has_option(DATADIR_CFG_SECTION, project):
        d = cfg.get(DATADIR_CFG_SECTION, project)
    else:
        scrapy_cfg = closest_scrapy_cfg()
        if not scrapy_cfg:
            raise NotConfigured("Unable to find scrapy.cfg file to infer project data dir")
        d = abspath(join(dirname(scrapy_cfg), '.scrapy'))
    if not exists(d):
        makedirs(d)
    return d 
Example 45
Project: openhatch   Author: campbe13   File: test_commands.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_runspider_unable_to_load(self):
        tmpdir = self.mktemp()
        os.mkdir(tmpdir)
        fname = abspath(join(tmpdir, 'myspider.txt'))
        with open(fname, 'w') as f:
            f.write("")
        p = self.proc('runspider', fname)
        log = p.stderr.read()
        self.assert_("Unable to load" in log) 
Example 46
Project: figures   Author: appsembler   File: test_settings.py    MIT License 5 votes vote down vote up
def root(*args):
    """
    Get the absolute path of the given path relative to the project root.
    """
    return join(abspath(dirname(__file__)), *args) 
Example 47
Project: django_linter   Author: geerk   File: test_settings.py    MIT License 5 votes vote down vote up
def setUpClass(cls):
        DATA = join(dirname(abspath(__file__)), 'settings')
        sys.path.insert(1, DATA) 
Example 48
Project: captivox   Author: expectocode   File: captivox.py    GNU General Public License v3.0 5 votes vote down vote up
def resource_path(relative_path):
    """
    Get absolute path to resource, works for dev and PyInstaller binary
    https://stackoverflow.com/questions/7674790/bundling-data-files-with-pyinstaller-onefile
    """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except AttributeError:
        base_path = path.abspath(".")

    return path.join(base_path, relative_path) 
Example 49
Project: Anamoly-Detection   Author: msmsk05   File: test_xgbod.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setUp(self):
        # Define data file and read X and y
        # Generate some data if the source data is missing
        this_directory = path.abspath(path.dirname(__file__))
        mat_file = 'pima.mat'
        try:
            mat = loadmat(path.join(*[this_directory, 'data', mat_file]))

        except TypeError:
            print('{data_file} does not exist. Use generated data'.format(
                data_file=mat_file))
            X, y = generate_data(train_only=True)  # load data
        except IOError:
            print('{data_file} does not exist. Use generated data'.format(
                data_file=mat_file))
            X, y = generate_data(train_only=True)  # load data
        else:
            X = mat['X']
            y = mat['y'].ravel()
            X, y = check_X_y(X, y)

        self.X_train, self.X_test, self.y_train, self.y_test = \
            train_test_split(X, y, test_size=0.4, random_state=42)

        self.clf = XGBOD(random_state=42)
        self.clf.fit(self.X_train, self.y_train)

        self.roc_floor = 0.8 
Example 50
Project: Volux   Author: DrTexx   File: essentials.py    GNU General Public License v3.0 5 votes vote down vote up
def get_version():

    here = path.abspath(path.dirname(__file__))

    with open(path.join(here, "version.txt"), "r") as f:
        return f.readline().splitlines()[0]