Example #1
0
def get_file_list_recursive(extension="*", file_list=[], dir_path=None, recurs_iter=0, recurs_max=8):
  """
  Returns a list of files with a specific extension by analysing directories recursively
  
  """

  cwd = os.getcwd()
  if dir_path is not None:
    os.chdir(dir_path)
  
  dir_path_add = os.getcwd()
  
  for _, dirs, files in os.walk("./"):
    
    if len(dirs) > 0:
      for dir_recur in dirs:
        file_list_dir = get_file_list_recursive(extension=extension, file_list=file_list, 
                                      dir_path=dir_recur, recurs_iter=recurs_iter+1, recurs_max=recurs_max)
      
    else:
      file_list_dir = glob.glob("*.%s" % (extension))
      
      # adding directory to the path 
      for i in range(len(file_list_dir)):
        file_list_dir[i] = os.path.join(dir_path_add, file_list_dir[i])
        
      # joining two lists, python makes it so easy :)
      file_list += file_list_dir
        
  os.chdir(cwd)
    
  return file_list
Example #2
0
def test_run_multiproc_nondaemon_with_flag(nondaemon_flag):
    '''
    Start a pipe with two nodes using the multiproc plugin and passing the nondaemon_flag.
    '''
    
    cur_dir = os.getcwd()
    temp_dir = mkdtemp(prefix='test_engine_')
    os.chdir(temp_dir)
    
    pipe = pe.Workflow(name='pipe')
    
    f1 = pe.Node(interface=Function(function=TestInterface.testFunction, input_names=['sum'], output_names=['sum_out']), name='f1')
    f2 = pe.Node(interface=Function(function=TestInterface.testFunction, input_names=['sum'], output_names=['sum_out']), name='f2')

    pipe.connect([(f1,f2,[('sum_out','sum')])])
    pipe.base_dir = os.getcwd()
    f1.inputs.sum = 0
    
    # execute the pipe using the MultiProc plugin with 2 processes and the non_daemon flag
    # to enable child processes which start other multiprocessing jobs
    execgraph = pipe.run(plugin="MultiProc", plugin_args={'n_procs':2, 'non_daemon':nondaemon_flag})
    
    names = ['.'.join((node._hierarchy,node.name)) for node in execgraph.nodes()]
    node = execgraph.nodes()[names.index('pipe.f2')]
    result = node.get_output('sum_out')
    yield assert_equal, result, 180 # n_procs (2) * numberOfThreads (2) * 45 == 180
    os.chdir(cur_dir)
    rmtree(temp_dir)
Example #3
0
def download_mango(url, path):   
    """
        Function: download_mango(url, path)
        Usage: download_mango('http://www.mangareader.net/poyopoyo-kansatsu-nikki/1', os.getcwd())
        Added in version: 0.1 Beta
    """
    if path != os.getcwd():
        pathchange(os.getcwd(), path)
    urlContent = urllib2.urlopen(url).read()
    imgUrls = re.findall('img .*?src="(.*?.jpg)"', urlContent)


    for imgUrl in imgUrls:
        try:
            imgData = urllib2.urlopen(imgUrl).read()
            fileName = basename(urlsplit(imgUrl)[2])
            output = open(fileName, 'wb')
            output.write(imgData)
            output.close()
        except IOError: 
            print "File not found or full disk. Try again."
            sys.exit(1)
        except KeyboardInterrupt:
            print "Operation aborted manually."
            sys.exit(1)
        except:
            print "Unknown error. If this persists, contact the author or create a ticket in the bugtracker."
            sys.exit(1)
