How to use absolutePath method in storybook-root

Best JavaScript code snippet using storybook-root

common_modules.py

Source:common_modules.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2""" Some common modules for this project."""3import os4import sys5import json6import time7import itertools8import collections9import pickle10import shutil11import dill12import numpy as np13import scipy.sparse14import scipy.io15import networkx as nx16from networkx.readwrite import json_graph17import logging18logging.basicConfig(level=logging.INFO,filename="LogFile.log",filemode="a",19 format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s: %(message)s',20 datefmt='%Y/%m/%d %H:%M:%S')21ErrorHandler = logging.StreamHandler()22ErrorHandler.setLevel(logging.ERROR)23ErrorHandler.setFormatter(logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s: %(message)s'))24logger = logging.getLogger()25logger.addHandler(ErrorHandler)26import Modules.progressbar.progressbar as progressbar27import Modules.progressbar.widgets as progressbar_widgets28class ProgressBar(object):29 def __init__(self):30 self.TotalResults = []31 self.NumberOfFinishedResults = 032 33 def Update(self):34 self.ProgressBar.update(self.NumberOfFinishedResults)35 return 36 def CallbackForProgressBar(self, res = ''): 37 """38 Callback function for pool.async if the progress bar needs to be displayed.39 Must use with DisplayProgressBar function.40 :param multiprocessing.pool.AsyncResult res: Result got from callback function in pool.async.41 """42 self.NumberOfFinishedResults += 143 self.TotalResults.append(res)44 return45 def DisplayProgressBar(self, ProcessingResults, ExpectedResultsSize, CheckInterval = 1, type = "minute"):46 '''47 Display a progress bar for multiprocessing. This function should be used after pool.close(No need to use pool.join anymore). 48 The call back function for pool.async should be set as CallbackForProgressBar.49 :param multiprocessing.pool.AsyncResult ProcessingResults: Processing results returned by pool.async.50 :param int ExpectedResultsSize: How many result you will reveive, i.e. the total length of progress bar.51 :param float CheckInterval: How many seconds will the progress bar be updated. When it's too large, the main program may hang there.52 :param String type: Three types: "minute", "hour", "second"; corresponds displaying iters/minute iters/hour and iters/second.53 '''54 self.ProcessingResults = ProcessingResults55 ProgressBarWidgets = [progressbar_widgets.Percentage(),56 ' ', progressbar_widgets.Bar(),57 ' ', progressbar_widgets.SimpleProgress(),58 ' ', progressbar_widgets.Timer(),59 ' ', progressbar_widgets.AdaptiveETA()]60 self.ProgressBar = progressbar.ProgressBar(ExpectedResultsSize, ProgressBarWidgets)61 self.StartTime = time.time()62 PreviousNumberOfResults = 063 self.ProgressBar.start()64 while self.ProcessingResults.ready()==False:65 self.Update()66 time.sleep(CheckInterval)67 time.sleep(CheckInterval)68 self.Update()69 self.ProgressBar.finish()70 self.EndTime = time.time()71 print "Processing finished."72 #print "Processing results: ", self.TotalResults73 print "Time Elapsed: %.2fs, or %.2fmins, or %.2fhours" % ((self.EndTime-self.StartTime),(self.EndTime-self.StartTime)/60,(self.EndTime-self.StartTime)/3600)74 logger.info("Processing finished.")75 logger.info("Processing results: "+ str(self.TotalResults))76 logger.info("Time Elapsed: %.2fs, or %.2fmins, or %.2fhours" % ((self.EndTime-self.StartTime),(self.EndTime-self.StartTime)/60,(self.EndTime-self.StartTime)/3600))77 return 78 #for i in progressbar.tqdm(range(ExpectedResultsSize),type=type):#Three types: iters/minute iters/hour and iters/second79 #while ProcessingResults.ready()==False:#While processing doesn't finish.80 #if self.NumberOfFinishedResults>PreviousNumberOfResults:81 # PreviousNumberOfResults += 182 # break 83 #else:84 # time.sleep(CheckInterval)#Define how many seconds between each check.85 86class DefaultOrderedDict(collections.OrderedDict):87 # Source: http://stackoverflow.com/a/6190500/56276988 def __init__(self, default_factory=None, *a, **kw):89 if (default_factory is not None and90 not isinstance(default_factory, collections.Callable)):91 raise TypeError('first argument must be callable')92 collections.OrderedDict.__init__(self, *a, **kw)93 self.default_factory = default_factory94 def __getitem__(self, key):95 try:96 return collections.OrderedDict.__getitem__(self, key)97 except KeyError:98 return self.__missing__(key)99 def __missing__(self, key):100 if self.default_factory is None:101 raise KeyError(key)102 self[key] = value = self.default_factory()103 return value104 def __reduce__(self):105 if self.default_factory is None:106 args = tuple()107 else:108 args = self.default_factory,109 return type(self), args, None, None, self.items()110 def copy(self):111 return self.__copy__()112 def __copy__(self):113 return type(self)(self.default_factory, self)114 def __deepcopy__(self, memo):115 import copy116 return type(self)(self.default_factory,117 copy.deepcopy(self.items()))118 def __repr__(self):119 return 'OrderedDefaultDict(%s, %s)' % (self.default_factory,120 collections.OrderedDict.__repr__(self))121def ListApkFiles(ApkDirectory):122 '''123Get the Apk file names for an ApkDirectory in a sorted order. Rerurn an empty list if ApkDirectory=="".124:param String ApkDirectory: absolute path of a apk file directory125:return ListOfApkFiles: The list of absolute paths of Apks under ApkDirectory126:rtype List[String]127 '''128 ListOfApkFiles=[]129 if(ApkDirectory==""):130 raise ValueError('Directory is empty!')131 filenames = os.listdir(ApkDirectory)132 for filename in filenames:133 #list filenames 134 #get the absolute path for the files135 AbsolutePath=os.path.abspath(os.path.join(ApkDirectory, filename))136 #get the absolute path for the files137 if os.path.splitext(filename)[1]==".apk":138 if os.path.isfile(AbsolutePath):139 ListOfApkFiles.append(AbsolutePath)140 return sorted(ListOfApkFiles)141def ListFiles(Directory, Extension):142 '''143 Given an extension, get the file names for a Directory in a sorted order. Rerurn an empty list if Directory == "".144 :param String Directory: absolute path of a file directory145 :param String Extension: Extension of the files you want. Better include "." in the Extension146 :return ListOfFiles: The list of absolute paths of the files you want under Directory147 :rtype List[String]148 '''149 ListOfFiles=[]150 if(Directory == "" or Directory == []):151 return []152 if(type(Directory) != list and os.path.isdir(Directory) == False):153 raise ValueError(Directory, 'Directory is not a directory!')154 if(type(Extension)!=str):155 raise ValueError(Extension, 'Extension is not a string!')156 if(Extension):157 if(Extension[0] != "."):158 Extension = "." + Extension[0]159 if type(Directory) == list:160 Directories = Directory161 for Directory in Directories:162 filenames = os.listdir(Directory)163 for filename in filenames:164 #list filenames 165 #get the absolute path for the files166 AbsolutePath=os.path.abspath(os.path.join(Directory, filename))167 #get the absolute path for the files168 if os.path.splitext(filename)[1]==Extension:169 if os.path.isfile(AbsolutePath):170 ListOfFiles.append(AbsolutePath)171 else:172 filenames = os.listdir(Directory)173 for filename in filenames:174 #list filenames 175 #get the absolute path for the files176 AbsolutePath=os.path.abspath(os.path.join(Directory, filename))177 #get the absolute path for the files178 if os.path.splitext(filename)[1]==Extension:179 if os.path.isfile(AbsolutePath):180 ListOfFiles.append(AbsolutePath)181 return sorted(ListOfFiles)182def ListAllFiles(Directory, Extension):183 '''184 Given an extension, get the file names for a Directory and all its sub-directories in a sorted order. Rerurn an empty list if Directory == "".185 :param String Directory: absolute path of a file directory186 :param String Extension: Extension of the files you want. Better include "." in the Extension187 :return ListOfFiles: The list of absolute paths of the files you want under Directory188 :rtype List[String]189 '''190 ListOfFiles=[]191 if(Directory == ""):192 raise ValueError(Directory, 'Directory is empty!')193 if(os.path.isdir(Directory) == False):194 raise ValueError(Directory, 'Directory is not a directory!')195 if(type(Extension)!=str):196 raise ValueError(Extension, 'Extension is not a string!')197 if(Extension):198 if(Extension[0] != "."):199 Extension = "." + Extension[0]200 for root, dirs, files in os.walk(Directory):201 for filename in files:202 #list filenames 203 #get the absolute path for the files204 AbsolutePath = os.path.join(root, filename)205 #get the absolute path for the files206 if os.path.splitext(filename)[1] == Extension:207 if os.path.isfile(AbsolutePath):208 ListOfFiles.append(AbsolutePath)209 return sorted(ListOfFiles)210def ListDirs(Directory):211 '''212 Get all sub-directory paths for a Directory in a sorted order. Rerurn an empty list if Directory == "". Modified from ListFiles(which means variable names remain the same...)213 :param String Directory: absolute path of a file directory214 :return ListOfFiles: The list of absolute paths of the sub-directories you want under the Directory215 :rtype List[String]216 '''217 ListOfFiles=[]218 if(Directory == ""):219 raise ValueError(Directory, 'Directory is empty!')220 if(os.path.isdir(Directory) == False):221 raise ValueError(Directory, 'Directory is not a directory!')222 filenames = os.listdir(Directory)223 for filename in filenames:224 #list filenames 225 #get the absolute path for the files226 AbsolutePath=os.path.abspath(os.path.join(Directory, filename))227 #get the absolute path for the files228 if os.path.isdir(AbsolutePath):229 ListOfFiles.append(AbsolutePath)230 return sorted(ListOfFiles)231 232 233def FileExist(FilePath):234 '''235 Given file path, determine a file exist or not.236 :param String FilePath: absolute path of a file or directory237 :rtype Boolean238 '''239 if os.path.exists(FilePath)==True:240 return True241 else:242 #if os.path.isdir(ApkFilePath)==False:243 # if(os.path.basename(ApkFilePath)) in os.listdir(os.getcwd()):244 # return True245 return False246def RemoveDirectory(Folder):247 '''248 Given Folder path, remove this folder(include all content inside).249 :param String Folder: absolute path of a directory250 :rtype Boolean251 '''252 if(FileExist(Folder) == False):253 raise IOError("Directory not found!")254 else:255 shutil.rmtree(Folder)256def ExportToJson(AbsolutePath, Content):257 '''258 Export something to json file. 259 Will automatic convert Set content into List.260 :param String AbsolutePath: absolute path to store the json file261 :param Variant Content: something you want to export262 '''263 try:264 if(isinstance(Content,set)):265 Content = list(Content)266 #if(isinstance(Content, collections.defaultdict)):267 # Content = dict(Content)268 f=open(AbsolutePath,"wb")269 # json.dump(Content, f, indent=4)270 for Key,Val in Content.items():271 for V in Val:272 print >>f, str(Key)+'_'+str(V)273 except Exception as e:274 print "Json data writing Failed."275 logger.error(e)276 logger.error("Json data writing Failed.")277 if "f" in dir():278 f.close()279 #sys.exit("Json data writing Failed.")280 else:281 logger.info("Json data of "+AbsolutePath+" written successfully.") 282 f.close()283def ExportToPkl(AbsolutePath,Content):284 '''285 Export something to pickle file. 286 Will automatic convert Set content into List.287 :param String AbsolutePath: absolute path to store the json file288 :param Variant Content: something you want to export289 '''290 try:291 if(isinstance(Content, set)):292 Content = list(Content)293 #if(isinstance(Content, collections.defaultdict)):294 # Content = dict(Content)295 f=open(AbsolutePath, "wb")296 pickle.dump(Content, f)297 except Exception, e:298 print "Pickle data writing Failed." + str(e)299 logger.error("Pickle data writing Failed.")300 if "f" in dir():301 f.close()302 #sys.exit("Json data writing Failed.")303 else:304 logger.info("Pickle data of " + AbsolutePath + " written successfully.") 305 f.close()306def ImportFromPkl(AbsolutePath):307 '''308 Import something from pickle file. 309 :param String AbsolutePath: absolute path of the pickle file310 :return Content: Content in the pickle file311 :rtype Variant312 ''' 313 try:314 File = open(AbsolutePath,"rb")315 Content = pickle.load(File)316 except:317 logger.error("Pickle data loading Failed.")318 if "File" in dir():319 File.close()320 #sys.exit("Json data loading Failed.") 321 else:322 logger.info("Pickle data of "+AbsolutePath+" loaded successfully.")323 File.close()324 return Content325def ExportToJsonNodeLinkData(AbsolutePath,GraphContent):326 '''327 Export graph node link date to json file. 328 :param String AbsolutePath: absolute path to store the json file329 :param nxGraph GraphContent: some graph you want to export330 ''' 331 try:332 f=open(AbsolutePath,"wb")333 Content=json_graph.node_link_data(GraphContent)334 json.dump(Content,f,indent=4)335 except Exception as e:336 print e337 logger.error("JsonNodeLinkData writing Failed.")338 if "f" in dir():339 f.close()340 #sys.exit("JsonNodeLinkData writing Failed.")341 else:342 logger.info("JsonNodeLinkData of "+AbsolutePath+" written successfully.")343 f.close()344def ExportToGML(AbsolutePath, GraphContent):345 '''346 Export graph node link date to json file. 347 :param String AbsolutePath: absolute path to store the json file348 :param nxGraph GraphContent: some graph you want to export349 ''' 350 try:351 nx.write_gml(GraphContent, AbsolutePath)352 except:353 logger.error("JsonNodeLinkData writing Failed.")354 #sys.exit("JsonNodeLinkData writing Failed.")355 else:356 logger.info("JsonNodeLinkData of "+AbsolutePath+" written successfully.")357def ImportFromJsonNodeLinkData(AbsolutePath):358 '''359Import graph node link date from json file.360:param String AbsolutePath: absolute path of the json file361:return GraphContent: Graph content in the json file362:rtype nxGraph363 ''' 364 try:365 f=open(AbsolutePath,"rb")366 Content=json.load(f)367 GraphContent=json_graph.node_link_graph(Content)368 except:369 logger.error("JsonNodeLinkData writing Failed.")370 if "f" in dir():371 f.close()372 #sys.exit("JsonNodeLinkData writing Failed.")373 else:374 logger.info("JsonNodeLinkData of "+AbsolutePath+" loaded successfully.")375 f.close()376 return GraphContent377def ImportFromJson(AbsolutePath):378 '''379 Import something from json file. 380 :param String AbsolutePath: absolute path of the json file381 :return Content: Content in the json file382 :rtype Variant383 ''' 384 try:385 File=open(AbsolutePath,"rb")386 Content=json.load(File, encoding = "utf-8")387 except Exception as e:388 logger.error(e)389 logger.error("Json data loading Failed.")390 if "File" in dir():391 File.close()392 #sys.exit("Json data loading Failed.") 393 else:394 logger.info("Json data of "+AbsolutePath+" loaded successfully.")395 File.close()396 return Content397def FlattenList(List):398 '''399 Flatten a list using itertools no matter how many nest it has. 400 E.g. [['foo', 'baz'], ['gg']] or [[['foo', 'baz'], ['gg']]] to ['foo', 'baz', 'gg'].401 :param List[Variant]: The list you want to flatten402 :return List: Flattened list403 :rtype List[Variant]404 '''405 for Element in List:406 if type(Element)==list:407 List = list(itertools.chain(*List))408 return FlattenList(List)409 return list(List)410def CombineSparseMatricesRowWise(MainMatrix, AddedMatrix):411 '''412 Stack two scipy sparse matrices vertically (row wise). Will initialize the main matrix to be two dimensional csr_matrix with all zero elements if the main matrix is empty.413 414 :param SparseMatrix MainMatrix: The main matrix that you want to add the AddedMatrix.415 :param SparseMatrix AddedMatrix: The matrix added followed by the main matrix.416 :return SparseMatrix Result: The result of Stack sparse matrices vertically (row wise).417 :rtype SparseMatrix418 '''419 if MainMatrix.size == 0:420 MainMatrix = scipy.sparse.csr_matrix([np.zeros(AddedMatrix.shape[1], dtype = int)])421 Result = scipy.sparse.vstack([MainMatrix, AddedMatrix])422 return Result423def DeleteLilMatrixRow(mat, i):424 '''425 Delete a row in a scipy.sparse.lil_matrix.426 :param scipy.sparse.lil_matrix mat: The scipy.sparse.lil_matrix you want to operate on.427 :param Int i: The row number that you want to delete428 :return SparseMatrix mat: The result of deleted sparse matrix.429 :rtype SparseMatrix430 '''431 if not isinstance(mat, scipy.sparse.lil.lil_matrix):432 #print mat.__class__433 raise ValueError("works only for LIL format -- use .tolil() first")434 mat.rows = np.delete(mat.rows, i)435 mat.data = np.delete(mat.data, i)436 mat._shape = (mat._shape[0] - 1, mat._shape[1])437 return mat438def DeleteCsrMatrixRow(mat, i):439 '''440 Delete a row in a scipy.sparse.csr_matrix.441 :param scipy.sparse.csr_matrix mat: The scipy.sparse.csr_matrix you want to operate on.442 :param Int i: The row number that you want to delete443 :return SparseMatrix mat: The result of deleted sparse matrix.444 :rtype SparseMatrix445 '''446 if not isinstance(mat, scipy.sparse.csr_matrix):447 try:448 print "Warning: works only for CSR format -- use .tocsr() first"449 mat = mat.tocsr()450 except:451 raise ValueError("cannot convert mat to CSR format")452 #raise ValueError("works only for CSR format -- use .tocsr() first")453 n = mat.indptr[i+1] - mat.indptr[i]454 if n > 0:455 mat.data[mat.indptr[i]:-n] = mat.data[mat.indptr[i+1]:]456 mat.data = mat.data[:-n]457 mat.indices[mat.indptr[i]:-n] = mat.indices[mat.indptr[i+1]:]458 mat.indices = mat.indices[:-n]459 mat.indptr[i:-1] = mat.indptr[i+1:]460 mat.indptr[i:] -= n461 mat.indptr = mat.indptr[:-1]462 mat._shape = (mat._shape[0]-1, mat._shape[1])463 return mat464def ExportNpArray(AbsolutePath, NpArray, Format = "%f"):465 '''466 Export a Numpy array to a file.467 468 :param String AbsolutePath: The stored file location.469 :param numpy.array NpArray: The Numpy array you want to store.470 :param String Format: How to print each element, e.g. %i, %10.5f471 '''472 try:473 with open(AbsolutePath, "w+") as File:474 np.savetxt(File, NpArray, fmt = Format)475 except:476 logger.error("NpArray saving Failed.")477def ImportNpArray(AbsolutePath, DataType, ndmin = 0):478 '''479 Import a Numpy array from a file.480 481 :param String AbsolutePath: The stored file location.482 :param data-type DataType: How to match each element, e.g. int, float483 :param int ndmin: How many dimensions of array at least you will have.484 :return NpArray: NpArray in the file485 :rtype NpArray486 '''487 try:488 NpArray = np.loadtxt(AbsolutePath, dtype = DataType, ndmin = ndmin)489 return NpArray490 except Exception as e:491 logger.error(e)492 logger.error("NpArray loading Failed.")493def ExportSparseMatrix(AbsolutePath, SparseMatrix):494 '''495 Export a scipy sparse matrix to a file using matrix market format.496 Please refer to http://math.nist.gov/MatrixMarket/formats.html for more information about this format.497 498 :param String AbsolutePath: The stored file location.499 :param scipy sparse matrix SparseMatrix: The scipy sparse matrix you want to store.500 '''501 try:502 with open(AbsolutePath, "w+") as File:503 scipy.io.mmwrite(File, SparseMatrix)504 except Exception as e:505 logger.error(e)506 logger.error("SparseMatrix saving Failed.")507def ImportSparseMatrix(AbsolutePath):508 '''509 Import a scipy sparse matrix from a file using matrix market format.510 511 :param String AbsolutePath: The stored file location.512 :return SparseMatrix: (converted) scipy csr_matrix in the file513 :rtype Scipy Sparse Matrix514 '''515 try:516 SparseMatrix = scipy.io.mmread(AbsolutePath)517 SparseMatrix = SparseMatrix.tocsr()518 return SparseMatrix519 except Exception as e:520 logger.error(e)521 logger.error("SparseMatrix loading Failed.")522def IfTwoSparseMatrixEqual(SparseMatrix1, SparseMatrix2):523 '''524 Check if two scipy sparse matrix is exactly the same.525 526 :param SparseMatrix SparseMatrix1: The first scipy sparse matrix.527 :param SparseMatrix SparseMatrix2: The second scipy sparse matrix.528 :return Equal: True if they are equal, otherwise will be false.529 :rtype Boolean530 '''531 try:532 if (SparseMatrix1 - SparseMatrix2).nnz == 0:533 return True534 else:535 return False536 except Exception as e:537 logger.error(e)538def ExportToDll(obj,filename):539 try:540 filename = os.path.join(os.getcwd(), filename)541 with open(filename, 'wb') as output_:542 dill.dump(obj, output_)543 except Exception as e:544 logger.error(e)545 logger.error("Exporting the variable to file Failed.")546def ImportFromDll(filename):547 try:548 with open(filename, 'rb') as input_:549 return dill.load(input_)550 except Exception as e:551 logger.error(e)...

