def __init__(self, client, object_type): self.client = client self.object_type = object_type.__name__.lower() + 's' self.selection = { 'devices': Selection(), 'sensors': Selection(), 'rules': Selection() } self.pipeline = [] self.operation = None
def find_snapshots(self, preds, disjunctive=False): """Find snapshots that match to the predicates.""" if not self._mode: raise TarCMS.TarCMSError('not open: %r' % self) sel = Selection(self._indexdb, preds, disjunctive=disjunctive) for x in sel: yield sel.get_snippet(x) return
def get_child_generation(self, parent_generation: Generation): selection = Selection(parent_generation, possibilites=self.possibilities) parent1, parent2 = getattr(selection, f"_{self.selection}_selection")() children = self.get_reproduce(parent1, parent2) return Generation(index=parent_generation.index + 1, genotypes=children, population=len(children))
def __init__(self, id, ai=False, score=0): self.id = id self.isAI = ai if ai: self.ai = AI(player=self) self.wall = Wall() self.queue = Queue() self.penalty = Penalty() self.selection = Selection() self.score = score
def next_generation(self, population): selection = Selection(deepcopy(population), strategy=SelectionStrategy.TOURNAMENT.value) mating = Mating(selection) crossover = Crossover(mating) for i, individual in enumerate(crossover.mating.selection.population.individuals): mutation = Mutation(individual) crossover.mating.selection.population.individuals[i] = mutation.mutate() print(f'Individuals: {len(self.individuals)}') print(f'New generation: {len(crossover.new_generation)}') return crossover.mating.selection.population
def EvolvePopulation(self): for g in tqdm(range(self.number_of_generations), desc='Generation'): self.best_fitness = 0 self.best_index = 0 self.best_x = np.zeros([1, self.number_of_variables]) self.EvaluatePopulation() temp_population = np.copy(self.population) for itVar in range(0, self.population_size, 2): i1 = Selection(self.population_fitness) i2 = Selection(self.population_fitness) chromosome1 = temp_population[i1, :] chromosome2 = temp_population[i2, :] r = np.random.rand() if r < self.crossover_probability: crossed1, crossed2 = CrossoverMutation(chromosome1, chromosome2, gene_length=1) temp_population[itVar, :] = crossed1 temp_population[itVar + 1, :] = crossed2 else: temp_population[itVar, :] = chromosome1 temp_population[itVar + 1, :] = chromosome2 for itVar in range(self.population_size): original_chromosome = temp_population[itVar, :] mutated_chromosome = GeneticMutation(original_chromosome) temp_population[itVar, :] = mutated_chromosome best_individual = self.population[self.best_index, :] temp_population[0, :] = np.copy(best_individual) self.population = np.copy(temp_population)
def __init__(self, population_size, m, k, d, crossover_type): """ Create the SGA, describing parameters of our fitness function as well as the type of crossover to be used """ self.population_size = population_size if (self.population_size % 2 == 1): print("Error: population size must be multiple of 2") sys.exit() self.fitness_function = FitnessFunction(m, k, d) self.genotype_length = m * k self.variation = Variation(crossover_type) self.selection = Selection() self.population = [] self.peak_fitnesses = []
def get_child_generation(self, parent_generation: Generation, max_generations: int): if parent_generation.genotypes: selection = Selection( parent_generation, max_generations, possibilities=self.possibilities_for_selection, crosses=self.crosses) parents = getattr(selection, f"_{self.selection}_selection")() childrens = [] for pair in parents: childrens += self.get_reproduce(pair[0], pair[1]) #childrens = [self.get_reproduce(pair[0], pair[1]) for pair in parents] else: childrens = list() return Generation(index=parent_generation.index + 1, genotypes=childrens, population=len(childrens))
from createtb import CreateTb from dbviews import DbViews from addel import AdDel from selection import Selection Rolodex_entry = AdDel() Rolodex_selection = Selection() #fake_entry = ["6", "a", "b", "1", "abc", "cash", True, "online"] #Rolodex_entry.new_rolodex_entry(fake_entry) Rolodex_selection.select_all_from_table(1, True)
def parse_cmd(self): parser = argparse.ArgumentParser() parser.add_argument( '-A', default=0, help='Algorithm type: 0 for genetic algorithm, 1 for CSP') parser.add_argument( '-GP', default=0, help= 'Genetic problem: 0 for string search, 1 for N-queens, 2 for 0-1 knapsack' ) parser.add_argument( '-KP', default=1, help='Knapsack problem number. Can be between 1 and 8') parser.add_argument('-QN', default=8, help='Queens number') parser.add_argument( '-QM', default=0, help= 'N-queens mutation type: 0 for exchange mutation, 1 for simple inversion mutation' ) parser.add_argument( '-QC', default=0, help= 'N-queens crossover type: 0 for PMX crossover, 1 for OX crossover') parser.add_argument( '-SF', default=0, help= 'String search fitness function: 0 for ASCII distance from target ' 'string, 1 for bulls and cows.') parser.add_argument( '-SC', default=0, help= 'String search crossover type: 0 for one-point crossover, 1 for two-point crossover.' ) parser.add_argument( '-S', default=0, help='Selection type: 0 for Random from the top half, 1 for RWS, ' '2 for aging, 3 for tournament.') parser.add_argument('-PS', default=2048, help='Population size') args = parser.parse_args() try: algorithm_type = int(args.A) if algorithm_type != 0 and algorithm_type != 1: print("Algorithm can only be 0 or 1.") sys.exit() except ValueError: print("Algorithm can only be 0 or 1.") sys.exit() try: genetic_prob = int(args.GP) if genetic_prob != 0 and genetic_prob != 1 and genetic_prob != 2: print("Genetic problem can only be 0, 1 or 2.") sys.exit() except ValueError: print("Genetic problem can only be 0, 1 or 2.") sys.exit() try: knapsack_problem = int(args.KP) if knapsack_problem != 1 and knapsack_problem != 2 and knapsack_problem != 3 and knapsack_problem != 4\ and knapsack_problem != 5 and knapsack_problem != 6 and knapsack_problem != 7\ and knapsack_problem != 8: print( "Knapsack problem number can only be a number between 1 and 8 (including)." ) sys.exit() except ValueError: print( "Knapsack problem number can only be a number between 1 and 8 (including)." ) sys.exit() try: queens_number = int(args.QN) if queens_number < 1 or queens_number > 100: print("Queens number can only be a number between 1 and 100.") sys.exit() except ValueError: print("Queens number can only be a number between 1 and 100.") sys.exit() try: mutation_number = int(args.QM) if mutation_number != 0 and mutation_number != 1: print("N-queens mutation number can only be 0 or 1.") sys.exit() except ValueError: print("N-queens mutation number can only be 0 or 1.") sys.exit() try: crossover_number = int(args.QC) if crossover_number != 0 and crossover_number != 1: print("N-queens crossover number can only be 0 or 1.") sys.exit() except ValueError: print("N-queens crossover number can only be 0 or 1.") sys.exit() try: fitness_function = int(args.SF) if fitness_function != 0 and fitness_function != 1: print("String search fitness function can only be 0 or 1.") sys.exit() except ValueError: print("String search fitness function can only be 0 or 1.") sys.exit() try: crossover_type = int(args.SC) if crossover_type != 0 and crossover_type != 1: print("String search crossover type can only be 0 or 1.") sys.exit() except ValueError: print("String search crossover type can only be 0 or 1.") sys.exit() try: selection_type = int(args.S) if selection_type != 0 and selection_type != 1 and selection_type != 2 and selection_type != 3: print("Selection type can only be 0, 1, 2 or 3.") sys.exit() except ValueError: print("Selection type can only be 0, 1, 2 or 3.") sys.exit() try: population_size = int(args.PS) if population_size < 10: print("Population size can only be 10 or larger.") sys.exit() except ValueError: print("Population size can only be a number, 10 or larger.") sys.exit() # Initialize general values self.algorithm = Algorithm(algorithm_type) self.genetic_problem = GeneticProblem(genetic_prob) self.selection = Selection(selection_type) self.original_selection = self.selection self.ga_popsize = population_size # Initialize string-search values self.string_search_crossover = StringSearchCrossOver(crossover_type) self.string_search_fitness = StringSearchFitness(fitness_function) # Initialize n-queens values self.queens_num = queens_number self.queens_mutation = NQueensMutation(mutation_number) self.queens_crossover = NQueensCrossover(crossover_number) # Initialize knapsack values: self.knapsack_problem = knapsack_problem - 1
from flask import Flask, request, render_template, redirect, url_for, Response from flaskext.mysql import MySQL from tts import TTS from selection import Selection from camera import VideoCamera tts = TTS() s = Selection(tts) mysql = MySQL() app = Flask(__name__) app.config['MYSQL_DATABASE_USER'] = '******' app.config['MYSQL_DATABASE_PASSWORD'] = '******' app.config['MYSQL_DATABASE_DB'] = 'jarvis' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app) data = None @app.route("/", methods=['GET', 'POST']) def auth(): con = mysql.connect() cursor = con.cursor() if request.method == 'POST': email = request.form["email"] passw = request.form["passw"] cursor.execute("select * from users where email='" + email + "' and password='******'") data = cursor.fetchone()
def FinishInit( self ): base.FinishInit() # Create project manager self.project = Project( self ) base.project = self.project self.frame.SetProjectPath( self.frame.cfg.Read( 'projDirPath' ) ) # Create grid self.SetupGrid() # Create frame rate meter self.frameRate = p3d.FrameRate() # Create shading mode keys dsp = p3d.DisplayShading() dsp.accept( '4', dsp.Wireframe ) dsp.accept( '5', dsp.Shade ) dsp.accept( '6', dsp.Texture ) # Set up gizmos self.SetupGizmoManager() # Bind mouse events self.accept( 'mouse1', self.OnMouse1Down ) self.accept( 'shift-mouse1', self.OnMouse1Down, [True] ) self.accept( 'control-mouse1', self.OnMouse1Down ) self.accept( 'mouse2', self.OnMouse2Down ) self.accept( 'mouse1-up', self.OnMouse1Up ) self.accept( 'mouse2-up', self.OnMouse2Up ) # Create selection manager self.selection = Selection( camera=base.edCamera, root2d=base.edRender2d, win=base.win, mouseWatcherNode=base.edMouseWatcherNode ) base.selection = self.selection # Create our managers. self.assetMgr = AssetManager() self.dDropMgr = DragDropManager() self.actnMgr = actions.Manager() # Bind events self.accept( 'z', self.Undo ) self.accept( 'shift-z', self.Redo ) self.accept( 'f', self.FrameSelection ) self.accept( 'del', lambda fn: cmds.Remove( fn() ), [self.selection.Get] ) self.accept( 'backspace', lambda fn: cmds.Remove( fn() ), [self.selection.Get] ) self.accept( 'control-d', lambda fn: cmds.Duplicate( fn() ), [self.selection.Get] ) self.accept( 'control-g', lambda fn: cmds.Group( fn() ), [self.selection.Get] ) self.accept( 'control-s', self.frame.OnFileSave, [None] ) self.accept( 'arrow_up', lambda fn: cmds.Select( fn() ), [self.selection.SelectParent] ) self.accept( 'arrow_down', lambda fn: cmds.Select( fn() ), [self.selection.SelectChild] ) self.accept( 'arrow_left', lambda fn: cmds.Select( fn() ), [self.selection.SelectPrev] ) self.accept( 'arrow_right', lambda fn: cmds.Select( fn() ), [self.selection.SelectNext] ) self.accept( 'projectFilesModified', self.OnProjectFilesModified ) # Create a "game" self.game = editor.Base() self.game.OnInit() # Start with a new scene self.CreateScene() self.doc.OnRefresh() return True
import random import numpy as np from math import sin, cos, pi from population import Population from selection import Selection from crossover import Crossover from mutation import Mutation from toolkits import GAEngine f = lambda x, y: y * sin(2 * pi * x) + x * cos(2 * pi * y) population = Population(100, [-2, 2], [-2, 2]).init() selection = Selection(f, 100) crossover = Crossover(pe=0.5) mutation = Mutation([-2, 2], [-2, 2], pm=0.5) engine = GAEngine(population, selection, crossover, mutation) if '__main__' == __name__: engine.run(200)
from crossover import Crossover from population import Population from selection import Selection import configuration import time if __name__ == '__main__': start: int = time.time_ns() population: Population = Population() population.createRandom(configuration.POPULATION_SIZE, configuration.TARGET) generationNumber: int = 1 while True: population.calculateFitness() population.sortByFitness() print(generationNumber, population.getBestSentence().text, "{:.3}".format(population.getBestSentence().fitness)) if population.isFinished(): break population = Selection( population, configuration.TARGET).tournamentSelectionWithCrossover() generationNumber += 1 end: int = time.time_ns() print("Time:", str((end - start) / 1000000000), "s")
parser.add_argument('--tournament_size', type=int, default=40, help='Choice size in tournament selection') parser.add_argument('--log', type=bool, default=True, help='Take the log on') parser.add_argument('--log_file', type=str, default='./log_dir_experiment2/eil51.log', help='Log file name') opt = parser.parse_args() tsp = TSPProblem(opt.source_data) tsp.cal_distance() distance = np.array(tsp.get_distance()) select = Selection(distance) population = Population(np.size(distance, 0), opt.pop_size) count = 0 start = time.clock() for i in range(opt.generation): if opt.select_type == 'fitness_proportional': select.fitness_proportional(population) else: select.tournament_selection(population, opt.tournament_size) pop = population.get_population() np.random.shuffle(pop) for j in range(int(len(pop) / 2)): r = np.random.rand() if r <= opt.cross_prob: m = pop[j] n = pop[len(pop) - j - 1]
else: log_level = logging.INFO if args.log: logging.basicConfig(filename=args.log, level=log_level) try: config = json.load(open(args.config, "U")) except IOError: raise EnrichError('Failed to open "%s"' % args.config, _DRIVER_NAME) except ValueError: raise EnrichError("Improperly formatted .json file", _DRIVER_NAME) if config_check.is_experiment(config): obj = Experiment(config) elif config_check.is_selection(config): obj = Selection(config) elif config_check.is_seqlib(config): obj = globals()[config_check.seqlib_type(config)](config) else: raise EnrichError("Unrecognized .json config", _DRIVER_NAME) if obj.output_base is None: raise EnrichError("No output directory set", _DRIVER_NAME) obj.calculate() obj.write_data() if args.plots: pass # obj.make_plots()
def parse_cmd(self): parser = argparse.ArgumentParser() parser.add_argument('-GP', default=4, help='Genetic problem: 0 for string search, 1 for N-queens, 2 for 0-1 knapsack, ' '3 for Baldwin effect, 4 for pareto optima') parser.add_argument('-KP', default=1, help='Knapsack problem number. Can be between 1 and 8') parser.add_argument('-LOS', default=0, help='Local optima signals. 0 for off, 1 for standard deviation, ' '2 for similarity of citizens') parser.add_argument('-ELO', default=0, help='Evade local optima. 0 for hyper mutations, 1 for niching and ' '2 for random immigrants') parser.add_argument('-QN', default=8, help='Queens number') parser.add_argument('-QM', default=0, help='N-queens mutation type: 0 for exchange mutation, 1 for simple inversion mutation') parser.add_argument('-QC', default=0, help='N-queens crossover type: 0 for PMX crossover, 1 for OX crossover') parser.add_argument('-SF', default=0, help='String search fitness function: 0 for ASCII distance from target ' 'string, 1 for bulls and cows.') parser.add_argument('-SC', default=0, help='String search crossover type: 0 for one-point crossover, 1 for two-point crossover.') parser.add_argument('-S', default=0, help='Selection type: 0 for Random from the top half, 1 for RWS, ' '2 for aging, 3 for tournament.') parser.add_argument('-PS', default=2048, help='Population size') args = parser.parse_args() try: genetic_prob = int(args.GP) if genetic_prob != 0 and genetic_prob != 1 and genetic_prob != 2 and genetic_prob != 3 \ and genetic_prob != 4: print("Genetic problem can only be 0, 1, 2, 3 or 4.") sys.exit() except ValueError: print("Genetic problem can only be 0, 1, 2, 3 or 4.") sys.exit() try: knapsack_problem = int(args.KP) if knapsack_problem != 1 and knapsack_problem != 2 and knapsack_problem != 3 and knapsack_problem != 4\ and knapsack_problem != 5 and knapsack_problem != 6 and knapsack_problem != 7\ and knapsack_problem != 8: print("Knapsack problem number can only be a number between 1 and 8 (including).") sys.exit() except ValueError: print("Knapsack problem number can only be a number between 1 and 8 (including).") sys.exit() try: local_optimal_signal = int(args.LOS) if local_optimal_signal != 0 and local_optimal_signal != 1 and local_optimal_signal != 2: print("Local optimal signal number can only be 0 for none, 1 for standard deviation and 2 for " "citizen similarity.") sys.exit() except ValueError: print("Local optimal signal number can only be 0 for none, 1 for standard deviation and 2 for " "citizen similarity.") sys.exit() try: evade_local_optima = int(args.ELO) if evade_local_optima != 0 and evade_local_optima != 1 and evade_local_optima != 2: print("Evade local optima number can only be 0 for hyper-mutations, 1 for niching and 2 for " "random immigrants.") sys.exit() except ValueError: print("Evade local optima number can only be 0 for hyper-mutations, 1 for niching and 2 for " "random immigrants.") sys.exit() try: queens_number = int(args.QN) if queens_number < 1 or queens_number > 100: print("Queens number can only be a number between 1 and 100.") sys.exit() except ValueError: print("Queens number can only be a number between 1 and 100.") sys.exit() try: mutation_number = int(args.QM) if mutation_number != 0 and mutation_number != 1: print("N-queens mutation number can only be 0 or 1.") sys.exit() except ValueError: print("N-queens mutation number can only be 0 or 1.") sys.exit() try: crossover_number = int(args.QC) if crossover_number != 0 and crossover_number != 1: print("N-queens crossover number can only be 0 or 1.") sys.exit() except ValueError: print("N-queens crossover number can only be 0 or 1.") sys.exit() try: fitness_function = int(args.SF) if fitness_function != 0 and fitness_function != 1: print("String search fitness function can only be 0 or 1.") sys.exit() except ValueError: print("String search fitness function can only be 0 or 1.") sys.exit() try: crossover_type = int(args.SC) if crossover_type != 0 and crossover_type != 1: print("String search crossover type can only be 0 or 1.") sys.exit() except ValueError: print("String search crossover type can only be 0 or 1.") sys.exit() try: selection_type = int(args.S) if selection_type != 0 and selection_type != 1 and selection_type != 2 and selection_type != 3: print("Selection type can only be 0, 1, 2 or 3.") sys.exit() except ValueError: print("Selection type can only be 0, 1, 2 or 3.") sys.exit() try: population_size = int(args.PS) if population_size < 10: print("Population size can only be 10 or larger.") sys.exit() except ValueError: print("Population size can only be a number, 10 or larger.") sys.exit() # Initialize general values if genetic_prob == 3: local_optimal_signal = LocalOptimaSignal.Off print("Baldwin effect turns off local optima signal") selection_type = 1 print("Baldwin effect runs only with roulette wheel selection (RWS)") if genetic_prob == 4: local_optimal_signal = LocalOptimaSignal.Off print("Parito optimal turns off local optima signal") self.genetic_problem = GeneticProblem(genetic_prob) self.selection = Selection(selection_type) self.original_selection = self.selection self.ga_popsize = population_size self.local_optima_signal = LocalOptimaSignal(local_optimal_signal) self.evade_local_optima_method = CombatEarlyConvergence(evade_local_optima) # Initialize string-search values self.string_search_crossover = StringSearchCrossOver(crossover_type) self.string_search_fitness = StringSearchFitness(fitness_function) # Initialize n-queens values self.queens_num = queens_number self.queens_mutation = NQueensMutation(mutation_number) self.queens_crossover = NQueensCrossover(crossover_number) # Initialize knapsack values: self.knapsack_problem = knapsack_problem - 1
def setUp(self): self.cms_selection = Selection() pass
starting_population = population.init_next_gen_population( next_gen_population=next_gen_population) # Reset next gen population list next_gen_population = [] # score chromosomes in the population against fitness goal scored_population = [] for chromosome in starting_population: fitness = Fitness(chromosome=chromosome, fitness_goal=fitness_goal) scored_chromosome = fitness.calculate_fitness() scored_population.append(scored_chromosome) # Select parents for offspring generation for ch in range(0, scored_population.__len__(), 1): # perform parent selection from scored population selection = Selection(population=scored_population) parents = selection.select() # perform crossover based on 50% probability crossover_prob = random.choice([True, False]) crossover = Crossover(parents, crossover_probability=crossover_prob) offspring = crossover.perform_crossover() # perform mutation based on 50% probability mutation_prob = random.choice([True, False]) mutation = Mutation(offspring, mutation_probability=mutation_prob) final_offspring = mutation.mutate() # add offspring to next generation next_gen_population.append(final_offspring)
action = None for action in actions: keyact[action['name']] = action keyact.update(adds or {}) if not keyact: raise common.message(_('No action defined')) if len(keyact) == 1: key = keyact.keys()[0] if data.get('context'): data['context'].update(rpc.session.context) return execute(keyact[key], **data) else: return Selection().create(keyact, **data) @tools.expose(template="/openerp/controllers/templates/closepopup.mako") def close_popup(reload=True): """ Closes an opened dialog box or popup. :param reload: whether the background view should be reloaded when closing the popup :type reload: bool :return: the rendered popup-closing template :rtype: str """ active_id = False if getattr(cherrypy.request, 'params', []): if getattr(cherrypy.request.params, 'context', {}):
from addel import AdDel from selection import Selection from editentry import EditEntry import datetime cannajobs_entry = AdDel() cannajobs_selection = Selection() cannajobs_edit = EditEntry() # job number, receive date, tests, status #cannajobs_selection.select_all_from_table_descending(7, True) #cannajobs_entry.delete_canna_customer_entry((258,)) cannajobs_selection.select_all_from_table_descending(1, True) cannajobs_entry.delete_cannajob_entry((1063, )) cannajobs_selection.select_all_from_table_descending(1, True) #cannajobs_edit = EditEntry() #cannajobs_edit.edit_cannajobs_entry(1, 452, 1) #print('----') #cannajobs_entry.delete_canna_customer_entry((193,))
def __init__(self): """Start the app.""" self.base = ShowBase() self.base.disableMouse() filters = CommonFilters(self.base.win, self.base.cam) filters.setBloom(blend=(0, 0, 0, 1)) self.base.render.setShaderAuto( BitMask32.allOn() & ~BitMask32.bit(Shader.BitAutoShaderGlow)) ts = TextureStage('ts') ts.setMode(TextureStage.MGlow) tex = self.base.loader.loadTexture('models/black.png') self.base.render.setTexture(ts, tex) self.terrain = Terrain(self.base.render, self.base.loader) minimap_size = 200 self.minimap = Minimap( self.base.win.makeDisplayRegion( 1 - minimap_size / self.base.win.getProperties().getXSize(), 1, 1 - minimap_size / self.base.win.getProperties().getYSize(), 1)) self.minimap.node_path.reparentTo(self.base.render) # self.light_nodes = self.set_lights() self.set_fog() self.key_state = dict.fromkeys(Object.values(config.key_map.character), False) self.set_key_state_handler() self.game_state = "pause" self.toggle_pause() self.selection = Selection(self.base.loader, self.terrain.geom_node) self.selection_text = OnscreenText( mayChange=True, scale=0.07, align=TextNode.ALeft, pos=(0.02 - self.base.getAspectRatio(), 1 - 0.07)) self.timer_text = OnscreenText(mayChange=True, scale=0.07, align=TextNode.ALeft, pos=(0.02 - self.base.getAspectRatio(), -1 + 0.02 + 0.07)) self.enemies = set() self.base.accept(config.key_map.utility.pause, self.toggle_pause) self.base.accept( "q", lambda: self.selection.advance_tower(self.base.loader)) self.base.accept("mouse1", self.player_click) self.base.cam.node().setCameraMask(BitMask32.bit(0)) self.base.setBackgroundColor(*config.map_params.colors.sky) self.player = Player() self.base.taskMgr.add(lambda task: self.terrain.start_up(), "start up") self.mouse_pos = (0.0, 0.0) self.base.taskMgr.add(self.move_player_task, "move_player_task") self.base.taskMgr.add(self.move_enemies_task, "move_enemies_task") self.base.taskMgr.add(self.player_select_task, "player_select_task") self.base.taskMgr.add(self.tower_task, "tower_task") self.base.taskMgr.add(self.check_end_game, "check_end_game_task") rand = Random() rand.seed(config.map_params.seed) self.base.taskMgr.doMethodLater(1, self.clock_task, 'clock_task', extraArgs=[rand]) self.rounds = 0 self.coin = 40
def select(self, start: int, end: int): if start > end or end >= len(self.__text): raise InvalidTextPositionError( "Требуемая позиция в тексте недоступна") return Selection(start, end)