Python os.path.pardir() Examples

The following are code examples for showing how to use os.path.pardir(). 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: calmjs   Author: calmjs   File: test_toolchain.py    GNU General Public License v2.0 6 votes vote down vote up
def test_toolchain_standard_build_dir_remapped(self):
        """
        This can either be caused by relative paths or symlinks.  Will
        result in the manually specified build_dir being remapped to its
        real location
        """

        fake = mkdtemp(self)
        real = mkdtemp(self)
        real_base = basename(real)
        spec = Spec()
        spec['build_dir'] = join(fake, pardir, real_base)

        with pretty_logging(stream=StringIO()) as s:
            with self.assertRaises(NotImplementedError):
                self.toolchain(spec)

        self.assertIn("realpath of 'build_dir' resolved to", s.getvalue())
        self.assertEqual(spec['build_dir'], real) 
Example 2
Project: swift-android-buildtools   Author: readdle   File: resources.py    MIT License 6 votes vote down vote up
def get_all_files_rec(srcs):
    res = []
    for src in srcs:
        base = path.normpath(path.join(src, path.pardir))
        if path.isfile(src):
            res.append(
                {
                    "into": path.normpath(path.join(src[len(base) + 1:], path.pardir)),
                    "base": base,
                    "files": [src]
                }
            )
        else:
            for root, dirs, files in os.walk(src):
                if len(files) > 0:
                    res.append(
                        {  # TestData/Input/Resource1/file1, TestData/Input/Resource1/file2
                            "into": path.normpath(path.join(path.join(root, files[0])[len(base) + 1:], path.pardir)),
                        # Resource1
                            "base": base,  # TestData/Input/
                            "files": [path.join(root, f) for f in files]  # [file1, file2]
                        }
                    )

    return res 
Example 3
Project: Blockly-rduino-communication   Author: technologiescollege   File: config.py    GNU General Public License v3.0 6 votes vote down vote up
def get_module_data_path(modname, relpath=None, attr_name='DATAPATH'):
    """Return module *modname* data path
    Note: relpath is ignored if module has an attribute named *attr_name*

    Handles py2exe/cx_Freeze distributions"""
    datapath = getattr(sys.modules[modname], attr_name, '')
    if datapath:
        return datapath
    else:
        datapath = get_module_path(modname)
        parentdir = osp.join(datapath, osp.pardir)
        if osp.isfile(parentdir):
            # Parent directory is not a directory but the 'library.zip' file:
            # this is either a py2exe or a cx_Freeze distribution
            datapath = osp.abspath(osp.join(osp.join(parentdir, osp.pardir),
                                            modname))
        if relpath is not None:
            datapath = osp.abspath(osp.join(datapath, relpath))
        return datapath 
Example 4
Project: gaitutils   Author: jjnurminen   File: envutils.py    GNU General Public License v3.0 6 votes vote down vote up
def _git_autoupdate():
    """Hacky way to update repo to latest master, if running under git.
    Return True if update was ran, else False"""
    mod_dir = resource_filename('gaitutils', '')
    repo_dir = op.abspath(op.join(mod_dir, op.pardir))
    if op.isdir(op.join(repo_dir, '.git')):
        logger.debug('running git autoupdate')
        o = subprocess.check_output(['git', 'pull'], cwd=repo_dir)
        updated = 'pdating' in o  # XXX: fragile as hell
        if updated:
            logger.debug('autoupdate status: %s' % o)
            return True
        else:
            logger.debug('package already up to date')
            return False
    else:  # not a git repo
        logger.debug('%s is a git repo, not running autoupdate' % repo_dir)
        return False 
Example 5
Project: weibo-analysis-system   Author: Superbsco   File: tests.py    MIT License 6 votes vote down vote up
def getComment(request):
        pass
        # if request.method == "GET":
        # text = request.GET.get("commentId")
        # resp = list(Target.objects.values('uid', 'cookie', 'add_time'))
        # uid = int(resp[0]["uid"])
        # cookie = {"Cookie": resp[0]["cookie"]}
        # wb = Weibo(uid,cookie)
        # print("数据库不存在该评论,正在爬虫生成")
        # mm = wb.get_comment_info(text)


      
