def getStaticFile(self, path): if path.find("..") != -1: self.send_response(400) self.end_headers() return # Convert path to actual path on the disk. path = os.path.join(self.server.filesDir, path) if not os.path.exists(path): self.send_response(404) self.end_headers() return self.send_response(200) # Specific check for cache manifests. if path.find("cache-manifest") != -1: self.send_header('Content-Type', "text/cache-manifest") ext = os.path.splitext(path)[1] if ext == '.js': self.send_header('Content-Type', "text/javascript") elif ext == '.css': self.send_header('Content-Type', "text/css") self.end_headers() f = open(path) lines = f.readlines() f.close() self.wfile.writelines(lines)
def __init__(self, path): self.path = path if path.find(':') < 0: if path.find('.root') < 0: self.rfile = '' self.rpath = path else: self.rfile = path self.rpath = '' else: self.rfile, self.rpath = path.split(':', 1) self.rpath = self.rpath.rstrip('/') self.norfile = not self.rfile self.norpath = not self.rpath self.relative = self.rpath.find('../') == 0 or \ self.rpath.find('/') > 0 if self.rfile and self.relative: raise ValueError('Relative path not allowed with file specifier') # utilities self.rfile_dirname = os.path.dirname(self.rfile) self.rfile_basename = os.path.basename(self.rfile) self.rfile_split = os.path.split(self.rfile) self.rpath_split = os.path.split(self.rpath) self.rpath_basename = os.path.basename(self.rpath) self.rpath_dirname = os.path.dirname(self.rpath)
def project_template_filter(blueberrypy_config, path): if path.endswith(".html_tmpl"): return Jinja2Environment(block_start_string="<%", block_end_string="%>", variable_start_string="<<", variable_end_string=">>", comment_start_string="<#", comment_end_string="#>") if path.endswith("_tmpl"): path = path[:-5] if path.endswith("rest_controller.py"): return blueberrypy_config.get("use_rest_controller") if path.endswith("controller.py") or path.find("static") != -1: return blueberrypy_config.get("use_controller") if path.find("/templates") != -1: return blueberrypy_config.get("use_controller") and \ blueberrypy_config.get("use_jinja2") if path.endswith("bundles.yml"): return blueberrypy_config.get("use_webassets") if path.endswith(".hidden"): return False if path.endswith("model.py") or path.endswith("api.py"): return blueberrypy_config.get("use_sqlalchemy") return True
def readVandFitfromTPV(): # TO BE USED IN updatefTPV directory, output, volume, Cgeo = TAQtGuiFunctions.getConfTxt() list_of_v_exp = [] list_of_t_fit = [] list_of_v_exp_fit = [] list_of_fit = [] t_exp, t_fit, v_exp_fit, fit = [], [], [], [] for path in glob.glob(output+'*'): if path.find('V_TPV') > 0 : t_exp, v_exp = [], [] with open(path,'r') as f: for linenumber,line in enumerate(f.readlines()): if linenumber > 3 : t_exp.append(1e6*float(line.split(' , ')[0])) v_exp.append(float(line.split(' , ')[2])) list_of_v_exp.append(v_exp) if path.find('Fit_TPV') > 0 : t_fit, v_exp_fit, fit = [], [], [] with open(path,'r') as f: for linenumber,line in enumerate(f.readlines()): if linenumber > 3 : t_fit.append(1e6*float(line.split(' , ')[0])) v_exp_fit.append(float(line.split(' , ')[1])) fit.append(float(line.split(' , ')[2])) list_of_t_fit.append(t_fit) list_of_v_exp_fit.append(v_exp_fit) list_of_fit.append(fit) return t_exp, list_of_v_exp, list_of_t_fit, list_of_v_exp_fit, list_of_fit
def cleanResourcePath(path): newPath = path if path.find("package://") == 0: newPath = newPath[len("package://"):] pos = newPath.find("/") if pos == -1: rospy.logfatal("%s Could not parse package:// format", path) quit(1) package = newPath[0:pos] newPath = newPath[pos:] package_path = rospkg.RosPack().get_path(package) if package_path == "": rospy.logfatal("%s Package [%s] does not exist", path.c_str(), package.c_str()); quit(1) newPath = package_path + newPath; elif path.find("file://") == 0: newPath = newPath[len("file://"):] if not os.path.isfile(newPath): rospy.logfatal("%s file does not exist", newPath) quit(1) return newPath;
def _absoluteToRelative(path, reference, dots): if path.find(reference) > -1: ending = path.find(reference) + len(reference) return dots + path[ending:] else: return _absoluteToRelative(path, os.path.dirname(reference), "/.." + dots)
def get(self, path): prefix = path[:path.find('\\')] prefix = path[:path.find('/')] trailing = path[path.find('\\')+1:] trailing = path[path.find('/')+1:] components = os.path.split(trailing) directory = components[0] filename = components[1] if prefix=='thumbnail': directory = TrainingSummary().get_thumbnail_dir() elif prefix=='model': directory = os.path.normpath(os.path.join(TrainingSummary().get_model_dir(), directory)) inpath = os.path.normpath(os.path.join(directory, filename)) try: with open(inpath, 'rb') as imgf: modified = datetime.datetime.fromtimestamp(os.path.getmtime(inpath)) self.set_header('Last-Modified', modified) self.set_header('Expires', datetime.datetime.utcnow() + \ datetime.timedelta(days=1)) self.set_header("Cache-Control", 'max-age=' + str(86400*1)) header = 'image/jpeg' self.add_header('Content-Type', header) self.write(imgf.read()) return except Exception: print('I/O Exception:', inpath) pass self.clear() self.set_status(404) self.finish('Image not found')
def get_first_subdir_component(path): """Helper used in extracting the first subdirectory from an archive toc. It expects a relative path. >>> import os >>> p1 = "." + os.sep + "foo" + os.sep + "bar" >>> get_first_subdir_component(p1) 'foo' >>> p2 = "foo" + os.sep + "bar" >>> get_first_subdir_component(p2) 'foo' >>> get_first_subdir_component("foo") 'foo' >>> p3 = "foo" + os.sep >>> get_first_subdir_component(p3) 'foo' >>> p4 = os.sep + "foo" + os.sep + "bar" >>> print get_first_subdir_component(p4) None """ if os.path.isabs(path): return None if path.find(_dotslash)==0: path = path[_dotslashlen:] if len(path)==0 or (path=="."): return None idx = path.find(os.sep) if idx==-1: return path else: return path[0:idx]
def on_query_completions(self, view, prefix, locations): window=sublime.active_window() view=window.active_view() self.clases=set() lang=utils.get_language() if lang=="html" or lang=="php": punto=view.sel()[0].a linea=view.substr(sublime.Region(view.line(punto).a, punto)).replace('"', "'") linea=linea[:linea.rfind("'")].strip() print("la linea es :"+linea) if linea.endswith("class="): print("en compass") cssFiles=utils.get_files({"ext":"css"}) self.clases=[] for cssFile in cssFiles: texto=open(cssFile).read() cssClases=re.findall("\.(?P<clase>[a-z][-\w]*)\s+", texto) self.clases=self.clases + cssClases self.clases=list(set(self.clases)) self.clases=[[clase + "\t(CSS)", clase] for clase in self.clases] return list(self.clases) linea=view.substr(sublime.Region(view.line(punto).a, punto)).replace('"', "'").strip() if linea.endswith("src='") and linea.startswith("<script"): path=view.file_name() path=path[:path.rfind("/")] if path.find("/")!=-1 else path[:path.rfind("\\")] RecursosHtml(path, "js").insertar() elif linea.endswith("href='") and linea.startswith("<link "): path=view.file_name() path=path[:path.rfind("/")] if path.find("/")!=-1 else path[:path.rfind("\\")] RecursosHtml(path, "css").insertar()
def resolve_package(path): '''Resolves `package://` URLs to their canonical form. The path does not need to exist, but the package does. Can be used to write new files in packages. Returns "" on failure. ''' if not path: return '' package_name = '' package_path1 = '' PREFIX = 'package://' if PREFIX in path: path = path[len(PREFIX):] # Remove 'package://' if '/' not in path: package_name = path path = '' else: package_name = path[:path.find('/')] path = path[path.find('/'):] if have_rospkg: rospack = rospkg.RosPack() package_path1 = rospack.get_path(package_name) else: package_path1 = subprocess.check_output( ["rospack", "find", package_name]).decode().strip() elif '~' in path: path = os.path.expanduser(path) new_path = os.path.realpath(package_path1 + path) return new_path
def diffFile(self, filetopatch, branch): self.loggreen("%s to branch %s" % (filetopatch.GetName(), branch)) path=filetopatch.GetFullName() index = path.find("eTenderSuite") if index == -1: msg = "Wrong file: %s cancel?" % filetopatch title = "Cancel?" if cvsgui.App.CvsAlert('Question', msg, 'Yes', 'No', '', '', title) != 'IDOK': return endindex = path.find("\\",index+1,len(path)) oldetenderSuit = path[index:endindex] newpath= path.replace(oldetenderSuit,branch) if os.path.exists(newpath): #diff p_extdiff = Persistent('P_Extdiff', '', 0) extdiff = str(p_extdiff) args = ['"%s"' % newpath, '"%s"' % path] args.insert(0, '"%s"' % extdiff) self.loggreen("try diff %s : %s -------> %s" % (extdiff, path, newpath)) if extdiff <> '' and os.path.exists(extdiff): os.spawnl(os.P_NOWAIT, extdiff, *args) time.sleep(0.5) else: self.logerror("External diff tool not found: %s" %extdiff) else: self.logerror("Other file does not exist: %s" %newpath)
def getHTMLFile(curdir, path): defaultAppendix = ['html','htm'] idx = path.find('?') if idx != -1: path = path[:path.find('?')] print 'no ? path =',path if path == '/': # Check for existence of default files. for item in defaultAppendix: #print curdir+path+'index.'+item if os.path.isfile(curdir+path+'index.'+item) == True: return curdir+path+'index.'+item else: if os.path.isfile(curdir+path) == True: return curdir+path # Append html or htm as default if we can't find any match for given filename for item in defaultAppendix: # handle htm <-> html idx = path.find('.htm') if idx != -1: path = path[:path.index('.htm')] print 'handled path',path if os.path.isfile(curdir+path+'.'+item) == True: return curdir+path+'.'+item return ''
def set_invgen_Experiments(path, arguments): arguments.extend([ "--horn-ice-c5-exec-path=C50/c5.0.dt_entropy", "--horn-ice-svm-exec-path=libsvm/svm-invgen" ]) arguments.extend(["--horn-ice-svm-coeff-bound=5"]) # For programs with multiple loops, it is a good idea to unroll CHCs a small nubmer of steps to accerlate # sampling positive data. For instance, the mergesort aglorithm. if (path.find("nested") != -1): arguments.extend(["--horn-rule-sample-length=10"]) elif (path.find("mergesort") != -1): arguments.extend([ "--horn-rule-sample-length=10", "--horn-ice-local-strengthening=1" ]) elif (path.find("seq-len") != -1): arguments.extend([ "--horn-rule-sample-length=10", "--horn-ice-svm-call-freq-pos=0", "--horn-ice-svm-call-freq-neg=30" ]) elif (path.find("split") != -1): arguments.extend([ "--horn-rule-sample-length=100", "--horn-ice-svm-call-freq-pos=0", "--horn-ice-svm-call-freq-neg=30" ]) else: arguments.extend([ "--horn-rule-sample-length=1", "--horn-ice-svm-call-freq-pos=0", "--horn-ice-svm-call-freq-neg=30" ]) return arguments
def refine_path(path): path = "/" + path if path.find('home') != -1: #getting user name to get home directory path out = sp.run(['echo $USER'], shell=True, stdout=sp.PIPE, stderr=sp.PIPE) user = out.stdout.decode().replace("\n", "") path = path.replace("home", "home/" + user) elif path.find('current', 0) != -1: #getting current directory path out = sp.run(['pwd'], shell=True, stdout=sp.PIPE, stderr=sp.PIPE) curr_dir = out.stdout.decode().replace("\n", "") path = path.replace("/current", curr_dir) #checking dir location exixts or not if not os.path.isdir(path): tts.convert_text_n_speak( "Sorry Location is invalid please check and try again") return print(path) return path
def readIandQfromTPC(): # TO BE USED IN updatefTPC() directory, output, volume, Cgeo = TAQtGuiFunctions.getConfTxt() list_of_i = [] list_of_q = [] ti, i = [], [] tq, q = [], [] for path in glob.glob(output+'*'): if path.find('I_TPC') > 0 : ti, i = [], [] with open(path,'r') as f: for linenumber,line in enumerate(f.readlines()): if linenumber > 3 : ti.append(1e6*float(line.split(' , ')[0])) i.append(float(line.split(' , ')[2])) list_of_i.append(i) if path.find('Q_TPC') > 0 : tq, q = [], [] with open(path,'r') as f: for linenumber,line in enumerate(f.readlines()): if( linenumber > 3 ): tq.append(1e6*float(line.split(' , ')[0])) q.append(1e9*float(line.split(' , ')[1])) list_of_q.append(q) return ti, list_of_i, tq, list_of_q
def resolve_package(path): '''Resolves `package://` URLs to their canonical form. The path does not need to exist, but the package does. Can be used to write new files in packages. Returns "" on failure. ''' if not path: return "" package_name = "" package_path1 = "" PREFIX = "package://" if PREFIX in path: path = path[len(PREFIX):] # Remove "package://" if "/" not in path: package_name = path path = "" else: package_name = path[:path.find("/")] path = path[path.find("/"):] package_path1 = subprocess.check_output( ["rospack", "find", package_name]).decode().strip() elif "~" in path: path = os.path.expanduser(path) new_path = os.path.realpath(package_path1 + path) return new_path
def test_create_mapimage_using_post(self, **kwargs): import Image, tempfile image = Image.new('RGB', (100, 100)) tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg') image.save(tmp_file) with open(tmp_file.name, 'rb') as data: response = self.client_user.post( self.urls[0], { 'project_id': self.project.id, 'media_file' : data }, HTTP_X_CSRFTOKEN=self.csrf_token ) self.assertEqual(status.HTTP_201_CREATED, response.status_code) # a few more checks to make sure that file paths are being # generated correctly: new_object = models.MapImage.objects.get(id=response.data.get("id")) file_name = tmp_file.name.split("/")[-1] file_name = unicode(file_name, "utf-8") path = new_object.encrypt_url(new_object.file_name_new) self.assertEqual(file_name, new_object.name) self.assertEqual(new_object.status.id, models.StatusCode.READY_FOR_PROCESSING) self.assertEqual(len(new_object.uuid), 8) self.assertEqual(file_name, new_object.file_name_orig) self.assertTrue(len(new_object.file_name_new) > 5) #ensure not empty self.assertEqual(settings.SERVER_HOST, new_object.host) self.assertNotEqual(path.find('/profile/map-images/'), -1) self.assertNotEqual(path.find(new_object.host), -1) self.assertTrue(len(path.split('/')[-2]) > 40) # and also check the file exists in the file system: fname = new_object.original_image_filesystem() self.assertTrue(fname.find(new_object.uuid) > -1) self.assertTrue(os.path.isfile(fname))
def getBoneNameAndAction(path): if not path.find('"') or not path.find('.'): print( "Could not find correct format for animation data path, skipping this key: ", path) return ['false', 'false'] return [path.split('"')[1], path.split('.')[-1]]
def lookForFiles() : directory, output, volume, Cgeo = getConfTxt() isThereACalibrationFile = False for path in glob.glob(directory+'*'): path = windowsFilenamesSuck(path) if path.find('jsc_') > 0 : isThereACalibrationFile = True CEFiles = 0 CEsuns = [] for path in glob.glob(directory+'*'): path = windowsFilenamesSuck(path) if path.find('CE_') > 0 : CEFiles += 1 CEsuns.append(float(path.split("_")[-1][:-9])) # COUNT THE NUMBER OF TPC FILES ARE PRESENT IN INPUT DIR TPCFiles = 0 TPCsuns = [] for path in glob.glob(directory+'*'): path = windowsFilenamesSuck(path) if path.find('TPC_') > 0 : TPCFiles += 1 TPCsuns.append(float(path.split("_")[-1][:-9])) # COUNT THE NUMBER OF TPV FILES ARE PRESENT IN INPUT DIR TPVFiles = 0 TPVsuns = [] for path in glob.glob(directory+'*'): path = windowsFilenamesSuck(path) if path.find('TPV_') > 0 : TPVFiles += 1 TPVsuns.append(float(path.split("_")[-1][:-9])) return isThereACalibrationFile, CEFiles, CEsuns, TPCFiles, TPCsuns, TPVFiles, TPVsuns
def AddResFile(collection, path): # There are two consumers of the the input .txt file: this script and # icupkg. We only care about .res files, but icupkg needs files they depend # on too, so it's not an error to have to ignore non-.res files here. end = path.find(".res") if end > 0: collection.add(path[path.find("/")+1:end]) return
def AddResFile(collection, path): # There are two consumers of the the input .txt file: this script and # icupkg. We only care about .res files, but icupkg needs files they depend # on too, so it's not an error to have to ignore non-.res files here. end = path.find(".res") if end > 0: collection.add(path[path.find("/") + 1:end]) return
def is_path_exists(self, path, check_type = 'FILE'): """ @path[string]: the path you want to check exists or not @check_type[string]: the type you check, FILE(default) or FOLDER If the path exists in the VM, return True, else return False """ if self.__login_flag == False: print 'Path check error: Sorry, but please login the VM first.' return False if check_type not in ['FILE', 'FOLDER']: print "Check path error: check_type must be set as 'FILE' or 'FOLDER'" return False if path.endswith('\\'): path = path[:-1] if path.find('\\') != -1 and path.find('/') != -1: print "Check path error: path must be set as 'c:\\temp\\file.file' or 'c:/temp/file.file'" return False if path.find('\\') != -1: location = path[0:path.rfind('\\')] check_item = path[path.rfind('\\')+1:].lower() if (check_item is None) or (check_item == ""): return False try: tmp_list = self.list_files(location) except Exception as e: raise e if check_type == 'FOLDER': if tmp_list is not None: for item in tmp_list: if item['path'].lower() == check_item and item['type'] == 'directory': return True return False elif check_type == 'FILE': if tmp_list is not None: for item in tmp_list: if item['path'].lower() == check_item and item['type'] == 'file': return True return False elif path.find('/') != -1: location = path[0:path.rfind('/')] check_item = path[path.rfind('/')+1:].lower() if (check_item is None) or (check_item == ""): return False try: tmp_list = self.list_files(location) except Exception, e: raise e if check_type == 'FOLDER': if tmp_list is not None: for item in tmp_list: if item['path'].lower() == check_item and item['type'] == 'directory': return True return False elif check_type == 'FILE': if tmp_list is not None: print ".........not valid "
def set_dillig_TACAS13_Experiments(path, arguments): arguments.extend(["--horn-ice-c5-exec-path=C50/c5.0.dt_entropy", "--horn-ice-svm-exec-path=libsvm/svm-invgen"]) arguments.extend(["--horn-ice-svm-coeff-bound=5", "--horn-rule-sample-length=1"]) arguments.extend(["--horn-ice-svm-call-freq-pos=0", "--horn-ice-svm-call-freq-neg=10"]) arguments.extend(["--horn-ice-local-strengthening=1"]) # benchmarks need invariants involving mod (%) operation if (path.find("benchmark2") != -1 or path.find("benchmark5") != -1 or path.find("benchmark6") != -1 or path.find("benchmark7") != -1): arguments.extend(["--horn-ice-mod=1"]) return arguments
def is_path_exists(self, path, check_type = 'FILE'): """ @path[string]: the path you want to check exists or not @check_type[string]: the type you check, FILE(default) or FOLDER If the path exists in the VM, return True, else return False """ if self.__login_flag == False: print 'Path check error: Sorry, but please login the VM first.' return False if check_type not in ['FILE', 'FOLDER']: print "Check path error: check_type must be set as 'FILE' or 'FOLDER'" return False if path.endswith('\\'): path = path[:-1] if path.find('\\') != -1 and path.find('/') != -1: print "Check path error: path must be set as 'c:\\temp\\file.file' or 'c:/temp/file.file'" return False if path.find('\\') != -1: location = path[0:path.rfind('\\')] check_item = path[path.rfind('\\')+1:].lower() if (check_item is None) or (check_item == ""): return False try: tmp_list = self.list_files(location) except Exception as e: raise e if check_type == 'FOLDER': if tmp_list is not None: for item in tmp_list: if item['path'].lower() == check_item and item['type'] == 'directory': return True return False elif check_type == 'FILE': if tmp_list is not None: for item in tmp_list: if item['path'].lower() == check_item and item['type'] == 'file': return True return False elif path.find('/') != -1: location = path[0:path.rfind('/')] check_item = path[path.rfind('/')+1:].lower() if (check_item is None) or (check_item == ""): return False try: tmp_list = self.list_files(location) except Exception, e: raise e if check_type == 'FOLDER': if tmp_list is not None: for item in tmp_list: if item['path'].lower() == check_item and item['type'] == 'directory': return True return False elif check_type == 'FILE': if tmp_list is not None:
def extract_language_from_path(path): language = None start = path.find('/pages/') if start != -1: start += 7 end = path.find('/', start) if end != -1: language = path[start:end] return language
def cache_base(path): path = trim_base(path).replace('/', '-').replace(' ', '_').replace('(', '').replace('&', '').replace(',', '').replace(')', '').replace('#', '').replace('[', '').replace(']', '').replace('"', '').replace("'", '').replace('_-_', '-').lower() while path.find("--") != -1: path = path.replace("--", "-") while path.find("__") != -1: path = path.replace("__", "_") if len(path) == 0: path = "root" return path
def read_input(path): if path.find('manual') > 0 or path.find('mask') > 0: x = np.array(Image.open(path)) / 255. else: x = np.array(Image.open(path)) / 255. if x.shape[-1] == 3: return x else: return x[..., np.newaxis]
def split_leading_dir(self, path): path = str(path) path = path.lstrip('/').lstrip('\\') if '/' in path and (('\\' in path and path.find('/') < path.find('\\')) or '\\' not in path): return path.split('/', 1) elif '\\' in path: return path.split('\\', 1) else: return path, ''
def find_file_type(path, root, fileName, filetype, addType): nameS = '' if path.find(filetype) != -1 and path.find('.meta') != -1: nameS = fileName.split(".")[0] filePath = root.split('langzh/')[1] i18n_string = (filePath) + "/" + (nameS) print(i18n_string) uuid = start_find_uuid(path, nameS) # 查找UUID是否被使用 if uuid: open_prefab(path, i18n_string, addType, "", "", "")
def cache_base(path, filepath=False): if len(path) == 0: return "root" elif filepath and len(path.split(os.sep)) < 2: path = "root-" + path path = trim_base(path).replace('/', '-').replace(' ', '_').replace('(', '').replace('&', '').replace(',', '').replace(')', '').replace('#', '').replace('[', '').replace(']', '').replace('"', '').replace("'", '').replace('_-_', '-').lower() while path.find("--") != -1: path = path.replace("--", "-") while path.find("__") != -1: path = path.replace("__", "_") return path
def Run(self, path, arguments, environment=None, timeout=-1, relative=False): default_dir = self.default_dir if not default_dir: default_dir = os.curdir if relative or ( not os.path.isabs(path) and (path.find(os.path.sep) != -1 or (os.path.altsep and path.find(os.path.altsep) != -1)) ): path = os.path.join(default_dir, path) path, arguments = self._FormSSHCommandLine(path, arguments, environment) return super(SSHHost, self).Run(path, arguments, None, timeout)
def Run(self, path, arguments, environment = None, timeout = -1, relative = False): if (relative or (not os.path.isabs(path) and (path.find(os.path.sep) != -1 or (os.path.altsep and path.find(os.path.altsep) != -1)))): path = os.path.join(os.curdir, path) arguments = self.command_args + [path] + arguments return local_host.LocalHost.Run(self, self.command, arguments, environment, timeout)
def cache_base(path, withoutslash=True): path = trim_base(path) if withoutslash: path = path.replace('/', '-') path = path.replace(' ', '_').replace('(', '').replace('&', '').replace(',', '').replace(')', '').replace('#', '').replace('[', '').replace(']', '').replace('"', '').replace("'", '').replace('_-_', '-').lower() while path.find("--") != -1: path = path.replace("--", "-") while path.find("__") != -1: path = path.replace("__", "_") if len(path) == 0: path = "root" return path
def cache_base(path): path = trim_base(path).replace(os.sep, '-').replace(' ', '_').\ replace('(', '').replace('&', '').replace(',', '').\ replace(')', '').replace('#', '').replace('[', '').\ replace(']', '').replace('"', '').replace("'", '').\ replace('_-_', '-').lower() while path.find("--") != -1: path = path.replace("--", "-") while path.find("__") != -1: path = path.replace("__", "_") if not path: path = "root" return path
def findPath(): try: path = str(raw_input("inserire il path assoluto del file >")) path.strip() if(os.path.isfile(path) != True or ((path.find("war") == -1) and (path.find("ear") == -1))): raise EapManagerException("ERRORE: il percorso non punta a un file valido") name = str(raw_input("inserire il nome dell'applicazione >")) return (path,name) except ValueError: raise EapManagerException("ERRORE: Inserire una stringa")
def EUPSManifestService(): path = os.environ["PATH_INFO"] if (path is None or len(path) == 0): raise ValueError, "no manifest file provided" # sys.stderr.write("path: %s" % path) ldr = Loader(pkgsdir) ldr.strict = False if path.endswith(".manifest"): path = path[:-len(".manifest")] if path.startswith("/"): path = path[1:] dir = None if path.find("/") > 0: # (dir, path) = path.rsplit("/", 1) dir = os.path.dirname(path) path = os.path.basename(path) if path.find("-") >= 0: (pkg, version) = path.split("-", 1) else: pkg = path lu = ldr.lookupCurrent(pkg) if lu is None or len(lu) == 0: raise ValueError, pkg + ": current version for package not found: " version = lu[0] if len(pkg) == 0 or len(version) == 0: raise ValueError, "bad manifest file name: " + os.environ["PATH_INFO"] flavor = dir if flavor is None or len(flavor) == 0: flavor = "generic" out = Manifest(pkg, version, flavor) try: ldr.load(out) sys.stdout.write("Content-type: text/plain\n\n") out.printRecord(sys.stdout) sys.stdout.close() except IOError, e: if e.errno == errno.ENOENT: # this is a hack to return a 404 response sys.stdout.write("Location: /manifests%s\n\n" % os.environ["PATH_INFO"]) else: raise e
def handle_starttag(self, tag, attrs): if tag == "meta": val = self.extract(attrs, "videourl") if val: self.values.videoUrl = val val = self.extract(attrs, "videourl_mp4") if val: self.values.videoUrlMP4 = val val = self.extract(attrs, "videourl_h264") if val: self.values.videoUrlH264 = val val = self.extract(attrs, "videourl_m3u8") if val: self.values.videoUrlM3U8 = val val = self.extract(attrs, "title") if val: self.values.title = val val = self.extract(attrs, "programmaTV") if val: self.values.program = val val = self.extract(attrs, "description") if val: self.values.description = val val = self.extract(attrs, "tipo") if val: self.values.type = val val = self.extract(attrs, "itemDate") if val: self.values.date = val val = self.extract(attrs, "idPageProgramma") if val: self.values.page = RAIUrls.base + RAIUrls.getWebFromID(val) elif tag == "param": if len(attrs) > 0: if attrs[0][0] == "value": path = attrs[0][1] if path.find("videoPath") == 0: firstEqual = path.find("=") firstComma = path.find(",") self.values.videoPath = path[firstEqual + 1: firstComma]
def handle_starttag(self, tag, attrs): if tag == "meta": val = self.extract(attrs, "videourl") if val: self.values.videoUrl = val val = self.extract(attrs, "videourl_mp4") if val: self.values.videoUrlMP4 = val val = self.extract(attrs, "videourl_h264") if val: self.values.videoUrlH264 = val val = self.extract(attrs, "videourl_m3u8") if val: self.values.videoUrlM3U8 = val val = self.extract(attrs, "title") if val: self.values.title = val val = self.extract(attrs, "programmaTV") if val: self.values.program = val val = self.extract(attrs, "description") if val: self.values.description = val val = self.extract(attrs, "tipo") if val: self.values.type = val val = self.extract(attrs, "itemDate") if val: self.values.date = val val = self.extract(attrs, "idPageProgramma") if val: self.values.page = RAIUrls.base + RAIUrls.getWebFromID(val) elif tag == "param": if len(attrs) > 0: if attrs[0][0] == "value": path = attrs[0][1] if path.find("videoPath") == 0: firstEqual = path.find("=") firstComma = path.find(",") self.values.videoPath = path[firstEqual + 1:firstComma]
def set_recursvie_Experiments(path, arguments): # arguments.extend(["--horn-ice-c5-exec-path=C50/c5.0"]) arguments.extend([ "--horn-ice-c5-exec-path=C50/c5.0", "--horn-ice-svm-exec-path=libsvm/svm-invgen", "--horn-ice-z3-exec-path=z3latest/z3" ]) arguments.extend(["--horn-ice-svm-coeff-bound=5"]) arguments.extend( ["--horn-ice-svm-call-freq-pos=0", "--horn-ice-svm-call-freq-neg=10"]) if (path.find("Add") != -1 or path.find("sum") != -1): arguments.extend(["--horn-ice-svm-exec-path=libsvm/svm-invgen"]) # Benchmarks need invariants involving mod (%) operation if (path.find("EvenOdd") != -1): arguments.extend(["--horn-ice-mod=1"]) if ((path.find("fibo") != -1 or path.find("Fibo") != -1) and path.find("false") == -1): arguments.extend(["--horn-ice-local-strengthening=1"]) # For programs with multiple loops, it is a good idea to unroll CHCs a small nubmer of steps to accerlate # sampling positive data. For instance, the mergesort aglorithm. if (path.find("100") != -1): arguments.extend(["--horn-rule-sample-length=100"]) elif (path.find("200") != -1): arguments.extend(["--horn-rule-sample-length=200"]) else: arguments.extend(["--horn-rule-sample-length=1"]) return arguments
def _get_first_subdir_component(path): """Helper used in extracting the first subdirectory from an archive toc. It expects a relative path. """ _dotslash = "." + os.sep _dotslashlen = len(_dotslash) if os.path.isabs(path): return None if path.find(_dotslash)==0: path = path[_dotslashlen:] if len(path)==0 or (path=="."): return None idx = path.find(os.sep) if idx==-1: return path else: return path[0:idx]
def unsafe_photo_carousel_html_generator(unsafe_photo_paths: list) -> str: html = """<div class="carousel-item active"><img class="carousel-center" src="assets/images/unsafe_pictures/0.jpg"><div class="carousel-caption d-none d-md-block"><p></p></div></div>""" html_item_start = """<div class="carousel-item"><img class="carousel-center" src="assets/images/unsafe_pictures/""" html_item_mid = """.jpg"><div class="carousel-caption d-none d-md-block"><p>""" html_item_end = """</p></div></div>""" iterator = 1 for path in unsafe_photo_paths: photo_caption = "in conversation: " + path[path.find("inbox/") + 6:path.find("_")].replace( "and", " and ") html += html_item_start + str( iterator) + html_item_mid + photo_caption + html_item_end iterator += 1 return html
def get_output(path): #img_id = path.split('/')[-1].split('.')[0] #img_id = np.int64(img_id) if path.find("thumb") != -1: labels = 0 elif path.find("mine") != -1: labels = 1 elif path.find("gta") != -1: labels = 2 elif path.find("star") != -1: labels = 3 categorical_labels = to_categorical(labels, num_classes=4) return (categorical_labels)
def Run(self, path, arguments, environment=None, timeout=-1, relative=False): if (relative or (not os.path.isabs(path) and (path.find(os.path.sep) != -1 or (os.path.altsep and path.find(os.path.altsep) != -1)))): path = os.path.join(os.curdir, path) arguments = self.command_args + [path] + arguments return local_host.LocalHost.Run(self, self.command, arguments, environment, timeout)
def setTestSuite(dname, suite): testSuiteList = {} for dirname, dirnames, filenames in os.walk(dname): for subdirname in dirnames: if subdirname in elem2Test.keys(): path = os.path.join(dirname, subdirname) run_sh = path + "/" + elem2Test[subdirname] if(os.access(run_sh, os.X_OK)): if(suite != "all"): if(path.find(suite) > -1): testSuiteList[suite] = path else: if(path.find(subdirname) > -1): testSuiteList[subdirname] = path return testSuiteList
def setTestSuite(dname, suite): testSuiteList = {} for dirname, dirnames, filenames in os.walk(dname): for subdirname in dirnames: if subdirname in elem2Test.keys(): path = os.path.join(dirname, subdirname) run_sh = path + "/" + elem2Test[subdirname] if (os.access(run_sh, os.X_OK)): if (suite != "all"): if (path.find(suite) > -1): testSuiteList[suite] = path else: if (path.find(subdirname) > -1): testSuiteList[subdirname] = path return testSuiteList
def Run(self, path, arguments, environment = None, timeout = -1, relative = False): default_dir = self.default_dir if not default_dir: default_dir = os.curdir if (relative or (not os.path.isabs(path) and (path.find(os.path.sep) != -1 or (os.path.altsep and path.find(os.path.altsep) != -1)))): path = os.path.join(default_dir, path) path, arguments = self._FormSSHCommandLine(path, arguments, environment) return super(SSHHost, self).Run(path, arguments, None, timeout)
def _load_file(self, path): self._internal_link = None if path.find('#') > -1: self._internal_link = path[path.find('#'):] path = path[:path.find('#')] for filepath in self._filelist: if filepath.endswith(path): self._view.load_uri('file://' + filepath) oldpage = self._loaded_page self._loaded_page = \ self._paginator.get_base_pageno_for_file(filepath) self._scroll_page() self._on_page_changed(oldpage, self._loaded_page) break
def leading_dirs(path): '''Return a set containing each directory in absolute path path, except for the root directory. For example: >>> sorted(leading_dirs('/a/b/c')) ['/a', '/a/b'] >>> pprint(leading_dirs('/a')) set() >>> leading_dirs('') Traceback (most recent call last): ... ValueError: path must have at least one element >>> leading_dirs('/') Traceback (most recent call last): ... ValueError: path must have at least one element >>> leading_dirs('//') Traceback (most recent call last): ... ValueError: path // contains adjacent slashes >>> leading_dirs('a/b/c') Traceback (most recent call last): ... ValueError: path a/b/c is not absolute''' if (len(path) <= 1): raise ValueError('path must have at least one element') if (path[0] != '/'): raise ValueError('path %s is not absolute' % (path)) if (path.find('//') != -1): raise ValueError('path %s contains adjacent slashes' % (path)) ldirs = set() dirs = path.split('/')[1:-1] for di in range(len(dirs)): ldirs.add('/' + '/'.join(dirs[:di+1])) return ldirs
def execute(self): cf = self.fm.thisfile path = cf.relative_path.replace("%", "%%") if path.find('.') != 0 and path.rfind('.') != -1 and not cf.is_directory: self.fm.open_console('rename ' + path, position=(7 + path.rfind('.'))) else: self.fm.open_console('rename ' + path)
def ami_abs_path(self, path): """return absolute amiga path from given path""" # current dir if path == "": return self.cur_vol + ":" + self.cur_path col_pos = path.find(':') # already with device name if col_pos > 0: return path # relative to cur device elif col_pos == 0: abs_prefix = self.cur_vol + ":" path = path[1:] # invalid parent path of root? -> remove if len(path)>0 and path[0] == '/': path = path[1:] # no path given -> return current path elif path == '': return self.cur_vol + ":" + self.cur_path # a parent path is given elif path[0] == '/': abs_prefix = self.cur_vol + ":" + self.cur_path while len(path)>0 and path[0] == '/': abs_prefix = self.ami_abs_parent_path(abs_prefix) path = path[1:] if path != "": abs_prefix += "/" # cur path else: abs_prefix = self.cur_vol + ":" + self.cur_path if self.cur_path != '': abs_prefix += '/' return abs_prefix + path
def createTable(dir) : table_probability_bad = {} table_probability_good = {} table_good = {} table_bad = {} paths = os.listdir(dir) numberOfSpam = 0 numberOfNonSpam = 0 for path in paths : path = dir + "/" + path table, number = calculate(path) pos = path.find("spam") if pos == -1 : for item in table.keys() : if item in table_good.keys() : table_good[item] += table[item] else : table_good[item] = table[item] numberOfNonSpam += number else : for item in table.keys() : if item in table_bad.keys() : table_bad[item] += table[item] else : table_bad[item] = table[item] numberOfSpam += number print "Training set:\nnon-spam size: " + str(numberOfNonSpam) +" emails\nspam size: " + str(numberOfSpam) + " emails\n" for item in table_bad.keys() : if item in table_good.keys() :
def getJscCal(self): # READ THE LIGHT LEVEL CALIBRATION FILE directory, output, volume, Cgeo = getConfTxt() for path in glob.glob(directory+'*'): if path.find("jsc_cal") > 0 : with open(path,'r') as f: suns,jsc,jsc_rev,voc,voc_rev,rev = [],[],[],[],[],0 for linenumber,line in enumerate(f.readlines()): if linenumber >= 21 : if len(suns) > 0 and float(line.split()[0]) == suns[-1] : rev=1 if rev : jsc_rev.append(np.abs(float(line.split()[4]))) voc_rev.append(float(line.split()[5])) else: suns.append(float(line.split()[0])) jsc.append(np.abs(float(line.split()[4]))) voc.append(float(line.split()[5])) jsc_rev=list(reversed(jsc_rev)) voc_rev=list(reversed(voc_rev)) initial_time = strftime("%Y-%m-%d %H:%M:%S",gmtime()) with open(output+"Summary.txt",'w') as fit: fit.write('Data calculated at %s \n' % (initial_time)) fit.write('Light Intensity , Jsc , Jsc rev , Voc , Voc rev\n') fit.write('Suns , mA , mA , V , V\n') fit.write('suns_LLC , jsc_LLC , jsc_rev_LLC , voc_LLC , voc_rev_LLC\n') fit.writelines('%0.2f , %e , %e , %e , %e\n' % (a,b,c,d,e) for a,b,c,d,e in zip(suns,jsc,jsc_rev,voc,voc_rev)) return