Example #4
0
    def run(self, args):
        namespace = self.parser.parse_args(args)
        # Get absolute paths
        namespace.pecan_config = os.path.join(os.getcwd(),
                                              namespace.pecan_config)
        namespace.api_paste_config = os.path.join(os.getcwd(),
                                                  namespace.api_paste_config)
        namespace.config_file = os.path.join(os.getcwd(),
                                             namespace.config_file)

        # Check conf files exist
        if not os.path.isfile(namespace.pecan_config):
            print("Bad config file: %s" % namespace.pecan_config,
                  file=sys.stderr)
            sys.exit(1)
        if not os.path.isfile(namespace.api_paste_config):
            print("Bad config file: %s" % namespace.api_paste_config,
                  file=sys.stderr)
            sys.exit(2)
        if not os.path.isfile(namespace.config_file):
            print("Bad config file: %s" % namespace.config_file,
                  file=sys.stderr)
            sys.exit(1)

        app.SurveilCommand().run(namespace)
Example #5
0
def create_backup():
    cwd = os.getcwd()
    os.chdir(BASE_DIR)
    current_date = datetime.utcnow().strftime(FILE_TIME_FORMAT)
    filename = os.path.join(MEDIA_ROOT, current_date + SQL_FORMAT)
    backup_name = "Ignite_" + current_date + TAR_FORMAT
    tar_name = os.path.join(MEDIA_ROOT, BACKUP, backup_name)

    db_dump(filename)

    file_obj = tarfile.open(tar_name, "w:gz")
    logger.debug("cwd = " + os.getcwd())
    for name in FILE_LIST:
        file_obj.add(MEDIA + "/" + name)

    file_obj.add(MEDIA + "/" + current_date + SQL_FORMAT)
    file_obj.close()

    try:
        os.remove(filename)
    except:
        delete_backup([current_date + TAR_FORMAT])
        raise IgniteException(ERR_FAILED_TO_REMOVE + filename)

    resp = {}
    resp["status"] = "success"
    resp["filename"] = backup_name
    os.chdir(cwd)
    return resp
Example #6
0
 def __upload_file(self,ip="",port=36000,username="",password="",file_name=""):
     """function:upload script file"""
     try:
         result=True
         code =0
         msg = "OK"
         t = paramiko.Transport((ip,port))
         t.connect(username=username,password=password)
         sftp =paramiko.SFTPClient.from_transport(t)
         #
         try:
             sftp.put(os.getcwd()+"/tools/"+file_name,"/tmp/"+file_name)
             #print "Upload Local File:",
         except Exception,e:
             print "Exception:",str(e)
             print "Try again"
             time.sleep(5)
             try:
                 sftp.put(os.getcwd()+"/tools/"+file_name,"/tmp/"+file_name)
             except Exception,e:
                 msg+=(str(e))
                 
                 result=False
                 code = 1
                 msg=str(e)
Example #7
0
def prompt_for_solution_stack(module_name=None):

    solution_stacks = elasticbeanstalk.get_available_solution_stacks()

    # get list of platforms
    platforms = []
    for stack in solution_stacks:
        if stack.platform not in platforms:
            platforms.append(stack.platform)

    cwd = os.getcwd()
    # First check to see if we know what language the project is in
    try:
        fileoperations._traverse_to_project_root()
        platform = heuristics.find_language_type()

        if platform == 'Docker':
            # Check to see if dockerrun is version one or two
            dockerrun_file = dockerrun.get_dockerrun(
                os.path.join(os.getcwd(), 'Dockerrun.aws.json'))
            if dockerrun_file:
                if dockerrun_file.get('AWSEBDockerrunVersion') in (1, '1'):
                    platform = 'Docker'
                else:
                    platform = 'Multi-container Docker'
    finally:
        os.chdir(cwd)

    if platform is not None:
        io.echo()
        io.echo(prompts['platform.validate'].replace('{platform}', platform))
        correct = io.get_boolean_response()

    if not platform or not correct:
        # ask for platform
        io.echo()
        io.echo(prompts['platform.prompt']
                if not module_name
                else prompts['platform.prompt.withmodule'].replace('{module_name}',
                                                                   module_name))
        platform = utils.prompt_for_item_in_list(platforms)

    # filter
    solution_stacks = [x for x in solution_stacks if x.platform == platform]

    #get Versions
    versions = []
    for stack in solution_stacks:
        if stack.version not in versions:
            versions.append(stack.version)

    #now choose a version (if applicable)
    if len(versions) > 1:
        io.echo()
        io.echo(prompts['sstack.version'])
        version = utils.prompt_for_item_in_list(versions)
    else:
        version = versions[0]

    return get_latest_solution_stack(version, stack_list=solution_stacks)
