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 image chanangle: number, optional The angle of the channel (None if unknown) chanapproxangle: number, optional If chanangle is None, the approximate channel angle isccsedge: boolean, default False Set to True if im is the dft of egde. False if it is an image of a channel. Returns: -------- width: number The channel width angle: number The corresponding angle Notes: ------ This function assumes two parallel lines along angle chanangle. The perpendicular line in the fourrier plane will have a mark of this, under the form of an oscillation at some frequency corresponding to the distance between the two parallel lines. This can be extracted by another fft. This second fft might have large components at low frequency, So the first few frequencies are neglected. The threshold is the first position below mean If the chanangle is not specified, the direction with higher contribution will be picked. If chanapproxangle is given, only angles close to this angle are taken into account """
# 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.centered_mag_sq_ccs(im) # if the channel direction is not given, deduce it from channel_angle if chanangle is None: chanangle = channel_angle(im, isshiftdftedge=True, chanapproxangle=chanapproxangle, truesize=truesize) # get vector perpendicular to angle fdir = np.asarray([math.cos(chanangle), -math.sin(chanangle)]) # y,x = 0,1 # need to be in the RHS of the cadran for rfft if fdir[1] < 0: fdir *= -1 # get center of shifted fft center = np.asarray([im.shape[0] // 2, 0]) # get size shape = np.asarray([im.shape[0] // 2, im.shape[1]]) # get evenly spaced positions between 0 and 1 (not included) # should be replaced with linspace pos = np.r_[:1:(shape.min() + 1) * 1j][:-1] # get index of a line of length 1 in normalized units from center # in direction of chdir idx = ((fdir * shape)[:, np.newaxis].dot(pos[np.newaxis]) + center[:, np.newaxis]) # get the line idx = np.float32(idx) f = cv2.remap(np.float32(im), idx[1, :], idx[0, :], cv2.INTER_LINEAR) f = np.squeeze(f) # The central line of the fft will have a periodic feature for parallel # lines which we can detect with fft f = abs(irfft(f**2)) # filter to avoid "interferences" f = gaussian_filter(f, 1) # the offset is determined by the first pixel below mean wmin = np.nonzero(f - f.mean() < 0)[0][0] """ import matplotlib.pyplot as plt plt.figure() plt.plot(f,'x') plt.plot([wmin,wmin],[0,f.max()]) plt.plot([0,500],[f.mean()+3*f.std(),f.mean()+3*f.std()]) #""" # find max excluding the first few points ret = reg.get_peak_pos(f[wmin:f.size // 2]) # return max and corresponding angle return (wmin + ret), chanangle
<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 channel image chanapproxangle: number, optional If not None, an approximation of the result isshiftdftedge: boolean, default False If The image has already been treated: (edge, dft, fftshift), set to True truesize: 2 numbers, required if isshiftdftedge is True The true size of the image Returns: -------- angle: number The channel angle """
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 first image im1: 2d array The second image scale: number, optional The scale difference if known ch0angle: number, optional The angle of the channel in the first image if known chanapproxangle: number, optional The approximate angle for both images if known Returns: -------- angle: number The angle difference scale: number The scale difference [y, x]: 2 numbers The offset e2: 2d array The second image rotated and translated for performances reasons """
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, chanapproxangle=chanapproxangle) w1, a1 = channel_width( fe1, isccsedge=True, chanapproxangle=chanapproxangle) # get angle diff angle = reg.clamp_angle(a0 - a1) if ch0angle is not None: a0 = ch0angle a1 = a0 - angle # if the scale is unknown, ratio of the channels if scale is None: scale = w1 / w0 #scale and rotate e2 = reg.rotate_scale(e1, angle, scale) # get edge from scaled and rotated im1 fe2 = reg.dft_optsize(np.float32(e2), shape=fe0.shape) # find offset y, x = reg.find_shift_dft(fe0, fe2, isccs=True) # return all infos return angle, scale, [y, x], e2
<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.is_mana_drain: # quick check before checking whole board if eot.parent.board.is_empty(): solution_node = eot break # if solution found, build the list of swaps solution_sequence = list() # empty sequence (no solution) by default if solution_node: node = solution_node while node: # record each swap in the path to the root if not isinstance(node, base.Swap): node = node.parent continue summary = base.Summary(node.parent.board, node.position_pair, None, None, None) solution_sequence.append(summary) node = node.parent return tuple(reversed(solution_sequence))
<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 try: int(tile_type) counts[standard_wildcard_type] += 1 except ValueError: counts[tile_type] += 1 skullbomb = counts['*'] skull = counts['s'] wildcard = counts[standard_wildcard_type] red = counts['r'] green = counts['g'] blue = counts['b'] yellow = counts['y'] exp = counts['x'] money = counts['m'] # always allow skullbomb with enough skulls if skullbomb and skullbomb + skull >= 3: return False # always allow wildcard with enough of one color if wildcard: if any(wildcard + color >= 3 for color in (red, green, blue, yellow)): return False # disallow simple cases since special cases didn't occur if any(tile and tile < 3 for tile in (red, green, blue, yellow, exp, money, skull)): return True # allow the state if counts seem ok 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 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 boards have the same path, then they are the same board. If there is any difference, a new branch will be created to store that path. Return: True if board already exists in the tree; False otherwise """
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 child.tile == new_tile: # same tile found in this position --> continue this branch node = child found_tile = True break if found_tile: pass # go on to the next position else: # different tile --> start new branch and mark not exact match child = _DuplicateTree(new_tile) node.graft_child(child) node = child is_duplicate_board = False # this will get set many times. ok return is_duplicate_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_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 versus board if board: for p, tile in board.positions_with_tile(): if tile.is_blank(): board = None # actors player = self._actor_from_game_image('player', game_image) opponent = self._actor_from_game_image('opponent', game_image) # extra actions extra_actions = self._count_extra_actions(game_image) return board, player, opponent, extra_actions
<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._board_tools['tile_id'] for p, borders in grid.borders_by_grid_position(board_image): t, l, b, r = borders tile = board_image[t:b, l:r] tile_character = tile_id.identify(tile) if tile_character is None: return None # soft failure board[p] = Tile.singleton(tile_character) 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 _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 percentage of a fixed maximum rather than the actual maximum in the game. Arguments: name: must be 'player' or 'opponent' game_image: opencv image of the main game area """
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['health_region'].region_in(game_image) health_image = game_image[t:b, l:r] health_image = numpy.rot90(health_image) # upright for the TankLevel how_full = tools['health_tank'].how_full(health_image) if how_full is None: return None # failure health = int(round(HEALTH_MAX * how_full)) args.append((health, HEALTH_MAX)) # mana for color in ('r', 'g', 'b', 'y'): t, l, b, r = tools[color + '_region'].region_in(game_image) mana_image = game_image[t:b, l:r] how_full = tools[color + '_tank'].how_full(mana_image) if how_full is None: return None # failure mana = int(round(MANA_MAX * how_full)) args.append((mana, MANA_MAX)) # experience and coins simply start at zero x_m = (0, 1000), (0, 1000) args.extend(x_m) # hammer and scroll are unused h_c = (0, 0), (0, 0) args.extend(h_c) # build the actor and return it return Actor(*args)
<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_w = game_image.shape[0:2] token_h = int(round(game_h * 27.0 / 960)) token_w = int(round(game_w * 22.0 / 1280)) sizes = (token_h, token_w), # sizes change every time so just remake it. # thresholds are tight since need to count conservatively finder = v.TemplateFinder(pq_data.extra_action_template, sizes=sizes, acceptable_threshold=0.1, immediate_threshold=0.1) found_tokens = finder.locate_multiple_in(token_region) return len(found_tokens)
<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. Arguments: Exactly one of: root: a start state with no parent or root_eot: an EOT or ManaDrain transition in the simulation """
# 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(), root_eot.parent.opponent.copy(), root_eot.parent.turn + 1, 1) root_eot.graft_child(start_state) # track states that are stable - i.e. no remaining chain reactions ready_for_action = [start_state] # simulate all actions for each state until reaching EOTs while ready_for_action: ready_state = ready_for_action.pop() # handle states that have run out of actions (end of turn) if ready_state.actions_remaining <= 0: root_eot = self._simulated_EOT(ready_state) yield root_eot continue # no more simulation for an EOT # handle swaps when there are actions remaining for swap_result in self._simulated_swap_results(ready_state): # handle any chain reactions if swap_result.actions_remaining \ >= ready_state.actions_remaining: already_used_bonus = True else: already_used_bonus = False chain_result = self._simulated_chain_result(swap_result, already_used_bonus) # chain results may be filtered so test first if chain_result: ready_for_action.append(chain_result) #at this point all swaps have been tried #if nothing was valid, it's a manadrain if not tuple(ready_state.children): mana_drain_eot = self._simulated_mana_drain(ready_state) yield mana_drain_eot continue # if something was valid, now spells can be simulated else: pass
<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 drain: Generates but does not continue simulation of mana drains. Arguments: root: a start state with no parent """
# 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 of eots (or just the root if first turn) to be run leaves = list(root.leaves()) kw_starts = list() if leaves[0] is root: # build ends of state kwargs as only the root kw_starts.append({'root': root}) else: # build ends of state kwargs as eots in the tree for leaf in leaves: # ignore mana drains if not leaf.is_mana_drain: kw_starts.append({'root_eot': leaf}) # run a single turn for each starting point for kw_start in kw_starts: for eot in self.ends_of_one_state(**kw_start): yield eot
<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 random fill is used together with this method, it will generate basically forever due to the huge number of possibilities it introduces. Arguments: root: a start state with no parent Note on mana drain: Generates but does not continue simulation of mana drains. Note on run time: This simulates a complete turn for each eot provided, rather than just one branch at a time. The method will only stop generating when all possibilities have been simulated or filtered. """
# 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 turn for each eot from a stack jobs = [root] while jobs: random_job_index = random.randint(0, len(jobs) - 1) start_eot = jobs.pop(random_job_index) # special case: handle the root once if start_eot is root: kw_root = {'root': start_eot} else: kw_root = {'root_eot': start_eot} for eot in self.ends_of_one_state(**kw_root): # only continue simulating non-mana drains if not eot.is_mana_drain: jobs.append(eot) yield eot
<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 chain reactions already_used_bonus: boolean indicating whether a bonus turn was already applied during this action Return: final result state or None (if state is filtered out in capture) Note that if there is no chain reaction, the final result is the same as the original state received. """
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(Filtered()) return None # no more simulation for this filtered state result_board, destroyed_groups = \ potential_chain.board.execute_once(random_fill= self.random_fill) # yield the state if nothing happened during execution (chain done) if not destroyed_groups: # yield this state as the final result of the chain return potential_chain # attach the transition chain = ChainReaction() potential_chain.graft_child(chain) # attach the result state if already_used_bonus: # disallow bonus action if already applied bonus_action = 0 else: # allow bonus action once and then flag as used bonus_action = any(len(group) >= 4 for group in destroyed_groups) already_used_bonus = True cls = potential_chain.__class__ chain_result = cls(board=result_board, turn=potential_chain.turn, actions_remaining= potential_chain.actions_remaining + bonus_action, player=potential_chain.player.copy(), opponent=potential_chain.opponent.copy()) # update the player and opponent base_attack = \ chain_result.active.apply_tile_groups(destroyed_groups) chain_result.passive.apply_attack(base_attack) chain.graft_child(chain_result) # prepare to try for another chain reaction potential_chain = chain_result
<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, random_fill=self.random_fill) if destroyed_groups: is_manadrain = False break # stop when the first valid swap found # attach appropriate EOT or ManaDrain if is_manadrain: end = self._simulated_mana_drain(state) else: end = EOT(False) state.graft_child(end) return end
<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_start_board = mana_drain_state.board.random_start_board() mana_drain_state.board = random_start_board # attach the mana drain EOT mana_drain = EOT(True) mana_drain_state.graft_child(mana_drain) return mana_drain
<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 reactions. Arguments: swap - pair of adjacent positions spell_changes - sequence of (position, tile) changes spell_destructions - sequence of positions to be destroyed Return: (copy of the board, destroyed tile groups) """
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 spell_destructions = spell_destructions or tuple() destruction_groups = [[p] for p in spell_destructions] destroyed_tile_groups = bcopy._destroy(destruction_groups) total_destroyed_tile_groups.extend(destroyed_tile_groups) # execute one time only # look for matched groups matched_position_groups = bcopy._match() # destroy and record matched groups destroyed_tile_groups = bcopy._destroy(matched_position_groups) total_destroyed_tile_groups.extend(destroyed_tile_groups) bcopy._fall() if random_fill: bcopy._random_fill() return bcopy, total_destroyed_tile_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 ValueError. """
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' ' {}'.format(p1, p2, square_distance)) a = self._array a[p1], a[p2] = a[p2], a[p1]
<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): #match in columns and transpose coordinates yield match
<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 once with original board and once with a transposed board. Arguments: optimized_lines is an optional argument that identifies the lines that need to be matched. transpose indicates whether the match is looking at rows or columns """
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 #set next start position as long as a match is still possible while start_position + MIN_LENGTH <= NUM_COLUMNS: group_type = a[row, start_position] # try to increase match length as long as there is room while start_position + match_length + 1 <= NUM_COLUMNS: next_tile = a[row, start_position + match_length] # if no match, stop looking for further matches if not group_type.matches(next_tile): break # if group_type is wildcard, try to find a real type if group_type.is_wildcard(): group_type = next_tile match_length += 1 #produce a matched position group if the current match qualifies if match_length >= MIN_LENGTH and not group_type.is_wildcard(): row_ = row target_positions = [(row_, col_) for col_ in range(start_position, start_position + match_length)] if transpose: target_positions = [(col_, row_) for row_, col_ in target_positions] yield target_positions #setup for continuing to look for matches after the current one start_position += match_length match_length = 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 _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 all claiming # groups have been stored (e.g. overlapping matches, bombs) clear_after_storing = list() new_target_position_groups = list() for target_position_group in target_position_groups: destroyed_tile_group = list() for target_position in target_position_group: target_tile = a[target_position] # no handling for blanks that appear in destruction if target_tile.is_blank(): continue destroyed_tile_group.append(target_tile) clear_after_storing.append(target_position) # skull bombs require further destructions if target_tile.is_skullbomb(): new_positions = self.__skullbomb_radius(target_position) # convert individual positions to position groups new_position_groups = [(new_position,) for new_position in new_positions] new_target_position_groups.extend(new_position_groups) if destroyed_tile_group: destroyed_tile_groups.append(destroyed_tile_group) # Finally clear positions after all records have been made for position in clear_after_storing: a[position] = blank # Replace the completed target position groups with any new ones target_position_groups = new_target_position_groups return destroyed_tile_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 __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 explosion_row in xrange(left, right + 1): for explosion_col in xrange(top, bottom + 1): yield (explosion_row, explosion_col)
<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_distance >= 0: # step up the target position if column[target_p].is_blank(): blank = column[target_p] # move the blank #find the next nonblank position while target_p - fall_distance >= 0: next_p = target_p - fall_distance if column[next_p].is_blank(): fall_distance += 1 else: break # stop expanding blank space when nonblank if target_p - fall_distance >= 0: #move the nonblank position to the target if gap exists source_position = target_p - fall_distance column[target_p] = column[source_position] column[source_position] = blank #in any case, move on to the next target position target_p -= 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 _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 all. """
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_allows(this_position, other_position): yield (this_position, other_position) #produce vertical swap for this position. not DRY but maybe ok if r < rows - 1: other_position = (r + 1, c) if self._swap_optimizer_allows(this_position, other_position): yield (this_position, other_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 _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() for t in (tile1, tile2)): return False # 3) disallow when both tiles (post-swap) are surrounded by non-matches center_other_pairs = ((p1, p2), (p2, p1)) class MatchedTiles(Exception): pass try: for center_p, other_p in center_other_pairs: up_down_left_right = ((center_p[0] - 1, center_p[1]), (center_p[0] + 1, center_p[1]), (center_p[0], center_p[1] - 1), (center_p[0], center_p[1] + 1)) post_swap_center_tile = a[other_p] for surrounding_p in up_down_left_right: # ignore out of bounds positions # and ignore the inner swap which is handled elsewhere if any((not (0 <= surrounding_p[0] <= 7), # out of bounds not (0 <= surrounding_p[1] <= 7), # out of bounds surrounding_p == other_p)): # inner swap continue surrounding_tile = a[surrounding_p] if post_swap_center_tile.matches(surrounding_tile): raise MatchedTiles() except MatchedTiles: pass # if any match found, stop checking and pass this filter else: return False # if no match is found, then this can be filtered 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 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.__class__(self.name, health, r, g, b, y, x, m, h, 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 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 get the group type if not group_type: # try to set the group type to a non-wildcard type if tile._type in self_increase_types: group_type = tile._type elif tile._type in attack_types: group_type = 's' # always use base skull # handle special case of wildcard if tile.is_wildcard(): type_multiplier *= int(tile._type) continue # done with this tile # handle special case of skullbomb / skull elif tile.is_skullbomb(): total_attack += 5 continue elif tile.is_skull(): total_attack += 1 continue # handle standard case of normal tiles else: type_count += 1 if group_type is None: continue # ignore this group. could be all wildcards or empty # adjust self value if type_count: new_value = type_count * type_multiplier original = getattr(self, group_type) setattr(self, group_type, original + new_value) # return any attack value return total_attack
<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 = Path(dst) / child.relative_to(src) new_dir.mkdir(exist_ok=True) # call recursively copytree(child, new_dir, overwrite, ignore_list, debug) elif child.is_file(): new_file = new_dir = Path(dst) / child.relative_to(src) if debug: print(" to file {}".format(new_file)) if new_file.exists(): if overwrite: new_file.unlink() shutil.copy2(child, new_file) else: shutil.copy2(child, new_file) else: if debug: print(" Skipping copy of {}".format(child))
<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 timeout is <= 0. In case timeout is None, the call to acquire_read blocks until the lock request can be serviced. If the lock has been successfully acquired, this function returns True, on a timeout it returns None. """
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 self.__writer is None: if self.__pending_writers: if me in self.__readers: # Grant the lock anyway if we already # hold one, because this would otherwise # cause a deadlock between the pending # writers and ourself. self.__readers[me] += 1 return True # else: does nothing, will wait below # writers are given priority else: self.__readers[me] = self.__readers.get(me, 0) + 1 return True if timeout is not None: remaining = endtime - time.time() if remaining <= 0: return None self.__condition.wait(remaining) else: self.__condition.wait() finally: self.__condition.release()
<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 timeout is <= 0. In case timeout is None, the call to acquire_write blocks until the lock request can be serviced. If the lock has been successfully acquired, this function returns True. On a timeout it returns None. In case a trivial deadlock condition is detected (the current thread already hold a reader lock) it returns False. """
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: # trivial deadlock detected (we do not handle promotion) return False self.__pending_writers.append(me) while True: if not self.__readers and self.__writer is None and self.__pending_writers[0] is me: self.__writer = me self.__writer_lock_count = 1 self.__pending_writers = self.__pending_writers[1:] return True if timeout is not None: remaining = endtime - time.time() if remaining <= 0: self.__pending_writers.remove(me) return None self.__condition.wait(remaining) else: self.__condition.wait() finally: self.__condition.release()
<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() elif me in self.__readers: self.__readers[me] -= 1 if self.__readers[me] == 0: del self.__readers[me] if not self.__readers: self.__condition.notifyAll() else: raise thread.error, "release unlocked lock" finally: self.__condition.release()
<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 current thread its recursive counter is incremented and True is returned. If already locked by another thread False is returned. """
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: self.lock.release() 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 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 interpolated or returned raw. By default, values are interpolated. fallback - The return value if key isn't in the component. """
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 resulting list will be returned. Arguments: key - the key to return fallback - The result to return if key isn't in the component. By default, this will be an empty list. split - The key to split the value on. By default, a comma (,). """
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 DJANGOSPAM_LOG: logger.log("SPAM REQUEST", request.method, request.path_info, request.META.get("HTTP_USER_AGENT", "undefined")) return response if DJANGOSPAM_LOG: logger.log("PASS REQUEST", request.method, request.path_info, request.META.get("HTTP_USER_AGENT", "undefined")) return 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 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 DJANGOSPAM_LOG: logger.log("PASS RESPONSE", request.method, request.path_info, request.META.get("HTTP_USER_AGENT", "undefined")) return response
<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 RuntimeError( "Unable to find version string in {}".format(version_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 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 string. @param cleanse: ``True`` to remove any separator character from the string, such as comma; ``False`` to keeps any character but space. @return: a string for which the first letter of each word has been capitalized without modifying the case of the rest of the word. """
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 address. @return: ``True`` if the string corresponds to an email address, ``False`` otherwise. """
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 space character and represent Unicode characters in ASCII. @param keywords: a list of keywords strip out any punctuation characters. @param keyword_minimal_length: minimal number of characters of the keywords to be returned. @return: the set of keywords cleansed from any special Unicode accentuated character, punctuation character, and double space character. """
# 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 = re.sub(r'\s{2,}', ' ', punctuationless_string) # Decompose the string into distinct keywords. keywords = set(cleansed_string.split(' ')) # Filter out sub-keywords of less than 2 characters. return [ keyword for keyword in keywords if len(keyword) > keyword_minimal_length ]
<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 with no dependnecies will be in layer 0, components that only depend on layer 0 will be in layer 1, and so on. If there's a circular dependency, those nodes and their dependencies will be colored red. Arguments targets - the targets explicitly requested components - full configuration for all components in a project """
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], []) resolved_component_tasks.append(resolved_task) if len(resolved_component_tasks) == expected_count: really_resolved.extend(resolved_component_tasks) del counts[resolved_task[0]] else: counts[resolved_task[0]] = resolved_component_tasks if really_resolved: indentation = " " * 4 print("{}subgraph cluster_{} {{".format(indentation, layer)) print('{}label="Layer {}"'.format(indentation * 2, layer)) dep_fn(indentation * 2, really_resolved) print("{}}}".format(indentation)) layer += 1 _do_dot(targets, components, tasks, _add_layer)
<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 plus any dependencies. If there's a circular dependency, those nodes and their dependencies will be colored red. Arguments targets - the targets explicitly requested components - full configuration for all components in a project """
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 configuration for all components in a project """
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 selected_paths: result.append(model[path][0]) return result
<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] else: return ()
<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 decide if an item should be visible, for example:: def is_visible(item): return True """
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: Either `asc` or `desc` indicating the direction of sorting """
# 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') if callable(attr_or_key): # is a key sort_func = self._key_sort_func else: # it's an attribute sort_func = self._attr_sort_func self.model.set_default_sort_func(sort_func, attr_or_key) self.model.set_sort_column_id(-1, 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 :param item: The item to be added :param select: Whether the item should be selected after adding """
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 the items as a child of, or None for top-level nodes. """
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 be recursively expanded. """
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 trimmable: indicate whether null attributes of this object need to be stripped out the JSON formatted string. @return: a JSON formatted string. """
# 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 item in obj] # MUST NOT remove nil value # elif isinstance(obj, dict): # return dict([(jsonify_ex(key, trimmable=trimmable), jsonify_ex(value, trimmable=trimmable)) # for (key, value) in obj.iteritems() if not trimmable or value is not None]) # elif isinstance(obj, (uuid.UUID, EnumValue, ISO8601DateTime, Locale)): # return str(obj) # elif isinstance(obj, datetime.datetime): # return str(ISO8601DateTime.from_datetime(obj)) if obj.tzinfo else str(obj) # elif '__dict__' in dir(obj): # return dict([(key, jsonify_ex(value, trimmable=trimmable)) # for (key, value) in obj.__dict__.iteritems() if not trimmable or value is not None]) # else: # return str(obj) # # return json.dumps(jsonify_ex(obj, trimmable=trimmable)) return json.dumps(stringify(obj, trimmable=trimmable))
<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 stringified when these values are not native Python types. This function differs from the standard Python ``str`` as the latter returns a string version of object, while this function returns an object which attributes have native Python types. @param obj: an instance to return its stringified version. @param trimmable: indicate whether null attributes of this object need to be stripped out. @return: an object which attributes values are either a native Python types, either a string. """
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), stringify(value, trimmable=trimmable)) for (key, value) in obj.iteritems() if not trimmable or value is not None]) elif isinstance(obj, (uuid.UUID, EnumValue, ISO8601DateTime, Locale)): return unicode(obj) elif isinstance(obj, datetime.datetime): return str(ISO8601DateTime.from_datetime(obj)) if obj.tzinfo else str(obj) elif hasattr(obj, '__dict__'): # '__dict__' in dir(obj): return dict([(key, stringify(value, trimmable=trimmable)) for (key, value) in obj.__dict__.iteritems() if not trimmable or value is not None]) else: return unicode(obj)
<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 this object. @param obj: an object to copy. @param attribute_names: a list of names of the attributes to copy. @param ignore_missing_attributes: ``False`` indicates that the function can ignore attributes that have been specified but that are not defined in the given object; ``True`` indicates that the function MUST raise a ``KeyError`` exception if some specified attributes are not defined in the given object. @return: a shallow copy of the given object with the specified attributes only. @raise KeyError: if the argument ``ignore_missing_attributes`` equals ``False`` and if some specified attributes are not defined in the the given object. """
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 return shallow_object
<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 object to build, or ``None``. @return: an instance ``Object`` with members built from the key/value pairs of the given JSON dictionary, or ``None`` if the payload is ``None`` or the given JSON dictionary is empty. """
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 and [Object.from_json(v) if isinstance(v, (dict, list)) else v for v in payload] else: raise ValueError('The payload MUST be a dictionary or a 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 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 return True 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 validate(self, value): """Base validation method. Check if type is valid, or try brute casting. Args: value (object): A value for validation. Returns: Base_type instance. Raises: SchemaError, if validation or type casting fails. """
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 are true: - it doesn't exist - it is empty - it contains an existing build cache """
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_path -- path to a build configuration cache_dir -- the directory where cache should be written cache_file -- The filename to write the cache. This will live inside cache_dir. **kwargs -- additional arguments used by some modifiers """
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) _add_package_options(cache) _write_config(cache, cache_dir) return 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 field: 2d complex np.ndarray Complex input field Returns ------- amp: 2d real np.ndarray Amplitude data pha: 2d real np.ndarray Phase data, corrected for 2PI offsets """
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.round(pha_offset / (2 * np.pi)) phase -= num_2pi * 2 * np.pi ampli = np.abs(field) return ampli, phase
<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): """Mie-simulated field behind a dielectric sphere Parameters radius: float Radius of the sphere [m] sphere_index: float Refractive index of the sphere medium_index: float Refractive index of the surrounding medium wavelength: float Vacuum wavelength of the imaging light [m] pixel_size: float Pixel size [m] grid_size: tuple of floats Resulting image size in x and y [px] center: tuple of floats Center position in image coordinates [px] focus: float .. versionadded:: 0.5.0 Axial focus position [m] measured from the center of the sphere in the direction of light propagation. arp: bool Use arbitrary precision (ARPREC) in BHFIELD computations Returns ------- qpi: qpimage.QPImage Quantitative phase data set """
# 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 # the array (because it is easier to work with). The pixel # indices run from (0, 0) to grid_size (without endpoint). BHFIELD # requires the extent to be given in µm. The distance in µm between # first and last pixel (measured from pixel center) is # (grid_size - 1) * pixel_size, size_um = (np.array(grid_size) - 1) * pixel_size * 1e6 # The same holds for the offset. If we use size_um here, # we already take into account the half-pixel offset. offset_um = np.array(center) * pixel_size * 1e6 - size_um / 2 kwargs = {"radius_sphere_um": radius_um, "refractive_index_medium": medium_index, "refractive_index_sphere": sphere_index, "measurement_position_um": propd_um, "wavelength_nm": wave_nm, "size_simulation_um": size_um, "shape_grid": grid_size, "offset_x_um": offset_um[0], "offset_y_um": offset_um[1]} background = np.exp(1j * 2 * np.pi * propd_lamd * medium_index) field = simulate_sphere(arp=arp, **kwargs) / background # refocus refoc = nrefocus.refocus(field, d=-((radius+focus) / pixel_size), nm=medium_index, res=wavelength / pixel_size) # Phase (2PI offset corrected) and amplitude amp, pha = field2ap_corr(refoc) meta_data = {"pixel size": pixel_size, "wavelength": wavelength, "medium index": medium_index, "sim center": center, "sim radius": radius, "sim index": sphere_index, "sim model": "mie", } qpi = qpimage.QPImage(data=(pha, amp), which_data="phase,amplitude", meta_data=meta_data) return qpi
<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 else: ip_count_old = int(content_list[0]) except IOError: ip_count_old = -1 logger.info('read IP count of %(count)d' % {'count': ip_count_old}) # if IPs have significantly changed, update the locations ip_count_now = IP.objects.count() if ip_count_now == -1 or ip_count_now > ip_count_old + app_settings.IP_ASSEMBLER_IP_CHANGED_THRESHOLD: logger.info('Checking IP counts, last: %(ip_count_old)d - now: %(ip_count_now)d' % { 'ip_count_old': ip_count_old, 'ip_count_now': ip_count_now }) # call the updater task UpdateHtaccessLocationsTask().delay() # write the new count to the file try: open(app_settings.IP_ASSEMBLER_IP_CHANGED_FILE, 'w').close() with open(app_settings.IP_ASSEMBLER_IP_CHANGED_FILE, 'w') as f: f.write(str(ip_count_now)) except IOError: logger.exception('unable to write to file %(file_path)s' % {'file_path': app_settings.IP_ASSEMBLER_IP_CHANGED_FILE}) else: logger.info('nothing to do here')
<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') # if everything was ok... if result == 'OK': # check number of mails mail_count = len(mail_indices[0].split()) logger.info('found %(mail_count)d mails...' % {'mail_count': mail_count}) # iterate the mail indices and fetch the mails ips_created = 0 for mail_index in mail_indices[0].split(): logger.info('fetching mail %(mail_index)s...' % {'mail_index': int(mail_index)}) # mail data is a list with a tuple sub_result, mail_data = box.fetch(mail_index, '(BODY[TEXT])') if sub_result == 'OK': # fetch the ips ips = list_remove_duplicates( self.find_ips(''.join([str(data) for data in mail_data[0]])) ) # if ips found, add them and delete the mail if len(ips) > 0: logger.info('found %(count)d IPs' % {'count': len(ips)}) ips_created += IP.batch_add_ips(ips) box.store(mail_index, '+FLAGS', '\\Deleted') else: logger.error('fetching mail with index %(index)d failed' % {'index': mail_index}) # finally, if ips were added, unify the IPs if ips_created > 0: logger.info('created %(count)d IPs' % {'count': ips_created}) IP.unify_ips() else: logger.error('search returned not OK') box.close() box.logout() except: logger.exception('retrieving mail failed')
<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 `credfile`. """
# 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, expiration=expiration, scope=scope) print("Please visit the following URL to authorize this app:") print(authorization_url) print('') print("Once you've authorized, copy and paste the token Trello gives you below.") # Py3K backwards-compatibility shim global input try: input = raw_input except NameError: pass verifier = input("Trello's token: ").strip() # 3. Obtain the access token oauth = OAuth1Session(client_key, client_secret=client_secret, resource_owner_key=request_token['oauth_token'], resource_owner_secret=request_token['oauth_token_secret'], verifier=verifier) access_token = oauth.fetch_access_token(OAUTH_ACCESS_TOKEN_URL) # Save all our creds to ~/.trlo so we can get at 'em later. # The names are specially chosen so we can do OAuth1Session(**creds) creds = { 'client_key': client_key, 'client_secret': client_secret, 'resource_owner_key': access_token['oauth_token'], 'resource_owner_secret': access_token['oauth_token_secret'], } with open(credfile, 'w') as fp: json.dump(creds, fp)
<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: col.props.resizable = self.resizable if self.width is not None: col.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED) col.set_fixed_width(self.width) for cell in self.cells: view_cell = cell.create_renderer(self, objectlist) view_cell.set_data('pygtkhelpers::column', self) # XXX: better control over packing col.pack_start(view_cell) col.set_cell_data_func(view_cell, cell.cell_data_func) col.set_reorderable(True) col.set_sort_indicator(False) col.set_sort_order(gtk.SORT_DESCENDING) if objectlist and objectlist.sortable and self.sorted: idx = objectlist.columns.index(self) sort_func = self._default_sort_func objectlist.model_sort.set_sort_func(idx, sort_func, objectlist) col.set_sort_column_id(idx) if objectlist and objectlist.searchable and self.searchable: self.search_by(objectlist) col.connect('clicked', self._on_viewcol_clicked) return col
<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: setter(val, self.tooltip_image_size) else: setter(val) 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 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 can be used to specify an option (e.g., during migration from one name to another). The values in keys should be ordered based on preference, as that's the order they'll be checked. If anything other than the first entry is selected, a warning will be displayed telling the user to migrate their configuration. Arguments: full_configuration - the full configuration for a run of the project keys - a list of keys to consider """
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 function helps deal with the boilerplate. Each option will be processed based on all modifications supported by dev-pipeline (i.e., profiles and overrides) in the proper order. Arguments: prefix -- The prefix for each argument. This will be applied to everything in args_dict. current_target -- Information about the current target being processed. args_dict -- Something that acts like a dictionary. The keys should be options to deal with and the value should be the separtor value the option requires. The separator can be any type that has a join method, or None if lists are supported for that key. value_found_fn -- A function to call when a match is found. """
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_found_fn(separator.join(value), 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 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 debug vs release builds), but manually creating those options is cumbersome and error-prone. This function handles that work by combining all possible comintations of the values in components. Arguments components -- A list of lists that should be combined to form options. """
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(components[1:]) return _prepend_first(components, sub_components) if len(components) == 1: return components[0] return []
<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:class:`~turberfield.dialogue.model.Model.Audio` object. :param bool wait: Force a blocking wait until playback is complete. :return: The supplied object. """
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() framesPerMilliSecond = nChannels * sampleRate // 1000 offset = framesPerMilliSecond * obj.offset duration = nFrames - offset duration = min( duration, framesPerMilliSecond * obj.duration if obj.duration is not None else duration ) data.readframes(offset) frames = data.readframes(duration) for i in range(obj.loop): waveObj = simpleaudio.WaveObject(frames, nChannels, bytesPerSample, sampleRate) playObj = waveObj.play() if obj.loop > 1 or wait: playObj.wait_done() return obj
<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 a folder which the application can choose to adopt as the next supplier of dialogue. This handler calls the interlude with the supplied arguments and returns the result. :param obj: A callable object. :param folder: A :py:class:`~turberfield.dialogue.model.SceneScript.Folder` object. :param int index: Indicates which scene script in the folder is being processed. :param ensemble: A sequence of Python objects. :param branches: A sequence of :py:class:`~turberfield.dialogue.model.SceneScript.Folder` objects. from which to pick a branch in the action. :return: A :py:class:`~turberfield.dialogue.model.SceneScript.Folder` object. """
if obj is None: return folder.metadata else: return obj(folder, index, ensemble, loop=loop, **kwargs)