Full Screen

Full Screen

CommonModules.py

Source:CommonModules.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2""" Some common modules for this project."""3import os4import sys5import json6import time7import itertools8import collections9import pickle10import shutil11import numpy as np12import scipy.sparse13import scipy.io14import networkx as nx15from networkx.readwrite import json_graph16import logging17logging.basicConfig(level=logging.INFO,filename="LogFile.log",filemode="a",18 format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s: %(message)s',19 datefmt='%Y/%m/%d %H:%M:%S')20ErrorHandler = logging.StreamHandler()21ErrorHandler.setLevel(logging.ERROR)22ErrorHandler.setFormatter(logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s: %(message)s'))23logger = logging.getLogger()24logger.addHandler(ErrorHandler)25import Modules.progressbar.progressbar as progressbar26import Modules.progressbar.widgets as progressbar_widgets27class ProgressBar(object):28 def __init__(self):29 self.TotalResults = []30 self.NumberOfFinishedResults = 031 32 def Update(self):33 self.ProgressBar.update(self.NumberOfFinishedResults)34 return 35 def CallbackForProgressBar(self, res = ''): 36 """37 Callback function for pool.async if the progress bar needs to be displayed.38 Must use with DisplayProgressBar function.39 :param multiprocessing.pool.AsyncResult res: Result got from callback function in pool.async.40 """41 self.NumberOfFinishedResults += 142 self.TotalResults.append(res)43 return44 def DisplayProgressBar(self, ProcessingResults, ExpectedResultsSize, CheckInterval = 1, type = "minute"):45 '''46 Display a progress bar for multiprocessing. This function should be used after pool.close(No need to use pool.join anymore). 47 The call back function for pool.async should be set as CallbackForProgressBar.48 :param multiprocessing.pool.AsyncResult ProcessingResults: Processing results returned by pool.async.49 :param int ExpectedResultsSize: How many result you will reveive, i.e. the total length of progress bar.50 :param float CheckInterval: How many seconds will the progress bar be updated. When it's too large, the main program may hang there.51 :param String type: Three types: "minute", "hour", "second"; corresponds displaying iters/minute iters/hour and iters/second.52 '''53 self.ProcessingResults = ProcessingResults54 ProgressBarWidgets = [progressbar_widgets.Percentage(),55 ' ', progressbar_widgets.Bar(),56 ' ', progressbar_widgets.SimpleProgress(),57 ' ', progressbar_widgets.Timer(),58 ' ', progressbar_widgets.AdaptiveETA()]59 self.ProgressBar = progressbar.ProgressBar(ExpectedResultsSize, ProgressBarWidgets)60 self.StartTime = time.time()61 PreviousNumberOfResults = 062 self.ProgressBar.start()63 while self.ProcessingResults.ready()==False:64 self.Update()65 time.sleep(CheckInterval)66 time.sleep(CheckInterval)67 self.Update()68 self.ProgressBar.finish()69 self.EndTime = time.time()70 print "Processing finished."71 #print "Processing results: ", self.TotalResults72 print "Time Elapsed: %.2fs, or %.2fmins, or %.2fhours" % ((self.EndTime-self.StartTime),(self.EndTime-self.StartTime)/60,(self.EndTime-self.StartTime)/3600)73 logger.info("Processing finished.")74 logger.info("Processing results: "+ str(self.TotalResults))75 logger.info("Time Elapsed: %.2fs, or %.2fmins, or %.2fhours" % ((self.EndTime-self.StartTime),(self.EndTime-self.StartTime)/60,(self.EndTime-self.StartTime)/3600))76 return 77 #for i in progressbar.tqdm(range(ExpectedResultsSize),type=type):#Three types: iters/minute iters/hour and iters/second78 #while ProcessingResults.ready()==False:#While processing doesn't finish.79 #if self.NumberOfFinishedResults>PreviousNumberOfResults:80 # PreviousNumberOfResults += 181 # break 82 #else:83 # time.sleep(CheckInterval)#Define how many seconds between each check.84 85class DefaultOrderedDict(collections.OrderedDict):86 # Source: http://stackoverflow.com/a/6190500/56276987 def __init__(self, default_factory=None, *a, **kw):88 if (default_factory is not None and89 not isinstance(default_factory, collections.Callable)):90 raise TypeError('first argument must be callable')91 collections.OrderedDict.__init__(self, *a, **kw)92 self.default_factory = default_factory93 def __getitem__(self, key):94 try:95 return collections.OrderedDict.__getitem__(self, key)96 except KeyError:97 return self.__missing__(key)98 def __missing__(self, key):99 if self.default_factory is None:100 raise KeyError(key)101 self[key] = value = self.default_factory()102 return value103 def __reduce__(self):104 if self.default_factory is None:105 args = tuple()106 else:107 args = self.default_factory,108 return type(self), args, None, None, self.items()109 def copy(self):110 return self.__copy__()111 def __copy__(self):112 return type(self)(self.default_factory, self)113 def __deepcopy__(self, memo):114 import copy115 return type(self)(self.default_factory,116 copy.deepcopy(self.items()))117 def __repr__(self):118 return 'OrderedDefaultDict(%s, %s)' % (self.default_factory,119 collections.OrderedDict.__repr__(self))120def ListApkFiles(ApkDirectory):121 '''122Get the Apk file names for an ApkDirectory in a sorted order. Rerurn an empty list if ApkDirectory=="".123:param String ApkDirectory: absolute path of a apk file directory124:return ListOfApkFiles: The list of absolute paths of Apks under ApkDirectory125:rtype List[String]126 '''127 ListOfApkFiles=[]128 if(ApkDirectory==""):129 raise ValueError('Directory is empty!')130 filenames = os.listdir(ApkDirectory)131 for filename in filenames:132 #list filenames 133 #get the absolute path for the files134 AbsolutePath=os.path.abspath(os.path.join(ApkDirectory, filename))135 #get the absolute path for the files136 if os.path.splitext(filename)[1]==".apk":137 if os.path.isfile(AbsolutePath):138 ListOfApkFiles.append(AbsolutePath)139 return sorted(ListOfApkFiles)140def ListFiles(Directory, Extension):141 '''142 Given an extension, get the file names for a Directory in a sorted order. Rerurn an empty list if Directory == "".143 :param String Directory: absolute path of a file directory144 :param String Extension: Extension of the files you want. Better include "." in the Extension145 :return ListOfFiles: The list of absolute paths of the files you want under Directory146 :rtype List[String]147 '''148 ListOfFiles=[]149 if(Directory == "" or Directory == []):150 return []151 if(type(Directory) != list and os.path.isdir(Directory) == False):152 raise ValueError(Directory, 'Directory is not a directory!')153 if(type(Extension)!=str):154 raise ValueError(Extension, 'Extension is not a string!')155 if(Extension):156 if(Extension[0] != "."):157 Extension = "." + Extension[0]158 if type(Directory) == list:159 Directories = Directory160 for Directory in Directories:161 filenames = os.listdir(Directory)162 for filename in filenames:163 #list filenames 164 #get the absolute path for the files165 AbsolutePath=os.path.abspath(os.path.join(Directory, filename))166 #get the absolute path for the files167 if os.path.splitext(filename)[1]==Extension:168 if os.path.isfile(AbsolutePath):169 ListOfFiles.append(AbsolutePath)170 else:171 filenames = os.listdir(Directory)172 for filename in filenames:173 #list filenames 174 #get the absolute path for the files175 AbsolutePath=os.path.abspath(os.path.join(Directory, filename))176 #get the absolute path for the files177 if os.path.splitext(filename)[1]==Extension:178 if os.path.isfile(AbsolutePath):179 ListOfFiles.append(AbsolutePath)180 return sorted(ListOfFiles)181def ListAllFiles(Directory, Extension):182 '''183 Given an extension, get the file names for a Directory and all its sub-directories in a sorted order. Rerurn an empty list if Directory == "".184 :param String Directory: absolute path of a file directory185 :param String Extension: Extension of the files you want. Better include "." in the Extension186 :return ListOfFiles: The list of absolute paths of the files you want under Directory187 :rtype List[String]188 '''189 ListOfFiles=[]190 if(Directory == ""):191 raise ValueError(Directory, 'Directory is empty!')192 if(os.path.isdir(Directory) == False):193 raise ValueError(Directory, 'Directory is not a directory!')194 if(type(Extension)!=str):195 raise ValueError(Extension, 'Extension is not a string!')196 if(Extension):197 if(Extension[0] != "."):198 Extension = "." + Extension[0]199 for root, dirs, files in os.walk(Directory):200 for filename in files:201 #list filenames 202 #get the absolute path for the files203 AbsolutePath = os.path.join(root, filename)204 #get the absolute path for the files205 if os.path.splitext(filename)[1] == Extension:206 if os.path.isfile(AbsolutePath):207 ListOfFiles.append(AbsolutePath)208 return sorted(ListOfFiles)209def ListDirs(Directory):210 '''211 Get all sub-directory paths for a Directory in a sorted order. Rerurn an empty list if Directory == "". Modified from ListFiles(which means variable names remain the same...)212 :param String Directory: absolute path of a file directory213 :return ListOfFiles: The list of absolute paths of the sub-directories you want under the Directory214 :rtype List[String]215 '''216 ListOfFiles=[]217 if(Directory == ""):218 raise ValueError(Directory, 'Directory is empty!')219 if(os.path.isdir(Directory) == False):220 raise ValueError(Directory, 'Directory is not a directory!')221 filenames = os.listdir(Directory)222 for filename in filenames:223 #list filenames 224 #get the absolute path for the files225 AbsolutePath=os.path.abspath(os.path.join(Directory, filename))226 #get the absolute path for the files227 if os.path.isdir(AbsolutePath):228 ListOfFiles.append(AbsolutePath)229 return sorted(ListOfFiles)230 231 232def FileExist(FilePath):233 '''234 Given file path, determine a file exist or not.235 :param String FilePath: absolute path of a file or directory236 :rtype Boolean237 '''238 if os.path.exists(FilePath)==True:239 return True240 else:241 #if os.path.isdir(ApkFilePath)==False:242 # if(os.path.basename(ApkFilePath)) in os.listdir(os.getcwd()):243 # return True244 return False245def RemoveDirectory(Folder):246 '''247 Given Folder path, remove this folder(include all content inside).248 :param String Folder: absolute path of a directory249 :rtype Boolean250 '''251 if(FileExist(Folder) == False):252 raise IOError("Directory not found!")253 else:254 shutil.rmtree(Folder)255def ExportToJson(AbsolutePath, Content):256 '''257 Export something to json file. 258 Will automatic convert Set content into List.259 :param String AbsolutePath: absolute path to store the json file260 :param Variant Content: something you want to export261 '''262 try:263 if(isinstance(Content,set)):264 Content = list(Content)265 #if(isinstance(Content, collections.defaultdict)):266 # Content = dict(Content)267 f=open(AbsolutePath,"wb")268 # json.dump(Content, f, indent=4)269 for Key,Val in Content.items():270 for V in Val:271 print >>f, str(Key)+'_'+str(V)272 except Exception as e:273 print "Json data writing Failed."274 logger.error(e)275 logger.error("Json data writing Failed.")276 if "f" in dir():277 f.close()278 #sys.exit("Json data writing Failed.")279 else:280 logger.info("Json data of "+AbsolutePath+" written successfully.") 281 f.close()282def ExportToPkl(AbsolutePath,Content):283 '''284 Export something to pickle file. 285 Will automatic convert Set content into List.286 :param String AbsolutePath: absolute path to store the json file287 :param Variant Content: something you want to export288 '''289 try:290 if(isinstance(Content, set)):291 Content = list(Content)292 #if(isinstance(Content, collections.defaultdict)):293 # Content = dict(Content)294 f=open(AbsolutePath, "wb")295 pickle.dump(Content, f)296 except:297 print "Pickle data writing Failed."298 logger.error("Pickle data writing Failed.")299 if "f" in dir():300 f.close()301 #sys.exit("Json data writing Failed.")302 else:303 logger.info("Pickle data of " + AbsolutePath + " written successfully.") 304 f.close()305def ImportFromPkl(AbsolutePath):306 '''307 Import something from pickle file. 308 :param String AbsolutePath: absolute path of the pickle file309 :return Content: Content in the pickle file310 :rtype Variant311 ''' 312 try:313 File = open(AbsolutePath,"rb")314 Content = pickle.load(File)315 except:316 logger.error("Pickle data loading Failed.")317 if "File" in dir():318 File.close()319 #sys.exit("Json data loading Failed.") 320 else:321 logger.info("Pickle data of "+AbsolutePath+" loaded successfully.")322 File.close()323 return Content324def ExportToJsonNodeLinkData(AbsolutePath,GraphContent):325 '''326 Export graph node link date to json file. 327 :param String AbsolutePath: absolute path to store the json file328 :param nxGraph GraphContent: some graph you want to export329 ''' 330 try:331 f=open(AbsolutePath,"wb")332 Content=json_graph.node_link_data(GraphContent)333 json.dump(Content,f,indent=4)334 except Exception as e:335 print e336 logger.error("JsonNodeLinkData writing Failed.")337 if "f" in dir():338 f.close()339 #sys.exit("JsonNodeLinkData writing Failed.")340 else:341 logger.info("JsonNodeLinkData of "+AbsolutePath+" written successfully.")342 f.close()343def ExportToGML(AbsolutePath, GraphContent):344 '''345 Export graph node link date to json file. 346 :param String AbsolutePath: absolute path to store the json file347 :param nxGraph GraphContent: some graph you want to export348 ''' 349 try:350 nx.write_gml(GraphContent, AbsolutePath)351 except:352 logger.error("JsonNodeLinkData writing Failed.")353 #sys.exit("JsonNodeLinkData writing Failed.")354 else:355 logger.info("JsonNodeLinkData of "+AbsolutePath+" written successfully.")356def ImportFromJsonNodeLinkData(AbsolutePath):357 '''358Import graph node link date from json file.359:param String AbsolutePath: absolute path of the json file360:return GraphContent: Graph content in the json file361:rtype nxGraph362 ''' 363 try:364 f=open(AbsolutePath,"rb")365 Content=json.load(f)366 GraphContent=json_graph.node_link_graph(Content)367 except:368 logger.error("JsonNodeLinkData writing Failed.")369 if "f" in dir():370 f.close()371 #sys.exit("JsonNodeLinkData writing Failed.")372 else:373 logger.info("JsonNodeLinkData of "+AbsolutePath+" loaded successfully.")374 f.close()375 return GraphContent376def ImportFromJson(AbsolutePath):377 '''378 Import something from json file. 379 :param String AbsolutePath: absolute path of the json file380 :return Content: Content in the json file381 :rtype Variant382 ''' 383 try:384 File=open(AbsolutePath,"rb")385 Content=json.load(File, encoding = "utf-8")386 except Exception as e:387 logger.error(e)388 logger.error("Json data loading Failed.")389 if "File" in dir():390 File.close()391 #sys.exit("Json data loading Failed.") 392 else:393 logger.info("Json data of "+AbsolutePath+" loaded successfully.")394 File.close()395 return Content396def FlattenList(List):397 '''398 Flatten a list using itertools no matter how many nest it has. 399 E.g. [['foo', 'baz'], ['gg']] or [[['foo', 'baz'], ['gg']]] to ['foo', 'baz', 'gg'].400 :param List[Variant]: The list you want to flatten401 :return List: Flattened list402 :rtype List[Variant]403 '''404 for Element in List:405 if type(Element)==list:406 List = list(itertools.chain(*List))407 return FlattenList(List)408 return list(List)409def CombineSparseMatricesRowWise(MainMatrix, AddedMatrix):410 '''411 Stack two scipy sparse matrices vertically (row wise). Will initialize the main matrix to be two dimensional csr_matrix with all zero elements if the main matrix is empty.412 413 :param SparseMatrix MainMatrix: The main matrix that you want to add the AddedMatrix.414 :param SparseMatrix AddedMatrix: The matrix added followed by the main matrix.415 :return SparseMatrix Result: The result of Stack sparse matrices vertically (row wise).416 :rtype SparseMatrix417 '''418 if MainMatrix.size == 0:419 MainMatrix = scipy.sparse.csr_matrix([np.zeros(AddedMatrix.shape[1], dtype = int)])420 Result = scipy.sparse.vstack([MainMatrix, AddedMatrix])421 return Result422def DeleteLilMatrixRow(mat, i):423 '''424 Delete a row in a scipy.sparse.lil_matrix.425 :param scipy.sparse.lil_matrix mat: The scipy.sparse.lil_matrix you want to operate on.426 :param Int i: The row number that you want to delete427 :return SparseMatrix mat: The result of deleted sparse matrix.428 :rtype SparseMatrix429 '''430 if not isinstance(mat, scipy.sparse.lil.lil_matrix):431 #print mat.__class__432 raise ValueError("works only for LIL format -- use .tolil() first")433 mat.rows = np.delete(mat.rows, i)434 mat.data = np.delete(mat.data, i)435 mat._shape = (mat._shape[0] - 1, mat._shape[1])436 return mat437def DeleteCsrMatrixRow(mat, i):438 '''439 Delete a row in a scipy.sparse.csr_matrix.440 :param scipy.sparse.csr_matrix mat: The scipy.sparse.csr_matrix you want to operate on.441 :param Int i: The row number that you want to delete442 :return SparseMatrix mat: The result of deleted sparse matrix.443 :rtype SparseMatrix444 '''445 if not isinstance(mat, scipy.sparse.csr_matrix):446 try:447 print "Warning: works only for CSR format -- use .tocsr() first"448 mat = mat.tocsr()449 except:450 raise ValueError("cannot convert mat to CSR format")451 #raise ValueError("works only for CSR format -- use .tocsr() first")452 n = mat.indptr[i+1] - mat.indptr[i]453 if n > 0:454 mat.data[mat.indptr[i]:-n] = mat.data[mat.indptr[i+1]:]455 mat.data = mat.data[:-n]456 mat.indices[mat.indptr[i]:-n] = mat.indices[mat.indptr[i+1]:]457 mat.indices = mat.indices[:-n]458 mat.indptr[i:-1] = mat.indptr[i+1:]459 mat.indptr[i:] -= n460 mat.indptr = mat.indptr[:-1]461 mat._shape = (mat._shape[0]-1, mat._shape[1])462 return mat463def ExportNpArray(AbsolutePath, NpArray, Format = "%f"):464 '''465 Export a Numpy array to a file.466 467 :param String AbsolutePath: The stored file location.468 :param numpy.array NpArray: The Numpy array you want to store.469 :param String Format: How to print each element, e.g. %i, %10.5f470 '''471 try:472 with open(AbsolutePath, "w+") as File:473 np.savetxt(File, NpArray, fmt = Format)474 except:475 logger.error("NpArray saving Failed.")476def ImportNpArray(AbsolutePath, DataType, ndmin = 0):477 '''478 Import a Numpy array from a file.479 480 :param String AbsolutePath: The stored file location.481 :param data-type DataType: How to match each element, e.g. int, float482 :param int ndmin: How many dimensions of array at least you will have.483 :return NpArray: NpArray in the file484 :rtype NpArray485 '''486 try:487 NpArray = np.loadtxt(AbsolutePath, dtype = DataType, ndmin = ndmin)488 return NpArray489 except Exception as e:490 logger.error(e)491 logger.error("NpArray loading Failed.")492def ExportSparseMatrix(AbsolutePath, SparseMatrix):493 '''494 Export a scipy sparse matrix to a file using matrix market format.495 Please refer to http://math.nist.gov/MatrixMarket/formats.html for more information about this format.496 497 :param String AbsolutePath: The stored file location.498 :param scipy sparse matrix SparseMatrix: The scipy sparse matrix you want to store.499 '''500 try:501 with open(AbsolutePath, "w+") as File:502 scipy.io.mmwrite(File, SparseMatrix)503 except Exception as e:504 logger.error(e)505 logger.error("SparseMatrix saving Failed.")506def ImportSparseMatrix(AbsolutePath):507 '''508 Import a scipy sparse matrix from a file using matrix market format.509 510 :param String AbsolutePath: The stored file location.511 :return SparseMatrix: (converted) scipy csr_matrix in the file512 :rtype Scipy Sparse Matrix513 '''514 try:515 SparseMatrix = scipy.io.mmread(AbsolutePath)516 SparseMatrix = SparseMatrix.tocsr()517 return SparseMatrix518 except Exception as e:519 logger.error(e)520 logger.error("SparseMatrix loading Failed.")521def IfTwoSparseMatrixEqual(SparseMatrix1, SparseMatrix2):522 '''523 Check if two scipy sparse matrix is exactly the same.524 525 :param SparseMatrix SparseMatrix1: The first scipy sparse matrix.526 :param SparseMatrix SparseMatrix2: The second scipy sparse matrix.527 :return Equal: True if they are equal, otherwise will be false.528 :rtype Boolean529 '''530 try:531 if (SparseMatrix1 - SparseMatrix2).nnz == 0:532 return True533 else:534 return False535 except Exception as e:...