Example #8
0
 def _quick_savefile(self, PTYPE=IMAGE_EXT):
     '''Save the current display via PyArt interface.'''
     imagename = self.display.generate_filename(
         self.Vfield.value, self.Vtilt.value, ext=IMAGE_EXT)
     self.canvas.print_figure(os.path.join(os.getcwd(), imagename), dpi=DPI)
     self.statusbar.showMessage(
         'Saved to %s' % os.path.join(os.getcwd(), imagename))
Example #9
0
    def test_absolute_paths(self):
        from certbot.configuration import NamespaceConfig

        config_base = "foo"
        work_base = "bar"
        logs_base = "baz"
        server = "mock.server"

        mock_namespace = mock.MagicMock(spec=['config_dir', 'work_dir',
                                              'logs_dir', 'http01_port',
                                              'tls_sni_01_port',
                                              'domains', 'server'])
        mock_namespace.config_dir = config_base
        mock_namespace.work_dir = work_base
        mock_namespace.logs_dir = logs_base
        mock_namespace.server = server
        config = NamespaceConfig(mock_namespace)

        self.assertTrue(os.path.isabs(config.config_dir))
        self.assertEqual(config.config_dir,
                         os.path.join(os.getcwd(), config_base))
        self.assertTrue(os.path.isabs(config.work_dir))
        self.assertEqual(config.work_dir,
                         os.path.join(os.getcwd(), work_base))
        self.assertTrue(os.path.isabs(config.logs_dir))
        self.assertEqual(config.logs_dir,
                         os.path.join(os.getcwd(), logs_base))
        self.assertTrue(os.path.isabs(config.accounts_dir))
        self.assertTrue(os.path.isabs(config.backup_dir))
        self.assertTrue(os.path.isabs(config.csr_dir))
        self.assertTrue(os.path.isabs(config.in_progress_dir))
        self.assertTrue(os.path.isabs(config.key_dir))
        self.assertTrue(os.path.isabs(config.temp_checkpoint_dir))
Example #10
0
    def OnButton_textUserButton(self, evt):
        '''txt 用户数据库处理'''
        wildcard = "txt (*.txt)|*.txt"
        try:
            Dir=unicode(os.getcwd(), self.textencoding)
        except:
            Dir=os.getcwd()
        
        #这里的style不能选 wx.CHANGE_DIR,更改后,会引起脚本执行目录的变化  
        dlg = wx.FileDialog(
            self, 
            message="Choose a txt file",
            defaultDir=Dir, 
            defaultFile="",
            wildcard=wildcard,
            style=wx.OPEN
            )

        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            self.mainStatusBar.SetLabel(path)    
            self.userControlPanelString=path
        dlg.Destroy()

        self.users=txtUserControl(self.userControlPanelString)
        if self.users.userDataInit()== userControlErrValue["OK"]:
            self.Config.setContrlMedia("txt")  
            self.Config.setControlMediaPath(self.userControlPanelString)
            self.Config.saveServerConfig()
        else:
            uiDebug("serverManager userDataInit error")
                         
        uiDebug("OnButton_textUserButton()")
