def _setupCategories(self, config): """Add buttons to browse between categories config -- ConfigParser containing application settings """ #Get all button data lines = [] ctr = 1 option = ini.image + str(ctr) while(config.has_option(ini.year, option)): line = config.get(ini.year, option) lines.append(line) ctr += 1 option = ini.image + str(ctr) #Create as many buttons as needed buttondata = zip(lines, self._years) if(len(buttondata) < len(self._years)): print('Warning! There are more categories than category buttons - some categories will not be shown') ctr = 0 for (line, year) in buttondata: tb = TransparentButton(self._canvas, self._settings.generalfont, line, self._scalefactor) tb.setText(year) tb.setCommand(self._ehYear) tb.index = ctr ctr += 1 self._activeInPreview.append(tb)
def test_tuple_reuse(self): if test_support.due_to_ironpython_incompatibility("implementation detail: http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=20279"): return # Tests an implementation detail where tuple is reused # whenever nothing else holds a reference to it self.assertEqual(len(set(map(id, list(enumerate(self.seq))))), len(self.seq)) self.assertEqual(len(set(map(id, enumerate(self.seq)))), min(1,len(self.seq)))
def test_len(self): if test_support.due_to_ironpython_incompatibility( "implementation detail"): return # This is an implementation detail, not an interface requirement from test.test_iterlen import len for s in ('hello', tuple('hello'), list('hello'), xrange(5)): self.assertEqual(len(reversed(s)), len(s)) r = reversed(s) list(r) self.assertEqual(len(r), 0) class SeqWithWeirdLen: called = False def __len__(self): if not self.called: self.called = True return 10 raise ZeroDivisionError def __getitem__(self, index): return index r = reversed(SeqWithWeirdLen()) self.assertRaises(ZeroDivisionError, len, r)
def compute_max_pile(numbers_ls): # from str to int numbers_ls = map(int, numbers_ls) # compute the "global xor" = xor of all elements global_xor = compute_group_xor(numbers_ls) # real sum of all elements global_sum = sum(numbers_ls) # all condition fitting groups relevant_groups = [] # for each size < length(numbers_ls) check if any of that size piles # fit our condition for k in range(1, len(numbers_ls)/2 + 1): for subset in k_subsets(numbers_ls, k): group_xor = compute_group_xor(subset) if group_xor ^ global_xor == group_xor: relevant_groups.append(subset) # find max of appropriate groups, if any group exists if len(relevant_groups) == 0: return None max_group = 0; for group in relevant_groups: group_sum = sum(group) group_sum = max([group_sum, global_sum - group_sum]) if group_sum > max_group: max_group = group_sum return max_group
def sort(self, data): if data == None or len(data) < 1: return data print data base_value = data[0] left_array = [] right_array = [] for index in range(1, len(data)): compare_value = data[index] if(base_value > compare_value): left_array.append(compare_value) else: right_array.append(compare_value) if len(left_array) > 1: sorted_array = self.sort(left_array) left_array = sorted_array if len(right_array) > 1: sorted_array = self.sort(right_array) right_array = sorted_array right_array.insert(0, base_value) left_array.extend(right_array) return left_array
def test_tuple_reuse(self): # Tests an implementation detail where tuple is reused # whenever nothing else holds a reference to it self.assertEqual(len(set(map(id, list(enumerate(self.seq))))), len(self.seq)) self.assertEqual(len(set(map(id, enumerate(self.seq)))), min(1, len(self.seq)))
def getSkuMap(url): content = urllib2.urlopen(url) token = "None" brace_level = 0 skuMap = [] parseStock = False for line in content: gbk_line = line.decode('gbk') m1 = re.search('"skuMap":', gbk_line) if m1: token = "skuMap" brace_level = brace_level + 1 continue if token == "skuMap": # print brace_level , " " , gbk_line if brace_level == 2: m1 = re.match('.*";(.*);".*', gbk_line) if m1: # We find a skumap # add a map to it skuMap.append({}) skuMap[len(skuMap) - 1]["index"] = m1.group(1) # print len(skuMap) , " " , m1.group(1) if brace_level == 3: m1 = re.match('.*"skuId" : "([0-9]*)".*', gbk_line) if m1: skuMap[len(skuMap) - 1]["skuId"] = m1.group(1) continue m1 = re.match('.*"price" : "([0-9\.]*)".*', gbk_line) if m1: skuMap[len(skuMap) - 1]["price"] = m1.group(1) continue m1 = re.search('stock', gbk_line) if m1: parseStock = True continue if parseStock: m1 = re.match('.*"([0-9]*)".*', gbk_line) if m1: skuMap[len(skuMap) - 1]["stock"] = m1.group(1) parseStock = False if re.match(".*{.*", gbk_line): brace_level = brace_level + 1 if re.match(".*}.*", gbk_line): brace_level = brace_level - 1 if brace_level == 0: token = "None" return skuMap
def getSkuMap(url): content = urllib2.urlopen(url) token = "None" brace_level = 0 skuMap = [] parseStock = False for line in content : gbk_line = line.decode('gbk') m1 = re.search('"skuMap":', gbk_line) if m1 : token = "skuMap" brace_level = brace_level + 1 continue if token == "skuMap" : # print brace_level , " " , gbk_line if brace_level == 2 : m1 = re.match('.*";(.*);".*', gbk_line) if m1 : # We find a skumap # add a map to it skuMap.append({}) skuMap[len(skuMap) - 1]["index"] = m1.group(1) # print len(skuMap) , " " , m1.group(1) if brace_level == 3 : m1 = re.match('.*"skuId" : "([0-9]*)".*', gbk_line) if m1 : skuMap[len(skuMap) - 1]["skuId"] = m1.group(1) continue m1 = re.match('.*"price" : "([0-9\.]*)".*', gbk_line) if m1 : skuMap[len(skuMap) - 1]["price"] = m1.group(1) continue m1 = re.search('stock', gbk_line) if m1 : parseStock = True continue if parseStock : m1 = re.match('.*"([0-9]*)".*', gbk_line) if m1 : skuMap[len(skuMap) - 1]["stock"] = m1.group(1) parseStock = False if re.match(".*{.*" , gbk_line) : brace_level = brace_level + 1 if re.match(".*}.*" , gbk_line) : brace_level = brace_level - 1 if brace_level == 0 : token = "None" return skuMap
def test_tuple_reuse(self): if test_support.due_to_ironpython_incompatibility( "implementation detail: http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=20279" ): return # Tests an implementation detail where tuple is reused # whenever nothing else holds a reference to it self.assertEqual(len(set(map(id, list(enumerate(self.seq))))), len(self.seq)) self.assertEqual(len(set(map(id, enumerate(self.seq)))), min(1, len(self.seq)))
def index(request): first_news = [] first_news_list = SportNews.objects.filter( priority='NEWS_MAIN').order_by('-created_at') if len(first_news_list) > 0: news_info = {} news_info['title'] = first_news_list[0].title news_info['img'] = '/media/' + str(first_news_list[0].photo) first_news.append(first_news_list[0].id) first_news.append(news_info) main_news = [] for news_prio in NEWS_PRIO: if news_prio[0] != 'NEWS_NORMAL' and news_prio[0] != 'NEWS_MAIN': main_news_list = SportNews.objects.filter( priority=news_prio[0]).order_by('-created_at') if len(main_news_list) > 0: news_info = {} news_info['title'] = main_news_list[0].title news_info['img'] = '/media/' + str(main_news_list[0].photo) news = [] news.append(main_news_list[0].id) news.append(news_info) main_news.append(news) other_news_list = SportNews.objects.all().order_by('-created_at')[:20] other_news = [] for other in other_news_list: news = [] news.append(other.id) news.append(other.photo) news.append(other.title) isItemInMainNews = False for mainNewsItem in main_news: if mainNewsItem[0] == news[0]: isItemInMainNews = True if not isItemInMainNews and first_news and other.id != first_news[0]: other_news.append(news) return render(request, 'main/index.html', { 'user_info': getUseInfo(request), 'navigationBar': getNavigationBar(), 'side_bar': getSideBar(), 'first_news': first_news, 'main_news': main_news, 'other_news': other_news, }, context_instance=RequestContext(request))
def getXMLNode(data): if len(data) < 5: print data return (2, "") eventDict = {} eventDict["date"] = strip(data[0]) eventDict["text"] = strip(data[1]) eventDict["img"] = strip(data[2]) eventDict["vetName"] = strip(data[3]) eventDict["vetID"] = strip(data[4]) isVetNode = ( eventDict["date"] == "" and eventDict["text"] == "" and eventDict["img"] == "" and not eventDict["vetName"] == "" and not eventDict["vetID"] == "" ) isEmpty = not isVetNode and eventDict["img"] == "" isCusLink = isCustomLink(eventDict["img"]) isBadVetID = isCustomLink(eventDict["vetID"]) isEmptyName = eventDict["vetName"] == "" if isEmpty or isCusLink or isBadVetID or isEmptyName: return (3, eventDict) if isVetNode: return (1, getVetNode(eventDict)) elif eventDict["date"] == "Date": return (2, "") else: return (0, getEventNode(eventDict))
def on_categoriesview_activated(self, index): articulo = self.categoriesview.model().asRecord(index) if len(articulo) > 0: nuevo = True for i, line in enumerate(self.editmodel.lines): if line.itemId == articulo[5]: nuevo = False fila = i line = self.editmodel.lines[self.editmodel.rowCount() - 1] if nuevo: fila = self.editmodel.rowCount() self.editmodel.insertRow(fila) self.parent.saveAct.setEnabled(True) linea = self.editmodel.lines[fila] linea.itemDescription = articulo[0] + " " + articulo[1] linea.itemPrice = Decimal(articulo[2]) linea.itemId = articulo[5] linea.quantityperbox = int(articulo[3]) self.editmodel.lines[fila].quantity += 1 self.editmodel.lines[fila].existencia = int( articulo[4]) - self.editmodel.lines[fila].quantity indice = self.editmodel.index(fila, 2) self.editmodel.dataChanged.emit(indice, indice) indice = self.editmodel.index(fila, 3) self.editmodel.dataChanged.emit(indice, indice) indice = self.editmodel.index(fila, 5) self.editmodel.dataChanged.emit(indice, indice)
def remove_adjacent(nums): listx = [] for num in nums: from test.test_iterlen import len if len(listx) == 0 or num != listx[-1]: listx.append(num) return listx
def on_categoriesview_activated(self,index): articulo = self.categoriesview.model().asRecord(index) if len(articulo)>0: nuevo = True for i, line in enumerate(self.editmodel.lines): if line.itemId == articulo [5]: nuevo = False fila = i line = self.editmodel.lines[self.editmodel.rowCount()-1] if nuevo: fila = self.editmodel.rowCount() self.editmodel.insertRow(fila) self.parent.saveAct.setEnabled(True) linea = self.editmodel.lines[fila] linea.itemDescription = articulo[0] + " " + articulo [1] linea.itemPrice = Decimal(articulo[2]) linea.itemId = articulo[5] linea.quantityperbox = int(articulo[3]) self.editmodel.lines[fila].quantity += 1 self.editmodel.lines[fila].existencia = int(articulo[4]) - self.editmodel.lines[fila].quantity indice =self.editmodel.index( fila,2) self.editmodel.dataChanged.emit( indice, indice ) indice =self.editmodel.index( fila,3) self.editmodel.dataChanged.emit( indice, indice ) indice =self.editmodel.index( fila,5) self.editmodel.dataChanged.emit( indice, indice )
def verbing(s): from test.test_iterlen import len if len(s) < 3: return s if s[-3:] == "ing": return s + "ly" else: return s + "ing"
def test_izip(self): ans = [(x, y) for x, y in izip("abc", count())] self.assertEqual(ans, [("a", 0), ("b", 1), ("c", 2)]) self.assertEqual(list(izip("abc", range(6))), zip("abc", range(6))) self.assertEqual(list(izip("abcdef", range(3))), zip("abcdef", range(3))) self.assertEqual(take(3, izip("abcdef", count())), zip("abcdef", range(3))) self.assertEqual(list(izip("abcdef")), zip("abcdef")) self.assertEqual(list(izip()), zip()) self.assertRaises(TypeError, izip, 3) self.assertRaises(TypeError, izip, range(3), 3) # Check tuple re-use (implementation detail) self.assertEqual([tuple(list(pair)) for pair in izip("abc", "def")], zip("abc", "def")) self.assertEqual([pair for pair in izip("abc", "def")], zip("abc", "def")) ids = map(id, izip("abc", "def")) self.assertEqual(min(ids), max(ids)) ids = map(id, list(izip("abc", "def"))) self.assertEqual(len(dict.fromkeys(ids)), len(ids))
def battleToSinglePC(self, enemy, battleType = 1, timeLimit = 1800): timeLeft = timeLimit dataList = [] infoFighter = [] infoEnemy = [enemy.getCommonValues_delta().copy()] fighterWin = False for item in self.getMyTeamInfomation(): if item['type'] == 1: #PlayerCharacter object player = PlayersManager().getPlayerByID(item['id']) if player is None: player = PlayersManager().createPlayerByID(item['id']) data = player.battle.fightTo(enemy, battleType, timeLeft) dataList.append(data) timeLeft -= data['overTime'] if data["winner"] != enemy.getBaseID(): fighterWin = True break infoFighter.append(player.getCommonValues_delta().copy()) elif item["type"] == 2: pass overTime = 0 HPMPDelta = [] result = [] startTime = 0 uL = dataList[-1]['battleEventProcessList'][-1] for i in dataList: i['battleEventProcessList'].pop(0) i['battleEventProcessList'].pop(-1) for e in i['battleEventProcessList']: e[0] += startTime for d in i["MPHPDelta"]: d["time"] += startTime result += i['battleEventProcessList'] HPMPDelta += i["MPHPDelta"] startTime += i["overTime"] # create end event if fighterWin: battleResult_set = [] result_i = [] #{} for i in range(len(infoFighter)): battleResult_set.append({'id':infoFighter[i]['id'], 'battleResult':result_i[i]}) event = [overTime, 2, -1, battleResult_set] import datetime result.insert(0, [0, 1, -1, [infoFighter, infoEnemy, str(datetime.datetime.now())]]) data = {} data['battleType'] = battleType data['maxTime'] = timeLimit data['timeLimit'] = timeLimit data['battleEventProcessList'] = result data['MPHPDelta'] = HPMPDelta#记录每秒玩家双方hp/mp增量 data['overTime'] = overTime return data return
def checkIfPasswordIsValid(password): if len(password) < 10: return False elif not checkIfStringContainsDigit(password): return False elif not CheckIfStringContainsCapitalLetter(password): return False else: return True
def test_izip(self): ans = [(x,y) for x, y in izip('abc',count())] self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)]) self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6))) self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3))) self.assertEqual(take(3,izip('abcdef', count())), zip('abcdef', range(3))) self.assertEqual(list(izip('abcdef')), zip('abcdef')) self.assertEqual(list(izip()), zip()) self.assertRaises(TypeError, izip, 3) self.assertRaises(TypeError, izip, range(3), 3) # Check tuple re-use (implementation detail) self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')], zip('abc', 'def')) self.assertEqual([pair for pair in izip('abc', 'def')], zip('abc', 'def')) ids = map(id, izip('abc', 'def')) self.assertEqual(min(ids), max(ids)) ids = map(id, list(izip('abc', 'def'))) self.assertEqual(len(dict.fromkeys(ids)), len(ids))
def test_cycle(self): for s in ("123", "", range(1000), ('do', 1.2), xrange(2000, 2200, 5)): for g in (G, I, Ig, S, L, R): tgtlen = len(s) * 3 expected = list(g(s)) * 3 actual = list(islice(cycle(g(s)), tgtlen)) self.assertEqual(actual, expected) self.assertRaises(TypeError, cycle, X(s)) self.assertRaises(TypeError, list, cycle(N(s))) self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
def test_main(verbose=None): support.run_unittest(__name__) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in range(len(counts)): support.run_unittest(__name__) counts[i] = sys.gettotalrefcount() print(counts)
def test_cycle(self): for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): tgtlen = len(s) * 3 expected = list(g(s))*3 actual = list(islice(cycle(g(s)), tgtlen)) self.assertEqual(actual, expected) self.assertRaises(TypeError, cycle, X(s)) self.assertRaises(TypeError, list, cycle(N(s))) self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
def k_subsets(s, k): ''' Yield all subsets of size k from set (or list) s s -- a set or list (any iterable will suffice) k -- an integer > 0 ''' s = list(s) n = len(s) for k_set in k_subsets_i(n, k): yield set([s[i] for i in k_set])
def test_main(verbose=None): test_support.run_unittest(__name__) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(__name__) counts[i] = sys.gettotalrefcount() print counts
def test_len(self): # This is an implementation detail, not an interface requirement from test.test_iterlen import len for s in ('hello', tuple('hello'), list('hello'), range(5)): self.assertEqual(len(reversed(s)), len(s)) r = reversed(s) list(r) self.assertEqual(len(r), 0) class SeqWithWeirdLen: called = False def __len__(self): if not self.called: self.called = True return 10 raise ZeroDivisionError def __getitem__(self, index): return index r = reversed(SeqWithWeirdLen()) self.assertRaises(ZeroDivisionError, len, r)
def test_izip(self): ans = [(x,y) for x, y in izip('abc',count())] self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)]) self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6))) self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3))) self.assertEqual(take(3,izip('abcdef', count())), zip('abcdef', range(3))) self.assertEqual(list(izip('abcdef')), zip('abcdef')) self.assertEqual(list(izip()), zip()) self.assertRaises(TypeError, izip, 3) self.assertRaises(TypeError, izip, range(3), 3) # Check tuple re-use (implementation detail) self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')], zip('abc', 'def')) self.assertEqual([pair for pair in izip('abc', 'def')], zip('abc', 'def')) # Does not apply to Jython - no tuple reuse # ids = map(id, izip('abc', 'def')) # self.assertEqual(min(ids), max(ids)) ids = map(id, list(izip('abc', 'def'))) self.assertEqual(len(dict.fromkeys(ids)), len(ids))
def create_node(parent, tag, content='',): ''' 创建一个新节点 @param parent:父节点 @param tag:子节点标签 @param content:节点闭合标签里的文本内容 ''' element = SubElement(parent, tag) if len(content) != 0: element.text = unicode(content , "gbk") #unicode转换 return element
def test_izip(self): ans = [(x,y) for x, y in izip('abc',count())] self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)]) self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6))) self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3))) self.assertEqual(take(3,izip('abcdef', count())), zip('abcdef', range(3))) self.assertEqual(list(izip('abcdef')), zip('abcdef')) self.assertEqual(list(izip()), zip()) self.assertRaises(TypeError, izip, 3) self.assertRaises(TypeError, izip, range(3), 3) # Check tuple re-use (implementation detail) self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')], zip('abc', 'def')) self.assertEqual([pair for pair in izip('abc', 'def')], zip('abc', 'def')) if test_support.check_impl_detail(): # izip "reuses" the same tuple object each time when it can ids = map(id, izip('abc', 'def')) self.assertEqual(min(ids), max(ids)) ids = map(id, list(izip('abc', 'def'))) self.assertEqual(len(dict.fromkeys(ids)), len(ids))
def create_node_attrib(parent, tag, attrib, content=''): ''' 创建一个新节点,带有属性 @param parent:父节点 @param tag:子节点标签 @param attrib:属性及属性值 z.B={'NUM':'123'} @param content:节点闭合标签里的文本内容 ''' element = SubElement(parent, tag, attrib) if len(content) != 0: element.text = unicode(content , "gbk") #unicode转换 return element
def index(request): first_news = [] first_news_list = SportNews.objects.filter(priority='NEWS_MAIN').order_by('-created_at') if len(first_news_list) > 0: news_info = {} news_info['title'] = first_news_list[0].title news_info['img'] = '/media/' + str(first_news_list[0].photo) first_news.append(first_news_list[0].id) first_news.append(news_info) main_news = [] for news_prio in NEWS_PRIO: if news_prio[0] != 'NEWS_NORMAL' and news_prio[0] != 'NEWS_MAIN': main_news_list = SportNews.objects.filter(priority=news_prio[0]).order_by('-created_at') if len(main_news_list) > 0: news_info = {} news_info['title'] = main_news_list[0].title news_info['img'] = '/media/' + str(main_news_list[0].photo) news = [] news.append(main_news_list[0].id) news.append(news_info) main_news.append(news) other_news_list = SportNews.objects.all().order_by('-created_at')[:20] other_news = [] for other in other_news_list: news = [] news.append(other.id) news.append(other.photo) news.append(other.title) isItemInMainNews = False for mainNewsItem in main_news: if mainNewsItem[0] == news[0]: isItemInMainNews = True if not isItemInMainNews and first_news and other.id != first_news[0]: other_news.append(news) return render(request, 'main/index.html', {'user_info': getUseInfo(request), 'navigationBar': getNavigationBar(),'side_bar': getSideBar(), 'first_news': first_news, 'main_news': main_news, 'other_news': other_news,}, context_instance=RequestContext(request) )
def test_main(verbose=None): testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig, TestReversed) test_support.run_unittest(*testclasses) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*testclasses) counts[i] = sys.gettotalrefcount() print counts
def mutatingtuple(tuple1, f, tuple2): # this builds a tuple t which is a copy of tuple1, # then calls f(t), then mutates t to be equal to tuple2 # (needs len(tuple1) == len(tuple2)). def g(value, first=[1]): if first: del first[:] f(z.next()) return value items = list(tuple2) items[1:1] = list(tuple1) gen = imap(g, items) z = izip(*[gen]*len(tuple1)) z.next()
def loadImages(dirName): from os import listdir hwLabels = [] trainingFileList = listdir(dirName) m = len(trainingFileList) trainingMat = zeros((m,1024)) for i in range(m): fileNameStr = trainingFileList[i] fileStr = fileNameStr.split('.')[0] classNumStr = int(fileStr.split('_')[0]) if classNumStr == 9:hwLabels.append(-1) else:hwLabels.append(1) trainingMat[i,:] = img2vector('%s/%s' % (dirName,fileNameStr)) return trainingMat,hwLabels
def divide(numerator, denominator, detect_repetition=True, digit_limit=None): # If repetition detection is off, you must # specify a limit on the digits returned if not detect_repetition and digit_limit == None: return None decimal_found = False # prime the loop v = numerator // denominator numerator = 10 * (numerator - v * denominator) answer = str(v) if numerator == 0: return answer answer += '.' # Maintain a list of all the intermediate numerators # and the length of the output at the point where that # numerator was encountered. If you encounter the same # numerator again, then the decimal repeats itself from # the last index that numerator was encountered at. states = {} while numerator > 0 and (digit_limit == None or digit_limit > 0): # print numerator if detect_repetition: prev_state = states.get(numerator, None) if prev_state != None: start_repeat_index = prev_state non_repeating = answer[:start_repeat_index] repeating = answer[start_repeat_index:] return non_repeating + '[' + repeating + ']' states[numerator] = len(answer) v = numerator // denominator # floor division. This gets the next digit in the decimal portion answer += str(v) # concatenate next digit to answer numerator -= v * denominator # next two lines do magic numerator *= 10 if digit_limit != None: digit_limit -= 1 if numerator > 0: return answer + '...' return answer
def readFile(self, filename, verbose): try: if verbose: print "started reading file: {}".format(filename) reader = open(filename,'r') if verbose: print "file in memory, loading lines into list" # a = 1 for line in reader: # if a > 100000: break line = line[1:] self.infile.append(line) # a+=1 self.numEntries = len(self.infile) if verbose: print "lines read" reader.close() except IOError: sys.exit('Cannot open input file: {}'.format(filename))
def chooseShoppingItem(shoppingItems) : valuelist = [] for key in shoppingItems.keys() : print "Choose : " , key for index , title in enumerate(shoppingItems[key].keys()): print index , " : " , title # make sure a valid choice index = inputValidNumber("Input the index : " , 0 , len(shoppingItems[key].keys())) # get the title if index != -1 : title = shoppingItems[key].keys()[index] print "You choose " , title valuelist.append(shoppingItems[key][title]) return valuelist
def selectJ(i,oS,Ei): maxK = -1;maxDeltaE = 0;Ej = 0 oS.eCache[i] = [1,Ei] validEcacheList = nonzero(oS.eCache[:,0].A)[0] if(len(validEcacheList)) > 1: for k in validEcacheList: if k == i:continue Ek = calcEk(oS, k) deltaE = abs(Ei - Ek) if(deltaE > maxDeltaE): maxK = k;maxDeltaE = deltaE;Ej = Ek return maxK,Ej else: j = selectJrand(i, oS.m) Ej = calcEk(oS, j) return j,Ej
def test_main(verbose=None): if support.is_jython: # XXX: CPython implementation details del EnumerateTestCase.test_tuple_reuse del TestReversed.test_len testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig, TestReversed) support.run_unittest(*testclasses) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in range(len(counts)): support.run_unittest(*testclasses) counts[i] = sys.gettotalrefcount() print(counts)
def test_main(verbose=None): test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC, RegressionTests, LengthTransparency) test_support.run_unittest(*test_classes) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() print counts # doctest the examples in the library reference test_support.run_doctest(sys.modules[__name__], verbose)
def chooseShoppingItem(shoppingItems): valuelist = [] for key in shoppingItems.keys(): print "Choose : ", key for index, title in enumerate(shoppingItems[key].keys()): print index, " : ", title # make sure a valid choice index = inputValidNumber("Input the index : ", 0, len(shoppingItems[key].keys())) # get the title if index != -1: title = shoppingItems[key].keys()[index] print "You choose ", title valuelist.append(shoppingItems[key][title]) return valuelist
def compute_final_element_list(case_line): case_line_arr = case_line.split() # create combinations list num_of_combs = int(case_line_arr[0]) combs_list = case_line_arr[1:num_of_combs + 1] combs_dict = {} for comb in combs_list: combs_dict[comb[:2]] = comb[2] combs_dict[comb[1] + comb[0]] = comb[2] # create oppositions list num_of_oppos = int(case_line_arr[num_of_combs + 1]) first_opp_index = num_of_combs + 2 oppos_list = case_line_arr[first_opp_index:first_opp_index + num_of_oppos] oppos_list = oppos_list + [opp[1] + opp[0] for opp in oppos_list] # create element list # num_of_elements = int(case_line_arr[first_opp_index + num_of_oppos]) elements_str = case_line_arr[first_opp_index + num_of_oppos + 1] elements_list = [] last_elem_index = -1 for elem in elements_str: if last_elem_index >= 0: cur_comb = elements_list[last_elem_index] + elem if combs_dict.has_key(cur_comb): elements_list[last_elem_index] = combs_dict[cur_comb] else: for elem_in_list in elements_list: if elem + elem_in_list in oppos_list: elements_list = [] last_elem_index = -1 break if len(elements_list) == 0: continue else: elements_list.append(elem) last_elem_index += 1 else: elements_list.append(elem) last_elem_index += 1 return elements_list
def updateLabels(self,index): articulo = self.categoriesview.model().asRecord(index) if len(articulo)>0: self.txtcategoria.setText( articulo[0]) self.txtmarca.setText( articulo[1]) self.articuloId = articulo[4] self.precioanterior = Decimal(articulo[2]) self.unidadesanterior = int(articulo[3]) if not self.ckprecio.isChecked(): self.precio = Decimal(articulo[2]) self.txtprecio.setValue(self.precio) if not self.ckunit.isChecked(): self.unidades = int(articulo[3]) self.txtunidades.setValue(self.unidades)
def main(): filepath = sys.argv[1] input_file = open(filepath, "rb") output_file = open(OUTPUT_FILEPATH, "wb") lines = input_file.readlines()[1:] input_file.close() for i, line in enumerate(lines): output_file.write("Case #%d: [" % (i + 1)) final_elems_ls = compute_final_element_list(line) if len(final_elems_ls) > 0: for elem in final_elems_ls[:-1]: output_file.write("%s, " % (elem)) output_file.write("%s]\n" % (final_elems_ls[-1])) else: output_file.write("]\n") output_file.close() return
def test_islice(self): for args in [ # islice(args) should agree with range(args) (10, 20, 3), (10, 3, 20), (10, 20), (10, 3), (20,) ]: self.assertEqual(list(islice(xrange(100), *args)), range(*args)) for args, tgtargs in [ # Stop when seqn is exhausted ((10, 110, 3), ((10, 100, 3))), ((10, 110), ((10, 100))), ((110,), (100,)) ]: self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs)) # Test stop=None self.assertEqual(list(islice(xrange(10), None)), range(10)) self.assertEqual(list(islice(xrange(10), None, None)), range(10)) self.assertEqual(list(islice(xrange(10), None, None, None)), range(10)) self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10)) self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2)) # Test number of items consumed SF #1171417 it = iter(range(10)) self.assertEqual(list(islice(it, 3)), range(3)) self.assertEqual(list(it), range(3, 10)) # Test invalid arguments self.assertRaises(TypeError, islice, xrange(10)) self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4) self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1) self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1) self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1) self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0) self.assertRaises(ValueError, islice, xrange(10), 'a') self.assertRaises(ValueError, islice, xrange(10), 'a', 1) self.assertRaises(ValueError, islice, xrange(10), 1, 'a') self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1) self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1) self.assertEqual(len(list(islice(count(), 1, 10, sys.maxint))), 1)
def test_islice(self): for args in [ # islice(args) should agree with range(args) (10, 20, 3), (10, 3, 20), (10, 20), (10, 3), (20,) ]: self.assertEqual(list(islice(xrange(100), *args)), range(*args)) for args, tgtargs in [ # Stop when seqn is exhausted ((10, 110, 3), ((10, 100, 3))), ((10, 110), ((10, 100))), ((110,), (100,)) ]: self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs)) # Test stop=None self.assertEqual(list(islice(xrange(10), None)), range(10)) self.assertEqual(list(islice(xrange(10), None, None)), range(10)) self.assertEqual(list(islice(xrange(10), None, None, None)), range(10)) self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10)) self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2)) # Test number of items consumed SF #1171417 it = iter(range(10)) self.assertEqual(list(islice(it, 3)), range(3)) self.assertEqual(list(it), range(3, 10)) # Test invalid arguments self.assertRaises(TypeError, islice, xrange(10)) self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4) self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1) self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1) self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1) self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0) self.assertRaises(ValueError, islice, xrange(10), 'a') self.assertRaises(ValueError, islice, xrange(10), 'a', 1) self.assertRaises(ValueError, islice, xrange(10), 1, 'a') self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1) self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1) self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
def checkIfUserNameAlreadyExists(username): users = User.objects.filter(username=username) if len(users) > 0: return True else: return False
queriess = raw_input("whats the query??") requests = queriess.split(" ") newqueries = regexp_tokenize(queriess, pattern=r'\"(.*?)\"') queries = regexp_tokenize(re.sub(r'\".*?\"', "", queriess), pattern=r'\w+') '''splitting of query into tokens using regex_tokenization''' if requests[0] == 'similar': similar(requests[1]) continue if requests[0] == 'df': req = ' '.join(requests[1:]) reqs = regexp_tokenize(re.sub(r'\".*?\"', "", req), pattern=r'\w+') print reqs if len(reqs) == 1: ''' handling single word queries''' if reqs[0] not in index: print 'Sorry, not found in any document!' else: print 'number of documents it appears in is', len( index[reqs[0]]) requestset = set() if len(reqs) > 1: ''' handling only < single word requests ''' print reqs for r0 in reqs: if r0 not in index: continue
def test_groupby(self): # Check whether it accepts arguments correctly self.assertEqual([], list(groupby([]))) self.assertEqual([], list(groupby([], key=id))) self.assertRaises(TypeError, list, groupby('abc', [])) self.assertRaises(TypeError, groupby, None) self.assertRaises(TypeError, groupby, 'abc', lambda x: x, 10) # Check normal input s = [(0, 10, 20), (0, 11, 21), (0, 12, 21), (1, 13, 21), (1, 14, 22), (2, 15, 22), (3, 16, 23), (3, 17, 23)] dup = [] for k, g in groupby(s, lambda r: r[0]): for elem in g: self.assertEqual(k, elem[0]) dup.append(elem) self.assertEqual(s, dup) # Check nested case dup = [] for k, g in groupby(s, lambda r: r[0]): for ik, ig in groupby(g, lambda r: r[2]): for elem in ig: self.assertEqual(k, elem[0]) self.assertEqual(ik, elem[2]) dup.append(elem) self.assertEqual(s, dup) # Check case where inner iterator is not used keys = [k for k, g in groupby(s, lambda r: r[0])] expectedkeys = set([r[0] for r in s]) self.assertEqual(set(keys), expectedkeys) self.assertEqual(len(keys), len(expectedkeys)) # Exercise pipes and filters style s = 'abracadabra' # sort s | uniq r = [k for k, g in groupby(sorted(s))] self.assertEqual(r, ['a', 'b', 'c', 'd', 'r']) # sort s | uniq -d r = [k for k, g in groupby(sorted(s)) if list(islice(g, 1, 2))] self.assertEqual(r, ['a', 'b', 'r']) # sort s | uniq -c r = [(len(list(g)), k) for k, g in groupby(sorted(s))] self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')]) # sort s | uniq -c | sort -rn | head -3 r = sorted([(len(list(g)), k) for k, g in groupby(sorted(s))], reverse=True)[:3] self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')]) # iter.next failure class ExpectedError(Exception): pass def delayed_raise(n=0): for i in range(n): yield 'yo' raise ExpectedError def gulp(iterable, keyp=None, func=list): return [func(g) for k, g in groupby(iterable, keyp)] # iter.next failure on outer object self.assertRaises(ExpectedError, gulp, delayed_raise(0)) # iter.next failure on inner object self.assertRaises(ExpectedError, gulp, delayed_raise(1)) # __cmp__ failure class DummyCmp: def __cmp__(self, dst): raise ExpectedError s = [DummyCmp(), DummyCmp(), None] # __cmp__ failure on outer object self.assertRaises(ExpectedError, gulp, s, func=id) # __cmp__ failure on inner object self.assertRaises(ExpectedError, gulp, s) # keyfunc failure def keyfunc(obj): if keyfunc.skip > 0: keyfunc.skip -= 1 return obj else: raise ExpectedError # keyfunc failure on outer object keyfunc.skip = 0 self.assertRaises(ExpectedError, gulp, [None], keyfunc) keyfunc.skip = 1 self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)
# Gets output Folder driver = webdriver.Firefox() main_window = driver.current_window_handle counter = 0 data = open(outputPath + "source" + str(counter) + qr_code + ".txt", 'w') for file in os.listdir(inputPath): if file.endswith(".html"): driver.find_element_by_css_selector('body').send_keys(Keys.CONTROL + 't') print "Parsing through: " + file driver.get("file:///" + inputPath + file) # Reads main data if len(driver.find_elements_by_css_selector('center')) != 0: main_data = driver.find_element_by_css_selector('center').text else: print "Could not find main_data for " + file continue if len(driver.find_elements_by_tag_name("b")) != 0: case_number = driver.find_elements_by_tag_name("b")[0].text else: print "Could not find case_number for " + file continue if len(main_data.split(case_number)) >= 2: if len(main_data.split(case_number)[1].split( case_type_string)) != 0: name = main_data.split(case_number)[1].split(
def test_repeat(self): from test.test_iterlen import len self.assertEqual(len(repeat(None, 50)), 50) self.assertRaises(TypeError, len, repeat(None))
query=json.loads(q.full_stat().replace(": ", ":").replace("'", '"').replace("\xa7", "§")) lowercasePlayers = [x.lower() for x in query['players']] try: tree = ET.parse(file) except: tree = ET.Element('logfile') root = tree.getroot() logentry = ET.SubElement ( root, 'logentry' ) datetime = ET.SubElement( logentry, 'datetime') datetime.text = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") players = ET.SubElement( logentry, 'datetime') players.text = query['numplayers'] count = ET.SubElement(logentry, 'count') adminPlusCount = ET.SubElement(count, 'admin+') adminPlusCount.text = len(_adminPlus.intersection(lowercasePlayers)) adminCount = ET.SubElement(count, 'admin') adminCount.text = len(_admin.intersection(lowercasePlayers)) staffCount = ET.SubElement(count, 'staff') staffCount.text = len(_staff.intersection(lowercasePlayers)) retiredCount = ET.SubElement(count, 'retired') retiredCount.text = len(_retired.intersection(lowercasePlayers)) artisanCount = ET.SubElement(count, 'artisan') artisanCount.text = len(_artisan.intersection(lowercasePlayers)) architectCount = ET.SubElement(count, 'architect') architectCount.text = len(_architect.intersection(lowercasePlayers)) for name in _adminPlus.intersection(lowercasePlayers): ET.SubElement(logentry, 'admin+').text = name for name in _admin.intersection(lowercasePlayers):
def next(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 return v
def test_tee(self): n = 200 def irange(n): for i in xrange(n): yield i a, b = tee([]) # test empty iterator self.assertEqual(list(a), []) self.assertEqual(list(b), []) a, b = tee(irange(n)) # test 100% interleaved self.assertEqual(zip(a, b), zip(range(n), range(n))) a, b = tee(irange(n)) # test 0% interleaved self.assertEqual(list(a), range(n)) self.assertEqual(list(b), range(n)) a, b = tee(irange(n)) # test dealloc of leading iterator for i in xrange(100): self.assertEqual(a.next(), i) del a self.assertEqual(list(b), range(n)) a, b = tee(irange(n)) # test dealloc of trailing iterator for i in xrange(100): self.assertEqual(a.next(), i) del b self.assertEqual(list(a), range(100, n)) for j in xrange(5): # test randomly interleaved order = [0] * n + [1] * n random.shuffle(order) lists = ([], []) its = tee(irange(n)) for i in order: value = its[i].next() lists[i].append(value) self.assertEqual(lists[0], range(n)) self.assertEqual(lists[1], range(n)) # test argument format checking self.assertRaises(TypeError, tee) self.assertRaises(TypeError, tee, 3) self.assertRaises(TypeError, tee, [1, 2], 'x') self.assertRaises(TypeError, tee, [1, 2], 3, 'x') # tee object should be instantiable a, b = tee('abc') c = type(a)('def') self.assertEqual(list(c), list('def')) # test long-lagged and multi-way split a, b, c = tee(xrange(2000), 3) for i in xrange(100): self.assertEqual(a.next(), i) self.assertEqual(list(b), range(2000)) self.assertEqual([c.next(), c.next()], range(2)) self.assertEqual(list(a), range(100, 2000)) self.assertEqual(list(c), range(2, 2000)) # test values of n self.assertRaises(TypeError, tee, 'abc', 'invalid') self.assertRaises(ValueError, tee, [], -1) for n in xrange(5): result = tee('abc', n) self.assertEqual(type(result), tuple) self.assertEqual(len(result), n) self.assertEqual(map(list, result), [list('abc')] * n) # tee pass-through to copyable iterator a, b = tee('abc') c, d = tee(a) self.assert_(a is c) # test tee_new t1, t2 = tee('abc') tnew = type(t1) self.assertRaises(TypeError, tnew) self.assertRaises(TypeError, tnew, 10) t3 = tnew(t1) self.assert_(list(t1) == list(t2) == list(t3) == list('abc')) # test that tee objects are weak referencable a, b = tee(xrange(10)) p = proxy(a) self.assertEqual(getattr(p, '__class__'), type(b)) del a self.assertRaises(ReferenceError, getattr, p, '__class__')