# Create your tests here.
# with urllib.request.urlopen("https://wx2.sinaimg.cn/large/" + '893ea4cely1g2kbqkzuzyj21hc0u0q9p', timeout=30) as response, open("893ea4cely1g2kbqkzuzyj21hc0u0q9p.jpg", 'wb') as f_save:
#     f_save.write(response.read())
#     f_save.flush()
#     f_save.close()
# print (path.dirname(path.abspath("__file__")))
# print (path.pardir)
# print (path.join(path.dirname("__file__"),path.pardir))
# print (path.abspath(path.join(path.dirname("__file__"),path.pardir)))
# print (path.abspath(path.join(os.getcwd(), "../../webview/static/"))) 
Example 6
Project: forestlayer   Author: PasaLab   File: storage_utils.py    Apache License 2.0 6 votes vote down vote up
def check_dir(path):
    """
    Check directory existence, if not, create the directory.

    :param path:
    :return:
    """
    if path is None:
        return
    d = osp.abspath(osp.join(path, osp.pardir))
    if not osp.exists(d):
        try:
            os.makedirs(d)
        except OSError as e:
            if e.errno != os.errno.EEXIST:
                raise e
            print("Attempted to create '{}', but the directory already "
                  "exists.".format(d))
        # Change the directory permissions so others can use it. This is
        # important when multiple people are using the same machine. But now we don't need it.
        # os.chmod(d, 0o0777) 
Example 7
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 8
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 9
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 10
Project: flasky   Author: RoseOu   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 11
Project: misp42splunk   Author: remg427   File: loaders.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 12
Project: TornadoWeb   Author: VxCoder   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 13
Project: Flask_Blog   Author: sugarguo   File: loaders.py    GNU General Public License v3.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 14
Project: Health-Checker   Author: KriAga   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 15
Project: OP_Manager   Author: adwuard   File: file_util.py    MIT License 5 votes vote down vote up
def fileTransferHelper(srclist, dest):
    """
    Pass in list of paths to file, and copy to root destination
    It will create patch's parent folder if not already exist in the destination folder
    For example:
        fileTransferHelper(["..../OP1_File_Organizer/NotUsed/..../patch.aif"], dest = "/..../synth")

    :param srclist: ["pwd/1.aif", "pwd/2.aif", "pwd/3.aif",....., "pwd/n.aif"]
    :param dest: Root of the synth and drum destination folder
    :return: NA
    """

    for i in srclist:
        srcParentFolderName = abspath(join(i, pardir)).split("/")[-1:][0]
        srcBaseName = basename(i)
        distParentFolderName = dest + "/" + str(srcParentFolderName)
        print(distParentFolderName)
        forcedir(distParentFolderName)
        image = Image.new('1', (128, 64))

        if workDir in srclist[0]:
            # Local to OP1
            image.paste(Image.open(workDir + "/Assets/Img/UploadPatches.png").convert("1"))
        else:
            # OP1 to Local
            image.paste(Image.open(workDir + "/Assets/Img/DownloadPatches.png").convert("1"))
        draw = ImageDraw.Draw(image)
        draw.text((20, 63), srcBaseName, font=GPIO_Init.getFont(), fill="white")
        GPIO_Init.displayImage(image)
        print(i, distParentFolderName + "/" + srcBaseName)
        shutil.copy2(i, distParentFolderName + "/" + srcBaseName)

    GPIO_Init.displayPng(workDir + "/Assets/Img/Done.png")
    GPIO_Init.getAnyKeyEvent()  # Press any key to proceed
    return 
Example 16
Project: recruit   Author: Frank-qlu   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 17
Project: recruit   Author: Frank-qlu   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 18
Project: maser4py   Author: maserlib   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        from sphinx.apidoc import main
        """Run command."""
        # process options as done in the source file of sphinx
        sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])

        print(sys.argv[0])
        # create the absolute paths to where to put things to avoid problems
        sourcedir = osp.join(
            osp.dirname(osp.abspath(__file__)))
        buildir = osp.join(
            osp.dirname(osp.abspath(__file__)),
            "build")

        apidir = osp.join(sourcedir, "api")

        rootdir = osp.join(
            osp.dirname(osp.abspath(__file__)),
            osp.pardir)

        # same here, and add path
        main([
            'sphinx-apidoc', '-f', '-o',
            osp.join(apidir, "maser4py"),
            osp.join(rootdir, "maser"),
            "--separate",
        ])

        # build the documentation as provided by sphinx
        self.run_command("build_sphinx") 