Example #11
0
    def OnButton_xmlUserButton(self, evt):
        '''xml 用户数据库处理'''
        wildcard = "xml (*.xml)|*.xml"

        try:
            Dir=unicode(os.getcwd(), self.textencoding)
        except:
            Dir=os.getcwd()

        dlg = wx.FileDialog(
            self, message="Choose a xml file",
            defaultDir=Dir, 
            defaultFile="",
            wildcard=wildcard,
            style=wx.OPEN
            )
        
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            self.mainStatusBar.SetLabel(path)
            self.userControlPanelString=path    
        dlg.Destroy()  
        
        self.users=xmlUserControl(self.userControlPanelString)
        if self.users.userDataInit()== userControlErrValue["OK"]:
            self.Config.setContrlMedia("xml")  
            self.Config.setControlMediaPath(self.userControlPanelString)
            self.Config.saveServerConfig()
        else:
            uiDebug("serverManager userDataInit error")
            
        uiDebug("serverManager OnButton_xmlUserButton()")
 def plot_graphs(self,path,count):
     '''Save graphs'''
     Gs=nx.to_agraph(self.gS)
     Gm=nx.to_agraph(self.gM)
     Gs_w=nx.to_agraph(self.gS_w)
     
     #add color to main nodes
     for node in self.gM.nodes():
         n=Gs.get_node(node)
         n.attr['shape']='box'
         n.attr['style']='filled'
         n.attr['fillcolor']='turquoise'
         
     #add weight to edges    
     for edge in self.gS_w.edges(data=True):
         ed=Gs_w.get_edge(edge[0],edge[1])
         ed.attr['label']=edge[2]['weight'] 
     
     loc= os.getcwd()+path+'/spanning/gS' + str(count)+'.png'
     loc1= os.getcwd()+path+'/projection/gM' + str(count)+'.png' 
     loc2= os.getcwd()+path+'/spanning_w/gS_w' + str(count)+'.png' 
     
     Gs.layout(prog='dot') # use dot
     Gm.layout(prog='dot') # use dot
     Gs_w.layout(prog='dot')
     
     Gs.draw(loc)
     Gm.draw(loc1)
     Gs_w.draw(loc2)
               
     return
Example #13
0
    def _call_avrdude(args):
        if utils.is_windows():
            avr_exe_path = os.path.join(pm.RES_PATH, 'avrdude.exe')
            avr_config_path = os.path.join(pm.RES_PATH, 'avrdude.conf')
        elif utils.is_mac():
            avr_exe_path = os.path.join(pm.RES_PATH, 'avrdude')
            avr_config_path = os.path.join(pm.RES_PATH, 'avrdude.conf')
        elif utils.is_linux():
            avr_exe_path = os.path.join(pm.RES_PATH, 'avrdude64' if utils.is64bits() else "avrdude")
            avr_config_path = os.path.join(pm.RES_PATH, 'avrdude.conf' if utils.is64bits() else "avrdude32.conf")
        else:
            raise Exception("Platform not supported")

        os.chmod(avr_exe_path, int("755", 8))  # force to have executable rights in avrdude

        avr_exe_path = os.path.normpath(os.path.relpath(avr_exe_path, os.getcwd()))
        avr_config_path = os.path.normpath(os.path.relpath(avr_config_path, os.getcwd()))

        cmd = [avr_exe_path] + ["-C"] + [avr_config_path] + args.split(" ")
        log.debug("Command executed: {}".format(cmd))
        p = subprocess.Popen(cmd, shell=utils.is_windows(), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             close_fds=(not utils.is_windows()))
        output = p.stdout.read()
        err = p.stderr.read()
        log.debug(output)
        log.debug(err)
        return output, err
Example #14
0
def parse_args():
    parser = argparse.ArgumentParser(description='Train a Region Proposal Network')
    parser.add_argument('--image_set', dest='image_set', help='can be trainval or train',
                        default='trainval', type=str)
    parser.add_argument('--year', dest='year', help='can be 2007, 2010, 2012',
                        default='2007', type=str)
    parser.add_argument('--root_path', dest='root_path', help='output data folder',
                        default=os.path.join(os.getcwd(), 'data'), type=str)
    parser.add_argument('--devkit_path', dest='devkit_path', help='VOCdevkit path',
                        default=os.path.join(os.getcwd(), 'data', 'VOCdevkit'), type=str)
    parser.add_argument('--pretrained', dest='pretrained', help='pretrained model prefix',
                        default=os.path.join(os.getcwd(), 'model', 'vgg16'), type=str)
    parser.add_argument('--epoch', dest='epoch', help='epoch of pretrained model',
                        default=1, type=int)
    parser.add_argument('--prefix', dest='prefix', help='new model prefix',
                        default=os.path.join(os.getcwd(), 'model', 'rpn'), type=str)
    parser.add_argument('--gpus', dest='gpu_ids', help='GPU device to train with',
                        default='0', type=str)
    parser.add_argument('--begin_epoch', dest='begin_epoch', help='begin epoch of training',
                        default=0, type=int)
    parser.add_argument('--end_epoch', dest='end_epoch', help='end epoch of training',
                        default=8, type=int)
    parser.add_argument('--frequent', dest='frequent', help='frequency of logging',
                        default=20, type=int)
    parser.add_argument('--kv_store', dest='kv_store', help='the kv-store type',
                        default='device', type=str)
    parser.add_argument('--work_load_list', dest='work_load_list', help='work load for different devices',
                        default=None, type=list)
    parser.add_argument('--finetune', dest='finetune', help='second round finetune', action='store_true')
    parser.add_argument('--resume', dest='resume', help='continue training', action='store_true')
    args = parser.parse_args()
    return args