Full Screen

Full Screen

main_file.py

Source:main_file.py Github

copy

Full Screen

1# Libraries used2from tkinter import *3import os4from PIL import ImageTk, Image5import BinaryLinear6from prettytable import PrettyTable7import AreaGraph8main_root = Tk()9def AbsolutePath(dir):10 AbsoluteDirectory = os.path.dirname(os.path.abspath(__file__))11 returnDir = os.path.join(AbsoluteDirectory, dir)12 return returnDir13def display_shortest_path(starting_area):14 temp_root = Toplevel()15 temp_root.geometry("1366x720")16 temp_root.config(bg='#1C1C1C')17 temp_root.geometry('1366x720')18 main_image = ImageTk.PhotoImage(Image.open(19 AbsolutePath('pictures_used/fourth_window_image.png')))20 temp_label = Label(temp_root, bg='#1C1C1C', image=main_image)21 temp_label.place(x=0, y=0, relwidth=1, relheight=1)22 picture_frame = Frame(temp_root, bg='#1C1C1C')23 picture_frame.grid(padx=225, pady=200)24 dictionary_for_areas_nodes = {25 'Gulshan e Iqbal': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/IqbalLoc.png'))),26 'Gulistan e Johar': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/JoharLoc.png'))),27 'Defence(Ph4,Ph5,Gizri)': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/D45GLoc.png'))),28 'Clifton Block (1,2,3)': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/C123Loc.png'))),29 'Saddar': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/SaddarLoc.png'))),30 'Defence(Ph1,Ph2)': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/D12Loc.png'))),31 'North Nazimabad': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/NNLoc.png'))),32 'Garden': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/GardenLoc.png'))),33 'Malir Cantt': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/MalirLoc.png'))),34 'Defence(Ph6,Ph7,Ph8)': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/D678Loc.png'))),35 'Shaheed e Millat': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/SeMLoc.png'))),36 'Federal B Area': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/FBLoc.png'))),37 'Clifton Block (7,8,9)': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/C789Loc.png'))),38 'Bahadurabad': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/BahadurabadLoc.png'))),39 'Clifton Cantt': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/CCLoc.png'))),40 'PECHS': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/PECHSLoc.png'))),41 'Habib University': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Areas Nodes/HULoc.png')))42 }43 temp_lst = AreaGraph.getShortesetPath(starting_area, 'Habib University')44 shortest_path = temp_lst[0]45 print(shortest_path)46 counter_for_row = 047 counter_for_column = 048 for i in range(len(shortest_path)):49 for j in dictionary_for_areas_nodes:50 if shortest_path[i] == j:51 Label(picture_frame, bg='#1C1C1C', image=dictionary_for_areas_nodes[j], height=100, width=225).grid(52 row=counter_for_row, column=counter_for_column)53 counter_for_column += 154 if counter_for_column >= 4:55 counter_for_column = 056 counter_for_row += 157 Label(temp_root, text='Total distance from your Area to HU is Approximately ' +58 str(temp_lst[1]) + " Km", bg='#1C1C1C', font=("Courier", 25, 'bold'), fg='#ffbd59').grid(padx=10, pady=40)59 temp_root.mainloop()60def creating_third_window(starting_area):61 top = Toplevel()62 top.geometry("1366x720")63 top.config(bg='#1C1C1C')64 top.geometry('1366x720')65 student_data_frame = Frame(top, bg='#1C1C1C')66 student_data_frame.grid()67 lst_of_data = BinaryLinear.main(starting_area)68 headline_image = ImageTk.PhotoImage(69 Image.open(AbsolutePath('pictures_used/HeadingPage3.png')))70 Label(student_data_frame, image=headline_image,71 bg='#1C1C1C', height=70).grid(row=0, column=0)72 # Creating table to display the data73 table = PrettyTable()74 label = Text(student_data_frame, bg='#1C1C1C', fg='white',75 height=22, width=75, borderwidth=0)76 label.config(font=("Courier", 15))77 table.field_names = ["S.N", "First Name", "Last name", "Id", "Email"]78 for i in range(len(lst_of_data)):79 table.add_rows([lst_of_data[i]], )80 label.insert(INSERT, table)81 label.config(state=DISABLED)82 label.grid(padx=300, pady=10, sticky=E+W)83 get_shortest_path_image = ImageTk.PhotoImage(84 Image.open(AbsolutePath('pictures_used/ShortestPath.png')))85 Button(student_data_frame, image=get_shortest_path_image, height=80, bg='#1C1C1C',86 command=lambda: display_shortest_path(starting_area), borderwidth=0).grid()87 top.mainloop()88def select_about_us_option():89 about_us = Toplevel()90 about_us.geometry("1366x720")91 bg_image = ImageTk.PhotoImage(92 Image.open(AbsolutePath('pictures_used/about_us_image.png')))93 label = Label(about_us, image=bg_image)94 label.place(x=0, y=0, relwidth=1, relheight=1)95 about_us.mainloop()96def select_your_area_option():97 root = Toplevel()98 root.geometry("1366x720")99 bg_image = ImageTk.PhotoImage(Image.open(100 AbsolutePath('pictures_used/second_window_image.png')))101 label = Label(root, image=bg_image)102 label.place(x=0, y=0, relwidth=1, relheight=1)103 my_new_frame = Frame(root, bg='#1C1C1C')104 my_new_frame.grid(pady=200, padx=60)105 dictionary_for_images = {106 'gulshan iqbal': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/GeI.png'))),107 'gulistane johar': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/GeJ.png'))),108 'Defence Phase4 5 and Gizri': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/D45G.png'))),109 'Clifton block 123': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/C123.png'))),110 'Saddar': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/saddar.png'))),111 'Defence Phase 1 and 2': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/D12.png'))),112 'north nazimabad': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/NN.png'))),113 'garden': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/Garden.png'))),114 'Malir cant': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/MC.png'))),115 'Defence Phase 6 7 8': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/D675.png'))),116 'Shaheed Milat': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/SeM.png'))),117 'Federal area': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/FBA.png'))),118 'Clifton block 7 8 9': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/C789.png'))),119 'Bahadurabad': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/Bahadurabad.png'))),120 'Clifton Cant': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/CC.png'))),121 'PECHS': ImageTk.PhotoImage(Image.open(AbsolutePath('pictures_used/Area pictures/PECHS.png')))122 }123 Button(my_new_frame, image=dictionary_for_images['gulshan iqbal'], bg='#1C1C1C', borderwidth=0, height=100,124 width=265, command=lambda: creating_third_window('Gulshan e Iqbal')).grid(row=1, pady=10, padx=5, column=0)125 Button(my_new_frame, image=dictionary_for_images['gulistane johar'], bg='#1C1C1C', borderwidth=0, height=100,126 width=265, command=lambda: creating_third_window('Gulistan e Johar')).grid(row=1, pady=10, padx=5, column=1)127 Button(my_new_frame, image=dictionary_for_images['Defence Phase4 5 and Gizri'], bg='#1C1C1C', borderwidth=0, height=100,128 width=265, command=lambda: creating_third_window('Defence(Ph4,Ph5,Gizri)')).grid(row=1, pady=10, padx=5, column=2)129 Button(my_new_frame, image=dictionary_for_images['Clifton block 123'], bg='#1C1C1C', borderwidth=0, height=100,130 width=265, command=lambda: creating_third_window('Clifton Block (1,2,3)')).grid(row=1, pady=10, padx=5, column=3)131 Button(my_new_frame, image=dictionary_for_images['Saddar'], borderwidth=0, bg='#1C1C1C', height=100,132 width=265, command=lambda: creating_third_window('Saddar')).grid(row=2, pady=10, padx=5, column=0)133 Button(my_new_frame, image=dictionary_for_images['Defence Phase 1 and 2'], bg='#1C1C1C', borderwidth=0, height=100,134 width=265, command=lambda: creating_third_window('Defence(Ph1,Ph2)')).grid(row=2, pady=10, padx=5, column=1)135 Button(my_new_frame, image=dictionary_for_images['north nazimabad'], bg='#1C1C1C', borderwidth=0, height=100,136 width=265, command=lambda: creating_third_window('North Nazimabad')).grid(row=2, pady=10, padx=5, column=2)137 Button(my_new_frame, image=dictionary_for_images['garden'], borderwidth=0, bg='#1C1C1C', height=100,138 width=265, command=lambda: creating_third_window('Garden')).grid(row=2, pady=10, padx=5, column=3)139 Button(my_new_frame, image=dictionary_for_images['Malir cant'], bg='#1C1C1C', borderwidth=0, height=100,140 width=265, command=lambda: creating_third_window('Malir Cantt')).grid(row=3, pady=10, padx=5, column=0)141 Button(my_new_frame, image=dictionary_for_images['Defence Phase 6 7 8'], bg='#1C1C1C', borderwidth=0, height=100,142 width=265, command=lambda: creating_third_window('Defence(Ph6,Ph7,Ph8)')).grid(row=3, pady=10, padx=5, column=1)143 Button(my_new_frame, image=dictionary_for_images['Shaheed Milat'], bg='#1C1C1C', borderwidth=0, height=100,144 width=265, command=lambda: creating_third_window('Shaheed e Millat')).grid(row=3, pady=10, padx=5, column=2)145 Button(my_new_frame, image=dictionary_for_images['Federal area'], bg='#1C1C1C', borderwidth=0, height=100,146 width=265, command=lambda: creating_third_window('Federal B Area')).grid(row=3, pady=10, padx=5, column=3)147 Button(my_new_frame, image=dictionary_for_images['Clifton block 7 8 9'], bg='#1C1C1C', borderwidth=0, height=100,148 width=265, command=lambda: creating_third_window('Clifton Block (7,8,9)')).grid(row=4, pady=10, padx=5, column=0)149 Button(my_new_frame, image=dictionary_for_images['Bahadurabad'], bg='#1C1C1C', borderwidth=0, height=100,150 width=265, command=lambda: creating_third_window('Bahadurabad')).grid(row=4, pady=10, padx=5, column=1)151 Button(my_new_frame, image=dictionary_for_images['Clifton Cant'], bg='#1C1C1C', borderwidth=0, height=100,152 width=265, command=lambda: creating_third_window('Clifton Cantt')).grid(row=4, pady=10, padx=5, column=2)153 Button(my_new_frame, image=dictionary_for_images['PECHS'], borderwidth=0, bg='#1C1C1C', height=100,154 width=265, command=lambda: creating_third_window('PECHS')).grid(row=4, pady=10, padx=5, column=3)155 root.mainloop()156if __name__ == '__main__':157 # setting up the background image158 main_root.title('HU CARPOOLING SERVICE')159 main_root.geometry("1366x720")160 main_root.config(bg='White')161 main_image = ImageTk.PhotoImage(Image.open(162 AbsolutePath('pictures_used/first_window_image.png')))163 temp_label = Label(main_root, image=main_image)164 temp_label.place(x=0, y=0, relwidth=1, relheight=1)165 # creating the buttons166 my_frame = Frame(main_root, bg='white', borderwidth=0)167 my_frame.grid(pady=380)168 about_us_image = ImageTk.PhotoImage(Image.open(169 AbsolutePath('pictures_used/About.png')))170 select_your_area_image = ImageTk.PhotoImage(171 Image.open(AbsolutePath('pictures_used/SelectArea.png')))172 select_your_area_button = Button(my_frame, image=select_your_area_image, bg='white', borderwidth=0, width=300,173 height=100, command=select_your_area_option)174 select_your_area_button.grid(pady=10, padx=100, row=1, column=2)175 about_us_button = Button(my_frame, image=about_us_image, bg='white',176 width=300, height=100, borderwidth=0, command=select_about_us_option)177 about_us_button.grid(pady=10, padx=100, row=2, column=2)...