Example 19
Project: jbox   Author: jpush   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 20
Project: bsrp   Author: abaveja313   File: cascade_classifier.py    MIT License 5 votes vote down vote up
def check_dir(path):
    d = osp.abspath(osp.join(path, osp.pardir))
    if not osp.exists(d):
        os.makedirs(d) 
Example 21
Project: bsrp   Author: abaveja313   File: data_cache.py    MIT License 5 votes vote down vote up
def check_dir(path):
    """ make sure the dir specified by path got created """
    d = osp.abspath(osp.join(path, osp.pardir))
    if not osp.exists(d):
        os.makedirs(d) 
Example 22
Project: bsrp   Author: abaveja313   File: ds_base.py    MIT License 5 votes vote down vote up
def get_dataset_base():
    return osp.abspath(osp.join(__file__, osp.pardir, osp.pardir, osp.pardir, osp.pardir, "datasets")) 
Example 23
Project: bsrp   Author: abaveja313   File: ds_base.py    MIT License 5 votes vote down vote up
def get_dataset_cache_base():
    return osp.abspath(osp.join(__file__, osp.pardir, osp.pardir, osp.pardir, osp.pardir, "datasets-cache")) 
Example 24
Project: bsrp   Author: abaveja313   File: ds_pickle.py    MIT License 5 votes vote down vote up
def save_dataset(data_path, X, y):
    print('Data Saving in {} (X.shape={},y.shape={})'.format(
            data_path, X.shape, y.shape))
    data_dir = osp.abspath(osp.join(data_path, osp.pardir))
    if not osp.exists(data_dir):
        os.makedirs(data_dir)
    data = {'X': X, 'y': y}
    with open(data_path, 'wb') as f:
        pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) 
Example 25
Project: bsrp   Author: abaveja313   File: base_estimator.py    MIT License 5 votes vote down vote up
def check_dir(path):
    d = osp.abspath(osp.join(path, osp.pardir))
    if not osp.exists(d):
        os.makedirs(d) 
Example 26
Project: neo4j-social-network   Author: bestvibes   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 27
Project: neo4j-social-network   Author: bestvibes   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 28
Project: AneMo   Author: jspargo   File: loaders.py    GNU General Public License v2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 29
Project: Mahjong-Solitaire   Author: MEASHY   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 30
Project: Mahjong-Solitaire   Author: MEASHY   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 31
Project: JFlask   Author: kaneg   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 32
Project: oa_qian   Author: sunqb   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 33
Project: sam-s-club-auctions   Author: sameer2800   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 34
Project: sublime-text-3-packages   Author: nickjj   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 35
Project: SonarQube-Report-Generator   Author: dtidigitalcrafters   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 36
Project: git_for_splunk   Author: ChrisYounger   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 37
Project: XMorbid   Author: NMTech0x90   File: loaders.py    GNU General Public License v3.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 38
Project: vnpy_crypto   Author: birforce   File: __init__.py    MIT License 5 votes vote down vote up
def get_includes():
    """Return a list of directories to include for linking against pyzmq with cython."""
    from os.path import join, dirname, abspath, pardir, exists
    base = dirname(__file__)
    parent = abspath(join(base, pardir))
    includes = [ parent ] + [ join(parent, base, subdir) for subdir in ('utils',) ]
    if exists(join(parent, base, 'include')):
        includes.append(join(parent, base, 'include'))
    return includes 
Example 39
Project: vnpy_crypto   Author: birforce   File: __init__.py    MIT License 5 votes vote down vote up
def get_library_dirs():
    """Return a list of directories used to link against pyzmq's bundled libzmq."""
    from os.path import join, dirname, abspath, pardir
    base = dirname(__file__)
    parent = abspath(join(base, pardir))
    return [ join(parent, base) ] 
