async def get_messages(self, *args, **kwargs): """ Same as :meth:`iter_messages`, but returns a list instead with an additional ``.total`` attribute on the list. If the `limit` is not set, it will be 1 by default unless both `min_id` **and** `max_id` are set (as *named* arguments), in which case the entire range will be returned. This is so because any integer limit would be rather arbitrary and it's common to only want to fetch one message, but if a range is specified it makes sense that it should return the entirety of it. If `ids` is present in the *named* arguments and is not a list, a single :tl:`Message` will be returned for convenience instead of a list. """ total = [0] kwargs['_total'] = total if len(args) == 1 and 'limit' not in kwargs: if 'min_id' in kwargs and 'max_id' in kwargs: kwargs['limit'] = None else: kwargs['limit'] = 1 msgs = UserList() async for x in self.iter_messages(*args, **kwargs): msgs.append(x) msgs.total = total[0] if 'ids' in kwargs and not utils.is_list_like(kwargs['ids']): return msgs[0] return msgs
def testSequenceArrayConversionTypeChecking(self): """Test error handling for sequence conversion to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam if six.PY3: from collections import UserList else: from UserList import UserList # This should work, because null / None is a valid value in an # array of reference types. items = UserList() for i in range(10): items.append(Spam(str(i))) items[1] = None result = ArrayConversionTest.EchoRange(items) self.assertTrue(result[0].__class__ == Spam) self.assertTrue(result[1] == None) self.assertTrue(len(result) == 10) def test(items=items): items[1] = 1 result = ArrayConversionTest.EchoRange(items) self.assertRaises(TypeError, test) def test(items=items): items[1] = "spam" result = ArrayConversionTest.EchoRange(items) self.assertRaises(TypeError, test)
async def get_messages(self, *args, **kwargs): """ Same as :meth:`iter_messages`, but returns a list instead with an additional ``.total`` attribute on the list. If the `limit` is not set, it will be 1 by default unless both `min_id` **and** `max_id` are set (as *named* arguments), in which case the entire range will be returned. This is so because any integer limit would be rather arbitrary and it's common to only want to fetch one message, but if a range is specified it makes sense that it should return the entirety of it. If `ids` is present in the *named* arguments and is not a list, a single :tl:`Message` will be returned for convenience instead of a list. """ total = [0] kwargs['_total'] = total if len(args) == 1 and 'limit' not in kwargs: if 'min_id' in kwargs and 'max_id' in kwargs: kwargs['limit'] = None else: kwargs['limit'] = 1 msgs = UserList() async for x in self.iter_messages(*args, **kwargs): msgs.append(x) msgs.total = total[0] if 'ids' in kwargs and not utils.is_list_like(kwargs['ids']): return msgs[0] return msgs
def test_sequence_array_conversion_type_checking(): """Test error handling for sequence conversion to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam # This should work, because null / None is a valid value in an # array of reference types. items = UserList() for i in range(10): items.append(Spam(str(i))) items[1] = None result = ArrayConversionTest.EchoRange(items) assert result[0].__class__ == Spam assert result[1] is None assert len(result) == 10 with pytest.raises(TypeError): items[1] = 1 _ = ArrayConversionTest.EchoRange(items) with pytest.raises(TypeError): items[1] = "spam" _ = ArrayConversionTest.EchoRange(items)
def find_peak(dset): totLstPeaks = UserList() with futures.ProcessPoolExecutor(max_workers=4) as executer: for _ret in executer.map(find_peak_concurrent,list(dset)): totLstPeaks.append(_ret) return totLstPeaks
def append(self, *others): for other in others: if not other: continue if isinstance(other, Frag) or \ type(other) == type(()) or \ type(other) == type([]): List.extend(self, other) else: List.append(self, other)
def removeOutlier(dsets,resdb,_limit, _slope): logging.info('Remove Outlier(minmax: %f, steepslope: %f)', str(_limit), str(_slope)) concurrResults = UserList() loopCount = 0 with futures.ProcessPoolExecutor(max_workers=4) as executor: for _dset in executor.map(removeOutlierDset, dsets): #logging.debug('Remove Outlier - Exp Num: %s, ISI num: %s', str(_dic['studentno']),str(_dic['isi'])) concurrResults.append(_dset) resdb.create_dataset('d'+str(100+loopCount),data=_dset,dtype=np.float16) loopCount = loopCount + 1 print('loopCount: ' + str(loopCount)) return concurrResults
def extractAlphaOnly(arrExperiment): """ 실험데이터중 alpha파만 분리하여 저장 :param arrExperiment: 3차원 실험데이터 [채널:실험:관측치] :return: """ merged_lstAlpha = UserList() with futures.ProcessPoolExecutor(max_workers=4) as executor: #for j in range(arrExperiment.shape[0]): # number of channels for userlist in executor.map(bandPassFilterConcurrent, arrExperiment.tolist()): merged_lstAlpha.append(userlist) return merged_lstAlpha
async def get_dialogs(self, *args, **kwargs): """ Same as :meth:`iter_dialogs`, but returns a list instead with an additional ``.total`` attribute on the list. """ total = [0] kwargs['_total'] = total dialogs = UserList() async for x in self.iter_dialogs(*args, **kwargs): dialogs.append(x) dialogs.total = total[0] return dialogs
def test_sequence_array_conversion(): """Test conversion of sequence-like obs to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam items = UserList() for i in range(10): items.append(Spam(str(i))) result = ArrayConversionTest.EchoRange(items) assert result[0].__class__ == Spam assert len(result) == 10
async def get_dialogs(self, *args, **kwargs): """ Same as :meth:`iter_dialogs`, but returns a list instead with an additional ``.total`` attribute on the list. """ total = [0] kwargs['_total'] = total dialogs = UserList() async for x in self.iter_dialogs(*args, **kwargs): dialogs.append(x) dialogs.total = total[0] return dialogs
async def get_participants(self, *args, **kwargs): """ Same as :meth:`iter_participants`, but returns a list instead with an additional ``.total`` attribute on the list. """ total = [0] kwargs['_total'] = total participants = UserList() async for x in self.iter_participants(*args, **kwargs): participants.append(x) participants.total = total[0] return participants
def test_recursion(self): from collections import UserList a = UserList() b = UserList() a.append(b) b.append(a) self.assertRaises(RecursionError, operator.eq, a, b) self.assertRaises(RecursionError, operator.ne, a, b) self.assertRaises(RecursionError, operator.lt, a, b) self.assertRaises(RecursionError, operator.le, a, b) self.assertRaises(RecursionError, operator.gt, a, b) self.assertRaises(RecursionError, operator.ge, a, b) b.append(17) self.assertTrue(not a == b) self.assertTrue(a != b) self.assertRaises(RecursionError, operator.lt, a, b) self.assertRaises(RecursionError, operator.le, a, b) self.assertRaises(RecursionError, operator.gt, a, b) self.assertRaises(RecursionError, operator.ge, a, b) a.append(17) self.assertRaises(RecursionError, operator.eq, a, b) self.assertRaises(RecursionError, operator.ne, a, b) a.insert(0, 11) b.insert(0, 12) self.assertTrue(not a == b) self.assertTrue(a != b) self.assertTrue(a < b)
def test_recursion(self): # Check that comparison for recursive objects fails gracefully from collections import UserList a = UserList() b = UserList() a.append(b) b.append(a) self.assertRaises(RuntimeError, operator.eq, a, b) self.assertRaises(RuntimeError, operator.ne, a, b) self.assertRaises(RuntimeError, operator.lt, a, b) self.assertRaises(RuntimeError, operator.le, a, b) self.assertRaises(RuntimeError, operator.gt, a, b) self.assertRaises(RuntimeError, operator.ge, a, b) b.append(17) # Even recursive lists of different lengths are different, # but they cannot be ordered self.assertTrue(not (a == b)) self.assertTrue(a != b) self.assertRaises(RuntimeError, operator.lt, a, b) self.assertRaises(RuntimeError, operator.le, a, b) self.assertRaises(RuntimeError, operator.gt, a, b) self.assertRaises(RuntimeError, operator.ge, a, b) a.append(17) self.assertRaises(RuntimeError, operator.eq, a, b) self.assertRaises(RuntimeError, operator.ne, a, b) a.insert(0, 11) b.insert(0, 12) self.assertTrue(not (a == b)) self.assertTrue(a != b) self.assertTrue(a < b)
def test_recursion(self): # Check that comparison for recursive objects fails gracefully from collections import UserList a = UserList() b = UserList() a.append(b) b.append(a) self.assertRaises(RecursionError, operator.eq, a, b) self.assertRaises(RecursionError, operator.ne, a, b) self.assertRaises(RecursionError, operator.lt, a, b) self.assertRaises(RecursionError, operator.le, a, b) self.assertRaises(RecursionError, operator.gt, a, b) self.assertRaises(RecursionError, operator.ge, a, b) b.append(17) # Even recursive lists of different lengths are different, # but they cannot be ordered self.assertTrue(not (a == b)) self.assertTrue(a != b) self.assertRaises(RecursionError, operator.lt, a, b) self.assertRaises(RecursionError, operator.le, a, b) self.assertRaises(RecursionError, operator.gt, a, b) self.assertRaises(RecursionError, operator.ge, a, b) a.append(17) self.assertRaises(RecursionError, operator.eq, a, b) self.assertRaises(RecursionError, operator.ne, a, b) a.insert(0, 11) b.insert(0, 12) self.assertTrue(not (a == b)) self.assertTrue(a != b) self.assertTrue(a < b)
def testSequenceArrayConversion(self): """Test conversion of sequence-like objects to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam if six.PY3: from collections import UserList else: from UserList import UserList items = UserList() for i in range(10): items.append(Spam(str(i))) result = ArrayConversionTest.EchoRange(items) self.assertTrue(result[0].__class__ == Spam) self.assertTrue(len(result) == 10)
def test_cmp(self): self.assertEqual(cmp(-1, 1), -1) self.assertEqual(cmp(1, -1), 1) self.assertEqual(cmp(1, 1), 0) # verify that circular objects are not handled a = []; a.append(a) b = []; b.append(b) from collections import UserList c = UserList(); c.append(c) self.assertRaises(RuntimeError, cmp, a, b) self.assertRaises(RuntimeError, cmp, b, c) self.assertRaises(RuntimeError, cmp, c, a) self.assertRaises(RuntimeError, cmp, a, c) # okay, now break the cycles a.pop(); b.pop(); c.pop() self.assertRaises(TypeError, cmp)
def testSequenceArrayConversion(self): """Test conversion of sequence-like objects to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam if six.PY3: from collections import UserList else: from UserList import UserList items = UserList() for i in range(10): items.append(Spam(str(i))) result = ArrayConversionTest.EchoRange(items) self.assertTrue(result[0].__class__ == Spam) self.assertTrue(len(result) == 10)
def test_sequence_nested_array_conversion(): """Test conversion of sequences to array-of-array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam items = UserList() for i in range(10): subs = UserList() for _ in range(10): subs.append(Spam(str(i))) items.append(subs) result = ArrayConversionTest.EchoRangeAA(items) assert len(result) == 10 assert len(result[0]) == 10 assert result[0][0].__class__ == Spam
def readDBTable(filepath): """<filepath> may be a string: path/to/spreadsheet ('.ods', '.xlsx'). Alternatively, it may be a file object with attribute 'filename'. """ sheet = Spreadsheet(filepath, mustexist=False) rows = UserList() rows.filepath = sheet.filepath rows.title = sheet.getValue(0, 1) rows.info = OrderedDict() headers = None for rowix in range(sheet.colLen()): # Get the value in the first column entry1 = sheet.getValue(rowix, 0) if not entry1: continue if headers == None: if entry1 == '#': key = sheet.getValue(rowix, 1) val = sheet.getValue(rowix, 2) rows.info[key] = val continue # Read the column headers from this line headers = OrderedDict() rows.headers = OrderedDict() i, j = 0, 0 for cellix in range(sheet.rowLen()): h = sheet.getValue(rowix, cellix) if h: headers[h] = i rows.headers[h] = j j += 1 i += 1 continue ### Read the row data rowdata = [] for col in headers.values(): try: rowdata.append(sheet.getValue(rowix, col)) except: rowdata.append(None) rows.append(rowdata) return rows
def readDBTable(filepath): sheet = Spreadsheet(filepath, mustexist=False) rows = UserList() rows.filepath = sheet.filepath rows.title = sheet.getValue(0, 1) rows.info = OrderedDict() headers = None for rowix in range(sheet.colLen()): # Get the value in the first column entry1 = sheet.getValue(rowix, 0) if not entry1: continue if headers == None: if entry1 == '#': key = sheet.getValue(rowix, 1) val = sheet.getValue(rowix, 2) rows.info[key] = val continue # Read the column headers from this line headers = OrderedDict() rows.headers = OrderedDict() i, j = 0, 0 for cellix in range(sheet.rowLen()): h = sheet.getValue(rowix, cellix) if h: headers[h] = i rows.headers[h] = j j += 1 i += 1 continue ### Read the row data rowdata = [] for col in headers.values(): try: rowdata.append(sheet.getValue(rowix, col)) except: rowdata.append(None) rows.append(rowdata) return rows
def train_model(cls, model, cooccurrence_matrix, epochs=5): ''' Train the model on a given cooccurence_matrix. ''' # Create Targes, Contexts and Labels targets = UserList() contexts = UserList() labels = UserList() # We only train on non-zero elements of X_ij for i, column in cooccurrence_matrix.items(): for j, xij in column.items(): if xij > 0: targets.append(i) contexts.append(j) labels.append(xij) targets = np.asarray(targets) contexts = np.asarray(contexts) labels = np.asarray(labels) # Run Training start_time = time() loss = model.fit([targets, contexts], labels, epochs=epochs) end_time = time() logging.info( "Training finished: Iterations: %d, loss=%f, Run-Time: %d sec", epochs, loss.history['loss'][-1], int(end_time - start_time))
def test_similarity_model(cls, model, dictionary, reverse_dictionary): ''' Check the similarity of a given list of words to test the quality of the embedding. ''' # For Bible: valid_examples = UserList() for entry in [ 'god', 'jesus', 'noah', 'egypt', 'john', 'gospel', 'moses', 'famine' ]: if dictionary.get(entry, None): valid_examples.append(dictionary[entry]) valid_size = len(valid_examples) # As suggested by the paper, the final weights are the sum of w_c and w_t # The do not average them. final_weights = (model.get_weights()[0] + model.get_weights()[1]) # Compute Pairwise Distance matrix: Vocabulary x Vocabulary distance_matrix = cosine_similarity(final_weights) # Get Top Embeddings for the Valid-Examples for i in range(valid_size): # Idx->Word valid_word = reverse_dictionary[valid_examples[i]] # number of nearest neighbors top_k = 8 valid_idx = valid_examples[i] # Select Idx Row, and sort columns, cosine similarity increases # therefore, the last k-entries have the highest similarity to i. # We keep the last entry as a check. It should be the same as i. nearest = distance_matrix[valid_idx].argsort()[-top_k:] log_str = 'Nearest to %s:' % valid_word for k in range(top_k): close_word = reverse_dictionary[nearest[k]] log_str = '%s %s,' % (log_str, close_word) logging.info(log_str)
def test_user_list(self) -> None: arg = UserList() arg.append({'a': 1, 'b': 2}) arg.append(None) arg.append({'a': 1, 'b': 2}) make = namedtuple('NamedTuple', ('a', 'b')) tup = make(1, 2) exp = [ tup, None, tup, ] res = to_namedtuple(arg) self.assertEqual(res, exp)
def santafe_id(column_id, contest_id, ctx): path = ctx['path'] ballots = [] ballot_length = 0 with open(path, "r", encoding='utf8') as f: reader = csv.reader(f) header = next(reader) s = 'Original/Cards/0/Contests/{}/Marks/{}/{}' rinds = [] cinds = [] for i in range(len(header)): try: rinds.append(header.index(s.format(column_id, i, 'Rank'))) except ValueError: break cinds.append(header.index(s.format(column_id, i, 'CandidateId'))) col = header.index('Original/Cards/0/Contests/{}/Id'.format(column_id)) for i, line in enumerate(reader): if line[col] == str(contest_id): choices = UserList([]) choices.voter_id = i ranks = [int(line[i]) for i in rinds if line[i] != ''] ballot_length = max(ranks + [ballot_length]) candidates = iter(cinds) for i in range(len(rinds)): c = ranks.count(i + 1) if c == 0: choices.append(SKIPPEDRANK) elif c == 1: choices.append(line[next(candidates)]) else: choices.append(OVERVOTE) ballots.append(choices) for b in ballots: b.data = b.data[:ballot_length] return ballots
def append(self, item): UserList.append(self, item) self.unique = False
def append(self, value): UserList.append(self, value) self._update()
def append(self, item): UserList.append(self, item) self._changed()
class Game(object): def __init__(self, font): self.di = DI() self.register_services() self.screen_height = 60 self.screen_width = 100 self.gamefont = sys.path[0] + '/data/fonts/' + font self.map = Map(80,45) self.fov_recompute = True self.game_state = "playing" self.player_action = None #create the root console libtcod.console_set_custom_font(self.gamefont.encode('utf-8'), libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_ASCII_INROW) libtcod.console_init_root(self.screen_width, self.screen_height, 'crogue'.encode('utf-8'), False) #Create a console to draw to the screen self.con = libtcod.console_new(self.screen_width, self.screen_height) self.player = Player(self.map.starting_pos[0], self.map.starting_pos[1]) self.objects = UserList() self.objects.append(self.player) self.Messages = self.di.Request("Console") self.Messages.add_message("Game has been started.") self.load_monsters() self.add_monsters() self.add_items() def add_object_to_map(self, item): while True: y = libtcod.random_get_int(0, 0, self.map.height - 1) x = libtcod.random_get_int(0, 0, self.map.width - 1) if not self.map.is_blocked(x, y): break item.x = x item.y = y self.objects.append(item) def add_monsters(self): maxmonst = len(self.Monsters) - 1 for i in range(100): ind = libtcod.random_get_int(0,0,maxmonst) monster = copy.deepcopy(self.Monsters[ind]) self.add_object_to_map(monster) def add_items(self): for i in range(100): self.add_object_to_map(Item(0,0)) def move_player(self, x, y): if self.objects.exists(lambda obj: obj.blocks(self.player, x, y)): return self.player.move(self.map, x, y) self.fov_recompute = True def handle_keys(self): key = libtcod.console_wait_for_keypress(True) if key.vk == libtcod.KEY_ENTER and key.lalt: #Alt+Enter: toggle fullscreen libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) elif key.vk == libtcod.KEY_ESCAPE: return "exit" #exit game elif key.vk == libtcod.KEY_F1: if self.game_state == "not-playing": self.game_state = "playing" return "exit-debug-screen" self.game_state = "not-playing" return "debug-screen" if self.game_state != "playing": return if libtcod.console_is_key_pressed(libtcod.KEY_UP): self.move_player(0,-1) elif libtcod.console_is_key_pressed(libtcod.KEY_DOWN): self.move_player(0,1) elif libtcod.console_is_key_pressed(libtcod.KEY_LEFT): self.move_player(-1,0) elif libtcod.console_is_key_pressed(libtcod.KEY_RIGHT): self.move_player(1,0) else: return "didn't-move" def render_all(self): self.render_timer1 = libtcod.sys_elapsed_milli() for object in self.objects: object.draw(self.con, self.map) if self.fov_recompute: #recompute FOV if needed (the player moved or something) self.fov_recompute = False self.map.recompute_fov(self.player.x, self.player.y) self.map.draw(self.con) messagePanel = self.Messages.render() libtcod.console_blit(messagePanel, 0, 0, 0, 0, self.con, 0, 46) libtcod.console_blit(self.con, 0, 0, 0, 0, 0, 0, 0) self.render_timer2 = libtcod.sys_elapsed_milli() def update_objects(self): self.update_timer1 = libtcod.sys_elapsed_milli() for object in self.objects: self.player.check_collision(object) if isinstance(object, Monster): if object.Alive is False: object.clear(self.con) self.objects.remove(object) self.update_timer2 = libtcod.sys_elapsed_milli() def main_loop(self): while not libtcod.console_is_window_closed(): libtcod.console_set_default_foreground(self.con, libtcod.white) self.update_objects() self.render_all() self.render_timers() libtcod.console_flush() for object in self.objects: object.clear(self.con) self.player_action = self.handle_keys() if self.player_action == "exit": break def render_timers(self): updateTime = self.update_timer2 - self.update_timer1 renderTime = self.render_timer2 - self.render_timer2 libtcod.console_set_default_foreground(self.con, libtcod.white) libtcod.console_print(self.con,0,0,("Update Timer: " + str(updateTime)).encode()) libtcod.console_print(self.con,0,1,("Render Timer: " + str(renderTime)).encode()) def load_monsters(self): file = open("./data/Monsters.json") monsterList = json.load(file) self.Monsters = [] for m in monsterList["Monsters"]: self.Monsters.append(Monster.create_from_dict(m)) def register_services(self): self.di.Register("Console", lambda: MessageDisplay()) self.di.Register("Gui", lambda: Gui())
def append(self, value): UserList.append(self, value) self._update()
def add_iterable(self, iterable): for i in iterable: if i not in self: UserList.append(self, i) return self
def append(self, item): UserList.append(self, item) self.send(append=item)
def extractAlphaPhase(_chnnDset): concurrResults = UserList() with futures.ProcessPoolExecutor(max_workers=4) as executor: for _concurrResult in executor.map(filterAlphaPhase, _chnnDset.tolist()): concurrResults.append(_concurrResult) return concurrResults
class BaseModule(object): def __init__(self): super(BaseModule, self).__init__() self.options = UserList() self.register_options() def show_info(self): # current = Framework._current try: # output a empty line for beauty print('') for item in ['name', 'path', 'author', 'version']: val = self.meta.get(item) if val: print('%s: %s' % (item.title().rjust(10), val)) # description print('') if 'description' in self.meta: desc = self.meta['description'] print('Description:') print('%s%s' % (' ' * 2, textwrap.fill(desc, 80))) print('') # options print('Options:') self.show_options() except Exception as e: self.perror('%s' % e) return def show_options(self): """ List options """ options = self.options print('') if options: v_mxlen = max([ len(i['value']) if i['value'] and len(i['value']) > 13 else 13 for i in options ]) n_mxlen = max( [len(i['name']) if len(i['name']) > 4 else 4 for i in options]) pattern = ' {} {} {} {}' print( pattern.format('Name'.ljust(n_mxlen), 'Current Value'.ljust(v_mxlen), 'Required'.ljust(8), 'Description')) print( pattern.format('-' * n_mxlen, '-' * v_mxlen, '-' * 8, '-' * 11)) for item in options: key = item['name'] val = item['value'] or 'NULL' rqd = 'YES' if item['required'] else 'NO' desc = item['description'] print( pattern.format(key.ljust(n_mxlen), val.ljust(v_mxlen), rqd.ljust(8), desc)) else: print(" No options found!") print('') def module_pre(self): pass def module_run(self, args): pass def module_post(self): pass def register_options(self): pass def register_option(self, name, value=None, required=False, description=''): if not value: value = 'NULL' if isinstance(value, int): value = str(value) option = Option(name=name, value=value, required=required, description=description) self.options.append(option) def set_option(self, args): k = args.key v = args.value or 'NULL' keys = [x['name'] for x in self.options] if args.key not in keys: print("The Key is not correct.Please use a correct key") return for item in self.options: if item['name'] == k: item['value'] = v def run(self): """ Run the module """ namespace = Namespace() for item in self.options: setattr(namespace, item['name'], item['value']) self.module_pre() self.module_run(namespace) self.module_post()
def test_list_copy(self): obj = UserList() obj.append(123) self._copy_test(obj)
from collections import Counter class OrderedCounter(Counter): pass #s = input() s = 'caabbbccde' s1 = sorted(s) s2 = UserList() for x, k in groupby(s1): l = list(k) s2.append([x, len(l)]) #print(s2) #s3 = sorted(s2,key=lambda x:x[1],reverse = True) s3 = sorted(s) print(s3) s4 = OrderedCounter(s4) print(*s4) s5 = s4.most_common(3) print(*s5) #print(s3) for j in range(3): #print(*s3[j]) pass ''' from collections import Counter
def append(self, item): UserList.append(self, item) self.unique = False
def append(self, item): UserList.append(self, item) self.notify()