Full Screen

Full Screen

piano.py

Source:piano.py Github

copy

Full Screen

1from tkinter import * # for the gui2import pygame # for the music3import os # used to get filepaths4import time # for the time delay between playing musical notes56class piano:7 def __init__(self):8 self.chordTime = 0.25 # seconds used to determine if multiple notes together are a chord9 self.past = time.time() # initializes time check10 self.localPath = "/musicalNotes/"11 self.root = Tk() # the root window12 self.root.title('Piano')13 self.topFrame = Frame(self.root) # we'll use this frame for the piano keys14 self.topFrame.pack() # put the frame on the window15 16 self.script_dir = os.path.dirname(17 os.path.abspath(__file__)) # filepath for the directory that this file exists in. (this file is piano.py)1819 pygame.init() # initialize pygame2021 # buttons for each of the musical musicalNotes2223 Cbutton = Button(self.topFrame, text="C", fg="black", bg="white", height=8, width=3, command=self.soundForC)24 Cbutton.pack(side=LEFT)25 Dbutton = Button(self.topFrame, text="D", fg="black", bg="white", height=8, width=3, command=self.soundForD)26 Dbutton.pack(side=LEFT)27 Ebutton = Button(self.topFrame, text="E", fg="black", bg="white", height=8, width=3, command=self.soundForE)28 Ebutton.pack(side=LEFT)29 Fbutton = Button(self.topFrame, text="F", fg="black", bg="white", height=8, width=3, command=self.soundForF)30 Fbutton.pack(side=LEFT)31 Gbutton = Button(self.topFrame, text="G", fg="black", bg="white", height=8, width=3, command=self.soundForG)32 Gbutton.pack(side=LEFT)33 Abutton = Button(self.topFrame, text="A", fg="black", bg="white", height=8, width=3, command=self.soundForA)34 Abutton.pack(side=LEFT)35 Bbutton = Button(self.topFrame, text="B", fg="black", bg="white", height=8, width=3, command=self.soundForB)36 Bbutton.pack(side=LEFT)37 HighCbutton = Button(self.topFrame, text="High\nC", fg="black", bg="white", height=8, width=3,38 command=self.soundForHighC)39 HighCbutton.pack(side=LEFT)40 EmptyBeatbutton = Button(self.topFrame, text="Empty\nBeat", fg="black", bg="white", height=8, width=5, command=self.emptyBeat)41 EmptyBeatbutton.pack(side=LEFT)42 43 self.root.bind('q',self.soundForC)44 self.root.bind('w', self.soundForD)45 self.root.bind('e', self.soundForE)46 self.root.bind('r', self.soundForF)47 self.root.bind('t', self.soundForG)48 self.root.bind('y', self.soundForA)49 self.root.bind('u', self.soundForB)50 self.root.bind('i', self.soundForHighC)51 self.root.bind('o', self.emptyBeat)5253 self.chords = []5455 self.root.mainloop() # keep gui on screen until user closes window5657 # functions to play the sound for each musical note58 59 def soundForC(self,event=None):60 if self.checkTime():61 self.chords.append("C")62 else:63 self.chords[len(self.chords)-1] = self.chords[len(self.chords)-1] + "C"64 relativePath = "C.wav"65 absolutePath = self.script_dir + self.localPath + relativePath66 sound = pygame.mixer.Sound(absolutePath)67 sound.play()68 return697071 def soundForD(self,event=None):72 if self.checkTime():73 self.chords.append("D")74 else:75 self.chords[len(self.chords)-1] = self.chords[len(self.chords)-1] + "D"76 relativePath = "D.wav"77 absolutePath = self.script_dir + self.localPath + relativePath78 sound = pygame.mixer.Sound(absolutePath)79 sound.play()80 return818283 def soundForE(self,event=None):84 if self.checkTime():85 self.chords.append("E")86 else:87 self.chords[len(self.chords)-1] = self.chords[len(self.chords)-1] + "E"88 relativePath = "E.wav"89 absolutePath = self.script_dir + self.localPath + relativePath90 sound = pygame.mixer.Sound(absolutePath)91 sound.play()92 return939495 def soundForF(self,event=None):96 if self.checkTime():97 self.chords.append("F")98 else:99 self.chords[len(self.chords)-1] = self.chords[len(self.chords)-1] + "F"100 relativePath = "F.wav"101 absolutePath = self.script_dir + self.localPath + relativePath102 sound = pygame.mixer.Sound(absolutePath)103 sound.play()104 return105106107 def soundForG(self,event=None):108 if self.checkTime():109 self.chords.append("G")110 else:111 self.chords[len(self.chords)-1] = self.chords[len(self.chords)-1] + "G"112 relativePath = "G.wav"113 absolutePath = self.script_dir + self.localPath + relativePath114 sound = pygame.mixer.Sound(absolutePath)115 sound.play()116 return117118119 def soundForA(self,event=None):120 if self.checkTime():121 self.chords.append("A")122 else:123 self.chords[len(self.chords)-1] = self.chords[len(self.chords)-1] + "A"124 relativePath = "A.wav"125 absolutePath = self.script_dir + self.localPath + relativePath126 sound = pygame.mixer.Sound(absolutePath)127 sound.play()128 return129130131 def soundForB(self,event=None):132 if self.checkTime():133 self.chords.append("B")134 else:135 self.chords[len(self.chords)-1] = self.chords[len(self.chords)-1] + "B"136 relativePath = "B.wav"137 absolutePath = self.script_dir + self.localPath + relativePath138 sound = pygame.mixer.Sound(absolutePath)139 sound.play()140 return141142143 def soundForHighC(self,event=None):144 if self.checkTime():145 self.chords.append("^C")146 else:147 self.chords[len(self.chords)-1] = self.chords[len(self.chords)-1] + "^C"148 relativePath = "HighC.wav"149 absolutePath = self.script_dir + self.localPath + relativePath150 sound = pygame.mixer.Sound(absolutePath)151 sound.play()152 return153 154 def emptyBeat(self,event=None):155 self.chords.append("?")156 return157 158 def playCompleteSong(self, song):159 for i in range(len(song)):160 time.sleep(1) #sleep for 1 second (to allow time between each musical note)161162 for j, note in enumerate(song[i]):163 #play each note in the completed song164 if j>0 and song[i][j-1] == "^" and note == "C":165 pass166 elif note == "C":167 relativePath = "\musicalNotes\C.wav"168 absolutePath = self.script_dir + relativePath169 sound = pygame.mixer.Sound(absolutePath)170 sound.play()171 elif note == "D":172 relativePath = "\musicalNotes\D.wav"173 absolutePath = self.script_dir + relativePath174 sound = pygame.mixer.Sound(absolutePath)175 sound.play()176 elif note == "E":177 relativePath = "\musicalNotes\E.wav"178 absolutePath = self.script_dir + relativePath179 sound = pygame.mixer.Sound(absolutePath)180 sound.play()181 elif note == "F":182 relativePath = "\musicalNotes\F.wav"183 absolutePath = self.script_dir + relativePath184 sound = pygame.mixer.Sound(absolutePath)185 sound.play()186 elif note == "G":187 relativePath = "\musicalNotes\G.wav"188 absolutePath = self.script_dir + relativePath189 sound = pygame.mixer.Sound(absolutePath)190 sound.play()191 elif note == "A":192 relativePath = "\musicalNotes\A.wav"193 absolutePath = self.script_dir + relativePath194 sound = pygame.mixer.Sound(absolutePath)195 sound.play()196 elif note == "B":197 relativePath = "\musicalNotes\B.wav"198 absolutePath = self.script_dir + relativePath199 sound = pygame.mixer.Sound(absolutePath)200 sound.play()201 elif note == "^":202 relativePath = "\musicalNotes\HighC.wav"203 absolutePath = self.script_dir + relativePath204 sound = pygame.mixer.Sound(absolutePath)205 sound.play()206 elif note == "?":207 pass208 else:209 print(note," is an invalid note")210211 # checks to see if the time threshold has been reached212 # if the threshold is reached, returns true. otherwise, false213 def checkTime(self):214 currentTime = time.time()215 if currentTime - self.past >= self.chordTime:216 self.past = currentTime217 return True218 else: ...