Example 40
Project: Where2Eat   Author: thetimothyp   File: loaders.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 41
Project: Blockly-rduino-communication   Author: technologiescollege   File: loaders.py    GNU General Public License v3.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 42
Project: Blockly-rduino-communication   Author: technologiescollege   File: controlpanel.py    GNU General Public License v3.0 5 votes vote down vote up
def command_prompt_path(self):
        return osp.join(self.distribution.target, osp.pardir,
                        "WinPython Command Prompt.exe") 
Example 43
Project: PennApps2015-Heartmates   Author: natanlailari   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 44
Project: HackZurich   Author: RefugeeMatchmaking   File: test.py    MIT License 5 votes vote down vote up
def run(verbosity=1,doctest=False,numpy=True):
    """Run NetworkX tests.

    Parameters
    ----------
    verbosity: integer, optional
      Level of detail in test reports.  Higher numbers provide  more detail.  

    doctest: bool, optional
      True to run doctests in code modules

    numpy: bool, optional
      True to test modules dependent on numpy
    """
    try:
        import nose
    except ImportError:
        raise ImportError(\
            "The nose package is needed to run the NetworkX tests.")

    sys.stderr.write("Running NetworkX tests:")
    nx_install_dir=path.join(path.dirname(__file__), path.pardir)
    # stop if running from source directory
    if getcwd() == path.abspath(path.join(nx_install_dir,path.pardir)):
        raise RuntimeError("Can't run tests from source directory.\n"
                           "Run 'nosetests' from the command line.")

    argv=[' ','--verbosity=%d'%verbosity,
          '-w',nx_install_dir,
          '-exe']
    if doctest:
        argv.extend(['--with-doctest','--doctest-extension=txt'])
    if not numpy:
        argv.extend(['-A not numpy'])


    nose.run(argv=argv) 
Example 45
Project: noobotkit   Author: nazroll   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 46
Project: DroidPot   Author: WhySoGeeky   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 47
Project: xuemc   Author: skycucumber   File: loaders.py    GNU General Public License v2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 48
Project: RSSNewsGAE   Author: liantian-cn   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 49
Project: Computable   Author: ktraunmueller   File: __init__.py    MIT License 5 votes vote down vote up
def get_includes():
    """Return a list of directories to include for linking against pyzmq with cython."""
    from os.path import join, dirname, abspath, pardir
    base = dirname(__file__)
    parent = abspath(join(base, pardir))
    return [ parent ] + [ join(parent, base, subdir) for subdir in ('utils',) ] 
Example 50
Project: chihu   Author: yelongyu   File: loaders.py    GNU General Public License v3.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 51
Project: open_api_schemas_to_markdown   Author: entrepreneur-interet-general   File: test_converter.py    MIT License 5 votes vote down vote up
def filepath(f):
    return op.join(op.abspath(op.join(__file__, op.pardir, op.pardir)), f) 
Example 52
Project: pyGISS   Author: afourmy   File: extended_pyGISS.py    MIT License 5 votes vote down vote up
def __init__(self, path_app):
        super().__init__()
        self.title('Extended PyGISS')
        path_icon = abspath(join(path_app, pardir, 'images'))
        
        # generate the PSF tk images
        img_psf = ImageTk.Image.open(join(path_icon, 'node.png'))
        selected_img_psf = ImageTk.Image.open(join(path_icon, 'selected_node.png'))
        self.psf_button_image = ImageTk.PhotoImage(img_psf.resize((100, 100)))
        self.node_image = ImageTk.PhotoImage(img_psf.resize((40, 40)))
        self.selected_node_image = ImageTk.PhotoImage(selected_img_psf.resize((40, 40)))

        for widget in (
                       'Button',
                       'Label', 
                       'Labelframe', 
                       'Labelframe.Label', 
                       ):
            ttk.Style().configure('T' + widget, background='#A1DBCD')

        self.map = Map(self)
        self.map.pack(side='right', fill='both', expand=1)

        self.menu = Menu(self)
        self.menu.pack(side='right', fill='both', expand=1)

        menu = tk.Menu(self)
        menu.add_command(label="Import shapefile", command=self.map.import_map)
        self.config(menu=menu)

        # if motion is called, the left-click button was released and we 
        # can stop the drag and drop process
        self.bind_all('<Motion>', self.stop_drag_and_drop)
        self.drag_and_drop = False

        self.image = None
        self.bind_all('<B1-Motion>', lambda _:_) 
