def test_indexOf(self): from operator import indexOf self.assertEqual(indexOf([1, 2, 2, 3, 2, 5], 1), 0) self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 2), 1) self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 3), 3) self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 5), 5) self.assertRaises(ValueError, indexOf, (1, 2, 2, 3, 2, 5), 0) self.assertRaises(ValueError, indexOf, (1, 2, 2, 3, 2, 5), 6) self.assertEqual(indexOf('122325', '2'), 1) self.assertEqual(indexOf('122325', '5'), 5) self.assertRaises(ValueError, indexOf, '122325', '6') self.assertRaises(TypeError, indexOf, 42, 1) self.assertRaises(TypeError, indexOf, indexOf, indexOf) f = open(TESTFN, 'w') try: f.write('a\nb\nc\nd\ne\n') finally: f.close() f = open(TESTFN, 'r') try: fiter = iter(f) self.assertEqual(indexOf(fiter, 'b\n'), 1) self.assertEqual(indexOf(fiter, 'd\n'), 1) self.assertEqual(indexOf(fiter, 'e\n'), 0) self.assertRaises(ValueError, indexOf, fiter, 'a\n') finally: f.close() try: unlink(TESTFN) except OSError: pass iclass = IteratingSequenceClass(3) for i in range(3): self.assertEqual(indexOf(iclass, i), i) self.assertRaises(ValueError, indexOf, iclass, -1)
def nothing(s): global tb, pos while True: for l in s.recv(10240).split("\n"): l = l.rstrip() print "received " + l if (l.startswith(">>>")): return elif (l.startswith("Cap'n Redbeard> ")): l = l[l.index(">") + 2:] if (l in msgSuccess): tb.append((indexOf(msgSuccess, l), len(msgSuccess))) elif (l in msgFail): tb.append((indexOf(msgFail, l), len(msgFail))) elif (l.startswith("[i] Your opponent missed while shooting at") or l.startswith( "[i] Your opponent hit a ship while shooting at ")): if (l.find("hit")): global rem rem -= 1 l = l[10:] tmp = l[l.index("[") + 1:l.index("]")] a, b = tmp.split(",") if (pos % 5 >= 3): tb.extend([(int(a), 10), (int(b), 10)]) pos += 1 elif (l.startswith("You lost")): sys.exit(-1)
def majority_preferences(election, choice1, choice2): """ Return the preferences of voters between two candidates in an election. """ return Counter(( choice1 if indexOf(vote, choice1) < indexOf(vote, choice2) else choice2 ) for vote in election)
def rotateChar(c): lower = list(string.ascii_lowercase) upper = list(string.ascii_uppercase) if c in lower: return lower[(operator.indexOf(lower, c) + 13) % 26] elif c in upper: return upper[(operator.indexOf(upper, c) + 13) % 26] else: return c
def __volUp(self): self.__mute = False index = indexOf(self.__volumeSteps, self.__volume)+1 if index < len(self.__volumeSteps): self.__volume = self.__volumeSteps[index] return self.__createVolumeCommand() return []
def parse_file_byte(src_folder, tt, all_keywords=None, all_extension=None): """TODO: Docstring for parse_file_byte. :returns: TODO """ X, y = [], [] all_files = [x for x in listdir(src_folder) if x[0] != '.'] if all_extension is None: temp = [splitext(x)[1] for x in all_files if x[0] != '.'] all_extension = list(set(temp)) all_extension = sorted(all_extension) for one in all_files: index = operator.indexOf(all_extension, splitext(one)[1]) with open(join(src_folder, one), 'r') as fh: feature = [ord(i) for i in fh.read()[:900]] X.append(feature) y.append([int(i == index) for i in range(len(all_extension))]) print 'The number of feature: %d' % (900) print 'The number of label: %d' % (len(all_extension)) with open('all_extension.txt', 'w') as tmp: tmp.write(str(all_extension)) sio.savemat(tt+'_sample', { 'input': X, 'label': y, }) with open(join(PARAM_FOLDER, 'extension'), 'w') as tmp: tmp.write(json.dumps(all_extension)) with open(join(PARAM_FOLDER, 'keyword'), 'w') as tmp: tmp.write(json.dumps(all_keywords)) return numpy.array(X), numpy.array(y)
def def_first(): """Game for matching word to definiton""" content = helpers.init() print('\nYou can exit at anytime by entering \'menu\'.\n') random.shuffle(content) count = len(content) correct = 0 incorrect = 0 for word in content: print('\n{}. {}'.format(operator.indexOf(content, word) + 1, word['definition'])) res = input('\nWhat word does this definition belong to?\n\t=>').lower() if res == word['key'].lower(): count -= 1 correct += 1 if count > 0: print('\nGood Job! next word!') elif res == 'menu': main.menu() else: incorrect += 1 count -= 1 if count > 1: print('\nIncorrect. Next word.') print('\nYou got {} correct and {} incorrect'.format(correct, incorrect)) helpers.callback(def_first)
def run301_04(): """ sequence ops :return: """ a = [1, 2, 3] b = ['a', 'b', 'c'] print('a=', a) print('b=', b) print('Constructive:') print('concat(a,b): ', concat(a, b)) print('\nSearching:') print('contains(a,1):', contains(a, 1)) print('contains(b,"d"):', contains(b, 'd')) print('countOf(a,1):', countOf(a, 1)) print('countOf(b,"d"):', countOf(b, 'd')) print('indexOf(a,1):', indexOf(a, 1)) # print('indexOf(a,5):', indexOf(a, 5)) # ValueError print('\nAccess Items:') print('getitem(b,1):', getitem(b, 1)) print('getitem(b,slice(1,3)):', getitem(b, slice(1, 3))) print('setitem(b,1,"d"):', setitem(b, 1, 'd')) print(b) print('setitem(a,slice(1,3),[4,5]):', setitem(a, slice(1, 3), [4, 5])) print(a) print('\nDestructive:') print('delitem(b,1)', delitem(b, 1)) print(b) print('delitem(a,slice(1,3))', delitem(b, slice(1, 3))) print(a)
def _on_exit(self, process, exit_status, term_signal): # exit callback called when a process exit # notify other that the process exited self._publish("proc.%s.exit" % process.name, name=process.name, pid=process.id, exit_status=exit_status, term_signal=term_signal) with self._lock: state = self.get_process_state(process.name) if process in self._stopped: # this exit was expected. remove it from the garbage # collection. del self._stopped[operator.indexOf(self._stopped, process)] else: # unexpected exit, remove the process from the list of # running processes. if process.id in self.running: self.running.pop(process.id) if state is not None: state.remove(process) # this remplate has been removed if not state: return if not state.stopped: # manage the template, eventually restart a new one. if self._check_flapping(state): self._manage_processes(state)
def __volDown(self): self.__mute = False index = indexOf(self.__volumeSteps, self.__volume)-1 if index >= 0: self.__volume = self.__volumeSteps[index] return self.__createVolumeCommand() return []
def main(): a = [1, 2, 3] b = ["a", "b", "c"] print("a =", a) print("b =", b) print("\nConstructive:") print(" concat(a, b)", operator.concat(a, b)) print("\nSearching:") print(" contains(a, 1) :", operator.contains(a, 1)) print(" contains(b, 'd'):", operator.contains(b, "d")) print(" countOf(a, 1) :", operator.countOf(a, 1)) print(" countOf(b, 'd') :", operator.countOf(b, "d")) print(" indexOf(a, 1) :", operator.indexOf(a, 1)) print("\nAccess Items:") print(" getitem(b, 1) :", operator.getitem(b, 1)) print(" getitem(b, slice(1, 3)) :", operator.getitem(b, slice(1, 3))) print(" setitem(b, 1, 'd') :", end=" ") operator.setitem(b, 1, "d") print(b) print(" setitem(a, slice(1, 3), [4,5]):", end=" ") operator.setitem(a, slice(1, 3), [4, 5]) print(a) print("\nDestructive:") print(" delitem(b, 1) :", end=" ") operator.delitem(b, 1) print(b) print(" delitem(a, slice(1, 3)):", end=" ") operator.delitem(a, slice(1, 3)) print(a)
def def_first(): """Game for matching word to definiton""" content = helpers.init() print("\nYou can exit at anytime by entering 'exit'.\n") random.shuffle(content) count = len(content) correct = 0 incorrect = 0 for word in content: print("\n{}. {}".format(operator.indexOf(content, word) + 1, word["definition"])) res = input("\nWhat word does this definition belong to?\n\t=>").lower() if res == word["key"].lower(): count -= 1 correct += 1 if count > 0: print("\nGood Job! next word!") elif res == "exit": return else: incorrect += 1 count -= 1 if count > 1: print("\nIncorrect. Next word.") print("\nYou got {} correct and {} incorrect".format(correct, incorrect)) helpers.callback(def_first)
def changeContent(self, body): '''Changes the template in a customized way. @param body: the HTML code of the page @return: the modified body ''' field = 'language' curLanguage = self.getField(field) values = [] for lang in self._session._supportedLanguages: if lang != 'en': values.append(lang) if curLanguage == None: ix = 0 else: ix = operator.indexOf(values, curLanguage) body = self.fillOpts(field, values, None, ix, body) if self._resultTitle == None: title = '' result = '' else: title = self._snippets.get('RESULT_TITLE') title = title.replace('{{title}}', self._resultTitle) if self._resultBody == None: result = self._snippets.get('EMPTY_BODY') else: result = self._resultBody body = body.replace('{{RESULT_TITLE}}', title) body = body.replace('{{RESULT}}', result) return body
def parse_multi_file(output_file, exclude_file): """TODO: Docstring for parse_multi_file. :returns: TODO """ all_keywords = {} all_files = [x for x in os.listdir('./train') if x[0] != '.'] all_keywords = fill_feature_dict(all_files, './train/', exclude_file) temp = [os.path.splitext(x)[1] for x in all_files if x[0] != '.'] all_extension = list(set(temp)) for one in all_files: single_list = [one] index = operator.indexOf(all_extension, os.path.splitext(one)[1]) + 1 keywords = fill_feature_dict(single_list, './train/') result = keyword_to_feature(keywords, all_keywords, index) output_file.write(result + os.linesep) with open('all_extension.txt', 'w') as extension_file: extension_file.write(json.dumps(all_extension)) with open('all_keywords.txt', 'w') as keyword_file: keyword_file.write(json.dumps(all_keywords)) with open('oct_extension.txt', 'w') as oct_extension: for extension in all_extension: oct_extension.write(extension + os.linesep)
def wzc_arith(opstr): """ calculator application for operators: + - * / % ** """ import operator ops = ('+', '-', '*', '/', '%', '**') expr = str(opstr).split() op = expr[1] op_index = operator.indexOf(ops, op) num1 = float(expr[0]) num2 = float(expr[2]) if op_index == 0: return num1 + num2 elif op_index == 1: return num1 - num2 elif op_index == 2: return num1 * num2 elif op_index == 3: return num1 / num2 elif op_index == 4: return num1 % num2 elif op_index == 5: return num1 ** num2
def wzc_arith(opstr): """ calculator application for operators: + - * / % ** """ import operator ops = ('+', '-', '*', '/', '%', '**') expr = str(opstr).split() op = expr[1] op_index = operator.indexOf(ops, op) num1 = float(expr[0]) num2 = float(expr[2]) if op_index == 0: return num1 + num2 elif op_index == 1: return num1 - num2 elif op_index == 2: return num1 * num2 elif op_index == 3: return num1 / num2 elif op_index == 4: return num1 % num2 elif op_index == 5: return num1**num2
def clusterize(self,noClusters,noNouranksToKeep,**kwargs): """ """ storage = getUtility(INounPhraseStorage) docids = storage.rankedNouns.keys() docnouns = [] allNouns = set() vectors = [] for key in docids: importantNouns = storage.getNounTerms( key, noNouranksToKeep) docnouns.append(importantNouns) allNouns = allNouns.union(importantNouns) for nouns in docnouns: vector = [(noun in nouns and 1 or 0) for noun in allNouns] vectors.append(numpy.array(vector)) clusterer = KMeansClusterer(noClusters,pearson,**kwargs) clusters = clusterer.cluster(vectors,True) result = {} for i in range(noClusters): result[i] = [] for docid in docids: index = indexOf(docids,docid) result[clusters[index]] = result[clusters[index]] + [docid] return result
def __delitem__(self, id_): """Delete a Holding by id. :raises ValueError: """ index = indexOf((x['id'] for x in self), str(id_)) del self._iterable[index]
def _choose_best_alternatives(self, journeys): to_keep = [] mapping = defaultdict(list) best = None functors = OrderedDict([ ('bss_walking', has_bss_first_and_walking_last), ('walking_bss', has_walking_first_and_bss_last), ('bss_bss', has_bss_first_and_bss_last), ('bike_walking', has_bike_first_and_walking_last), ('bike_bss', has_bike_first_and_bss_last), ('car', has_car_and_tc), ]) for idx, journey in enumerate(journeys): if journey.type in non_pt_types: to_keep.append(idx) for key, func in functors.items(): if func(journey): mapping[key].append(journey) for key, _ in functors.items(): if not best and mapping[key]: best = min(mapping[key], key=attrgetter('duration')) to_keep.append(indexOf(journeys, best)) logger = logging.getLogger(__name__) logger.debug('from alternatives we keep: %s', [journeys[i].type for i in to_keep]) to_delete = list(set(range(len(journeys))) - set(to_keep)) to_delete.sort(reverse=True) for idx in to_delete: del journeys[idx]
def encode(self,message,key = 0): if (key != 0): self.key = key nm = "" for letter in message: nm += self.dict[(operator.indexOf(self.dict,letter) + self.key) % 27] return nm
def AddData(self, words, labels): self.context.append([]) self.spelling.append([]) self.both.append([]) for word in words: self.both[len(self.spelling) - 1].append(word) if word[0:3] == 'in=': self.spelling[len(self.spelling) - 1].append(word) else: self.context[len(self.spelling) - 1].append(word) if sum(labels) == 1: self.labels.append(indexOf(labels, 1)) self.seedlabels.append(indexOf(labels, 1) + 1) else: self.labels.append(-1) self.seedlabels.append(-1)
def AddData(self, words, labels): self.context.append([]) self.spelling.append([]) self.both.append([]) for word in words: self.both[len(self.spelling)-1].append(word) if word[0:3] == 'in=': self.spelling[len(self.spelling)-1].append(word) else: self.context[len(self.spelling)-1].append(word) if sum(labels) == 1: self.labels.append(indexOf(labels, 1)) self.seedlabels.append(indexOf(labels, 1)+1) else: self.labels.append(-1) self.seedlabels.append(-1)
def score_name(s): """Score a word by giving each letter its value in the alphabet (a->1, b->2, ...) and summing the results""" score = 0 alpha = " abcdefghijklmnopqrstuvwxyz" for i in s.lower(): score += operator.indexOf(alpha, i) return score
def decode(self,message, key = 0): if (key != 0): self.key = key om = "" for letter in message: om += self.dict[(operator.indexOf(self.dict,letter) - self.key) %27] return om
def update(self): self.queue_draw() cellsToPop=[] for cell in self.cells: cell.update(self.currentState) if cell.type=="NormalCell": if cell.posX+cell.width<0 or (cell.status=="Dead" and len(cell.dyingParticles)<=0): cellsToPop.append(cell) for cell in cellsToPop: self.cells.pop(indexOf(self.cells,cell)) if cell==self.virus[0].targetCell: self.virus[0].targetCell=None if self.currentState=="Running": self.ticksToNextCell-=1 if self.ticksToNextCell<=0: self.ticksToNextCell=random.randint(self.minTimeToNextCell,self.maxTimeToNextCell) newCell=Cell(WINDOW_SIZE, random.randint(0,TRAINING_ZONE_LIMIT-CELL_HEIGHT)) newCell.velX=-random.random()*2 newCell.type="NormalCell" self.cells.append(newCell) #update virus for virus in self.virus: if not virus.isDead: virus.update(self.currentState) if len(self.cells)>0 and virus.targetCell==None: virus.targetCell=self.cells[len(self.cells)-1] #This is a temprorary decision function #Actual classification should do this self.classify_cell(widget=None) if virus.is_colliding_with(virus.targetCell): if not virus.targetCell.status: if virus.status=="Attacking": virus.targetCell.status="Dying" if virus.status=="Eating": virus.targetCell.status="BeingEaten" if virus.targetCell.status=="Dead": virus.targetCell=None for (cell,type) in self.trainingSet: for i in xrange(len(self.classificationList)): if type==self.classificationList[i]: rightLimit=self.divisionPoints[i] if i==0: leftLimit=0 else: leftLimit=self.divisionPoints[i-1] break cell.update(self.currentState,[leftLimit,rightLimit-cell.width,TRAINING_ZONE_LIMIT,WINDOW_SIZE-cell.height])
def spawn_link(cls, func, *args, **kwargs): curr = core.getcurrent() if not hasattr(curr, 'mailbox'): curr = cls.wrap(curr) if operator.indexOf(self.links, curr.ref) < 0: self.links.append(curr.ref) return cls.spawn(func, *args, **kwargs)
def _get_arg(self, args, argname) : if not argname in args : print 'given arguments do not contain files argument {0}. Please supply it'.format(argname) return -1 ix = operator.indexOf(args, argname) if args[ix+1] in self.arglist : print 'invalid argument value given for argument {0}'.format(argname) return -1 return args[ix+1]
def test_indexOf_file(self): f = open(TESTFN, "w", encoding="utf-8") try: f.write("a\n" "b\n" "c\n" "d\n" "e\n") finally: f.close() f = open(TESTFN, "r", encoding="utf-8") try: fiter = yp_iter(f) self.assertEqual(indexOf(fiter, "b\n"), 1) self.assertEqual(indexOf(fiter, "d\n"), 1) self.assertEqual(indexOf(fiter, "e\n"), 0) self.assertRaises(ValueError, indexOf, fiter, "a\n") finally: f.close() try: unlink(TESTFN) except OSError: pass
def escape_to_url(urlvalue): escapeCode_value = {'+':'%2B',' ':'%20','/':'%2F','?':'%3F','%':'%25','#':'%23','&':'%26','=':'%3D'} res = 0 for k in escapeCode_value.iterkeys(): try: res = operator.indexOf(urlvalue,k) urlvalue = urlvalue.replace(k,escapeCode_value.get) except: pass return urlvalue
def get_version(product_class, firmware_revision): mod = importlib.import_module('libgqe.unit.{}'.format( product_class.lower())) revs = mod.FIRMWARE_REVISIONS if firmware_revision in revs: return firmware_revision revs.append(firmware_revision) revs.sort() return mod.FIRMWARE_REVISIONS[ operator.indexOf(revs, firmware_revision) - 1]
def taskwakeup(self, task): if task is None: return try: del self._squeue[operator.indexOf(self._squeue, task)] except ValueError: pass self.append(task)
def simplify_digits(i, j): """Do a "stupid" digits simplification in the i/j fraction""" ni, nj = i, j for k, e in enumerate(str(i)): if e in str(j): ni = int("".join([n for m, n in enumerate(str(i)) if m != k])) nj = int("".join([n for m, n in enumerate(str(j)) if m != operator.indexOf(str(j), e)])) if 0 in (ni, nj): return i, j return ni, nj
def encode(self,message,a = 0, k = 0): if not (a == 0): self.a = a if not (k == 0): self.k = k nm = "" for letter in message: nm += self.dict[(operator.indexOf(self.dict,letter)*self.a + self.k) % 27] return nm
def climbingLeaderboard_2(scores, alice): # This is very inefficient because of the time complexity of the operations. alices_ranks = [] for score in alice: scores.append(score) ranks = list(set(scores)) ranks.sort(reverse=True) alices_ranks.append(operator.indexOf(ranks, score) + 1) return alices_ranks
def test_indexOf(self): from operator import indexOf self.assertEqual(indexOf([1, 2, 2, 3, 2, 5], 1), 0) self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 2), 1) self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 3), 3) self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 5), 5) self.assertRaises(ValueError, indexOf, (1, 2, 2, 3, 2, 5), 0) self.assertRaises(ValueError, indexOf, (1, 2, 2, 3, 2, 5), 6) self.assertEqual(indexOf("122325", "2"), 1) self.assertEqual(indexOf("122325", "5"), 5) self.assertRaises(ValueError, indexOf, "122325", "6") self.assertRaises(TypeError, indexOf, 42, 1) self.assertRaises(TypeError, indexOf, indexOf, indexOf) f = open(TESTFN, "w") try: f.write("a\n" "b\n" "c\n" "d\n" "e\n") finally: f.close() f = open(TESTFN, "r") try: fiter = iter(f) self.assertEqual(indexOf(fiter, "b\n"), 1) self.assertEqual(indexOf(fiter, "d\n"), 1) self.assertEqual(indexOf(fiter, "e\n"), 0) self.assertRaises(ValueError, indexOf, fiter, "a\n") finally: f.close() try: unlink(TESTFN) except OSError: pass iclass = IteratingSequenceClass(3) for i in range(3): self.assertEqual(indexOf(iclass, i), i) self.assertRaises(ValueError, indexOf, iclass, -1)
def test_indexOf(self): from operator import indexOf self.assertEqual(indexOf([1, 2, 2, 3, 2, 5], 1), 0) self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 2), 1) self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 3), 3) self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 5), 5) self.assertRaises(ValueError, indexOf, (1, 2, 2, 3, 2, 5), 0) self.assertRaises(ValueError, indexOf, (1, 2, 2, 3, 2, 5), 6) self.assertEqual(indexOf("122325", "2"), 1) self.assertEqual(indexOf("122325", "5"), 5) self.assertRaises(ValueError, indexOf, "122325", "6") self.assertRaises(TypeError, indexOf, 42, 1) self.assertRaises(TypeError, indexOf, indexOf, indexOf) self.assertRaises(ZeroDivisionError, indexOf, BadIterableClass(), 1) f = open(TESTFN, "w") try: f.write("a\n" "b\n" "c\n" "d\n" "e\n") finally: f.close() f = open(TESTFN, "r") try: fiter = iter(f) self.assertEqual(indexOf(fiter, "b\n"), 1) self.assertEqual(indexOf(fiter, "d\n"), 1) self.assertEqual(indexOf(fiter, "e\n"), 0) self.assertRaises(ValueError, indexOf, fiter, "a\n") finally: f.close() try: unlink(TESTFN) except OSError: pass iclass = IteratingSequenceClass(3) for i in range(3): self.assertEqual(indexOf(iclass, i), i) self.assertRaises(ValueError, indexOf, iclass, -1)
def parse(self, response): if response.status == 200: title = response.xpath('//dt[contains(@class,"clearfix join_tc_icon")]//h1/@title').extract()[0] job_id = response.xpath('//input[contains(@id,"jobid")]/@value').extract()[0] job_request = response.xpath('//dd[contains(@class,"job_request")]//span/text()').extract() job_other_ben = response.xpath('//dd[contains(@class,"job_request")]/text()').extract() job_des = response.xpath('//dd[contains(@class,"job_bt")]//p/text()').extract() job_address = response.xpath('//dl[contains(@class,"job_company")]//div/text()').extract()[2] job_benefits = job_other_ben[-2].strip() job_benefits_arr = job_benefits[operator.indexOf(job_benefits, ":") + 1:].split(u"、") job_item = JobItem(title, job_request[0], job_address.strip(), job_des, job_benefits_arr, job_request[1:], response.url, job_id) mongo_store.save(job_item)
def decode(self,message,a = 0, k = 0): if not (a == 0): self.a = a if not (k == 0): self.k = k om = "" inv = self.mi() for letter in message: aa = inv * (operator.indexOf(self.dict,letter)-self.k) om += self.dict[aa % 27] return om
def __setitem__(self, key, new): try: idx = indexOf(self._allowed_keys, (key)) except ValueError: raise ValueError("key '%s' not allowed" % key) t = self._allowed_types[idx] if type(new) != t: try: new = t(new) except Exception as e: raise TypeError("Conversion to %s failed for %s: %s" % (t, key, e)) dict.__setitem__(self, key, new)
def goodPrecisionFloToStr(floatNumber): # returns string from rational or irrational float containing "0" or "9" resA, resB = str(floatNumber), "0" if "." in resA: resA, resB = resA.split(".") if fabs(floatNumber) < 0.1 or fabs(floatNumber) > 999: return "%.1E" % floatNumber if "0" in resB: T0 = indexOf(resB, "0") else: T0 = -1 if "9" in resB: T9 = indexOf(resB, "9") if len(resB) >= T9 + 2: if resB[T9+1] < 6: T9 = -1 else: T9 = -1 else: T9 = -1 if T0 == -1: if T9 == -1: return resA + "." + resB if T9 == 0: return str(int(resA) + 1) return resA + "." + str(int(resB[:T9]) + 1) elif T9 == -1: if T0 == 0: return resA return resA + "." + resB[:T0] elif T9 < T0: if T9 == 0: return str(int(resA) + 1) return resA + "." + str(int(resB[:T9]) + 1) if T0 == 0: return resA return resA + "." + resB[:T0]
def test(all_extension, all_keywords, exclude_file=[]): """TODO: Docstring for parse_multi_file. :returns: TODO """ all_files = [x for x in os.listdir('./test') if x[0] != '.'] with open('test.txt', 'w') as test_file: for one in all_files: single_list = [one] index = operator.indexOf(all_extension, os.path.splitext(one)[1]) + 1 keywords = fill_feature_dict(single_list, './test/') result = keyword_to_feature(keywords, all_keywords, index) test_file.write(result + os.linesep)
def merge_practices(*args, **kwargs): """Merge two or more dictionaries, preferring values in increasing order of index in `order`. Treats practices with no `status` as 'na'. """ order = kwargs.pop('order', ['unknown', 'na', 'nudge', 'warn', 'ok']) assert len(kwargs) == 0 practices = dict() for practice in set( itertools.chain.from_iterable(arg.keys() for arg in args)): practices[practice] = max( (arg.get(practice, {'status': 'unknown'}) for arg in args), key=lambda _practice: operator.indexOf( order, _practice.get('status', 'unknown'))) return practices
def create_predict_file(filename, all_extension, all_keywords, exclude_file): """TODO: Docstring for predict. :filename: TODO :exclude_file: TODO :returns: TODO """ keywords = {} single_file = [filename] index = operator.indexOf(all_extension, os.path.splitext(filename)[1]) + 1 keywords = fill_feature_dict(single_file, './unknow/') result = keyword_to_feature(keywords, all_keywords, index) with open('unknow.txt', 'w') as unknow_file: unknow_file.write(result + os.linesep)
def toys(w): w.sort() total = 0 i = 0 j = 0 while (i < len(w)): start = w[i] end = start + 4 j = end while (j >= start): if (w[i:].count(j) != 0): i = len(w) - operator.indexOf(reversed(w), j) - 1 total += 1 break j -= 1 i += 1 return total
def merge_practices(*args, **kwargs): """Merge two or more dictionaries, preferring values in increasing order of index in `order`. Treats practices with no `status` as 'na'. """ order = kwargs.pop('order', ['unknown', 'na', 'nudge', 'warn', 'ok']) if len(kwargs) > 0: raise TypeError("merge_practices() got unexpected keyword argument(s) {:s}" "".format(', '.join("'{:s}'".format(kw) for kw in six.iterkeys(kwargs)))) practices = dict() for practice in set(itertools.chain.from_iterable(arg.keys() for arg in args)): practices[practice] = max( (arg.get(practice, {'status': 'unknown'}) for arg in args), key=lambda _practice: operator.indexOf(order, _practice.get('status', 'unknown')) ) return practices
def unregister(self, ref_or_name): """ unregister a name in the registery. If the name doesn't exist we safely ignore it. """ try: if isinstance(ref_or_name, six.string_types): with self._lock: ref = self._registered_names[ref_or_name] names = self._by_ref[ref] del names[operator.indexOf(names, ref_or_name)] del self._registered_names[ref_or_name] else: with self._lock: names = self._by_ref[ref_or_name] for name in names: del self._registered_names[name] except (KeyError, IndexError): pass
def add_records_to_array(self,records,array): if(len(array) == 0): array.append(self.field_names) self.used_array = [False for i in self.field_names] name_hash = {} header = records.pop(0) for field in self.field_names: if(field in header): name_hash[field] = operator.indexOf(header,field) for record in records: output = ['' for s in self.field_names] for name in self.field_names: if(name in name_hash): s = record[name_hash[name]].strip() if(len(s) > 0): n = self.field_hash[name] output[n] = s self.used_array[n] = True array.append(output)
def add_records_to_array(self, records, array): if (len(array) == 0): array.append(self.field_names) self.used_array = [False for i in self.field_names] name_hash = {} header = records.pop(0) for field in self.field_names: if (field in header): name_hash[field] = operator.indexOf(header, field) for record in records: output = ['' for s in self.field_names] for name in self.field_names: if (name in name_hash): s = record[name_hash[name]].strip() if (len(s) > 0): n = self.field_hash[name] output[n] = s self.used_array[n] = True array.append(output)
def operator_sequence_operation(): """ we do some sequence operation like following. ---CRUD--- container :: in, append, extend, clear, remove, __new__, __eq__ sized :: len, index iterable :: set, get """ a = [1, 2, 3] b = list('abc') print('a =', a) print('b =', b) # concatenate print('\nConstructive:') print(' concat(a, b):', operator.concat(a, b)) # search print('\nSearch:') print(' contains(a, 1) :', operator.contains(a, 1)) print(' contains(b, "d"):', operator.contains(b, "d")) print(' countOf(a, 1) :', operator.countOf(a, 1)) print(' countOf(b, "d") :', operator.countOf(b, "d")) print(' indexOf(a, 1) :', operator.indexOf(a, 1)) # access items print('\nAccess:') print(' getitem(b, 1) :', operator.getitem(b, 1)) print(' getitem(b, slice(1, 3)) :', operator.getitem(b, slice(1, 3))) print(' setitem(b, 1, "d") :', end=' ') operator.setitem(b, 1, "d") print(b) print(' setitem(a, slice(1, 3), [4, 5]) :', end=' ') operator.setitem(a, slice(1, 3), [4, 5]) print(a) # remove items print('\nDestructive:') print(' delitem(b, 1) :', end=' ') operator.delitem(b, 1) print(b) print(' delitem(a, slice(1, 3)) :', end=' ') operator.delitem(a, slice(1, 3)) print(a)
def findLongest() -> int: seqLengths = [] currSeq = [] for i in range(1000000): currNum = i + 1 currSeq = [] currSeq.append(currNum) while (currNum > 1): if (currNum % 2 == 0): #Value is even currNum = currNum / 2 else: #number is odd currNum = 3 * currNum + 1 currSeq.append(currNum) seqLengths.append(len(currSeq)) return operator.indexOf(seqLengths, max(seqLengths)) + 1
def runme(fid,infile,outfile): fin = open(infile,'r') fout = open(outfile,'w') tot_up = Parameters.parameters['view']['levels_up'] tot_down = Parameters.parameters['view']['levels_down'] print "up=",tot_up," down=",tot_down # trigger too difficult for now trigger = Parameters.parameters['find']['immediate_children_threshold'] for line in fin.xreadlines(): a=line.split() b=a[2:] # find fid in a try: i=operator.indexOf(b,fid) # write out stuff according to tot_up and tot_down if i < tot_up: c = i else: c = tot_up print >>fout,"%s %s %s"%(a[0],a[1],string.join(b[i-c:i+1+tot_down])) except ValueError: pass
def remove_process(self, name): """ remove the process and its config from the manager """ with self._lock: if name not in self.processes: raise KeyError("%r not found" % name) # stop all processes self._stop_processes(name) # remove it the from the list state = self.processes.pop(name) # also remove it from the group if any. if state.group is not None: if state.group in self.groups: g = self.groups[state.group] del g[operator.indexOf(g, name)] self.groups[state.group] = g # notify other that this template has been deleted self._publish("delete", name=name)
def test_indexOf(self): from operator import indexOf self.assertEqual(indexOf([1, 2, 2, 3, 2, 5], 1), 0) self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 2), 1) self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 3), 3) self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 5), 5) self.assertRaises(ValueError, indexOf, (1, 2, 2, 3, 2, 5), 0) self.assertRaises(ValueError, indexOf, (1, 2, 2, 3, 2, 5), 6) self.assertEqual(indexOf("122325", "2"), 1) self.assertEqual(indexOf("122325", "5"), 5) self.assertRaises(ValueError, indexOf, "122325", "6") self.assertRaises(TypeError, indexOf, 42, 1) self.assertRaises(TypeError, indexOf, indexOf, indexOf) iclass = IteratingSequenceClass(3)
def create_block(self, previous_block_hash, signer): """ Add a block of transactions to the core """ # `signer_limit` value is according to Clique PoA consensus protocol # (https://github.com/ethereum/EIPs/issues/225) block = OrderedDict({ 'block_number': len(self.chain), 'signer': signer, 'signer_count': len(self.valid_signers), 'signer_limit': math.floor(len(self.valid_signers) / 2) + 1, 'signer_index': indexOf(self.valid_signers, signer), 'timestamp': time(), 'transactions': self.transactions, 'additional_payload': self.block_payload, 'transactions_merkle_root': self._get_merkle_root_for_transactions(self.transactions), 'previous_block_hash': previous_block_hash }) block['block_header'] = self.hash(block) block['signature'] = self._sign_block(block) # Reset the current list of transactions self.transactions = [] self.chain.append(block) return block
def test_indexOf(self): from operator import indexOf with self.nohtyPCheck(enabled=False): self.assertEqual(indexOf(yp_list([1, 2, 2, 3, 2, 5]), 1), 0) self.assertEqual(indexOf(yp_tuple((1, 2, 2, 3, 2, 5)), 2), 1) self.assertEqual(indexOf(yp_tuple((1, 2, 2, 3, 2, 5)), 3), 3) self.assertEqual(indexOf(yp_tuple((1, 2, 2, 3, 2, 5)), 5), 5) self.assertRaises(ValueError, indexOf, yp_tuple( (1, 2, 2, 3, 2, 5)), 0) self.assertRaises(ValueError, indexOf, yp_tuple( (1, 2, 2, 3, 2, 5)), 6) self.assertEqual(indexOf(yp_str("122325"), "2"), 1) self.assertEqual(indexOf(yp_str("122325"), "5"), 5) self.assertRaises(ValueError, indexOf, yp_str("122325"), "6") self.assertRaises(TypeError, indexOf, yp_int(42), 1) self.assertRaises(TypeError, indexOf, yp_func_chr, yp_func_chr)