Full Screen

Full Screen

simplepath.py

Source:simplepath.py Github

copy

Full Screen

1from typing import Iterable, List2class InvalidPathError(Exception):3 pass4class NotARelativePathError(InvalidPathError):5 pass6class NotAnAbsolutePathError(InvalidPathError):7 pass8_valid_path_chars = 'abcdefghijklmnopqrstuvwxyz0123456789-_.'9def _validate_and_shorten(is_absolute: bool, elements: Iterable[str]) \10 -> List[str]:11 '''12 >>> _validate_and_shorten(True, ['a', 'b', 'c', '..', '..'])13 ['a']14 >>> _validate_and_shorten(False, ['..', '..'])15 ['..', '..']16 >>> _validate_and_shorten(True, ['..', '..'])17 Traceback (most recent call last):18 ...19 hyperdiary.simplepath.InvalidPathError: traversing over root20 >>> _validate_and_shorten(True, ['x', '..'])21 []22 >>> _validate_and_shorten(False, ['x', '..'])23 []24 >>> _validate_and_shorten(True, [''])25 []26 >>> _validate_and_shorten(True, [])27 []28 >>> _validate_and_shorten(False, ['.'])29 []30 >>> _validate_and_shorten(False, [''])31 []32 >>> _validate_and_shorten(False, [])33 []34 >>> _validate_and_shorten(False, ['.'])35 []36 '''37 new_elements = [] # type: List[str]38 for el in elements:39 if el == '.' or not el:40 continue41 elif el == '..':42 if not new_elements:43 if is_absolute:44 raise InvalidPathError('traversing over root')45 else:46 new_elements.append('..')47 else:48 if new_elements[-1] == '..':49 new_elements.append('..')50 else:51 new_elements.pop()52 else:53 if not all(c in _valid_path_chars for c in el):54 raise InvalidPathError('invalid character in path element "{}"'55 .format(el))56 new_elements.append(el)57 return new_elements58class RelativePath:59 def __init__(self, path: str) -> None:60 '''61 >>> RelativePath('a/b/c')62 RelativePath('./a/b/c')63 >>> RelativePath('..')64 RelativePath('..')65 >>> RelativePath('.')66 RelativePath('.')67 >>> RelativePath('')68 RelativePath('.')69 '''70 if path.startswith('/'):71 raise NotARelativePathError(path)72 self.elements = _validate_and_shorten(False, path.split('/'))73 def __str__(self) -> str:74 '''75 >>> str(RelativePath('a/b/c'))76 './a/b/c'77 '''78 prefix = '.' + ('/' if self.elements else '')79 if self.elements and self.elements[0] == '..':80 prefix = ''81 return prefix + '/'.join(self.elements)82 def __repr__(self) -> str:83 '''84 >>> RelativePath('d/e/f')85 RelativePath('./d/e/f')86 >>> RelativePath('./../f')87 RelativePath('../f')88 '''89 return 'RelativePath(\'{}\')'.format(self)90class AbsolutePath:91 def __init__(self, path: str) -> None:92 '''93 >>> AbsolutePath('/a/b/c')94 AbsolutePath('/a/b/c')95 >>> AbsolutePath('/')96 AbsolutePath('/')97 >>> AbsolutePath('/folder/index.html')98 AbsolutePath('/folder/index.html')99 >>> AbsolutePath('a/b/c')100 Traceback (most recent call last):101 ...102 hyperdiary.simplepath.NotAnAbsolutePathError: a/b/c103 >>> AbsolutePath('')104 Traceback (most recent call last):105 ...106 hyperdiary.simplepath.NotAnAbsolutePathError107 '''108 if not path.startswith('/'):109 raise NotAnAbsolutePathError(path)110 self.elements = _validate_and_shorten(True, path.split('/'))111 def __eq__(self, other: object) -> bool:112 '''113 >>> AbsolutePath('/a/b/c') == AbsolutePath('/a/b/c')114 True115 >>> AbsolutePath('/a/b/c') == AbsolutePath('/a/./b/c/../c')116 True117 >>> AbsolutePath('/a/b/c') == AbsolutePath('/a')118 False119 >>> AbsolutePath('/a/b/c') != AbsolutePath('/a')120 True121 '''122 if not isinstance(other, AbsolutePath):123 return False124 if not len(self.elements) == len(other.elements):125 return False126 return all(el1 == el2 for el1, el2 in zip(self.elements,127 other.elements))128 def __add__(self, other: RelativePath) -> 'AbsolutePath':129 '''130 >>> AbsolutePath('/a/b/c') + RelativePath('d/e/f')131 AbsolutePath('/a/b/c/d/e/f')132 >>> AbsolutePath('/a/b/c') + RelativePath('../..')133 AbsolutePath('/a')134 >>> AbsolutePath('/a/b/c') + RelativePath('../../..')135 AbsolutePath('/')136 >>> AbsolutePath('/a/b/c') + RelativePath('../../../..')137 Traceback (most recent call last):138 ...139 hyperdiary.simplepath.InvalidPathError: traversing over root140 >>> AbsolutePath('/a/b/c/././') + RelativePath('../../../x/y') \141 == AbsolutePath('/x/y')142 True143 '''144 return AbsolutePath('{}/{}'.format(self, other))145 def __sub__(self, other: 'AbsolutePath') -> RelativePath:146 '''147 >>> AbsolutePath('/a/b/c') - AbsolutePath('/a/b/c')148 RelativePath('.')149 >>> AbsolutePath('/a/b/c') - AbsolutePath('/a/b/x')150 RelativePath('../c')151 >>> AbsolutePath('/a/b/c') - AbsolutePath('/d/e/f')152 RelativePath('../../../a/b/c')153 >>> a = AbsolutePath('/a/b/c'); b = AbsolutePath('/a/x/y')154 >>> b + (a - b) == a155 True156 >>> a + (b - a) == b157 True158 '''159 e1 = self.elements.copy()160 e2 = other.elements.copy()161 while e1 and e2 and e1[0] == e2[0]:162 e1.pop(0)163 e2.pop(0)164 return RelativePath('../' * len(e2) + '/'.join(e1))165 def __str__(self) -> str:166 '''167 >>> str(AbsolutePath('/a/b/c'))168 '/a/b/c'169 '''170 return '/' + '/'.join(self.elements)171 def __repr__(self) -> str:172 '''173 >>> AbsolutePath('/a/b/c')174 AbsolutePath('/a/b/c')175 '''176 return 'AbsolutePath(\'{}\')'.format(self)177 def __hash__(self) -> int:...