Example 53
Project: fbs   Author: mherrmann   File: _source.py    GNU General Public License v3.0 5 votes vote down vote up
def default_path(path_str):
    defaults_dir = join(dirname(__file__), pardir, 'fbs', '_defaults')
    return path(defaults_dir, path_str) 
Example 54
Project: fbs   Author: mherrmann   File: _frozen.py    GNU General Public License v3.0 5 votes vote down vote up
def get_resource_dirs():
    app_dir = dirname(sys.executable)
    return [join(app_dir, pardir, 'Resources') if is_mac() else app_dir] 
Example 55
Project: pipenv   Author: pypa   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 56
Project: profitpy   Author: hpsilva   File: connectiondisplay.py    GNU General Public License v2.0 5 votes vote down vote up
def commandStrings():
    """ Returns keystroke helper and TWS command strings.

    """
    binDir = abspath(join(dirname(abspath(__file__)), pardir, 'bin'))
    keyCmd =  join(binDir, 'login_helper') + ' -v'
    brokerCmd = join(binDir, 'ib_tws')
    if hasTerm():
        commandFs = 'xterm -title %s -e %s'
        keyCmd = commandFs % ('helper', keyCmd, )
        brokerCmd = commandFs % ('ibtws', brokerCmd, )
    return keyCmd, brokerCmd 
Example 57
Project: encrypt-ctf   Author: mishrasunny174   File: loaders.py    GNU General Public License v3.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 58
Project: hackathon   Author: vertica   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 59
Project: blockhooks   Author: EthereumWebhooks   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 60
Project: Python   Author: andreiarnautu   File: loaders.py    GNU General Public License v3.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 61
Project: Python   Author: andreiarnautu   File: loaders.py    GNU General Public License v3.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 62
Project: Emotion-Evaluator   Author: Attriumph   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 63
Project: OpenXR-SDK-Source   Author: KhronosGroup   File: loaders.py    Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 64
Project: url_shortener   Author: martydill   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 65
Project: forum-xblock   Author: DANCEcollaborative   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 66
Project: simple-guardian   Author: esoadamo   File: requirements_updater.py    MIT License 5 votes vote down vote up
def save_hash(self):  # type: () -> None
        """
        Saves hash of current requirements file
        :return: None
        """
        if not path.exists(self.hashes_file):
            par_dir = path.abspath(path.join(self.hashes_file, path.pardir))
            if not os.path.exists(par_dir):
                os.makedirs(par_dir)

        with open(self.requirements_file, 'rb') as r:
            with open(self.hashes_file, 'w') as w:
                w.write(md5(r.read()).hexdigest()) 
Example 67
Project: table-schema-to-markdown   Author: AntoineAugusti   File: test_convert.py    MIT License 5 votes vote down vote up
def filepath(f):
    return op.join(
        op.abspath(op.join(__file__, op.pardir, op.pardir, "tests/files")), f
    ) 
Example 68
Project: musapaedia   Author: rossgoodwin   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 69
Project: taker_v0   Author: taker-project   File: test_repository.py    GNU General Public License v3.0 5 votes vote down vote up
def test_repo(tmpdir, monkeypatch):
    tmpdir = Path(str(tmpdir))
    task_dir = tmpdir / 'task'
    Path.mkdir(task_dir)

    repo = TaskRepository(Path(task_dir))
    repo.init_task()

    assert repo.relpath(Path(path.pardir) / path.curdir) == Path(path.pardir)
    assert repo.relpath(tmpdir) == Path(path.pardir)
    assert repo.abspath(Path(path.pardir) / path.curdir) == tmpdir
    assert repo.abspath(tmpdir) == tmpdir

    del repo

    with pytest.raises(TaskDirNotFoundError):
        find_task_dir()

    new_dir = task_dir / 'parent' / 'subparent'
    Path.mkdir(new_dir, parents=True)
    Path.mkdir(tmpdir / '42')
    monkeypatch.chdir(str(new_dir))

    assert find_task_dir(task_dir) == task_dir
    assert find_task_dir(new_dir) == task_dir

    repo = TaskRepository(find_task_dir())
    assert repo.directory.samefile(task_dir)
    assert (repo.relpath(task_dir.parent / '42') ==
            Path(path.pardir) / '42')
    assert (repo.abspath(Path(path.pardir) / '42') ==
            task_dir.parent / '42')

    with mock.patch('os.chdir'):
        repo.to_task_dir()
        os.chdir.assert_called_once_with(str(task_dir)) 
