def one_word(line): try: string.index(line," ") return False except ValueError: return True
def GetParameters(self): """ Collects every member of every section object and filters out those that are not parameters of the model. The function will collect: * every parameter of the the mechanisms * every mechanism * some default parameters that are always included in a model, and pointprocesses that are not some sort of Clamp :return: the filtered content of the model in a string matrix """ matrix=[] temp=[] temp2="" temp3="" for sec in self.hoc_obj.allsec(): temp.append(str(self.hoc_obj.secname())) defaults="L"+", cm"+", Ra"+", diam"+", nseg" for n in ["ena","ek","eca"]: try: index(dir(self.hoc_obj),n) defaults+=", "+n except ValueError: continue for n in sec(0.5).point_processes(): try: index(n.hname(),"Clamp") continue except ValueError: not_param=set(['Section', '__call__', '__class__', '__delattr__', '__delitem__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__len__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'allsec', 'amp', 'baseattr', 'cas', 'delay', 'dur', 'get_loc', 'has_loc', 'hname', 'hocobjptr', 'i', 'loc', 'next', 'ref', 'setpointer']) defaults+=", "+", ".join(list(set(dir(n)).difference(not_param))) temp.append(defaults) for seg in sec: for mech in seg: #print dir(mech) temp2=temp2+" "+str(mech.name()) if self.contains(dir(mech),str(mech.name()))!="": temp3=temp3+self.contains(dir(mech),str(mech.name()))+" " temp.append( temp3 ) temp.append(temp2) matrix.append(temp) temp2="" temp3="" temp=[] break return matrix
def replaceChar(strEURL): """ replace CHAR() with character """ if 'CHAR(' in strEURL: urllist = strEURL.split('CHAR(') strReturnWithChars = "" for s in urllist: strTmpPart = "" if ")" in s or 'CHAR(' in s: if len(s) > string.index(s, ')') + 1: tmpChrCode = s[:string.index(s, ')')] if tmpChrCode.isdigit(): if int(s[:string.index(s, ')')]) < 257: seq = (strReturnWithChars, chr(int(s[:string.index(s, ')')])),s[string.index(s, ')') +1 -len(s):]) strReturnWithChars = strTmpPart.join( seq ) else: print (s[:string.index(s, ')')] + " is not a valid char number") seq = (strReturnWithChars, s ) strReturnWithChars = strTmpPart.join(seq ) else: print ('error parsing text. Char code is not numeric') print s else: seq = (strReturnWithChars, s ) strReturnWithChars = strTmpPart.join(seq ) else: seq = (strReturnWithChars, s ) strReturnWithChars = strTmpPart.join(seq ) else: strReturnWithChars = strEURL return strReturnWithChars
def filter_message(message): """ Filter a message body so it is suitable for learning from and replying to. This involves removing confusing characters, padding ? and ! with ". " so they also terminate lines and converting to lower case. """ # to lowercase message = string.lower(message) # remove garbage message = string.replace(message, "\"", "") # remove "s message = string.replace(message, "\n", " ") # remove newlines message = string.replace(message, "\r", " ") # remove carriage returns # remove matching brackets (unmatched ones are likely smileys :-) *cough* # should except out when not found. index = 0 try: while 1: index = string.index(message, "(", index) # Remove matching ) bracket i = string.index(message, ")", index+1) message = message[0:i]+message[i+1:] # And remove the ( message = message[0:index]+message[index+1:] except ValueError, e: pass
def ParseAddTests(cmakefile): resp = [] ifstream = open(cmakefile) lines = ifstream.readlines() ifstream.close() current_test_cmake_code = [] current_test_name = "" in_addtest = False for line in lines: if line.count("add_test"): in_addtest = True try: start = string.index(line,"add_test") end = string.index(line," ",start) current_test_name = line[start+9:end] except ValueError: try: start = string.index(line,"add_test") current_test_name = line[start+9:] except ValueError: pass if in_addtest: current_test_cmake_code.append(line) if line.count(")"): if in_addtest: current_test_name.strip() resp.append((current_test_name, current_test_cmake_code)) in_addtest = False current_test_cmake_code = [] current_test_name = "" return resp
def encode(self): s = self.validated if self.checksum == -1: if len(s) <= 10: self.checksum = 1 else: self.checksum = 2 if self.checksum > 0: # compute first checksum i = 0; v = 1; c = 0 while i < len(s): c = c + v * string.index(self.chars, s[-(i+1)]) i = i + 1; v = v + 1 if v > 10: v = 1 s = s + self.chars[c % 11] if self.checksum > 1: # compute second checksum i = 0; v = 1; c = 0 while i < len(s): c = c + v * string.index(self.chars, s[-(i+1)]) i = i + 1; v = v + 1 if v > 9: v = 1 s = s + self.chars[c % 10] self.encoded = 'S' + s + 'S'
def _run(self): for filename, file_data in self.files.items(): try: contents = file_data['_contents'] except KeyError: continue if contents.startswith('{{{\n'): try: end_pos = string.index(contents, '\n}}}') except ValueError: continue file_data.update(json.loads('{' + contents[:end_pos + 4].strip().lstrip('{').rstrip('}') + '}')) contents = contents[end_pos + 4:] self.mark_matched(filename) elif contents.startswith('---\n'): try: end_pos = string.index(contents, '\n---') except ValueError: continue file_data.update(yaml.load(contents[:end_pos])) contents = contents[end_pos + 4:] self.mark_matched(filename) file_data['_contents'] = contents
def __init__(self, inf): R = string.split(inf.read(), "\n") self.preamble = [ ] self.globalFuncs = globalFuncs = [ ] self.parFlag = 0 i = 0 while i < len(R): x = R[i] # find functions and consume them got_it = 0 if self.parOnRe.search(x): self.parFlag = 1 elif self.parOffRe.search(x): self.parFlag = 0 elif self.parFlag and self.globalDeclRe.search(x): try: string.index(x, "(") isAFunc = 1 except ValueError: isAFunc = 0 if isAFunc: f = Function(x) globalFuncs.append(f) i = i + 1 + f.read(R[i+1:]) got_it = 1 if not got_it: # anything else is preamble self.preamble.append(x) i = i + 1
def format(self, data): points = {} # build dictionary 'points' where key is point_name # and value is a list of values for that point. for entry in data: for point in entry.keys(): if points.has_key(point): points[point].append(entry[point]) else: points[point] = [entry[point]] timestamps = points["timestamp"] point_names = points.keys() point_names.remove("timestamp") point_names.sort() lines = [] for point_name in point_names: units = "" meter_id = point_name if "," in point_name: units = string.strip(point_name[string.index(point_name, ",") + 1 :]) meter_id = point_name[0 : string.index(point_name, ",")] lines.extend( self._format_data(self.parent.scheduled_time(), timestamps, meter_id, units, points[point_name]) ) return string.join(lines, "\r\n")
def __init__(self, pos, offset, line): """Initialize the synset from a line off a WN synset file.""" self.pos = pos "part of speech -- one of NOUN, VERB, ADJECTIVE, ADVERB." self.offset = offset """integer offset into the part-of-speech file. Together with pos, this can be used as a unique id.""" tokens = string.split(line[:string.index(line, '|')]) self.ssType = tokens[2] self.gloss = string.strip(line[string.index(line, '|') + 1:]) self.lexname = Lexname.lexnames and Lexname.lexnames[ int(tokens[1])] or [] (self._senseTuples, remainder) = _partition( tokens[4:], 2, int(tokens[3], 16)) (self._pointerTuples, remainder) = _partition( remainder[1:], 4, int(remainder[0])) if pos == VERB: (vfTuples, remainder) = _partition( remainder[1:], 3, int(remainder[0])) def extractVerbFrames(index, vfTuples): return tuple(map(lambda t: int(t[1]), filter(lambda t, i=index: int(t[2], 16) in (0, i), vfTuples))) senseVerbFrames = [] for index in range(1, len(self._senseTuples) + 1): senseVerbFrames.append(extractVerbFrames(index, vfTuples)) self._senseVerbFrames = senseVerbFrames self.verbFrames = tuple(extractVerbFrames(None, vfTuples)) """A sequence of integers that index into
def crypt(self, plain): """Doesn't really encrypt, but rotates 13 chars through the alphabet""" lowerA = "abcdefghijklmnopqrstuvwxyz" lowerB = "nopqrstuvwxyzabcdefghijklm" upperA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" upperB = "NOPQRSTUVWXYZABCDEFGHIJKLM" digitA = "0123456789" digitB = "5678901234" res = "" import string for char in plain: if char in lowerA: res = res + lowerB[string.index(lowerA, char)] elif char in upperA: res = res + upperB[string.index(upperA, char)] elif char in digitA: res = res + digitB[string.index(digitA, char)] else: res = res + char return res
def signupSuccess (request, userID): model = object() context = {} useremail = "" username = "" user_type_initial = userID[-1] if user_type_initial == 'c': model = Customers elif user_type_initial == 't': model = Tradesman new_user = get_object_or_404(model, userID = userID) if user_type_initial == "c": useremail = new_user.customer.email username = new_user.customer.first_name else: useremail = new_user.user.email username = new_user.user.first_name emailprovider = useremail[string.index(useremail, "@") + 1 : string.index(useremail,".")] context['username'] = username context['emailprovider'] = emailprovider context['useremail'] = useremail # new_user = get_object_or_404(Tradesman, userID = userID) # useremail = new_user.customer.email # emailprovider = useremail[string.index(useremail, "@") + 1 : string.index(useremail,".")] # context = {} # context['username'] = new_user.customer.first_name # context['emailprovider'] = emailprovider # context['useremail'] = new_user.customer.email return render(request, 'fixit/main/registration_success.html', context)
def rename(source, dest): """ Renames files specified by UNIX inpattern to those specified by UNIX outpattern. Can only handle a single '*' in the two patterns!!! Usage: rename (source, dest) e.g., rename('*.txt', '*.c') """ infiles = glob.glob(source) outfiles = [] incutindex = string.index(source, "*") outcutindex = string.index(source, "*") findpattern1 = source[0:incutindex] findpattern2 = source[incutindex + 1 :] replpattern1 = dest[0:incutindex] replpattern2 = dest[incutindex + 1 :] for fname in infiles: if incutindex > 0: newname = re.sub(findpattern1, replpattern1, fname, 1) if outcutindex < len(dest) - 1: if incutindex > 0: lastone = string.rfind(newname, replpattern2) newname = newname[0:lastone] + re.sub(findpattern2, replpattern2, fname[lastone:], 1) else: lastone = string.rfind(fname, findpattern2) if lastone <> -1: newname = fname[0:lastone] newname = newname + re.sub(findpattern2, replpattern2, fname[lastone:], 1) print fname, newname os.rename(fname, newname) return
def IDtoURL(id): """Convert an authorization or notification ID from address to URL format Example: "*****@*****.**" becomes "http://example.org/notify/54DC1B81-1729-4396-BA15-AFE6B5068E32" """ return "http://"+ id[string.index(id, "@")+1:] + "/notify/" + id[0:string.index(id, "@")] # TODO: Will need to change to https://
def getText(string = None): if string != None: try: closeBkt = string.index('>') + len('>') openBkt = string.index('<', closeBkt) return string[closeBkt:openBkt] except ValueError: return ""
def testGenerateStanzaWildCard(self): a = SourceSet(set(['foo.c']), set([SourceListCondition('x64', 'Chromium', '*')])) stanza = a.GenerateGnStanza() string.index(stanza, '== "x64"') string.index(stanza, 'ffmpeg_branding == "Chromium"') # OS is wild-card, so it should not be mentioned in the stanza. self.assertEqual(-1, string.find(stanza, 'OS =='))
def strip_address(address): """ Strip the leading & trailing <> from an address. Handy for getting FROM: addresses. """ start = string.index(address, '<') + 1 end = string.index(address, '>') return address[start:end]
def getCollaborators( rawWikiText, lang ): """ return a list of tuple with ( user, value ), where user is the name of user that put a message on the page, and the value is the number of times that he appear in rawText passed. parameter: lang: lang of wiki [it|nap|vec|en|la] rawWikiText: text in wiki format (normally discussion in wiki) """ import re resname = [] start = 0 search = '[['+i18n[lang][1]+":" searchEn = '[['+i18n['en'][1]+":" io = len(search) while True: #search next user try: iu = index( rawWikiText, search, start ) #index of username except ValueError: if search == searchEn: break # now search for English signatures search = searchEn start = 0 io = len(search) continue #begin of the username start = iu + io #find end of username with regex username = re.findall( "[^]|&/]+",rawWikiText[start:] )[0] if username == '' or username == None: print "Damn! I cannot be able to find the name!" print "This is the raw text:" print rawWikiText[start:start+30] print "What is the end character? (all the character before first were ignored)" newdelimiter = sys.stdin.readline().strip()[0] try: end.append( index( rawWikiText, newdelimiter, start ) ) except ValueError: print "Damn! you give me a wrong character!.." exit(0) resname.append( username ) # list of all usernames (possibly more than one times for one) start += len(username) + 1 # not consider the end character #return a list of tuple, the second value of tuple is the weight return weight( resname )
def expandvars(path): """Expand paths containing shell variable substitutions. The following rules apply: - no expansion within single quotes - no escape character, except for '$$' which is translated into '$' - ${varname} is accepted. - varnames can be made out of letters, digits and the character '_'""" # XXX With COMMAND.COM you can use any characters in a variable name, # XXX except '^|<>='. if '$' not in path: return path res = '' index = 0 pathlen = len(path) while index < pathlen: c = path[index] if c == '\'': # no expansion within single quotes path = path[index + 1:] pathlen = len(path) try: index = string.index(path, '\'') res = res + '\'' + path[:index + 1] except string.index_error: res = res + path index = pathlen -1 elif c == '$': # variable or '$$' if path[index + 1:index + 2] == '$': res = res + c index = index + 1 elif path[index + 1:index + 2] == '{': path = path[index+2:] pathlen = len(path) try: index = string.index(path, '}') var = path[:index] if os.environ.has_key(var): res = res + os.environ[var] except string.index_error: res = res + path index = pathlen - 1 else: var = '' index = index + 1 c = path[index:index + 1] while c != '' and c in varchars: var = var + c index = index + 1 c = path[index:index + 1] if os.environ.has_key(var): res = res + os.environ[var] if c != '': res = res + c else: res = res + c index = index + 1 return res
def parse_timestamp(self, event, line): start = string.index(line, "[") end = string.index(line, "]") if end - start < 20: raise Exception("Incorrect [date_time] field found in " + line) event.now = line[start + 1:end] line = line[end+1:].strip() return line
def split_to(address): """ Return 'address' as undressed (host, fulladdress) tuple. Handy for use with TO: addresses. """ start = string.index(address, '<') + 1 sep = string.index(address, '@') + 1 end = string.index(address, '>') return address[sep:end], address[start:end]
def rem_parens(string): try: begin = string.index("(") end = string.index(")", beg=begin) remove = string[begin:end] print remove result = string.replace(string, remove, "") except: result = string return result
def QuotedFileName(fname): """Given a filename, return a quoted version if necessary """ import regutil, string try: string.index(fname, " ") # Other chars forcing quote? return '"%s"' % fname except ValueError: # No space in name. return fname
def get_vid_from_script(script): index1 = string.find(script, 'vid:') if index1 is -1: return None index1 = string.index(script, "'", index1) index2 = string.index(script, "'", index1 + 1) youku_vid = script[index1 + 1: index2] youku_vid = youku_vid.strip().strip('.') print youku_vid return youku_vid
def convertOnePoseLineToPython(self, poseTableLine, poseNum=None, comment=None): ''' Given a single Puppet pose, return a string with all the correspoinding Python script lines. @param poseTableLine: line with all Puppet pose function, rarm(...);larm(...);head(...)... @type poseTableLine: string @param poseNum: Option sequence number of pose. If provided, a comment of the form 'Pose x:\n' is prepended to the series of Python statements that correspond to the passed-in pose. @type poseNum: {int | string} @param comment: Option comment that will be prepended to the Python script statements. @type comment: string ''' puppetCommands = poseTableLine.split(';'); translation = "\n"; if poseNum is not None: translation += "# Pose %s:\n" % str(poseNum); if comment is not None: translation += "# %s\n" % comment; for puppetCommand in puppetCommands: openParenPos = string.index(puppetCommand, '('); closeParenPos = string.index(puppetCommand, ')'); args = puppetCommand[openParenPos + 1:closeParenPos]; args = args.split(','); funcName = puppetCommand[:openParenPos]; argStr = puppetCommand[openParenPos + 1:closeParenPos]; try: if len(argStr) > 0: translation += self.TRANSLATION_METHOD_MAP[funcName](*args); else: translation += self.TRANSLATION_METHOD_MAP[funcName](); except KeyError: self.dialogService.showErrorMsg("Puppet function %s cannot be translated to Python." % funcName); continue; if string.find(poseTableLine, "rarm") > -1 and string.find(poseTableLine, "larm") > -1: translation += 'arm.wait_for(BOTH)\n'; elif string.find(poseTableLine, "rarm") > -1: translation += 'arm.wait_for(RIGHT)\n'; elif string.find(poseTableLine, "larm") > -1: translation += 'arm.wait_for(LEFT)\n'; if string.find(poseTableLine, "lgrip") > -1 and string.find(poseTableLine, "rgrip") > -1: translation += 'gripper.wait_for(BOTH)\n'; elif string.find(poseTableLine, "lgrip") > -1: translation += 'gripper.wait_for(LEFT)\n'; elif string.find(poseTableLine, "rgrip") > -1: translation += 'gripper.wait_for(RIGHT)\n'; # head.wait_for() exists in Python script, but it # hangs indefinitely; so we don't use it: # if string.find(poseTableLine, "head") > -1: # translation += 'head.wait_for()\n'; # Torso does not have a wait_for: # if string.find(poseTableLine, "torso") > -1: # translation += 'torso.wait_for()\n'; return translation;
def stripAddress(self, address): """ Strip the leading & trailing <> from an address. Handy for getting FROM: addresses. """ if '<' in address: start = string.index(address, '<') + 1 end = string.index(address, '>') return address[start:end] else: return address
def uncompressdir(dir, androiddir, uncatdir, undecompdir): tarpath = dir + '/*.tar*' tarfiles = glob.glob(tarpath) for onetar in tarfiles: periodindex = string.index(onetar, ".tar") lastslashindex = string.rindex(onetar, "/") tarname = onetar[lastslashindex+1 : periodindex] nowtarpath = dir + '/' + tarname if not os.path.exists(nowtarpath): os.makedirs(nowtarpath) tar = tarfile.open(onetar, 'r') for item in tar: tar.extract(item, nowtarpath) categorizedir(nowtarpath, androiddir, uncatdir) zippath = dir + '/*.zip' zipfiles = glob.glob(zippath) for onezip in zipfiles: periodindex = string.index(onezip, ".zip") lastslashindex = string.rindex(onezip, "/") zipname = onezip[lastslashindex+1 : periodindex] nowzippath = dir + '/' + zipname if not os.path.exists(nowzippath): os.makedirs(nowzippath) fZip = open(onezip, 'rb') zip = zipfile.ZipFile(fZip) is_encpted = 0 for zinfo in zip.infolist(): is_encpted = zinfo.flag_bits & 0x1 if is_encpted: break if is_encpted: passwd = 'infected666' + zipname[len(zipname) - 1] # This is default password used, need change for other uses for item in zip.namelist(): try: zip.extract(item, nowzippath, passwd) # Sometimes password is needed except RuntimeError as e: if 'password' in e[0]: passwd = 'infected' try: zip.extract(item, nowzippath, passwd) except RuntimeError as e: print 'nowzip', print onezip print 'RuntimeError in second trail e: ', print e[0] os.system("mv " + onezip + " " + undecompdir) os.system("rm -rf " + nowzippath) break else: for item in zip.namelist(): zip.extract(item, nowzippath) categorizedir(nowzippath, androiddir, uncatdir)
def bad_id(string): try: string.index("'") return True except ValueError: try: string.index("\\") return True except ValueError: return False
def event_func(): req = urllib2.Request('http://bbs.byr.cn/index') response = urllib2.urlopen(req) rawdata = response.read() response.close() usernump = re.compile(r'span class="c-user">.*?</span>人') usernummatch = usernump.findall(rawdata) if usernummatch: currentnum=usernummatch[0] currentnum=currentnum[string.index(currentnum,'>')+1:string.index(currentnum,'<')] print "Current Time:",time.strftime('%Y,%m,%d,%H,%M',time.localtime(time.time())),'User num:',currentnum
def html_grab(data, key): """Find the value corresponding to key within the pokes page.""" try: searchString = '"{0}":"'.format(key) a = string.index(data, searchString) + len(searchString) b = a + string.index(data[a:], '"') return data[a:b] except ValueError: # A ValueError typically indicates that the login information # was incorrect. raise LoginError()
def null_terminate_string(self, string): ''' Searches a string for the first null byte and terminates the string there. Returns the truncated string. ''' try: i = string.index(b'\x00') except Exception as e: i = len(string) return string[0:i]
def contains(self,string,ss): """ Checks if substring is in the given ``list`` and creates a string which contains only the matching elements separated by spaces. :param string: ``list`` of strings :param ss: the substring to be matched :return: a string which contains only the matching elements separated by spaces """ temp="" for n in string: try: index(n, ss) temp=temp+" "+str(n) except ValueError: pass return temp
def getMajorMinor(deviceName, dmsetupLs): """ Given output of dmsetup ls this will return themajor:minor (block name) of the device deviceName """ startingIndex = string.rindex(dmsetupLs, deviceName) + len(deviceName) endingIndex = string.index(dmsetupLs[startingIndex:], "\n") + startingIndex # trim the preceding tab and ()'s newStr = dmsetupLs[startingIndex + 2:endingIndex - 1] return newStr
def findAll(lst, el): """ Returns a list of positions of all occurences of el in list lst. """ pos = [] next = 0 while True: try: next = string.index(substr, next) + 1 pos.append(next - 1) except: return pos
def find_index_iterative(string, pattern): string = string.lower() position = 0 for char in enumerate(string): print(char, pattern[position]) if char[1] is pattern[position]: if position is len(pattern)-1: return string.index(pattern) position += 1 else: position = 0 return 'Pattern does not exist in provided string.'
def get_account(self, cr, uid, name, what_is, type): """ Return account profil about incomes/ expenses """ ids2 = self.pool.get('hr.provision.account').search( cr, uid, [(what_is, '=', True), ('type', '=', type)]) in_desc = self.pool.get('hr.provision.account').read( cr, uid, ids2, ['description', 'account']) for it in in_desc: try: if index(name, it['description']) >= 0: return it['account'] except: print "no coincidio solo por depreciacion"
def get_section_header(line): # Returns the section if the line is a section header, else None if line[0] == "[": end = string.find(line, "]") if end == -1: end = len(line) rc = string.lower(line[1:end]) try: i = string.index(rc, ":") return rc[:i], rc[i + 1:] except ValueError: return rc, "" return None, None
def next(self): while '}' not in self.buffer and not self.response_done: self._read() if '}' in self.buffer: idx = string.index(self.buffer, '}') + 1 chunk = self.buffer[:idx] self.buffer = self.buffer[idx:] field = json.loads(chunk)[self._json_field] return field else: raise StopIteration
def _code(data, key): if type(data) == _ICOpaqueDataType: return data.data if '\245' in key: key2 = key[:string.index(key, '\245')+1] else: key2 = key if _decoder_table.has_key(key2): coder = _decoder_table[key2][1] else: coder = _code_default return coder(data, key)
def parseFrame(self, frame): # Parse a passed-in frame for name-value pairs. # Same as from_rfc_822_format in cgi-bin/PubSub/EventFormat.pm . message = {} while len(frame): pos = string.index(frame, "\n") header = None value = None header = frame[:pos] frame = frame[pos + 1:] if not pos: # The rest of the frame is the "kn_payload" value. name = "kn_payload" value = frame frame = "" else: # Now we've parsed out a header line. Split into name and value. sep = string.index(header, ":") nameEscaped = header[:sep] valueEscaped = string.lstrip(header[sep + 1:]) # Decode them. nameEscapedStream = cStringIO.StringIO(nameEscaped) valueEscapedStream = cStringIO.StringIO(valueEscaped) nameStream = cStringIO.StringIO() valueStream = cStringIO.StringIO() quopri.decode(nameEscapedStream, nameStream) quopri.decode(valueEscapedStream, valueStream) nameStream.seek(0) valueStream.seek(0) name = nameStream.read() value = valueStream.read() # Decode UTF-8. nameU = unicode(name, "UTF-8", "replace") valueU = unicode(value, "UTF-8", "replace") # Add this name-value pair to the message. if message.has_key(nameU): valueU = message[nameU] + ", " + valueU message[nameU] = valueU continue self.onMessage(message)
def contains_full_msg(self, message): prefix = -1 try: prefix = string.index(message, " ") except ValueError: return -1 if prefix == -1: return -1 length = int(message[:prefix]) if len(message) >= prefix + length + 1: return prefix else: return -1
def forward_packet(self, data): """ data contains ethernet iface ' ' packet""" index = string.index(data, " ") iface = data[:index] ethernet_data = data[index + 1:] msg = of.ofp_packet_out() msg.data = ethernet_data msg.in_port = of.OFPP_NONE output_port = self.find_port_from_iface(iface) action = of.ofp_action_output(port=output_port) msg.actions.append(action) self.connection.send(msg)
def load(self, fname): d = {} if posixpath.exists(fname): f = open(fname, 'r') while 1: l = f.readline() if not l: break l = l[:-1] try: ix = string.index(l, '#') l = l[0:ix] except ValueError: pass try: ix = string.index(l, ':') name = string.strip(l[0:ix]) value = string.strip(l[(ix + 1):]) d[name] = value except ValueError: pass f.close() return d
def double_check(string): i=0 string_cpy = string[:] while(i<= len(string)): if(start_follow in string): i = string.index(start_follow) cut_str = string[(i+start_follow_length):len(string)] if(cut_str.index(end_follow)!=0): final_strings.remove(string_cpy) break else: i = i +(start_follow_length+end_follow_length) string = string[i:len(string)]
def readString(self, line, colno): apos = "'" nextFound = index(line, apos, colno) value = '' while line[nextFound + 1] == apos: value = value + line[colno:nextFound] + apos nextFound = index(line, "'", nextFound + 2) colno = nextFound + 2 value = value + line[colno:nextFound] colno = nextFound + 1 if line[colno:colno + 2] == 'xc': value = translateHexstring(value) escapeAll = 1 colno = colno + 2 else: value, count = translateEscapes(value) escapeAll = (count == len(value)) if len(value) == 1: litval = CharacterLiteral(value) else: litval = StringLiteral(value, escapeAll) return litval, colno
def _getConnectionByConnString(connString): if not _connStringToConnections.has_key(connString): if connString[:5] != 'pydo:': raise ValueError, ("invalid connect string: doesn't start" " with pydo: <%s>") % connString rconnString = connString[5:] colInd = string.index(rconnString, ':') driverName = rconnString[:colInd] driverString = rconnString[colInd+1:] _connStringToConnections[connString] = _getDriver( driverName)(driverString) return _connStringToConnections[connString]
def insertFormatted(self, location, text, add_sep=False): """Similar to self.insert(), but instead of plain text, uses pygments to provide a set of formatting tags. The formatter should return stream of tagged lines of the format tagName:payload_string\n, which this class then inserts in tagged way. Note that if the given text is smaller than a "complete syntactic unit" of the language being syntax-highlighted, insertFormatted() probably won't result in correct syntax highlighting. Use self.reformatRange() or self.reformatEverything() to reformat a larger enclosing range if you're making micro-inserts.""" #RPC: Added this to stop the formatter from replacing liternal '\n'. if add_sep: self.edit_separator() text = string.replace(text, r'\n', chr(1)) textTagged = pygments.highlight(text, self.lexer, self.formatter) insertList = [] #inQuotes = False for chunk in textTagged.splitlines(): # split tagged lines into component parts tagEnd = string.index(chunk, ':') tagName, stringPart = chunk[:tagEnd], chunk[tagEnd+1:] # clean up / unquote / reformat data as necessary #num = stringPart.count('"') + stringPart.count("'") stringPart = string.replace(stringPart, r'\n', "\n") #Convert literal '\n' back. stringPart = string.replace(stringPart, chr(1), r'\n') #print stringPart # add to the insert list insertList.append(stringPart) insertList.append(tagName) # pygments.highlight() can send back extra linefeed markers at the end. # So if we didn't mean to end with a return, check for these, and if # they're just linefeeds, truncate them if not text.endswith("\n"): penultimate = insertList[-2] if (penultimate.endswith("\n")): if penultimate == "\n": insertList = insertList[:-2] else: insertList[-2] = insertList[-2][:-1] # if something to insert, do it (actual typed returns are the missing # else case here; net-net they don't get formatted through pygments) #print insertList if insertList: self.insert(location, *insertList)
def _addHotkeyToOptions(self, menuName, kw, textKey, traverseSpec): if (not self['hotkeys'] or kw.has_key('underline') or not kw.has_key(textKey)): return if type(traverseSpec) == types.IntType: kw['underline'] = traverseSpec return hotkeyList = [] if menuName is None: for menuName in self._menuInfo.keys(): if self._menuInfo[menuName][0] is None: menubutton = self.component(menuName + '-button') underline = string.atoi(str(menubutton.cget('underline'))) if underline != -1: label = str(menubutton.cget(textKey)) if underline < len(label): hotkey = string.lower(label[underline]) if hotkey not in hotkeyList: hotkeyList.append(hotkey) else: menu = self.component(menuName + '-menu') end = menu.index('end') if end is not None: for item in range(end + 1): if menu.type(item) not in ('separator', 'tearoff'): underline = string.atoi( str(menu.entrycget(item, 'underline'))) if underline != -1: label = str(menu.entrycget(item, textKey)) if underline < len(label): hotkey = string.lower(label[underline]) if hotkey not in hotkeyList: hotkeyList.append(hotkey) name = kw[textKey] if type(traverseSpec) == types.StringType: lowerLetter = string.lower(traverseSpec) if traverseSpec in name and lowerLetter not in hotkeyList: kw['underline'] = string.index(name, traverseSpec) else: targets = string.digits + string.letters lowerName = string.lower(name) for letter_index in range(len(name)): letter = lowerName[letter_index] if letter in targets and letter not in hotkeyList: kw['underline'] = letter_index break
def __init__(self, url, rootPath): InstallMethod.__init__(self, rootPath) if url.startswith("ftp"): isFtp = 1 else: isFtp = 0 # build up the url. this is tricky so that we can replace # the first instance of // with /%3F to do absolute URLs right i = string.index(url, '://') + 3 self.baseUrl = url[:i] rem = url[i:] i = string.index(rem, '/') + 1 self.baseUrl = self.baseUrl + rem[:i] rem = rem[i:] # encoding fun so that we can handle absolute paths if rem.startswith("/") and isFtp: rem = "%2F" + rem[1:] self.baseUrl = self.baseUrl + rem if self.baseUrl[-1] == "/": self.baseUrl = self.baseUrl[:-1] # self.baseUrl points at the path which contains the 'RedHat' # directory with the hdlist. if self.baseUrl[-6:] == "/disc1": self.multiDiscs = 1 self.pkgUrl = self.baseUrl[:-6] else: self.multiDiscs = 0 self.pkgUrl = self.baseUrl self.intf = None
def getCharPosition(rawWikiText, search, start): """ return the position of the first character in rawWikiText, choosed from search. If doesn't find any end character, show 30 character after start position in rawWikiText, and get end character by standard input. Parameter: rawWikiText: wiki text search: string comma-separated, with the search character start: an integer with the start position in rawWikiText """ list = split(search, ",") end = [] for delimiter in list: try: end.append(index(rawWikiText, delimiter, start)) except ValueError: #print delimiter pass if len(end) == 0: print "Damn! I cannot be able to find the end of the username!..." print "can you suggest me how is the end character of the username?" print "This is the raw text:" print rawWikiText[start:start + 30] print "What is the end character? (all the character before first were ignored)" newdelimiter = sys.stdin.readline().strip()[0] try: end.append(index(rawWikiText, newdelimiter, start)) except ValueError: print "Damn! you give me a wrong character!.." exit(0) end.sort() return end[0]
def getSnippet(self, key): data = self.data match = re.search(self.startPattern + self.ws + key, data) if not match: raise KeyError, key try: start = match.end() start = string.index(data, '\n', start) + 1 except: raise KeyError, key match = self.endPatternRE.search(data, start) if not match: raise KeyError, key return data[start:match.start()]
def __init__(self, pos, offset, line): "Initialize the synset from a line off a WN synset file." self.pos = pos "part of speech -- one of NOUN, VERB, ADJECTIVE, ADVERB." self.offset = offset """integer offset into the part-of-speech file. Together with pos, this can be used as a unique id.""" tokens = string.split(line[:string.index(line, '|')]) self.ssType = tokens[2] self.gloss = string.strip(line[string.index(line, '|') + 1:]) self.lexname = Lexname.lexnames[int(tokens[1])] (self._senseTuples, remainder) = _partition(tokens[4:], 2, string.atoi(tokens[3], 16)) (self._pointerTuples, remainder) = _partition(remainder[1:], 4, int(remainder[0])) if pos == VERB: (vfTuples, remainder) = _partition(remainder[1:], 3, int(remainder[0])) def extractVerbFrames(index, vfTuples): return tuple(map(lambda t:string.atoi(t[1]), filter(lambda t,i=index:string.atoi(t[2]) in (0, i), vfTuples))) senseVerbFrames = [] for index in range(1, len(self._senseTuples) + 1): senseVerbFrames.append(extractVerbFrames(index, vfTuples)) self._senseVerbFrames = senseVerbFrames self.verbFrames = tuple(extractVerbFrames(None, vfTuples)) """A sequence of integers that index into
def _colorizeTag(source, tag): s = [] tagtext = tag.tagText() #print 'args = ', tagtext, tag.name tagnameEnd = string.index(tagtext, tag.tagname) + len(tag.tagname) s.append('<FONT COLOR=BLUE>%s' % tagtext[:tagnameEnd]) argsText = tagtext[tagnameEnd:len(tagtext) - 2] if argsText: s.append('</FONT>%s<FONT COLOR=BLUE>' % _colorizeTagArgs(tagtext[2:-2])) #scanners.common.plainEscape(argsText)) s.append(':></FONT>') return string.join(s, '')
def parse_l0(self): f = False sname = None for l in self.fh.readlines(): if f: if l[0:4] == 'END ' and string.index( l,sname) == 4: f = False self._parse_l0_section.close() else: self._parse_l0_section.add( l ) elif l[0:6] == 'START ': sname = string.strip( string.split(l)[1] ) self._parse_l0_section = section_parser_l0( self, sname ) f = True
def parse_response(self, f): # read response from input file, and parse it def binary_cb(data): b = Binary() b.decode(data) return b def boolean_cb(value): if value == 0: return False elif value == 1: return True else: raise TypeError, "bad boolean value" def fault_cb(arg): raise apply(Fault, (), arg) my_thread = threading.currentThread() unmarshaller = ximian_unmarshaller.new(binary_cb, boolean_cb, fault_cb) first_pass = 1 while 1: if my_thread in self.__cancelled: f.close() self.__cancelled.remove(my_thread) return () response = f.read(1024) if not response: break if self.verbose: print "response:", repr(response) # FIXME: This is evil and wrong and papers over what appears # to be a race in rcd. Essentially there is garbage on the # wire, including null bytes, and the unmarshaller will throw # a TypeError if this happens, so we move past the bad data # to the start of the actual XML if first_pass: ind = string.index(response, "<?xml") if self.verbose and ind > 0: print "Moving past %d bad bytes" % ind response = response[ind:] unmarshaller.feed(response, 0) first_pass = 0 f.close() unmarshaller.feed("", 1) return unmarshaller.close()
def first_non_repeating_letter(string): string_to_evaluate = string.lower() count = [] dictionary_count = {} for letter in string_to_evaluate: if letter not in count: count.append(letter) if len(count) > 0: dictionary_count = {l: string_to_evaluate.count(l) for l in count} print(dictionary_count) unique_l = [k for k, v in dictionary_count.items() if v == 1][0] idx = string.index(unique_l) print(string, dictionary_count, idx, string[idx]) return string[idx]
def parseSectionNames(filename, arch): # For platform-specific dependency sections = [] for name in CONF_SECTIONS: pipe = Popen('grep "^\['+name+':.*'+arch+'.*\]" '+filename, stdout=PIPE, stderr=PIPE, shell=True) line = pipe.communicate()[0].strip() if pipe.returncode != 0: sections.append(name) continue line = line.split(']')[0] if arch in line[string.index(line, ':')+1:].split(','): sections.append(line[1:]) else: sections.append(name) return sections
def main(argv): try: workDir = sys.argv[1] except Exception: log.exception("Invalid argument. Must be working Directory.") sys.exit(os.EX_USAGE) try: log.info("Executing WMO header formatting...") #Get tailored AWIPS NC4 file name nc4File = readPSF(workDir) #Get PCF parameters gzipFlag = readPCF(workDir, "Compression_Flag") jobStart = readPCF(workDir, "job_coverage_start") #Compress the file if gzipFlag and re.match("On", gzipFlag, re.I): gzFile = nc4File + '.gz' log.debug("Compressing file, " + gzFile + " , using gzip") gzipFile(workDir + '/' + nc4File) else: gzFile = nc4File #Find the WMO header string from file name idx = string.index(gzFile, "KNES") wmoHeader = string.join(string.split(gzFile[idx - 7:idx + 4], "_")) day = jobStart[6:8] hour = jobStart[8:10] min = jobStart[10:12] wmoHeader += " " + day + hour + min log.info("FOUND WMO header: " + wmoHeader) #Open and read in binary file, write wmo header to new file and wrote # contents of file wmoFile = gzFile + '.wmo' log.info("Writing WMO header file: " + wmoFile) with open(workDir + '/' + gzFile, 'rb') as old, open(workDir + '/' + wmoFile, 'wb') as new: new.write(wmoHeader + "\r\r\n") for chunk in iter(lambda: old.read(65536), b""): new.write(chunk) #Write new file name to PSF writePSF(workDir, wmoFile) log.info("WMO header formatting successful. Exiting.") except Exception: log.exception("Writing WMO header failed. Exiting.") sys.exit(os.EX_SOFTWARE)
def methodHelp (self, name, member): try: doc = member.__doc__ if not doc: return try: summary = doc [:index (doc, '\n')] more = ' ...' except ValueError: summary = doc more = '' print '%-15s %s%s' % (name, summary, more) except AttributeError: pass
def get_split_string(self, message): prefix = -1 try: prefix = string.index(message, " ") except ValueError: return (None, message) if prefix == -1: return (None, message) length = int(message[:prefix]) if len(message) >= prefix + length: return (message[prefix + 1:prefix + length + 1], message[prefix + length + 1:]) else: return (None, message)