Full Screen

Full Screen

maya__env__.py

Source:maya__env__.py Github

copy

Full Screen

...1314def set_env():15 # Icarus env vars16 # (N.B. Project path vars are set in templates/projectDir.xml)17 os.environ['IC_MAYA_RENDER_EXECUTABLE'] = os_wrapper.absolutePath('%s/Render' % os.path.dirname(os.environ['IC_MAYA_EXECUTABLE']))18 os.environ['IC_MAYA_SHARED_RESOURCES'] = os_wrapper.absolutePath('$IC_FILESYSTEM_ROOT/_Library/3D/Maya') # Store this in app settings / IC global prefs?1920 # Maya config vars21 os.environ['MAYA_DEBUG_ENABLE_CRASH_REPORTING'] = "0"22 os.environ['MAYA_ENABLE_LEGACY_VIEWPORT'] = "1"23 os.environ['MAYA_FORCE_PANEL_FOCUS'] = "0" # This should prevent panel stealing focus from Qt window on keypress.24 os.environ['MAYA_DISABLE_CLIC_IPM'] = "1" # Disable the In Product Messaging button (should improve Maya startup & shutdown time).25 os.environ['MAYA_DISABLE_CIP'] = "1" # Disable the Customer Involvement Program (should improve Maya startup & shutdown time).2627 #os.environ['MAYA_MODULE_PATH'] = 28 #os.environ['MAYA_PRESET_PATH'] = os_wrapper.absolutePath('$IC_BASEDIR/rsc/maya/presets')29 #os.environ['MI_CUSTOM_SHADER_PATH'] = os_wrapper.absolutePath('$IC_BASEDIR/rsc/maya/shaders/include')30 #os.environ['MI_LIBRARY_PATH'] = os_wrapper.absolutePath('$IC_BASEDIR/rsc/maya/shaders')31 #os.environ['VRAY_FOR_MAYA_SHADERS'] = os_wrapper.absolutePath('$IC_BASEDIR/rsc/maya/shaders')32 #os.environ['VRAY_FOR_MAYA2014_PLUGINS_x64'] += os.pathsep + os_wrapper.absolutePath('$IC_BASEDIR/rsc/maya/plugins')3334 maya_ver = os.environ['IC_MAYA_VERSION']35 pluginsPath = os_wrapper.absolutePath('$IC_BASEDIR/rsc/maya/plugins') + os.pathsep \36 + os_wrapper.absolutePath('$IC_MAYA_SHARED_RESOURCES/%s/plug-ins' % maya_ver)37 scriptsPath = os_wrapper.absolutePath('$IC_BASEDIR/rsc/maya/env') + os.pathsep \38 + os_wrapper.absolutePath('$IC_BASEDIR/rsc/maya/scripts') + os.pathsep \39 + os_wrapper.absolutePath('$IC_MAYA_PROJECT_DIR/scripts') + os.pathsep \40 + os_wrapper.absolutePath('$IC_JOBPUBLISHDIR/scripts') + os.pathsep \41 + os_wrapper.absolutePath('$IC_SHOTPUBLISHDIR/scripts') + os.pathsep \42 + os_wrapper.absolutePath('$IC_MAYA_SHARED_RESOURCES/scripts') + os.pathsep \43 + os_wrapper.absolutePath('$IC_MAYA_SHARED_RESOURCES/%s/scripts' % maya_ver)44 iconsPath = os_wrapper.absolutePath('$IC_BASEDIR/rsc/maya/icons') + os.pathsep \45 + os_wrapper.absolutePath('$IC_JOBPUBLISHDIR/icons') + os.pathsep \46 + os_wrapper.absolutePath('$IC_MAYA_SHARED_RESOURCES/%s/icons' % maya_ver)47 if os.environ['IC_RUNNING_OS'] == "Linux": # Append the '%B' bitmap placeholder token required for Linux48 iconsPathsModified = []49 for path in iconsPath.split(os.pathsep):50 iconsPathsModified.append(path + r"/%B")51 iconsPath = os.pathsep.join(n for n in iconsPathsModified)5253 os.environ['MAYA_SHELF_PATH'] = os_wrapper.absolutePath('$IC_JOBPUBLISHDIR/ma_shelves') # For custom job shelf54 os.environ['MAYA_PLUG_IN_PATH'] = pluginsPath55 os.environ['MAYA_SCRIPT_PATH'] = scriptsPath56 # os.environ['PYTHONPATH'] = scriptsPath # this should only happen at Maya launch ...