Example 70
Project: geofire-python   Author: ininex   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 71
Project: SejongHackathon   Author: min942773   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 72
Project: Rovers   Author: RIT-Space-Exploration   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 73
Project: Rovers   Author: RIT-Space-Exploration   File: loaders.py    MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 74
Project: bratiaa   Author: kldtz   File: common.py    MIT License 5 votes vote down vote up
def relpath(path, start):
    """Return a relative version of a path."""
    from os.path import abspath, sep, pardir, commonprefix
    from os.path import join as path_join
    if not path:
        raise ValueError("no path specified")
    start_list = abspath(start).split(sep)
    path_list = abspath(path).split(sep)
    # Work out how much of the filepath is shared by start and path.
    i = len(commonprefix([start_list, path_list]))
    rel_list = [pardir] * (len(start_list) - i) + path_list[i:]
    if not rel_list:
        return path
    return path_join(*rel_list) 
Example 75
Project: cheetah-gui   Author: shmilylty   File: cheetah_proxy_support.py    GNU General Public License v3.0 5 votes vote down vote up
def save_proxy():
    proxys = w.Scrolledlistbox1.get(0, 'end')
    proxy_path = path.abspath(path.join(path.dirname(__file__), path.pardir, 'data', 'proxy.txt'))
    with open(proxy_path, mode='a') as proxy_file:
        proxy_file.write("\n".join(proxys)) 
Example 76
Project: pyGISS   Author: afourmy   File: extended_pyGISS.py    MIT License 4 votes vote down vote up
def __init__(self, path_app):
        super().__init__()
        self.path_shapefiles = join(path_app, pardir, 'shapefiles')
        self.path_projects = join(path_app, pardir, 'projects')
        path_icon = join(path_app, pardir, 'images')
        self.setWindowIcon(QIcon(join(path_icon, 'globe.png')))
        
        central_widget = QWidget(self)
        self.setCentralWidget(central_widget)
        
        import_shapefile_icon = QIcon(join(path_icon, 'globe.png'))
        import_shapefile = QAction(import_shapefile_icon, 'Import a shapefile', self)
        import_shapefile.setStatusTip('Import a shapefile')
        import_shapefile.triggered.connect(self.import_shapefile)
        
        import_project_icon = QIcon(join(path_icon, 'import_project.png'))
        import_project = QAction(import_project_icon, 'Import a Excel project', self)
        import_project.setStatusTip('Import a project (Excel format)')
        import_project.triggered.connect(self.import_project)
        
        toolbar = self.addToolBar('')
        toolbar.resize(1500, 1500)
        toolbar.setIconSize(QSize(70, 70))
        toolbar.addAction(import_shapefile)
        toolbar.addAction(import_project)
        
        # paths to the icons (standard node and selected node)
        path_node = join(path_icon, 'node.png')
        path_selected_node = join(path_icon, 'selected_node.png')
        
        # used as a label for the menu
        self.node_pixmap = QPixmap(path_node)
        
        # used on the canvas
        self.gnode_pixmap = QPixmap(path_node).scaled(
                                                    QSize(100, 100), 
                                                    Qt.KeepAspectRatio,
                                                    Qt.SmoothTransformation
                                                    )
        self.selected_gnode_pixmap = QPixmap(path_selected_node).scaled(
                                                    QSize(100, 100), 
                                                    Qt.KeepAspectRatio,
                                                    Qt.SmoothTransformation
                                                    )
        
        self.view = View(self)
        self.main_menu = MainMenu(self)
        
        layout = QHBoxLayout(central_widget)
        layout.addWidget(self.main_menu) 
        layout.addWidget(self.view) 