Example #15
0
def copy_rails_config_file(directory, filename, flag=0):
    """
    Description:

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

        fin.close()
        fout.close()

    else:
        shutil.copyfile(f_src, f_dst)
    print "File copied"
    print "\t", "From: %s" % f_src
    print "\t", "To: %s" % f_dst
Example #16
0
def display_path(path):
    """Gives the display value for a given path, making it relative to cwd
    if possible."""
    path = os.path.normcase(os.path.abspath(path))
    if path.startswith(os.getcwd() + os.path.sep):
        path = '.' + path[len(os.getcwd()):]
    return path
Example #17
0
def get_extensions():
    from distutils.extension import Extension

    common_extension_args = {
        'include_dirs': get_include_dirs(),
        'library_dirs': get_library_dirs(),
        'libraries': get_libraries()}

    try:
        from Cython.Build import cythonize        
        sources = [os.path.join(os.getcwd(), 'pyfftw', 'pyfftw.pyx')]
        have_cython = True

    except ImportError as e:
        # no cython
        sources = [os.path.join(os.getcwd(), 'pyfftw', 'pyfftw.c')]
        if not os.path.exists(sources[0]):
            raise ImportError(
                str(e) + '. ' + 
                'Cython is required to build the initial .c file.')
        
        have_cython = False

    ext_modules = [
        Extension('pyfftw.pyfftw', sources=sources, 
                  **common_extension_args)]

    if have_cython:
        return cythonize(ext_modules)

    else:
        return ext_modules
def render_all(template_path=None, output_path=None, static_path=None):
    if not template_path:
        template_path = 'lae_site/templates/'
    if not output_path:
        output_path = 'lae_rendered/'
    if not static_path:
        static_path = 'content/static/'
    env = Environment(loader=MyLoader(template_path))
    # find all the files inside all the subdirectories of the template path
    all_the_things = os.walk(template_path)
    for root, dirs, files in all_the_things:
        for f in files:
            # check that it's a template file
            if f[-5:] == '.html' and f[:1] != '_':
                full_path = root + '/' + f
                # path relative to template_path
                relative_path = full_path[len(template_path) + 1:]
                print "Rendering " + relative_path
                # render the template
                template = env.get_template(relative_path)
                # calculate directory output should go in
                dirname = os.path.dirname(output_path + '/' + relative_path)
                # and if it doesn't exist yet, create it
                if not os.path.exists(dirname):
                    os.makedirs(dirname)
                # make rendered html file
                with codecs.open(output_path + '/' + relative_path, 'w', 'utf-8') as render_file:
                    for line in template.render():
                        render_file.write(line)
    if not os.path.isdir(output_path + 'static'):
        subprocess.check_call(['ln', '-s', '../' + static_path, 'static'], cwd=os.getcwd() + '/' + output_path)
    print "Made symlink to static files."
    subprocess.check_call(['python', '-m', 'SimpleHTTPServer', '8002'], cwd=os.getcwd() + '/' + output_path)
Example #19
0
def unzip_input(file):
    print "* Unzipping" + file
    zfile = zipfile.ZipFile(os.getcwd() + "/input/" + file + ".zip")
    for name in zfile.namelist():
        (dirname, filename) = os.path.split(name)
        zfile.extract(name, os.getcwd() + "/input/")
    zfile.close()
def main():
    description = ("Output an LZW compressed binary file and JSON dict"
                   "containing the keycodes for decompression, or decompress a"
                   "previously LZW compressed file.")
    parser = argparse.ArgumentParser(description=description)
    subparsers = parser.add_subparsers()
    parser_comp = subparsers.add_parser("compress")
    parser_comp.add_argument("--infile", nargs="?",
                             type=argparse.FileType("r"), default=sys.stdin)
    parser_comp.add_argument("--outfile", nargs="?",
                             type=argparse.FileType("wb"),
                             default=os.path.join(os.getcwd(), "output.bin"))
    parser_comp.add_argument("--keycode-file", nargs="?",
                             type=argparse.FileType("w"),
                             default=os.path.join(os.getcwd(), "keycodes.json"))
    parser_comp.set_defaults(func=parse_for_compress)
    parser_decomp = subparsers.add_parser("decompress")
    parser_decomp.add_argument("--infile", nargs="?",
                               type=argparse.FileType("rb"),
                               default=os.path.join(os.getcwd(), "output.bin"))
    parser_decomp.add_argument("--keycode-file", nargs="?",
                               type=argparse.FileType("r"),
                             default=os.path.join(os.getcwd(), "keycodes.json"))
    parser_decomp.add_argument("--outfile", nargs="?",
                               type=argparse.FileType("w"), default=sys.stdout)
    parser_decomp.set_defaults(func=parse_for_decompress)

    args = parser.parse_args()
    args.func(args)
    args.infile.close()
    args.outfile.close()
    args.keycode_file.close()
Example #21
0
def download_dir(dsvc,dir_file,depth=0):
	
	cwd = os.getcwd()
	
	out_root = os.path.join(cwd,dir_file['title'])
	disp_path = out_root.replace(PROG_ROOT,"")
	print("ChangeDir to %s" % disp_path)
	if(not os.path.exists(out_root)):
		os.makedirs(out_root)
	os.chdir(out_root)
	
	file_list = get_file_meta(dsvc,"'%s' in parents" % dir_file['id'])
	
	counter = 1
	total = len(file_list)
	for file in file_list:
		if(file['mimeType'] == "application/vnd.google-apps.folder"):
			print("[%s%d/%d] %s (Directory)" % ((depth * "-"),counter,total,file['title']))
			download_dir(dsvc,file,depth+1)
		else:
			#We have a file.
			fsmb = float(float(file['fileSize']) / (1024*1024))
			print("[%s%d/%d] %s (%.2fMB)" % ((depth * "-"),counter,total,file['title'],fsmb))
			download_file(dsvc,file)
		counter +=1
	
	os.chdir("..")
	cwd = os.getcwd()
	disp_path = cwd.replace(PROG_ROOT,"")
	if(disp_path != ""):
		print("ChangeDir to %s" % disp_path)
	def load_XRF_data(self):
		file = '%s/XRF_Training_Set.xlsx'%os.getcwd()

		wb = xlrd.open_workbook(filename = 'XRF_Training_Set.xlsx')
		sh = wb.sheet_by_index(0)

		row_index = 1
		while True: 
			try:
				XRF_data_list = []
				column_index = 1

				while True: 
					try: 
						XRF_data_list.append(sh.cell_value(row_index, column_index))

						column_index += 1
					except: 
						break 

				with open('%s/controlData_AVG_Files/%s Ref Data/XRF_%s.json'%(os.getcwd(), sh.cell_value(row_index, 0), sh.cell_value(row_index, 0)), 'w') as j:
					j.write(json.dumps(XRF_data_list, sort_keys=True, indent=4, separators=(',', ': ')))

				with open('%s/controlData_AVG_Files/%s Ref Data/XRF_%s.csv'%(os.getcwd(), sh.cell_value(row_index, 0), sh.cell_value(row_index, 0)), 'w') as c:
					writer = csv.writer(c)
					writer.writerow(XRF_data_list)

				row_index += 1
				self.XRF_listLength = len(XRF_data_list)

			except:
				break
Example #23
0
 def paipai(self):
         self.parent.cam.saveSnapshot(os.getcwd() + '/image/s2.png', timestamp=self.timestamp, boldfont=self.boldfont, quality=self.quality)
         self.autoCam()
         img = ImageProcess()
         img.thumbnails(os.getcwd() + '/image/s2.png', os.getcwd() + '/image/s3.png', 170, 170)
         self.parent.showimage()
         self.close()
Example #24
0
def create(username, site_name):
    import re
    newsite = "bench new-site " + site_name
    installapp = "bench --site "+ site_name + " install-app erpnext"

    # NOTETHIS: check if site_name already exists
    print "Creating new site.."
    os.system(newsite)
    print "Installing erpnext to site.."
    os.system(installapp)

    # get database name from site_config.json of new site
    old_dir = os.getcwd()
    path = '/home/testuser/frappe-bench/sites/'+ site_name
    os.chdir(path)
    print os.getcwd()
    with open('site_config.json') as f:
        content = f.readlines()
    tmp = content[1].strip()
    tmp = tmp.split(":")[1]
    db_name = re.sub('\W+','',tmp)
    os.chdir(old_dir)

    # add site to database, mapped to owner
    newsite = User_Sites()
    newsite.username = username
    newsite.db_name = db_name
    newsite.site_name = site_name
    newsite.save()

    print "Done!"
Example #25
0
def filter_files(kernel, is_relative, exclude, write_files):
  extra=''
  for i in exclude:
    extra += ' -not -path "*' + i + '/*" '
  if kernel:
    cmd="""find {0}  \
      -path "$PWD/arch/*" ! -path "$PWD/arch/x86*" -prune -o               \
      -path "$PWD/include/asm-*" ! -path "$PWD/include/asm-i386*" -prune -o  \
      -path "$PWD/sound*" -prune -o                                         \
      -path "$PWD/firmware*" -prune -o                                     \
      {1} \
      -iname "*.[chxsS]" -print > {2}
      """.format('.' if is_relative else os.getcwd(), extra, write_files)
  else:
    cmd="""find {0}  \( \
      -name '*.py' \
      -o -name '*.php' \
      -o -name '*.java' \
      -o -iname '*.[ch]' \
      -o -name '*.cpp' \
      -o -name '*.cc' \
      -o -name '*.hpp' \) \
      {1} \
      > {2}
      """.format('.' if is_relative else os.getcwd(), extra, write_files)
  print cmd
  process = subprocess.Popen(cmd, stdout=subprocess.PIPE,shell=True)
  out, err = process.communicate()
  print out
Example #26
0
    def __init__(self, defaults=None, confFile=None, *args, **kwds):
        """Initialize the parser.

        *defaults* -- defaults values.
        *confFile* -- the file (or list of files) to parse."""
        ConfigParser.ConfigParser.__init__(self, defaults=defaults)
        if confFile is None:
            dotFileName = '.' + confFileName
            # Current and home directory.
            confFile = [os.path.join(os.getcwd(), confFileName),
                        os.path.join(os.getcwd(), dotFileName),
                        os.path.join(os.path.expanduser('~'), confFileName),
                        os.path.join(os.path.expanduser('~'), dotFileName)]
            if os.name == 'posix':
                sep = getattr(os.path, 'sep', '/')
                # /etc/ and /etc/conf.d/
                confFile.append(os.path.join(sep, 'etc', confFileName))
                confFile.append(os.path.join(sep, 'etc', 'conf.d',
                                            confFileName))
            else:
                # etc subdirectory of sys.prefix, for non-unix systems.
                confFile.append(os.path.join(sys.prefix, 'etc', confFileName))
        for fname in confFile:
            try:
                self.read(fname)
            except (ConfigParser.MissingSectionHeaderError,
                    ConfigParser.ParsingError), e:
                _aux_logger.warn('Troubles reading config file: %s' % e)
            # Stop at the first valid file.
            if self.has_section('imdbpy'):
                break
Example #27
0
def SanityCheckDirectory():
  if os.getcwd().endswith(SAFE_DIR_SUFFIX):
    return
  logging.error('httpd.py should only be run from the %s', SAFE_DIR_SUFFIX)
  logging.error('directory for testing purposes.')
  logging.error('We are currently in %s', os.getcwd())
  sys.exit(1)
Example #28
0
def verifyArguments(args):
    # Verify supplied arguments
    if args.application is None or os.path.exists(args.application) is False:
        # Before we error, lets verfiy if current parent directory matches
        # the application they were supplying:
        if os.path.basename(os.getcwd()) != args.application:
            print 'You must specify a path to the application you wish to build an SQA documentation for.'
            sys.exit(1)
        else:
            args.application = os.getcwd()
    else:
        if os.path.exists(os.path.join(args.application, 'doc/sqa', args.requirements)) is False:
            print 'I could not find ', os.path.join(os.path.abspath(args.application), 'doc/sqa', args.requirements), 'file.' \
              '\nPlease see the directory:', os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), '..', 'framework/doc/sqa'), 'for a working example'
            sys.exit(1)

    args.application_path = os.path.abspath(args.application)
    args.requirements_path = os.path.join(args.application_path, 'doc/sqa', args.requirements)
    args.application_name = os.path.split(args.application_path)[1]

    # Set the current working directory to this script location
    # We to do this _after_ discovering application path in case
    # the user supplied a relative path instead of an absolute
    # path
    args.cwd = os.getcwd()
    os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))

    # Set MOOSE_DIR to parent directory (were sitting
    # in moose/scripts at the moment)
    args.moose_dir = os.path.abspath('..')

    return args
Example #29
0
def create_filetree(path=None, depth=0, max_depth=0):

    tree = None

    if max_depth == 0 or depth < max_depth:
        if path is None:
            path = os.getcwd()

        tree = dict(name=os.path.basename(path), children=[])

        try:
            lst = os.listdir(path)
        except OSError:
            pass  # ignore errors
        else:
            for name in lst:
                fn = os.path.join(path, name)
                if (os.path.isdir(fn) and
                        re.match('^.*(Compiled)$', fn) is None):
                    child = create_filetree(fn, depth + 1, max_depth)
                    if child is not None:
                        tree['children'].append(child)
                elif re.match('^.*\.(m|def|txt|csv)$', fn) is not None:
                    tree['children'].append(dict(name=fn.replace(
                        os.getcwd() + os.path.sep, "")))

    return tree
Example #30
0
File: setup.py Project: imcj/pybbs
def install(**kwargs):
    """setup entry point"""
    if USE_SETUPTOOLS:
        if '--force-manifest' in sys.argv:
            sys.argv.remove('--force-manifest')
    # install-layout option was introduced in 2.5.3-1~exp1
    elif sys.version_info < (2, 5, 4) and '--install-layout=deb' in sys.argv:
        sys.argv.remove('--install-layout=deb')
    if subpackage_of:
        package = subpackage_of + '.' + modname
        kwargs['package_dir'] = {package : '.'}
        packages = [package] + get_packages(os.getcwd(), package)
        if USE_SETUPTOOLS:
            kwargs['namespace_packages'] = [subpackage_of]
    else:
        kwargs['package_dir'] = {modname : '.'}
        packages = [modname] + get_packages(os.getcwd(), modname)
    if USE_SETUPTOOLS and install_requires:
        kwargs['install_requires'] = install_requires
        kwargs['dependency_links'] = dependency_links
    kwargs['packages'] = packages
    return setup(name = distname,
                 version = version,
                 license = license,
                 description = description,
                 long_description = long_description,
                 author = author,
                 author_email = author_email,
                 url = web,
                 scripts = ensure_scripts(scripts),
                 data_files = data_files,
                 ext_modules = ext_modules,
                 cmdclass = {'install_lib': MyInstallLib},
                 **kwargs
                 )