Full Screen

Full Screen

osUse.py

Source:osUse.py Github

copy

Full Screen

1# -*- Coding:utf-8 -*-2"""3 osUes.py4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~5 os模块的应用6 @author: Manchester7 @data: 2018-04-23 8"""9import os10from os.path import join, getsize11import time 12absolutePath = os.path.realpath(__file__)13print(__file__)14print('当前文件绝的对路径地址:>', absolutePath)15absoluteDir = os.path.dirname(absolutePath)16print('当前文件目录的绝对地址:>', absoluteDir)17absolutePath.split('\\')[-1]18fileName = os.path.basename(absolutePath)19print(absolutePath.split('\\')[-1])20print('当前文件的名称:>', fileName)21projectDir = os.getcwd()22print('当前工程的绝对路径地址:>', projectDir)23fileSize = os.path.getsize(absolutePath)24print('当前路径的文件的大小为:%s字节' % fileSize)25createTime = os.path.getctime(absolutePath)26accessTime = os.path.getatime(absolutePath)27modifyTime = os.path.getatime(absolutePath)28toTime = lambda timeStamps : time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(timeStamps)).encode('utf8', 'ignore').decode('GBK', 'ignore')29print(type(toTime(createTime)))30print('当前路径文件的创建的时间戳:%s' % toTime(createTime))31print('当前路径文件的最后访问的时间戳:%s' % toTime(accessTime))32print('当前路径文件的最后修改的时间戳:%s' % toTime(modifyTime))33#help('os')34print('~'*50)35def fileInfo(filePath):36 #os.system('cls')37 absolutePath = os.path.realpath(filePath)38 fileName = os.path.basename(absolutePath)39 if os.path.isdir(filePath):40 size = 041 for root,dirs,files in os.walk(filePath):42 size += sum([getsize(join(root, filename)) for filename in files])43 else:44 size = os.path.getsize(absolutePath)45 createTime = os.path.getctime(absolutePath)46 accessTime = os.path.getatime(absolutePath)47 modifyTime = os.path.getatime(absolutePath)48 toTime = lambda timeStamps : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeStamps)).encode('GBK', 'ignore').decode('utf8', 'ignore')49 print('文件对象的名称:>', fileName)50 print('文件对象的类型:>', ['文件', '文件夹'][os.path.isdir(filePath)]) 51 print('文件对象的地址:>', absolutePath)52 print('文件对象的大小:> %s字节' % size)53 print('文件对象的创建时间:> %s' % toTime(createTime))54 print('文件对象的修改时间:> %s' % toTime(modifyTime))55 print('文件对象的访问时间:> %s' % toTime(accessTime))56if __name__ == '__main__':57 filePath = input('请输入需要查找的文件:>')58 try:59 fileInfo(filePath)60 except FileNotFoundError:...