Example 77
Project: timezonefinder   Author: MrMinimal64   File: timezonefinder.py    MIT License 4 votes vote down vote up
def __init__(self, bin_file_location=None, in_memory=False):
        """
        Class for quickly finding the timezone of a point on earth offline.
        Opens the required data in binary files to enable fast access.
        currently per half degree of latitude and per degree of longitude a set of candidate polygons are stored
        this gives a SHORTCUT to which of the 27k+ polygons should be tested
        (tests evaluated this to be the fastest setup when being used with Numba)

        :param bin_file_location: path to the binary data files to use
        :param in_memory: whether to completely read and keep the binary files in memory
        """
        self.in_memory = in_memory

        if self.in_memory:
            self.fromfile = fromfile_memory
        else:
            self.fromfile = fromfile

        # open all the files in binary reading mode
        # for more info on what is stored in which .bin file, please read the comments in file_converter.py
        if bin_file_location is None:
            bin_file_location = abspath(join(__file__, pardir))

        for attribute_name in DATA_ATTRIBUTE_NAMES:
            bin_file = open(join(bin_file_location, attribute_name + DATA_FILE_ENDING), mode='rb')
            if self.in_memory:
                bf_in_mem = BytesIO(bin_file.read())
                bf_in_mem.seek(0)
                bin_file.close()
                bin_file = bf_in_mem
            setattr(self, attribute_name, bin_file)

        with open(join(bin_file_location, TIMEZONE_NAMES_FILE), 'r') as f:
            self.timezone_names = json.loads(f.read())

        # store for which polygons (how many) holes exits and the id of the first of those holes
        # since there are very few (~22) it is feasible to keep them in the memory
        self.hole_registry = {}
        # read the polygon ids for all the holes
        for i, block in enumerate(iter(lambda: self.hole_poly_ids.read(NR_BYTES_H), b'')):
            poly_id = unpack(DTYPE_FORMAT_H, block)[0]
            try:
                amount_of_holes, hole_id = self.hole_registry[poly_id]
                self.hole_registry.update({
                    poly_id: (amount_of_holes + 1, hole_id),
                })
            except KeyError:
                self.hole_registry.update({
                    poly_id: (1, i),
                }) 
Example 78
Project: cheetah-gui   Author: shmilylty   File: cheetah_support.py    GNU General Public License v3.0 4 votes vote down vote up
def req_get(payload, times, options):
    header = forge_header(options)
    if options.req_delay != 0:
        format_output('i', 'Sleeping ' + str(options.time) + ' seconds to request')
        time.sleep(options.time)
    format_output('i', 'Sending ' + str(times) + 'the group payload')
    format_output('i', 'Waiting for web server response')
    proxies = get_proxy(options)
    try:
        r = requests.get(url=options.url,
                         headers=header,
                         params=payload,
                         timeout=options.time_out,
                         proxies=proxies,
                         verify=False)
    except Exception as e:
        format_output('e', e.message)
        return 'error'

    error_msg = options.url + ' response code: ' + str(r.status_code)
    if r.status_code == 404:
        format_output('e', error_msg)
        format_output('w', 'Maybe the request url incorrect')
        format_output('h', 'Try to check the url ' + options.url)
        return 'error'

    code = [413, 414, 500]
    if r.status_code in code:
        format_output('e', error_msg)
        format_output('w', 'Request url too long when request ' + options.url)
        format_output('h', 'Try to specify a smaller parameter value')
        return 'error'

    if r.status_code in range(200, 300):
        format_output('i', 'Web server responds successfully')
        if r.text in payload:
            find_path = path.abspath(path.join(path.dirname(__file__), path.pardir, 'data', 'find.txt'))
            with io.open(find_path, mode='a', encoding='utf-8') as find_file:
                find_file.write(options.url + '\t\t' + r.text + '\n')
            format_output('h', 'The password of {} is {}'.format(options.url, r.text))
            title = "Cheetah Info"
            message = "The password of {} is {}".format(options.url, r.text)
            showinfo(title, message, parent=root)
            format_output('h', 'Password has been written to ../data/find.txt')
            return 'find'
        else:
            format_output('h', 'The password not in ' + str(times) + 'th group payload')
            return 'notfind'
    else:
        format_output('e', error_msg)
        return 'error' 
