text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def channel_width(im, chanangle=None, *, chanapproxangle=None, isccsedge=False): """Get an estimation of the channel width. Parameters: im: 2d array The channel ...
# check input is numpy array im = np.asarray(im) # Compute the dft if it is not already done if not isccsedge: im = reg.dft_optsize(np.float32(edge(im))) # save the truesize for later use truesize = im.shape # get centered magnitude squared (This changes the size) im = reg.ce...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def channel_angle(im, chanapproxangle=None, *, isshiftdftedge=False, truesize=None): """Extract the channel angle from the rfft Parameters: im: 2d array The chan...
im = np.asarray(im) # Compute edge if not isshiftdftedge: im = edge(im) return reg.orientation_angle(im, isshiftdft=isshiftdftedge, approxangle=chanapproxangle, truesize=truesize)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_channel(im0, im1, scale=None, ch0angle=None, chanapproxangle=None): """Register the images assuming they are channels Parameters: im0: 2d array The ...
im0 = np.asarray(im0) im1 = np.asarray(im1) # extract the channels edges e0 = edge(im0) e1 = edge(im1) fe0, fe1 = reg.dft_optsize_same(np.float32(e0), np.float32(e1)) # compute the angle and channel width of biggest angular feature w0, a0 = channel_width( fe0, isccsedge=True, c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uint8sc(im): """Scale the image to uint8 Parameters: im: 2d array The image Returns: -------- im: 2d array (dtype uint8) The scaled image to uint8 """
im = np.asarray(im) immin = im.min() immax = im.max() imrange = immax - immin return cv2.convertScaleAbs(im - immin, alpha=255 / imrange)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle(self, args): """ Greet each person by name. """
salutation = { 'french': 'Bonjour', 'spanish': 'Hola', 'english': 'Hello', }[args.lang.lower()] output = [] for name in args.name: output.append("{} {}!".format(salutation, name)) return "\n".join(output)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def capture(board): """Try to solve the board described by board_string. Return sequence of summaries that describe how to get to the solution. """
game = Game() v = (0, 0) stub_actor = base.Actor('capture', v, v, v, v, v, v, v, v, v) root = base.State(board, stub_actor, stub_actor, turn=1, actions_remaining=1) solution_node = None for eot in game.all_ends_of_turn(root): # check for a solution if eot.i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _disallow_state(self, state): """Disallow states that are not useful to continue simulating."""
disallow_methods = (self._is_duplicate_board, self._is_impossible_by_count) for disallow_method in disallow_methods: if disallow_method(state): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_impossible_by_count(self, state): """Disallow any board that has insufficient tile count to solve."""
# count all the tile types and name them for readability counts = {tile_type: 0 for tile_type in base.Tile._all_types} standard_wildcard_type = '2' for p, tile in state.board.positions_with_tile(): # count all wildcards as one value tile_type = tile._type ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_or_graft(self, board): """Build a tree with each level corresponding to a fixed position on board. A path of tiles is stored for each board. If any two ...
is_duplicate_board = True # assume same until find a difference # compare each position node = self for p, new_tile in board.positions_with_tile(): found_tile = False # assume no tile in same position until found for child in node.children: if c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_capture(self): """Return the capture board or None if can't find it."""
# game game_image = self._game_image_from_screen('capture') if game_image is None: return # board board = self._board_from_game_image(game_image) if board is None: return if board.is_empty(): return return board
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_versus(self): """Return the versus board, player, opponent and extra actions. Return None for any parts that can't be found. """
# game game_image = self._game_image_from_screen('versus') if game_image is None: return None, None, None, None # nothing else will work # board board = self._board_from_game_image(game_image) # may be None # safety check. there should be no blanks in a ver...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _game_image_from_screen(self, game_type): """Return the image of the given game type from the screen. Return None if no game is found. """
# screen screen_img = self._screen_shot() # game image game_rect = self._game_finders[game_type].locate_in(screen_img) if game_rect is None: return t, l, b, r = game_rect game_img = screen_img[t:b, l:r] return game_img
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _board_from_game_image(self, game_image): """Return a board object matching the board in the game image. Return None if any tiles are not identified. """
# board image board_rect = self._board_tools['board_region'].region_in(game_image) t, l, b, r = board_rect board_image = game_image[t:b, l:r] # board grid and tiles --> fill in a Board object board = Board() grid = self._board_tools['grid'] tile_id = self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _actor_from_game_image(self, name, game_image): """Return an actor object matching the one in the game image. Note: Health and mana are based on measured per...
HEALTH_MAX = 100 MANA_MAX = 40 # get the set of tools for investigating this actor tools = {'player': self._player_tools, 'opponent': self._oppnt_tools}[name] # setup the arguments to be set: args = [name] # health: t, l, b, r = tools['...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _count_extra_actions(self, game_image): """Count the number of extra actions for player in this turn."""
proportional = self._bonus_tools['extra_action_region'] # Use ProportionalRegion to isolate the extra actions area t, l, b, r = proportional.region_in(game_image) token_region = game_image[t:b, l:r] # Use TemplateFinder (multiple) to check for extra actions game_h, game_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ends_of_one_state(self, root=None, root_eot=None): """Simulate a complete turn from one state only and generate each end of turn reached in the simulation. A...
# basic confirmation of valid arguments self._argument_gauntlet(root_eot, root) # setup the starting state if root: start_state = root else: start_state = State(root_eot.parent.board.copy(), root_eot.parent.player.copy(), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ends_of_next_whole_turn(self, root): """Simulate one complete turn to completion and generate each end of turn reached during the simulation. Note on mana dr...
# simple confirmation that the root is actually a root. # otherwise it may seem to work but would be totally out of spec if root.parent: raise ValueError('Unexpectedly received a node with a parent for' ' root:\n{}'.format(root)) # build the list...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all_ends_of_turn(self, root): """Simulate the root and continue generating ends of turn until everything has reached mana drain. Warning on random fill: If r...
# simple confirmation that the root is actually a root. # otherwise it may seem to work but would be totally out of spec if root.parent: raise ValueError('Unexpectedly received a node with a parent for' ' root:\n{}'.format(root)) # run a single t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _simulated_chain_result(self, potential_chain, already_used_bonus): """Simulate any chain reactions. Arguments: potential_chain: a state to be tested for cha...
while potential_chain: # hook for capture game optimizations. no effect in base # warning: only do this ONCE for any given state or it will # always filter the second time if self._disallow_state(potential_chain): potential_chain.graft_child(Filte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _simulated_EOT(self, state): """Simulate a normal or mana drain EOT and return it."""
# determine if this is a manadrain or just end of turn is_manadrain = True # default mana drain until valid swap found for swap_pair in state.board.potential_swaps(): result_board, destroyed_groups = \ state.board.execute_once(swap=swap_pair, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _simulated_mana_drain(self, mana_drain_state): """Apply mana drain effects to this state, attach a mana drain EOT and return the mana drain EOT."""
# clear all mana mana_drain_state.player.apply_mana_drain() mana_drain_state.opponent.apply_mana_drain() # force change of turn mana_drain_state.actions_remaining = 0 # randomize the board if this game uses random fill if self.random_fill: random_star...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_start_board(cls): """Produce a full, stable start board with random tiles."""
board = cls() board._random_fill() destructions = True # prime the loop while destructions: board, destructions = board.execute_once() board._random_fill() return board
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_once(self, swap=None, spell_changes=None, spell_destructions=None, random_fill=False): """Execute the board only one time. Do not execute chain react...
bcopy = self.copy() # work with a copy, not self total_destroyed_tile_groups = list() # swap if any bcopy._swap(swap) # spell changes if any bcopy._change(spell_changes) # spell destructions and record if any # first convert simple positions to groups ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _swap(self, swap): """Simulate swapping as in PQ. swap should be a sequence of two positions with a square distance of exactly 1. Non-adjacent swaps cause a ...
if swap is None: return p1, p2 = swap square_distance = abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) if square_distance != 1: raise ValueError('Positions unexpectedly not adjacent: square' ' distance between {} and {} is' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _change(self, changes): """Apply the given changes to the board. changes: sequence of (position, new tile) pairs or None """
if changes is None: return for position, new_tile in changes: self._array[position] = new_tile
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _match(self): """Find all matches and generate a position group for each match."""
#disable optimized matching optimized_rows = None optimized_columns = None for match in self.__match_rows(optimized_rows): #match in rows yield match for match in self.__match_rows(optimized_columns, transpose=True):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __match_rows(self, optimized_lines=None, transpose=False): """Main functionality of _match, but works only on rows. Full matches are found by running this on...
MIN_LENGTH = 3 a = self._array if transpose: a = a.T rows = optimized_lines or range(8) # check for matches in each row separately for row in rows: NUM_COLUMNS = 8 match_length = 1 start_position = 0 # next tile pointer ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _destroy(self, target_position_groups): """Destroy indicated position groups, handle any chain destructions, and return all destroyed groups."""
target_position_groups = list(target_position_groups) # work on a copy destroyed_tile_groups = list() blank = Tile.singleton('.') a = self._array while target_position_groups: # continue as long as more targets exist # delay actual clearing of destroyed tiles until...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __skullbomb_radius(self, position): """Generate all valid positions in the square around position."""
#get the boundaries of the explosion sb_row, sb_col = position left = max(sb_row - 1, 0) # standard radius or 0 if out of bounds right = min(sb_row + 1, 7) # standard radius or 7 if out of bounds top = max(sb_col - 1, 0) bottom = min(sb_col + 1, 7) for explosio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fall(self): """Cause tiles to fall down to fill blanks below them."""
a = self._array for column in [a[:, c] for c in range(a.shape[1])]: # find blanks and fill them with tiles above them target_p = column.shape[0] - 1 # start at the bottom fall_distance = 1 # increases every time a new gap is found while target_p - fall_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _random_fill(self): """Fill the board with random tiles based on the Tile class."""
a = self._array for p, tile in self.positions_with_tile(): if tile.is_blank(): a[p] = Tile.random_tile()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def potential_swaps(self): """Generate a sequence of at least all valid swaps for this board. The built-in optimizer filters out many meaningless swaps, but not ...
a = self._array rows, cols = a.shape for this_position, tile in self.positions_with_tile(): #produce horizontal swap for this position r, c = this_position if c < cols - 1: other_position = (r, c + 1) if self._swap_optimizer_al...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _swap_optimizer_allows(self, p1, p2): """Identify easily discarded meaningless swaps. This is motivated by the cost of millions of swaps being simulated. """
# setup local shortcuts a = self._array tile1 = a[p1] tile2 = a[p2] # 1) disallow same tiles if tile1 == tile2: return False # 2) disallow matches unless a wildcard is involved if tile1.matches(tile2) and not any(t.is_wildcard() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """Return a copy of this actor with the same attribute values."""
health = self.health, self.health_max r = self.r, self.r_max g = self.g, self.g_max b = self.b, self.b_max y = self.y, self.y_max x = self.x, self.x_max m = self.m, self.m_max h = self.h, self.h_max c = self.c, self.c_max return self.__cla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_mana_drain(self): """Clear current mana values."""
self.r = self.g = self.b = self.y = 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_tile_groups(self, tile_groups): """Increase mana, xp, money, anvils and scrolls based on tile groups."""
self_increase_types = ('r', 'g', 'b', 'y', 'x', 'm', 'h', 'c') attack_types = ('s', '*') total_attack = 0 for tile_group in tile_groups: group_type = None type_count = 0 type_multiplier = 1 for tile in tile_group: # try to ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copytree(src, dst, overwrite=False, ignore_list=None, debug=False): """ Copy a tree of files over. Ignores a file if it already exists at the destination. ""...
if ignore_list is None: ignore_list = [] if debug: print('copytree {} to {}'.format(src, dst)) for child in Path(src).iterdir(): if debug: print(" on file {}".format(child)) if child.name not in ignore_list: if child.is_dir(): new_dir...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acquire_read(self, timeout=None): """ Acquire a read lock for the current thread, waiting at most timeout seconds or doing a non-blocking check in case timeo...
if timeout is not None: endtime = time.time() + timeout me = threading.currentThread() self.__condition.acquire() try: if self.__writer is me: self.__writer_lock_count += 1 return True while True: if sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acquire_write(self, timeout=None): """ Acquire a write lock for the current thread, waiting at most timeout seconds or doing a non-blocking check in case tim...
if timeout is not None: endtime = time.time() + timeout me = threading.currentThread() self.__condition.acquire() try: if self.__writer is me: self.__writer_lock_count += 1 return True if me in self.__readers: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def release(self): """ Release the currently held lock. In case the current thread holds no lock, a thread.error is thrown. """
me = threading.currentThread() self.__condition.acquire() try: if self.__writer is me: self.__writer_lock_count -= 1 if self.__writer_lock_count == 0: self.__writer = None self.__condition.notifyAll() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def try_acquire(self, elt): """ elt must be hashable. If not yet locked, elt is captured for the current thread and True is returned. If already locked by the cu...
me = threading.currentThread() self.lock.acquire() try: if elt not in self.locked: self.locked[elt] = [me, 1] return True elif self.locked[elt][0] == me: self.locked[elt][1] += 1 return True finally:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key, raw=False, fallback=None): """ Get a string value from the componnet. Arguments: key - the key to retrieve raw - Control whether the value is ...
return self._component.get(key, raw=raw, fallback=fallback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_list(self, key, fallback=None, split=","): """ Retrieve a value in list form. The interpolated value will be split on some key (by default, ',') and the ...
fallback = fallback or [] raw = self.get(key, None) if raw: return [value.strip() for value in raw.split(split)] return fallback
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, key, value): """ Set a value in the component. Arguments: key - the key to set value - the new value """
if self._component.get(key, raw=True) != value: self._component[key] = value self._main_config.dirty = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self): """Write the configuration."""
if self.dirty: with open(self._cache_path, "w") as output_file: self._config.write(output_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_request(self, request): """Discovers if a request is from a knwon spam bot and denies access."""
if COOKIE_KEY in request.COOKIES and \ request.COOKIES[COOKIE_KEY] == COOKIE_SPAM: # Is a known spammer. response = HttpResponse("") # We do not reveal why it has been forbbiden: response.status_code = 404 if D...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_response(self, request, response): """Sets "Ok" cookie on unknown users."""
if COOKIE_KEY not in request.COOKIES: # Unknown user, set cookie and go on... response.set_cookie(COOKIE_KEY, COOKIE_PASS, httponly=True, expires=datetime.now()+timedelta(days=30)) # Only logged if we have to set the PASS cookie if DJA...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_version(): """ Parse the version information from the init file """
version_file = os.path.join("paps_settings", "__init__.py") initfile_lines = open(version_file, 'rt').readlines() version_reg = r"^__version__ = ['\"]([^'\"]*)['\"]" for line in initfile_lines: mo = re.search(version_reg, line, re.M) if mo: return mo.group(1) raise Runti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inicap_string(string, cleanse=False): """ Convert the first letter of each word to capital letter without touching the rest of the word. @param string: a str...
return string and ' '.join(word[0].upper() + word[1:] for word in (string.split() if cleanse else string.split(' ')))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_email_address(string): """ Check whether the specified string corresponds to an email address. @param string: a string that is expected to be an email add...
return string and isinstance(string, base_string) \ and REGEX_PATTERN_EMAIL_ADDRESS.match(string.strip().lower())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def string_to_keywords(string, keyword_minimal_length=1): """ Remove any punctuation character from the specified list of keywords, remove any double or more spa...
# Convert the string to ASCII lower characters. ascii_string = unidecode.unidecode(string).lower() # Replace any punctuation character with space. punctuationless_string = re.sub(r"""[.,\\/#!$%\^&*;:{}=\-_`~()<>"']""", ' ', ascii_string) # Remove any double space character. cleansed_string = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkout(self, *args, **kwargs): """This function checks out source code."""
self._call_helper("Checking out", self.real.checkout, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, *args, **kwargs): """This funcion updates a checkout of source code."""
self._call_helper("Updating", self.real.update, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _print_layers(targets, components, tasks): """ Print dependency information, grouping components based on their position in the dependency graph. Components ...
layer = 0 expected_count = len(tasks) counts = {} def _add_layer(resolved, dep_fn): nonlocal layer nonlocal counts nonlocal expected_count really_resolved = [] for resolved_task in resolved: resolved_component_tasks = counts.get(resolved_task[0], []...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _print_graph(targets, components, tasks): """ Print dependency information using a dot directed graph. The graph will contain explicitly requested targets pl...
indentation = " " * 4 _do_dot( targets, components, tasks, lambda resolved, dep_fn: dep_fn(indentation, resolved), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _print_dot(targets, components, tasks): """ Deprecated function; use print_graph. Arguments targets - the targets explicitly requested components - full conf...
print("Warning: dot option is deprecated. Use graph instead.", file=sys.stderr) _print_graph(targets, components, tasks)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_selected_item(self): """The currently selected item"""
selection = self.get_selection() if selection.get_mode() != gtk.SELECTION_SINGLE: raise AttributeError('selected_item not valid for select_multiple') model, selected = selection.get_selected() if selected is not None: return self._object_at_sort_iter(selected)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_selected_items(self): """List of currently selected items"""
selection = self.get_selection() if selection.get_mode() != gtk.SELECTION_MULTIPLE: raise AttributeError('selected_items only valid for ' 'select_multiple') model, selected_paths = selection.get_selected_rows() result = [] for path in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_selected_ids(self): """List of currently selected ids"""
selection = self.get_selection() if selection.get_mode() != gtk.SELECTION_MULTIPLE: raise AttributeError('selected_ids only valid for select_multiple') model, selected_paths = selection.get_selected_rows() if selected_paths: return zip(*selected_paths)[0] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, item): """Manually update an item's display in the list :param item: The item to be updated. """
self.model.set(self._iter_for(item), 0, item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_item_down(self, item): """Move an item down in the list. Essentially swap it with the item below it. :param item: The item to be moved. """
next_iter = self._next_iter_for(item) if next_iter is not None: self.model.swap(self._iter_for(item), next_iter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_item_up(self, item): """Move an item up in the list. Essentially swap it with the item above it. :param item: The item to be moved. """
prev_iter = self._prev_iter_for(item) if prev_iter is not None: self.model.swap(prev_iter, self._iter_for(item))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def item_after(self, item): """The item after an item """
next_iter = self._next_iter_for(item) if next_iter is not None: return self._object_at_iter(next_iter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def item_before(self, item): """The item before an item :param item: The item to get the previous item relative to """
prev_iter = self._prev_iter_for(item) if prev_iter is not None: return self._object_at_iter(prev_iter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_visible_func(self, visible_func): """Set the function to decide visibility of an item :param visible_func: A callable that returns a boolean result to de...
self.model_filter.set_visible_func( self._internal_visible_func, visible_func, ) self._visible_func = visible_func self.model_filter.refilter()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_by(self, attr_or_key, direction='asc'): """Sort the view by an attribute or key :param attr_or_key: The attribute or key to sort by :param direction: Ei...
# work out the direction if direction in ('+', 'asc', gtk.SORT_ASCENDING): direction = gtk.SORT_ASCENDING elif direction in ('-', 'desc', gtk.SORT_DESCENDING): direction = gtk.SORT_DESCENDING else: raise AttributeError('unrecognised direction') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(self, position, item, select=False): """Insert an item at the specified position in the list. :param position: The position to insert the item at :par...
if item in self: raise ValueError("item %s already in list" % item) modeliter = self.model.insert(position, (item,)) self._id_to_iter[id(item)] = modeliter if select: self.selected_item = item self.emit('item-inserted', item, position)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extend(self, iter, parent=None): """Add a sequence of items to the end of the list :param iter: The iterable of items to add. :param parent: The node to add ...
for item in iter: self.append(item, parent)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand_item(self, item, open_all=True): """Display a node as expanded :param item: The item to show expanded :param open_all: Whether all child nodes should ...
self.expand_row(self._view_path_for(item), open_all)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jsonify(obj, trimmable=False): """ Serialize an object to a JSON formatted string. @param obj: an instance to convert to a JSON formatted string. @param trim...
# def jsonify_ex(obj, trimmable=False): # if obj is None: # return None # elif isinstance(obj, (basestring, bool, int, long, float, complex)): # return obj # elif isinstance(obj, (list, set, tuple)): # return [jsonify_ex(item, trimmable=trimmable) for ite...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stringify(obj, trimmable=False): """ Convert an object to a stringified version of this object where the initial object's attribute values have been stringif...
if obj is None: return None elif isinstance(obj, (basestring, bool, int, long, float, complex)): return obj elif isinstance(obj, (list, set, tuple)): return [stringify(item, trimmable=trimmable) for item in obj] elif isinstance(obj, dict): return dict([(unicode(key), str...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shallow_copy(obj, attribute_names, ignore_missing_attributes=True): """ Return a shallow copy of the given object, including only the specified attributes of...
shallow_object = copy.copy(obj) shallow_object.__dict__ = {} for attribute_name in attribute_names: try: setattr(shallow_object, attribute_name, getattr(obj, attribute_name)) except KeyError, error: if not ignore_missing_attributes: raise error ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_json(payload): """ Build an object from a JSON dictionary. @param payload: a JSON dictionary which key/value pairs represent the members of the Python o...
if payload is None: return None if isinstance(payload, dict): return Object(**dict([(k, v if not isinstance(v, (dict, list)) else Object.from_json(v)) for (k, v) in payload.iteritems()])) elif isinstance(payload, list): return payload an...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allow(self, comment, content_object, request): """Tests comment post requests for the djangospam cookie."""
# Tests for cookie: if settings.COOKIE_KEY not in request.COOKIES \ and (settings.DISCARD_SPAM or settings.DISCARD_NO_COOKIE): return False elif settings.COOKIE_KEY not in request.COOKIES: comment.is_removed = True comment.is_public = False ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, value): """Base validation method. Check if type is valid, or try brute casting. Args: value (object): A value for validation. Returns: Base_...
cast_callback = self.cast_callback if self.cast_callback else self.cast_type try: return value if isinstance(value, self.cast_type) else cast_callback(value) except Exception: raise NodeTypeError('Invalid value `{}` for {}.'.format(value, self.cast_type))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cast_callback(value): """Override `cast_callback` method. """
# Postgresql / MySQL drivers change the format on 'TIMESTAMP' columns; if 'T' in value: value = value.replace('T', ' ') return datetime.strptime(value.split('.')[0], '%Y-%m-%d %H:%M:%S')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_cache_dir_appropriate(cache_dir, cache_file): """ Determine if a directory is acceptable for building. A directory is suitable if any of the following ar...
if os.path.exists(cache_dir): files = os.listdir(cache_dir) if cache_file in files: return True return not bool(files) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_config(raw_path, cache_dir, cache_file, **kwargs): """ Read a build configuration and create it, storing the result in a build cache. Arguments raw_p...
config = _create_cache(raw_path, cache_dir, cache_file) for modifier in _CONFIG_MODIFIERS: modifier(config, **kwargs) # pylint: disable=protected-access cache = devpipeline_configure.cache._CachedConfig( config, os.path.join(cache_dir, cache_file) ) _handle_value_modifiers(cache...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_urls(self): """ Returns the urls for the model. """
urls = super(IPAdmin, self).get_urls() my_urls = patterns( '', url(r'^batch_process_ips/$', self.admin_site.admin_view(self.batch_process_ips_view), name='batch_process_ips_view') ) return my_urls + urls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def field2ap_corr(field): """Determine amplitude and offset-corrected phase from a field The phase jumps sometimes appear after phase unwrapping. Parameters fiel...
phase = unwrap.unwrap_phase(np.angle(field), seed=47) samples = [] samples.append(phase[:, :3].flatten()) samples.append(phase[:, -3:].flatten()) samples.append(phase[:3, 3:-3].flatten()) samples.append(phase[-3:, 3:-3].flatten()) pha_offset = np.median(np.hstack(samples)) num_2pi = np....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mie(radius=5e-6, sphere_index=1.339, medium_index=1.333, wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80), center=(39.5, 39.5), focus=0, arp=True): """...
# simulation parameters radius_um = radius * 1e6 # radius of sphere in um propd_um = radius_um # simulate propagation through full sphere propd_lamd = radius / wavelength # radius in wavelengths wave_nm = wavelength * 1e9 # Qpsphere models define the position of the sphere with an index in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_single_item(d): """Get an item from a dict which contains just one item."""
assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d) return next(six.iteritems(d))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_single_key(d): """Get a key from a dict which contains just one item."""
assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d) return next(six.iterkeys(d))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_single_value(d): """Get a value from a dict which contains just one item."""
assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d) return next(six.itervalues(d))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distinct(xs): """Get the list of distinct values with preserving order."""
# don't use collections.OrderedDict because we do support Python 2.6 seen = set() return [x for x in xs if x not in seen and not seen.add(x)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure(self): # type: () -> None """ Configures object based on its initialization """
for i in vars(self): if i.startswith("_"): continue val = self.__get(i, return_type=type(getattr(self, i))) if val is not None: setattr(self, i, val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, **kwargs): """ Does the magic! """
logger.info('UpdateLocationsIfNecessaryTask was called') # read last ip count try: with open(app_settings.IP_ASSEMBLER_IP_CHANGED_FILE, 'r') as f: content_list = f.readlines() if len(content_list) == 0: ip_count_old = -1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, **kwargs): """ Checks the IMAP mailbox for new mails and tries to handle them. """
try: # connect to server and login box = imaplib.IMAP4_SSL(settings.IMAP_SERVER) box.login(settings.IMAP_USERNAME, settings.IMAP_PASSWORD) box.select() # search for all mails in the mailbox result, mail_indices = box.search(None, 'ALL') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorize(client_key, client_secret, credfile=CONFIG_FILE, app='trlo.py', expiration='never', scope='read,write'): """ Authorize with Trello, saving creds to...
# 1. Obtain the request token. oauth = OAuth1Session(client_key, client_secret=client_secret) request_token = oauth.fetch_request_token(OAUTH_REQUEST_TOKEN_URL) # 2. Authorize the user (in the browser). authorization_url = oauth.authorization_url(OAUTH_BASE_AUTHORIZE_URL, name=app, expirat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCountry(value): """ returns the country name from country code @return string """
if not helpers.has_len(value): return False return COUNTRIES.get(str(value).lower(), False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(value): """ checks if given value is a valid country codes @param string value @return bool """
if not helpers.has_len(value): return False return COUNTRIES.has_key(str(value).lower())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_treecolumn(self, objectlist): """Create a gtk.TreeViewColumn for the configuration. """
col = gtk.TreeViewColumn(self.title) col.set_data('pygtkhelpers::objectlist', objectlist) col.set_data('pygtkhelpers::column', self) col.props.visible = self.visible if self.expand is not None: col.props.expand = self.expand if self.resizable is not None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_tooltip(self, tooltip, obj): """Render the tooltip for this column for an object """
if self.tooltip_attr: val = getattr(obj, self.tooltip_attr) elif self.tooltip_value: val = self.tooltip_value else: return False setter = getattr(tooltip, TOOLTIP_SETTERS.get(self.tooltip_type)) if self.tooltip_type in TOOLTIP_SIZED_TYPES: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def choose_tool_key(full_configuration, keys): """ Select the key for a tool from a list of supported tools. This function is designed to help when multiple keys...
tool_key = _choose_key(full_configuration.config, keys) if tool_key != keys[0]: full_configuration.executor.warning( "{} is deprecated; migrate to {}".format(tool_key, keys[0]) ) return tool_key
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tool_builder(component, key, tool_map, *args): """This helper function initializes a tool with the given args."""
# pylint: disable=protected-access tool_name = component.get(key) if tool_name: tool_fn = tool_map.get(tool_name) if tool_fn: return tool_fn[0](*args) raise Exception("Unknown {} '{}' for {}".format(key, tool_name, component.name)) raise MissingToolKey(key, component...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def args_builder(prefix, current_target, args_dict, value_found_fn): """ Process arguments a tool cares about. Since most tools require configuration, this funct...
current_config = current_target.config for key, separator in args_dict.items(): option = "{}.{}".format(prefix, key) value = current_config.get_list(option) if value: if separator is None: separator = _NullJoiner(current_config.name, option) value...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_flex_args_keys(components): """ Helper function to build a list of options. Some tools require require variations of the same options (e.g., cflags for...
def _prepend_first(components, sub_components): ret = [] for first in components[0]: for sub_component in sub_components: ret.append("{}.{}".format(first, sub_component)) return ret if len(components) > 1: sub_components = build_flex_args_keys(compo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def join(self, vals): """ Either return the non-list value or raise an Exception. Arguments: vals - a list of values to process """
if len(vals) == 1: return vals[0] raise Exception( "Too many values for {}:{}".format(self._component_name, self._key) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_audio(obj, wait=False): """Handle an audio event. This function plays an audio file. Currently only `.wav` format is supported. :param obj: An :py:cla...
if not simpleaudio: return obj fp = pkg_resources.resource_filename(obj.package, obj.resource) data = wave.open(fp, "rb") nChannels = data.getnchannels() bytesPerSample = data.getsampwidth() sampleRate = data.getframerate() nFrames = data.getnframes(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_interlude( self, obj, folder, index, ensemble, loop=None, **kwargs ): """Handle an interlude event. Interlude functions permit branching. They return ...
if obj is None: return folder.metadata else: return obj(folder, index, ensemble, loop=loop, **kwargs)