def test_to_String(self): """Test the to_String() method.""" assert to_String(1) == "1", to_String(1) assert to_String([1, 2, 3]) == str([1, 2, 3]), to_String([1, 2, 3]) assert to_String("foo") == "foo", to_String("foo") try: import UserString s1 = UserString.UserString('blah') assert to_String(s1) == s1, s1 assert to_String(s1) == 'blah', s1 class Derived(UserString.UserString): pass s2 = Derived('foo') assert to_String(s2) == s2, s2 assert to_String(s2) == 'foo', s2 if hasattr(types, 'UnicodeType'): s3 = UserString.UserString(unicode('bar')) assert to_String(s3) == s3, s3 assert to_String(s3) == unicode('bar'), s3 assert type(to_String(s3)) is types.UnicodeType, \ type(to_String(s3)) except ImportError: pass if hasattr(types, 'UnicodeType'): s4 = unicode('baz') assert to_String(s4) == unicode('baz'), to_String(s4) assert type(to_String(s4)) is types.UnicodeType, \ type(to_String(s4))
def generate_csv(URI, username, auth_token): url = "https://api.spotify.com/v1/users/%s/playlists/%s/tracks"\ % (username, URI) response = requests.get(url, headers={ 'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % (auth_token) }) data = json.loads(response.text) csv_data = UserString.MutableString('\n') try: if data['items']: None except: raise Exception("Either token is not good, or username or playlist\ URI") for track in xrange(len(data['items'])): name = data['items'][track]['track']['name'] artist = data['items'][track]['track']['artists'][0]['name'] album = data['items'][track]['track']['album']['name'] date = data['items'][track]['added_at'] csv_data.append(', '.join([name, artist, album, date]) + '\n') csv_data = str(csv_data) try: f = open('playlist.csv', 'w+') f.write(csv_data) f.close() except Exception as e: raise Exception("Couldn't write csv file to disk") return 'playlist.csv'
def transmit(self, canId, data, length=None): msg = UserString.MutableString("c" * 17) msg[0] = '%c' % ((canId >> 24) & 0xFF) msg[1] = '%c' % ((canId >> 16) & 0xFF) msg[2] = '%c' % ((canId >> 8) & 0xFF) msg[3] = '%c' % (canId & 0xFF) if (None == length): length = len(data) assert length <= 8 msg[4] = '%c' % (length) #DLC for i in range(0, length): msg[5 + i] = '%c' % ((data[i]) & 0xFF) for i in range(length, 8): msg[5 + i] = '%c' % (0x55) msg[13] = '%c' % ((self.__rxPort >> 24) & 0xFF) msg[14] = '%c' % ((self.__rxPort >> 16) & 0xFF) msg[15] = '%c' % ((self.__rxPort >> 8) & 0xFF) msg[16] = '%c' % ((self.__rxPort) & 0xFF) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('127.0.0.1', self.__txPort)) sock.send(msg.data) sock.close() except: print('ERROR: CanBusServer isn\'t started.')
def test_is_String(self): assert is_String("") if hasattr(types, 'UnicodeType'): exec "assert is_String(u'')" try: import UserString except: pass else: assert is_String(UserString.UserString('')) assert not is_String({}) assert not is_String([]) assert not is_String(())
def get_reply_url(self): """ :return: Return the reply url of the ad """ replyURL = UserString.MutableString(self.url) del replyURL[replyURL.find('/fbh') - 1] del replyURL[replyURL.find('/fbh') - 1] del replyURL[replyURL.find('/fbh') - 1] replyURL = str(replyURL) replacewith = self.get_city_cl_code(self.city) replyURL = str( replyURL.replace(".org/", ".org/reply/" + replacewith).replace(".html", "")) return (replyURL)
def convert_phrase_to_list(phrase, color=[255,255,255]): if len(phrase.split()) == 1: return [[phrase, color]] phrase_list = [e+' ' for e in re.split("(?<!\\s) ", phrase) if e] phrase_list[-1] = UserString.MutableString(phrase_list[-1]) del phrase_list[-1][-1] phrase_list[-1] = str(phrase_list[-1]) texts_input = [] for word in phrase_list: texts_input.append([word, color]) return texts_input
def getMatrix(self): matrix = UserString.MutableString('\0' * len(DioList) * 2) for Index in range(0, len(DioList)): data = 0 for i in range(0, cMaxDioSize): Dio = self.cellWidget(Index, i) if (Dio != None): if (Dio.getLevel() == STD_HIGH): data |= (1 << i) & 0xFF matrix[Index] = '%c' % (data) for Index in range(0, len(DioList)): data = 0 for i in range(0, cMaxDioSize): Dio = self.cellWidget(Index, i) if (Dio != None): if (Dio.getDirection() == cDioOutput): data |= (1 << i) & 0xFF matrix[len(DioList) + Index] = '%c' % (data) return matrix.data
return n.value else: values = [] for son in n.childs: son.value = min_max(son) values.append(son.value) if n.deep % 2 == 0: n.ifcount = True return max(values) else: n.ifcount = True return min(values) deep = 5 state = us.MutableString("123456789") n = node.node(state=state, father=None, deep=0) while 1: print n.state[0:3] print n.state[3:6] print n.state[6:9] print "" if ifwin(n.state): print "You Win" exit() #build tree wait_to_expand_queue = Queue.Queue() wait_to_expand_queue.put(n) while not (wait_to_expand_queue.empty()): current_n = wait_to_expand_queue.get()
exp6_1 = "p2=v2&p1=v1" exp6_2 = "p1=v1&p2=v2" # dict input, only string values, doseq==1 act6 = urllib.urlencode(in6, doseq=1) verify(act6 == exp6_1 or act6 == exp6_2, "urllib.urlencode problem 4 dict") # list input, only string values act6list = urllib.urlencode(in6list, doseq=1) verify(act6list == exp6_2, "urllib.urlencode problem 4 list") in7 = "p1=v1&p2=v2" try: act7 = urllib.urlencode(in7) print "urllib.urlencode problem 5 string" except TypeError: pass import UserDict in8 = UserDict.UserDict() in8["p1"] = "v1" in8["p2"] = ["v1", "v2"] exp8_1 = "p1=v1&p2=v1&p2=v2" exp8_2 = "p2=v1&p2=v2&p1=v1" act8 = urllib.urlencode(in8, doseq=1) verify(act8 == exp8_1 or act8 == exp8_2, "urllib.urlencode problem 6 UserDict") import UserString in9 = UserString.UserString("") exp9 = "" act9 = urllib.urlencode(in9, doseq=1) verify(act9 == exp9, "urllib.urlencode problem 7 UserString")
#!/usr/bin/python # -*- coding: latin1 -*- import UserString print 'É possível usar strings mutáveis no Python, através do módulo UserString,\ que define o tipo MutableString:' print 'Basicamente ele realiza uma substituicao de caractere' a = UserString.MutableString('RAFAEL') a[2:] = 'RAFA' s = UserString.MutableString('Python') s[0] = 'p' print '\nDepois da funcao' print a print s
def test_userstring_key(self): self.w({UserString.UserString('a'): 'b'}, u'{"a":"b"}')
def test_userstring_coerce(self): self.w({UserString.UserString('a'): 'b'}, u'{"a":"b"}', coerce_keys=True)
# Minimal test of the quote function from test_support import verify, verbose import urllib chars = 'abcdefghijklmnopqrstuvwxyz'\ '\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356' \ '\357\360\361\362\363\364\365\366\370\371\372\373\374\375\376\377' \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ '\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317' \ '\320\321\322\323\324\325\326\330\331\332\333\334\335\336' expected = 'abcdefghijklmnopqrstuvwxyz' \ '%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE' \ '%EF%F0%F1%F2%F3%F4%F5%F6%F8%F9%FA%FB%FC%FD%FE%FF' \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ '%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF' \ '%D0%D1%D2%D3%D4%D5%D6%D8%D9%DA%DB%DC%DD%DE' test = urllib.quote(chars) verify(test == expected, "urllib.quote problem 1") test2 = urllib.unquote(expected) verify(test2 == chars) in1 = "abc/def" out1_1 = "abc/def" out1_2 = "abc%2Fdef" verify(urllib.quote(in1) == out1_1, "urllib.quote problem 2") verify(urllib.quote(in1, '') == out1_2, "urllib.quote problem 3") in2 = "abc?def" out2_1 = "abc%3Fdef" out2_2 = "abc?def" verify(urllib.quote(in2) == out2_1, "urllib.quote problem 4") verify(urllib.quote(in2, '?') == out2_2, "urllib.quote problem 5") in3 = {"p1": "v1", "p2": "v2"}
def test_userstring(self): self.w([UserString.UserString('test')], u'["test"]')
import numpy as np import pandas as pd filename = 'part1.txt' with open(filename) as f: content = f.readlines() content = [x.strip() for x in content] import UserString s = UserString.MutableString(content[0]) #broken = True #while broken: # indices_to_remove = [] # for i in range(len(s)-1): # if s[i].islower() and i not in indices_to_remove: # if s[i].lower() == s[i+1].lower() and s[i+1].isupper(): # indices_to_remove.append(i) # indices_to_remove.append(i+1) # elif s[i].isupper() and i not in indices_to_remove: # if s[i].lower() == s[i+1].lower() and s[i+1].islower(): # indices_to_remove.append(i) # indices_to_remove.append(i+1) # for index in sorted(indices_to_remove, reverse=True): # del s[index] # if len(indices_to_remove) == 0: # broken=False #print(len(s)) #more effficient
st = string.Template('$aviso aconteceu em $quando') # Preenche o modelo com um dicionário s = st.substitute({'aviso': 'Falta de eletricidade', 'quando': '03 de Abril de 2002'}) # Mostra: # Falta de eletricidade aconteceu em 03 de Abril de 2002 print (s) # String mutável s = UserString.MutableString('JESUS') s[0] = 'J' print ('\n'+ s) # mostra "Jesus" #As strings unicode podem convertidas para strings convencionais através do método decode() # String unicode u = u'Hüsker Dü' # Convertendo para str s = u.encode('latin1') print ('\n'+ s, '=>', type(s))
def __mod__(self, args): result = UserString.UserString(self.msg % args) result.level = self.level return result
class OldStyleClass: pass osc = OldStyleClass() dataDict = { isSequence: ( (nsc, False), (osc, False), (False, False), (5, False), (7.5, False), (u'unicode string', False), ('regular string', False), (UserString.UserString("user string"), False), (dict(), False), (set(), False), (list(), True), ((), True), ), isCollection: ( (nsc, False), (osc, False), (False, False), (5, False), (7.5, False), (u'unicode string', False), ('regular string', False), (UserString.UserString("user string"), False), (dict(), True),
print isAString(u_str), isExactlyAString(u_str) def isStringLike(anobj): # the general Python approach to type-checking is known as # duck typing: if it walks like a duck and quacks like a duck, # it's duck-like enough for our purpose. try: anobj.lower() + anobj + '' except: return False else: return True import UserString usr_str = UserString.UserString("userstring") print isAString(usr_str) print isStringLike(usr_str) # 1.4 Aligning Strings print '|', "Left".ljust(20), '|', 'Right'.rjust(20), '|', 'Center'.center( 20), '|' print ' Center '.center(20, '+') # 1.5 Trimming Space from the Ends of a String x = ' hej ' print '|', x.lstrip(), '|', x.rstrip(), '|', x.strip(), '|' x = 'xyxxyy hejxy yyx' print '|' + x.strip('xy') + '|'
# importando o módulo UserString import UserString s = UserString.MutableString('Python') s[0] = 'p' print (s) # mostra "python"
def __init__(self, bufsize=32 * 1024): if bufsize == 0: bufsize = min_buf_size self.__buf = UserString.MutableString('\0' * bufsize) self.__bufsize = bufsize self.__datsize = 0