Full Screen

Full Screen

database.py

Source:database.py Github

copy

Full Screen

1import os2import sqlite33from lucidity.system.log import logger4#noinspection PyDefaultArgument5class Database:6 def __init__(self, absolutePath:"str", schemaPath:"str"):7 self.absolutePath = absolutePath8 self.schemaPath = schemaPath9 def query(self, statement:"str", args:"list"=[], commit:"bool"=False): pass10 def verifyDatabase(self, absolutePath:"str", schemaPath:"str"): pass11#noinspection PyDefaultArgument12class Sqlite3Database(Database):13 def __init__(self, absolutePath:"str", schemaPath:"str"):14 Database.__init__(self, absolutePath, schemaPath)15 self._connection = self._getConnection(absolutePath, schemaPath)16 def _getConnection(self, absolutePath:"str", schemaPath:"str"):17 if not os.path.exists(absolutePath):18 self._createDatabase(absolutePath, schemaPath)19 else:20 self.verifyDatabase(absolutePath, schemaPath)21 return sqlite3.connect(absolutePath)22 def _createDatabase(self, absolutePath:"str", schemaPath:"str"):23 connection = sqlite3.connect(absolutePath)24 schemaFile = open(schemaPath, 'r')25 connection.executescript(schemaFile.read())26 schemaFile.close()27 connection.commit()28 connection.close()29 def verifyDatabase(self, absolutePath:"str", schemaPath:"str"):30 # TODO: Add missing columns from schema, max/min values31 pass32 def query(self, statement:"str", args:"list"=[], commit:"bool"=False):33 try:34 cursor = self._connection.cursor()35 cursor.execute(statement, args)36 if commit:37 self._connection.commit()38 return cursor39 except sqlite3.InterfaceError as error:...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { absolutePath } from 'storybook-root';2import { absolutePath } from 'storybook-root';3import { absolutePath } from 'storybook-root';4import { absolutePath } from 'storybook-root';5import { absolutePath } from 'storybook-root';6import { absolutePath } from 'storybook-root';7import { absolutePath } from 'storybook-root';8import { absolutePath } from 'storybook-root';9import { absolutePath } from 'storybook-root';10import { absolutePath } from 'storybook-root';11import { absolutePath } from 'storybook-root';12import { absolutePath } from 'storybook-root';13import { absolutePath } from 'storybook-root';14import { absolutePath } from 'storybook-root';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { absolutePath } from 'storybook-root';2import { absolutePath } from '/absolute/path/to/storybook-root';3import { absolutePath } from '/absolute/path/to/storybook-root';4import { absolutePath } from '/absolute/path/to/storybook-root';5import { absolutePath } from '/absolute/path/to/storybook-root';6import { absolutePath } from '/absolute/path/to/storybook-root';7import { absolutePath } from '/absolute/path/to/storybook-root';

Full Screen

Using AI Code Generation

copy

Full Screen

1var path = require('storybook-root-require').absolutePath;2var absolutePath = path('example.js');3console.log(absolutePath);4var path = require('storybook-root-require').absolutePath;5var absolutePath = path('example.js');6console.log(absolutePath);7var path = require('storybook-root-require').rootPath;8var rootPath = path('example.js');9console.log(rootPath);10var path = require('storybook-root-require').rootPath;11var rootPath = path('example.js');12console.log(rootPath);13var path = require('storybook-root-require').relativePath;14var relativePath = path('example.js');15console.log(relativePath);16var path = require('storybook-root-require').relativePath;17var relativePath = path('example.js');18console.log(relativePath);19var requireRoot = require('storybook-root-require').requireRoot;20var rootPath = requireRoot('example.js');21console.log(rootPath);22var requireRoot = require('storybook-root-require').requireRoot;23var rootPath = requireRoot('example.js');24console.log(rootPath);25var requireRelative = require('storybook-root-require').requireRelative;26var relativePath = requireRelative('example.js');27console.log(relativePath);28var requireRelative = require('storybook-root-require').requireRelative;29var relativePath = requireRelative('example.js');30console.log(relativePath);31var requireAbsolute = require('storybook-root-require').requireAbsolute;

Full Screen

Using AI Code Generation

copy

Full Screen

1const absolutePath = require('storybook-root-alias/absolutePath');2const path = require('path');3const absolutePath = require('storybook-root-alias/absolutePath');4const path = require('path');5const relativePath = './src/components/MyComponent';6const absolutePath = absolutePath(relativePath);7console.log(absolutePath);8const absolutePath = '/Users/username/Projects/my-project/src/components/MyComponent';9const relativePath = absolutePath(absolutePath);10console.log(relativePath);11const absolutePath = require('storybook-root-alias/absolutePath');12const path = require('path');13module.exports = (baseConfig, env, config) => {14 const babelLoader = config.module.rules.find(rule => rule.loader === 'babel-loader');15 const include = babelLoader.include;16 include.push(absolutePath('./src'));17 return config;18};

Full Screen

Using AI Code Generation

copy

Full Screen

1const path = require('storybook-root');2console.log(path.absolutePath('test.js'));3const path = require('storybook-root');4console.log(path.pathFromRoot('test.js'));5const path = require('storybook-root');6console.log(path.pathFromRoot('test.js', 'project'));7const path = require('storybook-root');8console.log(path.pathFromRoot('test.js', 'project', 'src'));9const path = require('storybook-root');10console.log(path.pathFromRoot('test.js', 'project', 'src', 'components'));11const path = require('storybook-root');12console.log(path.pathFromRoot('test.js', 'project', 'src', 'components', 'test'));13const path = require('storybook-root');14console.log(path.pathFromRoot('test.js', 'project', 'src', 'components', 'test', 'test'));15const path = require('storybook-root');16console.log(path.pathFromRoot('test.js', 'project', 'src', 'components', 'test', 'test', 'test'));17const path = require('storybook-root');18console.log(path.pathFromRoot('test.js', 'project', 'src', 'components', 'test', 'test', 'test', 'test'));

Full Screen

Using AI Code Generation

copy

Full Screen

1const storybookRoot = require('storybook-root');2const absolutePath = storybookRoot.absolutePath;3console.log(absolutePath('test.js'));4const storybookRoot = require('storybook-root');5const relativePath = storybookRoot.relativePath;6console.log(relativePath('/Users/username/Documents/Projects/StorybookRoot/test.js'));7const storybookRoot = require('storybook-root');8const relativePath = storybookRoot.relativePath;9console.log(relativePath('test.js'));10const storybookRoot = require('storybook-root');11const relativePath = storybookRoot.relativePath;12console.log(relativePath('test.js'));13const storybookRoot = require('storybook-root');14const relativePath = storybookRoot.relativePath;15console.log(relativePath('test.js'));16const storybookRoot = require('storybook-root');17const relativePath = storybookRoot.relativePath;18console.log(relativePath('test.js'));19const storybookRoot = require('storybook-root');20const relativePath = storybookRoot.relativePath;21console.log(relativePath('test.js'));22const storybookRoot = require('storybook-root');23const relativePath = storybookRoot.relativePath;24console.log(relativePath('test.js'));

Full Screen

Using AI Code Generation

copy

Full Screen

1const path = require('path');2const rootPath = require('storybook-root').absolutePath;3const myPath = rootPath('src/components/MyComponent');4console.log(myPath);5const path = require('path');6const rootPath = require('storybook-root').absolutePath;7const myPath = rootPath('src/components/MyComponent');8console.log(myPath);9const path = require('path');10const rootPath = require('storybook-root').absolutePath;11const myPath = rootPath('src/components/MyComponent');12console.log(myPath);13const path = require('path');14const rootPath = require('storybook-root').absolutePath;15const myPath = rootPath('src/components/MyComponent');16console.log(myPath);17const path = require('path');18const rootPath = require('storybook-root').absolutePath;19const myPath = rootPath('src/components/MyComponent');20console.log(myPath);21const path = require('path');22const rootPath = require('storybook-root').absolutePath;23const myPath = rootPath('src/components/MyComponent');24console.log(myPath);25const path = require('path');26const rootPath = require('storybook-root').absolutePath;27const myPath = rootPath('src/components/MyComponent');28console.log(myPath);29const path = require('path');30const rootPath = require('storybook-root').absolutePath;31const myPath = rootPath('src/components/MyComponent');32console.log(myPath);

Full Screen

Using AI Code Generation

copy

Full Screen

1const path = require('path');2const pathToStorybook = require('storybook-root');3console.log(pathToStorybook);4console.log(path.join(pathToStorybook, 'path/to/file'));5const pathToStorybook = require('storybook-root');6console.log(pathToStorybook.absolutePath('path/to/file'));7const pathToStorybook = require('storybook-root');8console.log(pathToStorybook.relativePath('../path/to/file'));9const pathToStorybook = require('storybook-root');10console.log(pathToStorybook.relativePath('../path/to/file'));11const pathToStorybook = require('storybook-root');12console.log(pathToStorybook.relativePath('../path/to/file'));13const pathToStorybook = require('storybook-root');14console.log(pathToStorybook.relativePath('../path/to/file'));15const pathToStorybook = require('storybook-root');16console.log(pathToStorybook.relativePath('../path/to/file'));17const pathToStorybook = require('storybook-root');18console.log(pathToStorybook.relativePath('../path/to/file'));19const pathToStorybook = require('storybook-root');20console.log(pathToStorybook.relativePath('../path/to/file'));

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful