def testValidity(): if len(sys.argv) == 3: try: directory = sys.argv[1] numberOfBestMatch = int(sys.argv[2]) except: print(__doc__) sys.exit(1) elif len(sys.argv) == 4: try: directory = sys.argv[1] pathToContigsIdFile = sys.argv[3] tempFile = open(pathToContigsIdFile, 'r') tempFile.close() numberOfBestMatch = int(sys.argv[2]) except: print(__doc__) sys.exit(1) else: print(__doc__) sys.exit(1) try: tempFile = open(directory+"/_DeNovoAssembly/Contigs.tsv", 'r') tempFile.close() except: Error.error("Unable to open: "+directory+"/_DeNovoAssembly/Contigs.tsv") sys.exit(1)
def close(text): if 'word' in text: return os.system('taskkill/f /im WINWORD.EXE') elif 'ppt' in text or 'powerpoint' in text: return os.system('taskkill/f /im POWERPNT.EXE') elif 'excel' in text: return os.system('taskkill/f /im EXCEL.EXE') elif 'pub' in text or 'publisher' in text: return os.system('taskkill/f /im MSPUB.EXE') elif 'outlook' in text: return os.system('taskkill/f /im OUTLOOK.EXE') elif 'onenote' in text: return os.system('taskkill/f /im ONENOTE.EXE') elif 'access' in text: return os.system('taskkill/f /im MSACCESS.EXE') elif 'browser' in text: return os.system('taskkill/f /im chrome.exe') elif 'notepad' in text: return os.system('taskkill/f /im notepad.exe') elif 'discord' in text: return os.system('taskkill/f /im Discord.exe') elif 'groove' in text: return os.system('taskkill/f /im Music.UI.exe') elif 'adobe' in text: return os.system('taskkill/f /im AcroRd32.exe') elif 'explorer' in text or 'windows explorer' in text: return os.system('taskkill/f /im explorer.exe & start explorer') else: if len(text) > 0: return Error.printline(f"[ERROR]: {text} is not available.") else: return Error.printline(f"[ERROR]: No input found.")
def AlterTableFK(nodo, tablaSimbolos): global useActual global consola base = tablaSimbolos.get(useActual) tabla = base.getTabla(nodo.idtabla) for i in range(len(nodo.idlocal)): idlocal = nodo.idlocal[i].valor idfk = nodo.idfk[i].valor columnafk = tablaSimbolos.getColumna(useActual, nodo.idtablafk, idfk) columnalocal = tabla.getColumna(idlocal) if columnafk != None and columnalocal != None: if columnafk.tipo.tipo == columnalocal.tipo.tipo: tabla.modificarFk(idlocal, nodo.idtablafk, idfk) listaFK.append( TS.llaveForanea(useActual, nodo.idtabla, nodo.idtablafk, idlocal, idfk)) consola += "Se agrego la llave foranea a " + idlocal + " exitosamente \n" else: listaSemanticos.append( Error.ErrorS( "Error Semantico", "La columna %s y la columna %s no tienen el mismo tipo" % (idlocal, idfk))) else: listaSemanticos.append( Error.ErrorS("Error Semantico", "No se encontró la columna"))
def inBetween(x, y): if x > y: temp = x x = y y = temp linex = getLineOfHole(x) liney = getLineOfHole(y) # first condition: if on same line, then # must be exactly two away for valid jump if liney == linex: if y - x == 2: return y - 1 else: raise e.InvalidJumpError() # second condition: if on different lines, those # lines must be two apart, leaving room for a piece # to be jumped but not too far of a jump elif liney - linex != 2: raise e.InvalidJumpError() # lastly, if on lines 2 apart must follow the rule: # going up 2 lines to the left, as would be required for a # legal jump, requires a difference of (2*line_no) + 1 # going up 2 lines to the right, as would be required for a # legal jump in that direction, requires difference of # (2*line_no) - 1, where line_no is the greater of the line # numbers of the two holes else: if x == y - (2*liney + 1): # going up left return y - (liney + 1) elif x == y - (2*liney - 1): # going up right return y - liney else: raise e.InvalidJumpError()
def Nome_Funcao(tokens, i, first, SemanticTable): linha = tokens[i][2] if (tokens[i][0] == 'function'): i += 1 else: Error.SyntaticError(tokens[i]) global escopo escopo = tokens[i][1] classificador = tokens[i][1] i = Identificador(tokens, i, first, SemanticTable) if (tokens[i][0] == 'Abreparêntese'): i += 1 else: Error.SyntaticError(tokens[i]) global flagparametro global numParametro flagparametro = True numParametro = 0 i = Variaveis(tokens, i, first, SemanticTable) flagparametro = False if (tokens[i][0] == 'Fechaparêntese'): i += 1 else: Error.SyntaticError(tokens[i]) if (tokens[i][0] == 'DoisPontos'): i += 1 else: Error.SyntaticError(tokens[i]) i = Tipo_Dado(tokens, i, first, SemanticTable) SemanticTable.append( [classificador, linha, 'global', tipo, 'function', numParametro]) return i
def unique_family_spouse_marriage_date(parsed_file, errors): """ US24:No more than one family with the same spouses by name and the same marriage date should appear in a GEDCOM file """ family_info = {} # fid:{spouse:[], marriage_date: str} for k in parsed_file['family'].keys(): family = parsed_file['family'][k] spouse1, spouse2 = family['Spouse 1 Name'], family['Spouse 2 Name'] marriage_date = family['Married'] for key, value in family_info.items(): if operator.eq(sorted([spouse1, spouse2]), sorted(value['spouses'])): us24Err = Error.Error(Error.ErrorEnum.US24) us24Err.alterErrMsg(key, k) errors.add(us24Err) continue if marriage_date == value['marriage_date']: us24Err = Error.Error(Error.ErrorEnum.US24) us24Err.alterErrMsg(key, k) errors.add(us24Err) else: family_info[k] = { 'spouses': [spouse1, spouse2], 'marriage_date': marriage_date } return errors
def __init__(self, ctl, ccver, platform, config, logfile, verbose): self.clsname = self.__class__.__name__ self.version = 1.0 # self.ctl = ctl self.ccver = ccver self.platform = platform self.config = config self.logfile = logfile self.verbose = verbose # # このファイルは ".../core/test/bin" に置くこと script_dir = os.path.abspath(__file__).split(os.sep)[:-1] script_dir = os.sep.join(script_dir) setup_file = script_dir + '../../../src/setup.conf' setup_file = os.path.abspath(setup_file) self.setup_file_exists = False if os.path.exists(setup_file): print(' setup file exists') self.setup_file_exists = True self.sf = SetupFile(setup_file) self.sf.setenv() # self.generator = self.__find_generator(ccver) self.error = Error(self.clsname)
def make_makefile(module, fname, interfs, inchdrs, srchdrs): target = '%s/EP%s.cpp' % (embpythondir, module) dependencies = [] dependencies.extend(interfs) dependencies.extend(inchdrs) dependencies.extend(srchdrs) if verbose: print(' target: [%s]' % target) print(' dependencies: [%s]' % dependencies) lines = [] lines.append('# Do not edit. RunSwig_EmbPython will update this file.') lines.append('# File: %s' % fname) lines.append('') lines.append('all:\t%s' % target) lines.append('%s:\t%s' % (target, ' '.join(dependencies))) lines.append('\t@python %s %s' % (swig, module)) lines.append('') for f in dependencies: lines.append('%s:' % f) fio = TextFio(fname, 'w') if fio.open() != 0: msg = '%s: can not open file (write)' % fname Error(prog).abort(msg) rc = fio.writelines(lines) fio.close() if rc != 0: msg = '%s: write failed' % fname Error(prog).abort(msg)
def findLCA(self, node1, node2): if self.nodeExist(node1) and self.nodeExist(node2): pass else: if not(self.nodeExist(node1)): sys.stderr.write("Node does not exist: "+str(node1)) if not(self.nodeExist(node2)): sys.stderr.write("Node does not exist: "+str(node2)) Error.error("Logic error, asked to find LCA for a node that does not exists"+str(node1) +str(node2)+"\n") parentsOfNode1 = [] parentsOfNode1.append(node1) parentsOfNode2 = [] parentsOfNode2.append(node2) lca = -1 #i = -1 while self.getNodes(node1).hasParent(): parentToAdd = self.getNodes(node1).getParents() parentsOfNode1.append(parentToAdd) node1 = parentToAdd while self.getNodes(node2).hasParent(): parentToAdd = self.getNodes(node2).getParents() parentsOfNode2.append(parentToAdd) node2 = parentToAdd for i in parentsOfNode1: if i in parentsOfNode2: lca = i break if lca == -1: Error.warning("Have not found the LCA for nodes:" +str(node1)+" and "+str(node2)) return lca
def __init__(self, root=None, url_info=None, folder_name=None, protected=False, name=None): """ A valid addon requires at least the root folder and url_info tuple (repo_type, url) or a root folder and an addon folder. @param root: the folder containing the addon folder(absolute path) @type root: str @param url_info: a (repo_type, url) tuple, which contains the url and the corresponding repository type (currently supporting: git, svn, hg) @type url_info: tuple @param folder_name: the addon folder name @type folder_name: str @param protected: a protected addon can't be modified @type protected: bool @param name: the addon's name (just for recognition) @type name: str #raise: Error.AddonRootError , Error.AddonInitError """ #note difference between self._root and self.url_info assignments #in the second case the property function _set_url_info is called try: if not root: raise Error.AddonRootError() if (url_info) or (folder_name): #TODO check if its an absolute path, does the url start with a '/' ? self._root = os.path.expanduser(root) self.name = name self.url_info = url_info #valid folder required for cloning if folder_name == None: self.folder_name = "TmpFolder_" + str( self.__class__.num_addons) else: self.folder_name = folder_name #protected addons cannot be changed, deleted, updated, cleaned, etc. self.protected = protected #config file (usually .pkgmeta file) #currently only changed by the parse_pkgmeta_file() function self._config_info = {} self._config_file_parsed = False #increment counter self.__class__.num_addons += 1 else: raise Error.AddonInitError() except (Error.AddonRootError, Error.AddonInitError) as e: print(e)
def AlterAddColumn(nodo, tablaSimbolos): global consola global useActual base = tablaSimbolos.get(useActual) tabla = base.getTabla(nodo.idtabla) for col in nodo.listaColumnas: auxcol = TS.SimboloColumna(col.idcolumna, col.tipo, False, None, None, None, True, None) if tabla.crearColumna(col.idcolumna, auxcol): b = jBase.alterAddColumn(useActual, nodo.idtabla, col.idcolumna) if b == 0: consola += "La columna " + col.idcolumna + " se agregó a la tabla " + nodo.idtabla + " \n" elif b == 1: listaSemanticos.append( Error.ErrorS("Error Semantico", "Error en la operacion.")) elif b == 2: listaSemanticos.append( Error.ErrorS("Error Semantico", "Error la base " + useActual + "no existe")) elif b == 3: listaSemanticos.append( Error.ErrorS( "Error Semantico", "Error la tabla " + nodo.idtabla + "no existe")) else: consola += "Error al crear la columna " + col.idcolumna + " \n"
def output(fname, lines): fobj = TextFio(fname, 'w', encoding='utf8') if fobj.open() < 0: Error(prog).error(fobj.error()) if fobj.writelines(lines, '\n') < 0: Error(prog).error(fobj.error()) fobj.close()
def __init__(self, name, time_stamp, header=None): self._platform = Platform.Platform() self._os = OS.OS() self._name = name self._ERR_FILE_EXIST = "ERROR: Log file '%s' already exists" % name self._ERR_FILE_OPEN = "ERROR: Unable to open log file '%s'" % name if self._os.is_file(name): raise Error.Error(msg=self._ERR_FILE_EXIST) else: try: f = open(name, 'w') except IOError: raise Error.Error(msg=self._ERR_FILE_OPEN) if header != None: f.write("%s\n" % header) line = "Generated %s" % time_stamp.as_string() f.write(line+"\n\n") line = "System: %s" % self._platform.system() f.write(line+"\n") line = "Python version: %s" % self._platform.python_version() f.write(line+"\n") line = ("Python implementation: %s" % self._platform.python_implementation()) f.write(line+"\n\n") f.close()
def execute(self, data, tbname, cons, idconst='ALTER'): #validate if listaid1 exists colindex = 0 found = False for colu in data.tablaSimbolos[ data.databaseSeleccionada]['tablas'][tbname]['columns']: if colu.name == self.id.upper(): found = True if not colu.pk == None or not colu.unique == None: error = Error( 'Semántico', 'Error(???): La primary key o unique no puede modificarse.', 0, 0) return error break colindex += 1 if not found: error = Error( 'Semántico', 'Error(???): No existe la columna ' + self.id.upper(), 0, 0) return error data.tablaSimbolos[data.databaseSeleccionada]['tablas'][tbname][ 'columns'][colindex].null = self.option print('Cambio Not null / null exitoso') return 'Cambio Not null / null exitoso'
def __mediasetSearch(self, html): mediasetchannel = re.findall('s.eVar3="(.*)"', html)[0] programa = re.findall('s.eVar7="(.*)"', html)[0] temporada = re.findall('s.eVar8=".* ([0-9].*)"', html)[0] capitulo = re.findall('s.eVar9=".* ([0-9].*)"', html)[0] if int(temporada) < 10: temporada = "0%s" % (temporada) if int(capitulo) < 10: capitulo = "0%s" % (capitulo) abuscar = urllib2.quote("%s T%sxC%s" % (programa, temporada, capitulo)) search = "http://www.%s.es/buscador/?text=%s" % (mediasetchannel, abuscar) self.debug(u"Programa: %s" % programa) self.debug(u"Temporada: %s" % temporada) self.debug(u"Capitulo: %s" % capitulo) self.debug(u"Search... %s" % search) results = Descargar.get(search) self.debug(search) try: r = results.split('<h2 class="headline')[1].split( 'href="')[1].split('"')[0] except IndexError: raise Error.GeneralPyspainTVsError( "mitele.es: RTMP no soportado para el canal por ahora.") mediasetLink = "http://www.%s.es%s" % (mediasetchannel, r) if mediasetchannel == "telecinco": from telecinco import Telecinco as newChannel elif mediasetchannel == "cuatro": from cuatro import Cuatro as newChannel else: raise Error.GeneralPyspainTVsError( "mitele.es: RTMP no soportado para el canal por ahora.") channel = newChannel(mediasetLink) return channel.getInfo()
def testValidity(): if len(sys.argv) == 3: try: directory = sys.argv[1] numberOfBestMatch = int(sys.argv[2]) except: print(__doc__) sys.exit(1) elif len(sys.argv) == 4: try: directory = sys.argv[1] pathToContigsIdFile = sys.argv[3] tempFile = open(pathToContigsIdFile, 'r') tempFile.close() numberOfBestMatch = int(sys.argv[2]) except: print(__doc__) sys.exit(1) else: print(__doc__) sys.exit(1) try: tempFile = open(directory + "/_DeNovoAssembly/Contigs.tsv", 'r') tempFile.close() except: Error.error("Unable to open: " + directory + "/_DeNovoAssembly/Contigs.tsv") sys.exit(1)
def findLCA(self, node1, node2): if self.nodeExist(node1) and self.nodeExist(node2): pass else: if not (self.nodeExist(node1)): sys.stderr.write("Node does not exist: " + str(node1)) if not (self.nodeExist(node2)): sys.stderr.write("Node does not exist: " + str(node2)) Error.error( "Logic error, asked to find LCA for a node that does not exists" + str(node1) + str(node2) + "\n") parentsOfNode1 = [] parentsOfNode1.append(node1) parentsOfNode2 = [] parentsOfNode2.append(node2) lca = -1 #i = -1 while self.getNodes(node1).hasParent(): parentToAdd = self.getNodes(node1).getParents() parentsOfNode1.append(parentToAdd) node1 = parentToAdd while self.getNodes(node2).hasParent(): parentToAdd = self.getNodes(node2).getParents() parentsOfNode2.append(parentToAdd) node2 = parentToAdd for i in parentsOfNode1: if i in parentsOfNode2: lca = i break if lca == -1: Error.warning("Have not found the LCA for nodes:" + str(node1) + " and " + str(node2)) return lca
def __cp(self, src, dst, follow_symlinks=True): if self.verbose: print('__cp: %s -> %s' % (src, dst)) # rc = 0 try: if self.verbose: print(' cwd: %s' % Util.upath(os.getcwd())) print(' src: %s' % Util.upath(src)) print(' dst: %s' % Util.upath(dst)) if os.path.isdir(src): if os.path.exists(dst): prog = '%s: cp' % self.clsname msg = '"%s" exists' % dst Error(prog).error(msg) return 1 if self.verbose: print(' shutil.copytree()') shutil.copytree(src, dst, follow_symlinks) else: if self.verbose: print(' shutil.copy2()') shutil.copy2(src, dst) except OSError as why: prog = '%s: cp' % self.clsname Error(prog).error(str(why)) rc = 1 return rc
def AlterRenameColumn(nodo, tablaSimbolos): base = tablaSimbolos.get(useActual) tabla = base.getTabla(nodo.idtabla) global consola op = tabla.renameColumna(nodo.idcolumna, nodo.idnuevo) if op == 0: for fk in listaFK: if fk.idcfk == nodo.idcolumna: fk.idcfk = nodo.idnuevo tablaRF = base.getTabla(fk.idtlocal) columnaRF = tablaRF.getColumna(fk.idclocal) columnaRF.foreign_key["columna"] = nodo.idnuevo elif fk.idclocal == nodo.idcolumna: fk.idclocal = nodo.idnuevo for cons in listaConstraint: if cons.idcol == nodo.idcolumna: cons.idcol = nodo.idnuevo consola += "Se cambio el nombre de la columna " + nodo.idcolumna + " a " + nodo.idnuevo + " con exito \n" elif op == 1: listaSemanticos.append( Error.ErrorS( "Error Semantico", "La columna con nombre " + nodo.idnuevo + " ya existe")) elif op == 2: listaSemanticos.append( Error.ErrorS( "Error Semantico", "La columna con nombre " + nodo.idactual + " no existe"))
def delete(): body_data = request.json print(body_data) try: pizza_type = body_data['pizza'] print(pizza) if pizza_type == "" or pizza_type is None: return err.ReturnValueError() conn = connect.ConnectMySql() print(f'Connection status : {conn.is_connected()}') if (conn is False): return err.ReturnConnectionError() else: cur1 = conn.cursor() print(f'Cursor object : {cur1}') query = (f'DELETE from orderPizza where pizza_type="{pizza}"') cur1.execute(query) cur2 = conn.cursor() selectquery = SelectQuery() cur2.execute(selectquery) msg = "Data deleted succesfully" result = res.generateResponse(cur2, msg) conn.close() return result except KeyError as e: return err.ReturnKeyError() except Exception as e: print(e) return e
def _remove_tree(self, file): """ A little support function to delete directories/files/links. Deleting files is only possible within the addon root folder. returns True, if everything worked. None otherwise @param file: file or folder (absolute path) to be removed recursively @type file: str OSError is handled """ try: try: #is it a subfolder/subfile in the addon root ? if file.startswith(self.root): if os.path.isfile(file): os.remove(file) else: shutil.rmtree(file) else: raise Error.CommonRemoveTreeError(self.root, file) return True except OSError as e: raise Error.CommonOSError(e) except Error.CommonRemoveTreeError as e: print(e) except Error.CommonOSError as e: print(e)
def fetch(): body_data = request.json print(body_data) try: status = body_data['status'] print(status) if status == "" or status is None: return err.ReturnValueError() conn = connect.ConnectMySql() print(f'Connection status : {conn.is_connected()}') if (conn is False): return ReturnConnectionError() else: cur = conn.cursor() print(f'Cursor object : {cur}') query = (f'SELECT * from orderPizza where status="{status}"') cur.execute(query) msg = "Fetched data succesfully" result = res.generateResponse(cur, msg) conn.close() return result except KeyError as e: return err.ReturnKeyError() except Exception as e: print(e) return err.ReturnFetchError()
def range(*args): """ Wrapper for range usage, returning an iterator regardless of if python 2 or python 3 is used """ if len(args) < 1 or len(args) > 3: err_msg = "ERROR: Anguilla range function takes 1, 2, or 3 arguments" raise Error.Error(msg=err_msg) start = 0 stop = 1 step = 1 if len(args) == 1: stop = args[0] if len(args) == 2: start = args[0] stop = args[1] if len(args) == 3: start = args[0] stop = args[1] step = args[2] if platform.is_python2(): return builtins.xrange(start, stop, step) elif platform.is_python3(): return builtins.range(start, stop, step) else: err_msg = "ERROR: Unknown python platform" raise Error.Error(msg=err_msg)
def parseRequest(self,request): try: lines=request.splitlines() index=lines.index("") if "" in lines else len(lines) headers=lines[1:index] body=lines[index+1:] method,path,version = lines[0].split() if not method in self.methods or version.upper()!='HTTP/1.1': raise Error('400') dic={ 'method':method, 'path':path, 'version':version, 'headers':{}, 'body':body[0] if len(body)>0 else '' } for i in range(0,len(headers)): title,content=headers[i].split(':',1) dic['headers'][title]=content.strip(' ') return dic except : raise Error('400')
def AlterDatabase(nodo, tablaSimbolos): global consola if nodo.rename: b = jBase.alterDatabase(nodo.id.valor, nodo.idnuevo) if b == 0: base = tablaSimbolos.renameBase(nodo.id.valor, nodo.idnuevo) if base: for fk in listaFK: if fk.idbase == nodo.id.valor: fk.idbase = nodo.idnuevo for cons in listaConstraint: if cons.idbase == nodo.id.valor: cons.idbase = nodo.idnuevo consola += "La base se renombró con éxito " + nodo.idnuevo + " \n" else: consola += "Error no se pudo renombrar la base " + nodo.id.valor + " en la tabla de simbolos \n" elif b == 2: listaSemanticos.append( Error.ErrorS( "Error Semantico", "La base de datos " + nodo.id.valor + " no existe")) elif b == 3: listaSemanticos.append( Error.ErrorS("Error Semantico", "La base de datos ya existe " + nodo.idnuevo)) elif b == 1: listaSemanticos.append( Error.ErrorS("Error Semantico", "Error en la operacion."))
def __read_usage(self, path): if not os.path.exists(path): msg = 'no such file: "%s"' % path Error(self.clsname).abort(msg) # read the file f = TextFio(path) if f.open() < 0: Error(self.clsname).abort(f.error()) lines = f.read() f.close() # find pattern usage = None patt = '#(define|undef)\s+USE_CLOSED_SRC' for line in lines: m = re.match(patt, line) if m: matched = m.group(1) if matched == 'define': usage = CSU.USE if matched == 'undef': usage = CSU.UNUSE break if usage is None: msg = 'bad closed-src-header' Error(self.clsname).abort(msg) return usage
def execute(self): left = self.leftOperator.execute() if isinstance(left, Error): return left right = self.rightOperator.execute() if isinstance(right, Error): return right if self.sign == '>': if (left.type == 'integer' and right.type == 'integer') or ( left.type == 'float' and right.type == 'float') or ( left.type == 'float' and right.type == 'integer') or ( left.type == 'integer' and right.type == 'float'): comp = int(left.val) > int(right.val) return Primitive('boolean', comp) else: error = Error( 'Semántico', 'Error de tipos en MAYOR QUE, no se puede operar ' + left.type + ' con ' + right.type, 0, 0) return error else: if (left.type == 'integer' and right.type == 'integer') or ( left.type == 'float' and right.type == 'float') or ( left.type == 'float' and right.type == 'integer') or ( left.type == 'integer' and right.type == 'float'): comp = int(left.val) < int(right.val) return Primitive('boolean', comp) else: error = Error( 'Semántico', 'Error de tipos en MENOR QUE, no se puede operar ' + left.type + ' con ' + right.type, 0, 0) return error
def translate_using_sequence(self, contig): """ Translate the SNPs at this position and give the proportion. :param contig: A Contig object with associated Gene(s) :return:A line to stdout """ if type(contig).__name__ != "Contig": Error.error("Genomic_environment: translate_using_sequence: The object passed is not of type Contig") #For each gene in Contig... we search for the one that contain the position gene = Gene.__init__() for orf in contig.genes: if orf.start <= self.position <= orf.end: gene = orf if gene.sequence == "": Error.error("Genomic_environment: translate_using_sequence: There is no sequence in the selected gene") orf_seq = Seq(gene.sequence, IUPAC.unambiguous_dna) amino_acid_sequence = str(orf_seq.translate(table=11)) orf_seq = orf_seq.tomutable() nucleotides_sequences = self.group_environment() total = len(self.reads) header = "Contig\tSNP position(contig)\tFrame\tAmino acid\tProportion\n" #We put - in the frame number column. print(header), for entry in nucleotides_sequences: mutation = entry[2] mutated_seq = copy.copy(orf_seq) mutated_seq[self.position-gene.start] = mutation mutated_prot_seq = str(mutated_seq.translate(table=11)) changed_amino_acid_position = math.ceil(float(self.position-gene.start+1)/3) changed_amino_acid = mutated_prot_seq[changed_amino_acid_position-1] #-1 cuz its a python string. line = (self.contig+"\t"+self.position+"\t-\t"+changed_amino_acid+"\t" + str(float(nucleotides_sequences[entry])/total)) print(line)
def execute(self, data, tbname = 'NADA'): if self.type == 'foreign': if self.tableExists(data): #validando que ambas listas tengan el mismo tamaño if len(self.list) != len(self.extra) : error = Error('Semántico', 'Error(FK): El númmero de FK especificadas no coincide con el de columnas de referencia.', 0, 0) return error #validando si las colunas de la lista extra existen tabla = self.id.upper() for col in self.extra : found = False for column in data.tablaSimbolos[data.databaseSeleccionada]['tablas'][tabla]['columns'] : if col.column.lower() == column.name.lower() : found = True if not found : error = Error('Semántico', 'Error(FK): La columna: ' + col.column.upper() +' no existe.', 0, 0) return error #validando que las columnas de la lista list existan colindex = [] for col in self.list : found = False i = 0 for column in data.tablaSimbolos[data.databaseSeleccionada]['tablas'][tbname.upper()]['columns'] : if col.column.lower() == column.name.lower() : found = True colindex.append(i) i += 1 if not found : error = Error('Semántico', 'Error(FK): La columna: ' + col.column.upper() +' no existe.', 0, 0) return error #agregando a tabla de simbolos referenceslist = [] for id in self.extra : referenceslist.append(Identificador(self.id.upper(), id.column.upper())) print(referenceslist) i = 0 for index in colindex : idconst = 'FK_'+tbname+'_'+data.tablaSimbolos[data.databaseSeleccionada]['tablas'][tbname]['columns'][index].name checkData = ConstraintData(idconst, referenceslist[i], 'fk') data.tablaSimbolos[data.databaseSeleccionada]['tablas'][tbname]['columns'][index].fk.append(checkData) i += 1 print(self) else: error = Error('Semántico', 'Error(FK): La tabla: ' + self.id +' no existe.', 0, 0) return error elif self.type == 'references' : print(self) return self
def __init__(self, *args, **kwargs): if kwargs.get('window_dimension') is None: raise Error.InputError('Window dimension', 'is a required parameter') self.window_dimension = kwargs.get('window_dimension') if self.__class__ is MovingWindow: raise Error.Error('MovingWindow is an abstract base class')
def loadConverter(self, file): sys.stderr.write("Loading converter from file\n") if FileUtility.isValid(file): f = open(file, "rb") self.Converter = pickle.load(f) f.close() sys.stderr.write("Converted loaded\n") else: Error.error("Converter.bin can not be opened. You should produce or reproduce it using prepare.py")
def find(self, key): if self.head is None: raise Error.EmptyLinkedList("No data found") curr = self.head while curr.next: if curr.data == key: return curr curr = curr.next raise Error.KeyNotFound("Key %s not found", str(key))
def register(toolname, protgen): global tools for t in tools: if t.name == toolname: registerToolGen(t, protgen) return protgen.tool = None Error.showWarningOnce("Could not find tool %s" % toolname)
def checkIfLvalueValid(self, token): if token.data[0].id == '&': raise SyntaxError(Error.generateErrorMessageWithNoArguement('Invalid lvalue type of assignment', token)) elif token.data[0].id in ('(identifier)', '(literal)'): return elif token.data[0].arity == 3 and token.data[0].id != '[': Error.generateErrorMessageWithNoArguement('Invalid lvalue type of assignment', token) else: self.checkIfLvalueValid(token.data[0])
def loadConverter(self, file_name): sys.stderr.write("Loading converter from file\n") if Utility.isValid(file_name): f = open(file_name, "rb") self.Converter = pickle.load(f) f.close() sys.stderr.write("Converted loaded\n") else: Error.error("Converter.bin can not be opened. You should produce or reproduce it using prepare.py");
def countLines(file_name): lines = 0 try: for i in open(file): lines += 1 except: lines = 0 if lines == 0: Error.error("File "+str(file)+" is empty") return lines
def addTaxonName(self, file_name): sys.stderr.write("Adding taxon name to tree\n") Utility.isValid(file_name) for line in open(file_name): id = int(line.split('\t')[0]) name = line.split('\t')[1] rank = line.split('\t')[2] if self.nodeExist(id): self.getNodes()[id].getTaxonName().setAll(name, rank) else: Error.warning("A taxon is missing")
def add_alignement_position(self, sample, gen_position): try: if gen_position.position <= 0: Error.error("Aligned_contig:add_alignement: The gen_position was not set") else: self.comparable_sample[sample].append(gen_position) self.comparable_sample[sample].sort(key=lambda x: x.position) #We keep the list in order for ordered output. #TODO: execute sort only when output is aksed? except: Error.error("Aligned_contig:set_alignement: Object is not good")
def parseDatabaseHeader(self) : databaseHeader = DatabaseHeader(self.inputPath) databaseHeader.parseDabaseHeader() if databaseHeader.getSignature() != -1985229329 : #\xef\xcd\xab\x89 Error.printError(0) self.status = databaseHeader.getStatus() self.pageSize = databaseHeader.getPageSize() self.version = databaseHeader.getVersion() self.revision = databaseHeader.getRevision() self.pageHeaderSize = databaseHeader.getPageHeaderSize() databaseHeader = None
def readPathsFile(pathToContigsIdFile): #TODO: verifier que si les fichiers ont ou non le ContigIdentifications.tsv a la fin. contigIdentificationsFiles = [] try: tempfile = open(pathToContigsIdFile, 'r') tempfile.close() except: Error.error("Unable to open: "+pathToContigsIdFile) sys.exit(1) for lines in open(pathToContigsIdFile, 'r'): contigIdentificationsFiles.append(lines[0:len(lines)-1]) return contigIdentificationsFiles
def StartClient(self): connected = False i = 0 while not connected and i != 5: try: self.local_socket.connect(("10.92.5.20", COM_PORT)) connected = True except: i += 1 if i >= 5: Error.error_msg() """ look for the ip again, gil sent a func that gets an ip (the servers ip) by the mac address """
def _postRequestRenderer(*args): global _doingDeferred _doingDeferred = 1 try: for name, argDict, auxArgs, compType, srcModTime, cached in _postRequestRenderList: try: DEBUG(COMPONENT, "deferredly rendering %s" % name) _renderComponentAndCache(name, argDict, auxArgs, compType, srcModTime, cached) except: Error.logException() _postRequestRenderList[:] = [] finally: _doingDeferred = 0
def _renderComponentAndCache(name, argDict, auxArgs, compType, srcModTime, cached): DEBUG(COMPONENT, "_renderComponentAndCache") try: mashed = argDict.copy() (out, cache_exp_time) = _realRenderComponent(name, argDict, auxArgs, compType, srcModTime) mashed.update(auxArgs) Cache.putCachedComponent(name, mashed, out, cache_exp_time) except: if cfg.Configuration.fallbackToCache and cached: DEBUG(COMPONENT, "execution explosion and fallback active") Error.logException() DEBUG(COMPONENT, "After logexc") return cached.out raise return out
def nud(self): self.arity = thisContext.PREFIX_UNARY thisContext.contextManager.parser.lexer.advance() returnedToken = thisContext.contextManager.parser.parse(120) idenToken = thisContext.getIdentifier(returnedToken) if idenToken is None: raise SyntaxError(Error.generateErrorMessageWithNoArguement('(literal) do not have address', returnedToken)) self.data.append(returnedToken) return self
def readItemBig(self, itemOffset, size): value = None parsingOffset = itemOffset + self.standdardOffset if size < 0 : Error.printError(1) elif size == 0 : value = 0 elif size == 1 : value = self.hexReader.readByte(parsingOffset) elif size == 2 : value = self.hexReader.readUnsignedShortBig(parsingOffset) elif size == 4 : value = self.hexReader.readUnsignedIntegerBig(parsingOffset) elif size == 8 : value = self.hexReader.readUnsignedLongBig(parsingOffset) else : value = self.hexReader.readUnsignedNumberBig(parsingOffset, size) return value
def readItem(self, itemOffset, size): value = None parsingOffset = itemOffset + self.standdardOffset if size < 0 : Error.printError(1) elif size == 0 : value = 0 elif size == 1 : value = self.hexReader.readByte(parsingOffset) elif size == 2 : value = self.hexReader.readShort(parsingOffset) elif size == 4 : value = self.hexReader.readInteger(parsingOffset) elif size == 8 : value = self.hexReader.readLong(parsingOffset) else : value = self.hexReader.readHexDump(parsingOffset, size) return value
def readContigIdentificationFiles(files, biologicalAbundanceContigs): for line in open(files, 'r'): if line == "": break if line[0] == '#': continue else: try: contigName = line.split()[0] sequenceName = line.split('\t')[6] sequenceLength = int(line.split('\t')[7]) matches = int(line.split('\t')[8]) biologicalAbundanceContigs[contigName].addNewContigIdentification(sequenceName, sequenceLength, matches) except: message = ("File: " + files + " can not be read or do not correspond to the usual patern. It has been discarded") Error.warning(message)
def checkTree(self): numOfNode = len(self.getNodes()) sys.stderr.write(str(numOfNode)+ " to be checked\n") checked = 0 root = [] for i in self.Nodes: #print(self.Nodes[i].getId()==1); #if not(self.Nodes[i].getId()): # print("my parents") # print(self.Nodes[i].getParents()); # print("my kids") # print(self.Nodes[i].getKids()); if self.Nodes[i].getParents(): if self.nodeExist(self.Nodes[i].getParents()): pass #print("One parent checked") else: Error.error("Logic error: tree is not valid because this parent does not exist:"+str(self.Nodes[i].getParents())); else: sys.stderr.write("Found a root\n") root.append(self.Nodes[i]) for k in self.Nodes[i].getKids(): if self.nodeExist(k): pass #print("One kid checked"); else: Error.error("Logic error: tree is not valid because this kid does not exist:"+str(k)); checked += 1 if checked % 50000 == 0: sys.stderr.write(str(checked)+" nodes checked\n") if len(root) > 1: Error.warning("There is more than one root\n") sys.stderr.write("Taxonomic tree is considered valid\n")
def start(self): i = 0 while i < MAX_CONNECTIONS: try: self.socket.connect((SERVER_ADDRESS, SERVER_PORT)) print "connected" break except: i += 1 if i == MAX_CONNECTIONS or i > MAX_CONNECTIONS: Error.server_error_msg() return self.socket.send('Hello\r\n') data = self.socket.recv(LEN_UNIT_BUF).split(END_LINE)[0] if not self.verify_hello(data): self.socket.close() return if Crypto().key_exchange(self.key, self.socket): print "finished key exchange" try: subprocess.Popen("ClientEngine.py 1", shell=True) except: Error.error_msg() return socket_obj = LocalPythonCommunication() socket_obj.StartServer() i = 0 while True: i += 1 request = socket_obj.Recv() while request == "": request = socket_obj.Recv() self.send(request) print "from client " + request + " request %d" % i answer = self.recv() socket_obj.Send(answer) print "from client " + answer + " answer %d" % i
def main(): batch=None username=raw_input("Username >>>") pwd=getpass.getpass("Password >>>") with open('TeacherRecords.txt') as readTeacherFile: jsonData1=json.load(readTeacherFile) for i in range(len(jsonData1)): if jsonData1[i]['username']==username and jsonData1[i]['password']==pwd : batch=jsonData1[i]['batch'] print "\n",jsonData1[i]['name']," -Batch ",batch,"\n","Access Granted" if jsonData1[i]['is_Marks_Updated']=="False": print "Reminder to upload the latest test marks" break if batch==None: print "Access Denied" print "Username or password or both are incorrect!!!Please try again" return while True: print "\n1. See the list of students in ur batch" print "2. Upload marks of the Latest Test" print "3. Modify marks of individual student" print "0. Quit" choice=input(">>>") obj=TeacherInterface() if choice==1: obj.showListOfStudents(batch) elif choice==2: obj.uploadMarks(batch) elif choice==3: obj.modifyMarks(batch) elif choice==0: break else: Error.showError()
def sendToFlash(message): try: flashConnection.send(message.encode('utf-8')) except socket.error: Error.flashClientFail(flashSock, iTunesSock)
flashSock.bind(('127.0.0.1', PORT)) flashSock.listen(1) # 60 second connection to flash timeout so aethyrHelper doesn't live forever flashSock.settimeout(60) # launch flash frontend if hasattr(sys, 'frozen'): os.startfile(os.path.abspath("AethyrBin.exe")) # wait for flash to connect try: flashConnection, address = flashSock.accept() except socket.error, e: print('Exception while connecting to Flash: ' + str(e)) Error.flashClientFail(flashSock, iTunesSock) # remove timeout flashSock.setblocking(1) flashConnection.setblocking(1) # must be non-blocking to utilize threads properly iTunesSock.setblocking(0) if (Helper.isNeedUpdate()): sendToFlash('needToUpdateClient' + DELIMITER) ########## global tracks global currentLibrary
def __init__(self, path) : self.path = path if not os.path.isfile(self.path) : Error.printError(0) self.f = open(self.path,"rb")
datadict={'name':jsonDataSorted[i]['name'],'marks':jsonDataSorted[i]['marks'],"batch":jsonDataSorted[i]['batch']} listObj.append(datadict) json.dump(listObj,open('MarkSheet.txt','w')) jsonDataSorted=json.load(open('MarkSheet.txt')) open('MarkSheet.txt','w').write(json.dumps(jsonDataSorted,indent=4)) os.system('MarkSheet.txt') def AdmInterface(choice): AdmObj=Administrator() if choice==2: AdmObj.startNewTest() #upload marks for all the students elif choice==3: AdmObj.reMapping() #Shuffle students and allot them batches while(True): print "\nPress 1 to Access the Coaching Students Database" print "Press 2 to start a new test(give reminders to teachers)" print "Press 3 for Batch Allotment" print "Press 0 to exit" choicefour=input(">>>") if choicefour==1: coachingtemp.accessStuData() elif choicefour==2 or choicefour==3: AdmInterface(choicefour) elif choicefour==0: break else: Error.showError()
def __init__(self, contig): if type(contig).__name__ != "Contig": Error.error("Aligned_contig: __init__: The object passed is not of type Contig") self.contig = contig self.comparable_samples = {} #a list of Genomic_position for each comparable sample self.bam_file_lists = {} #Sample name, list of bam_file. The sample names are the same than in comparable_samples
def translate_all_frames(self): """ Will translate every possible amino acid that are in the environment. :return: A tsv table to stdout """ nucleotides_sequences = self.group_environment() total = 0 for entry in nucleotides_sequences: total += nucleotides_sequences[entry] if total != len(self.reads): Error.LogicError("Genomic_environment: translate_all_frames: Total is different" + " than depth") frames = [] for i in range(0, 6): new_frame = {} frames.append(new_frame) for entry in nucleotides_sequences: #Kinda fuzzy... we must find the amino acid in all frames. #We will have a list of frame where each fram is a dict stored with aa. if len(entry) != 5: Error.error("Length of sequence: %s is not 5" % entry) #I dont see a way to avoid hardcoding :( #Frame 1 print(entry) print(entry[0:3]) #print(len(entry[0:3])) codon = Seq(entry[0:3], IUPAC.unambiguous_dna) aa = str(codon.translate(table=11)) if not aa in frames[0]: frames[0][aa] = 0 frames[0][aa] += nucleotides_sequences[entry] #frame 2 print(entry[1:4]) codon = Seq(entry[1:4], IUPAC.unambiguous_dna) aa = str(codon.translate(table=11)) if not aa in frames[1]: frames[1][aa] = 0 frames[1][aa] += nucleotides_sequences[entry] #Frame 3 print(entry[2:5]) codon = Seq(entry[2:5], IUPAC.unambiguous_dna) aa = str(codon.translate(table=11)) if not aa in frames[2]: frames[2][aa] = 0 frames[2][aa] += nucleotides_sequences[entry] reverse_entry = entry[::-1] #Frame 4 (reverse starting from right) print(reverse_entry[0:3]) codon = Seq(reverse_entry[0:3], IUPAC.unambiguous_dna) aa = str(codon.translate(table=11)) if not aa in frames[3]: frames[3][aa] = 0 frames[3][aa] += nucleotides_sequences[entry] #Frame 5 print(reverse_entry[1:4]) codon = Seq(reverse_entry[1:4], IUPAC.unambiguous_dna) aa = str(codon.translate(table=11)) if not aa in frames[4]: frames[4][aa] = 0 frames[4][aa] += nucleotides_sequences[entry] #Frame 6 print(reverse_entry[2:5]) codon = Seq(reverse_entry[2:5], IUPAC.unambiguous_dna) aa = str(codon.translate(table=11)) if not aa in frames[5]: frames[5][aa] = 0 frames[5][aa] += nucleotides_sequences[entry] ##We output this in a cute way header = "Contig\tSNP position(contig)\tFrame\tAmino acid\tProportion\n" print(header), for frame in range(0, 6): frame_number = str(frame+1) for amino_acid in frames[frame]: line = "" line = self.contig+"\t"+str(self.position)+'\t'+frame_number+"\t"+amino_acid+"\t"+str(float(frames[frame][amino_acid]/total)) print(line)
def checkFiles(listOfFile): for i in listOfFile: if not(isValid(i)): Error.error("File"+str(i)+"can't be opened")
def getNode(self, nodeId): if self.nodeExist(nodeId): return self.Nodes[nodeId] else: Error.error("Logic error: required node does not exist")
def addNode(self, node): if self.nodeExist(node.getId()): Error.error("Logic error: node already exist. Node number:"+str(node.getId())) self.Nodes[node.getId()] = node
def nud(self): raise SyntaxError(Error.generateErrorMessageWithNoArguement('Expect (identifier) before {}', self, self.id))