Example 79
Project: cheetah-gui   Author: shmilylty   File: cheetah_support.py    GNU General Public License v3.0 4 votes vote down vote up
def req_post(payload, times, options):
    header = forge_header(options)
    if options.req_delay != 0:
        format_output('i', 'Sleeping ' + str(options.req_delay) + ' seconds to request')
        time.sleep(options.req_delay)
        format_output('i', 'Posting ' + str(times) + 'th group payload')
        format_output('i', 'Waiting for web server response')
    proxies = get_proxy(options)
    try:
        r = requests.post(url=options.url,
                          headers=header,
                          data=payload,
                          timeout=options.time_out,
                          proxies=proxies,
                          verify=False)
    except Exception as e:
        format_output('e', str(e))
        return 'error'

    error_msg = options.url + ' response code: ' + str(r.status_code)
    if r.status_code == 404:
        format_output('e', error_msg)
        format_output('w', 'Maybe the request url incorrect')
        format_output('h', 'Try to check the url ' + options.url)
        return 'error'

    code = [413, 414, 500]
    if r.status_code in code:
        format_output('w', 'Request url too long when request ' + options.url)
        format_output('h', 'Try to specify a smaller parameter value')
        return 'error'

    if r.status_code in range(200, 300):
        format_output('i', 'Web server responds successfully')
        if r.text in payload:
            find_path = path.abspath(path.join(path.dirname(__file__), path.pardir, 'data', 'find.txt'))
            with io.open(find_path, mode='a', encoding='utf-8') as find_file:
                find_file.write(options.url + '\t\t' + r.text + '\n')
            format_output('h', 'The password of {} is {}'.format(options.url, r.text))
            title = "Cheetah Info"
            message = "The password of {} is {}".format(options.url, r.text)
            showinfo(title, message, parent=root)
            format_output('h', 'Password has been written to ../data/find.txt')
            return 'find'
        else:
            format_output('h', 'The password not in ' + str(times) + 'th group payload')
            return 'notfind'
    else:
        format_output('e', error_msg)
        return 'error' 
Example 80
Project: cheetah-gui   Author: shmilylty   File: cheetah_update_support.py    GNU General Public License v3.0 4 votes vote down vote up
def check_updates():
    if check_update.get() == "OK":
        exit_update()
    if check_update.get() == "Update":
        w.TButton1.configure(state="disable")
        w.TButton2.configure(state="disable")
        process = os.popen("git --version")
        output = process.read()
        process.close()
        par_dir = path.abspath(path.join(path.dirname(__file__), path.pardir))
        if "git version" in output:
            if path.exists(path.join(par_dir, '.git')):
                os.chdir(par_dir)
                os.system('git pull origin master')
                title = "Cheetah Info"
                message = "Cheetah has completed the update."
                showinfo(title, message, parent=root)
                destroy_window()
            else:
                os.chdir(par_dir)
                message = "Cheetah is about to be updated, " \
                          "please do not do anything else during the update!"
                title = "Cheetah Warn"
                showwarning(title, message, parent=root)
                os.system('git clone https://github.com/sunnyelf/cheetah.git new_cheetah')
                title = "Cheetah Info"
                message = "Cheetah has completed the update."
                showinfo(title, message, parent=root)
                destroy_window()
        else:
            url = 'https://github.com/sunnyelf/cheetah/archive/master.zip'
            r = requests.get(url, verify=False)
            with open("cheetah.zip", "wb") as f:
                f.write(r.content)
            zip_path = path.join(par_dir, "cheetah.zip")
            title = "Cheetah Info"
            message = "The latest version of Cheetah has been downloaded.\n" \
                      "File path: %s" % zip_path
            showinfo(title, message, parent=root)
            destroy_window()
    if check_update.get() == "Check":
        w.TButton1.configure(state="disable")
        update_log_url = "https://pastebin.com/raw/n6YYbzri"
        r = requests.get(update_log_url, verify=False)
        update_log_json = r.json()
        update_ver = update_log_json['ver']
        update_log = update_log_json['log']
        if update_ver > current_ver:
            msg = "The latest Cheetah version is %.1f, " \
                  "do you need to update it now?\n" % update_ver
            update_msg.set(msg + 'New version: ' + update_log)
            w.TButton1.configure(state="normal")
            check_update.set("Update")
        else:
            msg = "The current Cheetah version {} is already the latest version.".format(current_ver)
            update_msg.set(msg)
            w.TButton1.configure(state="normal")
            check_update.set("OK")