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 run(files, temp_folder): """Check isort errors in the code base. For the --quiet option, at least isort >= 4.1.1 is required. https://github.com/timothycrosl...
try: import isort # NOQA except ImportError: return NO_ISORT_MSG py_files = filter_python_files(files) # --quiet because isort >= 4.1 outputs its logo in the console by default. return bash('isort -df --quiet {0}'.format(' '.join(py_files))).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 run(files, temp_folder, arg=None): "Check we're not committing to a blocked branch" parser = get_parser() argos = parser.parse_args(arg.split()) current_branch = bash('git symbolic-ref HEAD').value() current_branch = current_branch.replace('refs/heads/', '').strip() if current_branch in arg...
<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(files, temp_folder, arg=None): "Check coding convention of the code base." try: import pylint except ImportError: return NO_PYLINT_MSG # set default level of threshold arg = arg or SCORE py_files = filter_python_files(files) if not py_files: 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 run(files, temp_folder): "Check to see if python files are py3 compatible" errors = [] for py_file in filter_python_files(files): # We only want to show errors if we CAN'T compile to py3. # but we want to show all the errors at once. b = bash('python3 -m py_compile {0}'.format(py...
<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(files, temp_folder): "Check flake8 errors in the code base." try: import flake8 # NOQA except ImportError: return NO_FLAKE_MSG try: from flake8.engine import get_style_guide except ImportError: # We're on a new version of flake8 from flake8.api.legacy...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tictactoe(w, i, player, opponent, grid=None): "Put two strategies to a classic battle of wits." grid = grid or empty_grid while True: w.render_to_terminal(w.array_from_text(view(grid))) if is_won(grid): print(whose_move(grid), "wins.") break if not success...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def memo(f): "Return a function like f that remembers and reuses results of past calls." table = {} def memo_f(*args): try: return table[args] except KeyError: table[args] = value = f(*args) return value return memo_f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def human_play(w, i, grid): "Just ask for a move." plaint = '' prompt = whose_move(grid) + " move? [1-9] " while True: w.render_to_terminal(w.array_from_text(view(grid) + '\n\n' + plaint + prompt)) key = c = i.next() try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def max_play(w, i, grid): "Play like Spock, except breaking ties by drunk_value." return min(successors(grid), key=lambda succ: (evaluate(succ), drunk_value(succ)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def drunk_value(grid): "Return the expected value to the player if both players play at random." if is_won(grid): return -1 succs = successors(grid) return -average(map(drunk_value, succs)) if succs else 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 evaluate(grid): "Return the value for the player to move, assuming perfect play." if is_won(grid): return -1 succs = successors(grid) return -min(map(evaluate, succs)) if succs else 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 is_won(grid): "Did the latest move win the game?" p, q = grid return any(way == (way & q) for way in ways_to_win)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def view(grid): "Show a grid human-readably." p_mark, q_mark = player_marks(grid) return grid_format % tuple(p_mark if by_p else q_mark if by_q else '.' for by_p, by_q in zip(*map(player_bits, grid)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_sdpa_out(filename, solutionmatrix=False, status=False, sdp=None): """Helper function to parse the output file of SDPA. :param filename: The name of the ...
primal = None dual = None x_mat = None y_mat = None status_string = None with open(filename, 'r') as file_: for line in file_: if line.find("objValPrimal") > -1: primal = float((line.split())[2]) if line.find("objValDual") > -1: 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 solve_with_sdpa(sdp, solverparameters=None): """Helper function to write out the SDP problem to a temporary file, call the solver, and parse the output. :par...
solverexecutable = detect_sdpa(solverparameters) if solverexecutable is None: raise OSError("SDPA is not in the path or the executable provided is" + " not correct") primal, dual = 0, 0 tempfile_ = tempfile.NamedTemporaryFile() tmp_filename = tempfile_.name tempfil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_row_to_sdpa_index(block_struct, row_offsets, row): """Helper function to map to sparse SDPA index values. """
block_index = bisect_left(row_offsets[1:], row + 1) width = block_struct[block_index] row = row - row_offsets[block_index] i, j = divmod(row, width) return block_index, i, j
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_to_human_readable(sdp): """Convert the SDP relaxation to a human-readable format. :param sdp: The SDP relaxation to write. :type sdp: :class:`ncpol2s...
objective = "" indices_in_objective = [] for i, tmp in enumerate(sdp.obj_facvar): candidates = [key for key, v in sdp.monomial_index.items() if v == i+1] if len(candidates) > 0: monomial = convert_monomial_to_string(candidates[0]) else: ...
<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_to_human_readable(sdp, filename): """Write the SDP relaxation to a human-readable format. :param sdp: The SDP relaxation to write. :type sdp: :class:`n...
objective, matrix = convert_to_human_readable(sdp) f = open(filename, 'w') f.write("Objective:" + objective + "\n") for matrix_line in matrix: f.write(str(list(matrix_line)).replace('[', '').replace(']', '') .replace('\'', '')) f.write('\n') f.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unget_bytes(self, string): """Adds bytes to be internal buffer to be read This method is for reporting bytes from an in_stream read not initiated by this Inp...
self.unprocessed_bytes.extend(string[i:i + 1] for i in range(len(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 _wait_for_read_ready_or_timeout(self, timeout): """Returns tuple of whether stdin is ready to read and an event. If an event is returned, that event is more ...
remaining_timeout = timeout t0 = time.time() while True: try: (rs, _, _) = select.select( [self.in_stream.fileno()] + self.readers, [], [], remaining_timeout) if not rs: return False, 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 send(self, timeout=None): """Returns an event or None if no events occur before timeout."""
if self.sigint_event and is_main_thread(): with ReplacedSigIntHandler(self.sigint_handler): return self._send(timeout) else: return self._send(timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _nonblocking_read(self): """Returns the number of characters read and adds them to self.unprocessed_bytes"""
with Nonblocking(self.in_stream): if PY3: try: data = os.read(self.in_stream.fileno(), READ_SIZE) except BlockingIOError: return 0 if data: self.unprocessed_bytes.extend(data[i:i+1] for i 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 event_trigger(self, event_type): """Returns a callback that creates events. Returned callback function will add an event of type event_type to a queue which ...
def callback(**kwargs): self.queued_events.append(event_type(**kwargs)) return callback
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scheduled_event_trigger(self, event_type): """Returns a callback that schedules events for the future. Returned callback function will add an event of type e...
def callback(when, **kwargs): self.queued_scheduled_events.append((when, event_type(when=when, **kwargs))) return callback
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def threadsafe_event_trigger(self, event_type): """Returns a callback to creates events, interrupting current event requests. Returned callback function will cre...
readfd, writefd = os.pipe() self.readers.append(readfd) def callback(**kwargs): self.queued_interrupting_events.append(event_type(**kwargs)) #TODO use a threadsafe queue for this logger.warning('added event to events list %r', self.queued_interrupting_events) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve_sdp(sdp, solver=None, solverparameters=None): """Call a solver on the SDP relaxation. Upon successful solution, it returns the primal and dual objectiv...
solvers = autodetect_solvers(solverparameters) solver = solver.lower() if solver is not None else solver if solvers == []: raise Exception("Could not find any SDP solver. Please install SDPA," + " Mosek, Cvxpy, or Picos with Cvxopt") elif solver is not None and solver no...
<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_sos_decomposition(sdp, y_mat=None, threshold=0.0): """Given a solution of the dual problem, it returns the SOS decomposition. :param sdp: The SDP relaxat...
if len(sdp.monomial_sets) != 1: raise Exception("Cannot automatically match primal and dual " + "variables.") elif len(sdp.y_mat[1:]) != len(sdp.constraints): raise Exception("Cannot automatically match constraints with blocks " + "in the dual sol...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_dual_value(sdp, monomial, blocks=None): """Given a solution of the dual problem and a monomial, it returns the inner product of the corresponding coe...
if sdp.status == "unsolved": raise Exception("The SDP relaxation is unsolved!") if blocks is None: blocks = [i for i, _ in enumerate(sdp.block_struct)] if is_number_type(monomial): index = 0 else: index = sdp.monomial_index[monomial] row_offsets = [0] cumulative_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_module(self, fullname): """ load_module is always called with the same argument as finder's find_module, see "How Import Works" """
mod = super(JsonLoader, self).load_module(fullname) try: with codecs.open(self.cfg_file, 'r', 'utf-8') as f: mod.__dict__.update(json.load(f)) except ValueError: # if raise here, traceback will contain ValueError self.e = "ValueError" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tick(self): """Returns a message to be displayed if game is over, else None"""
for npc in self.npcs: self.move_entity(npc, *npc.towards(self.player)) for entity1, entity2 in itertools.combinations(self.entities, 2): if (entity1.x, entity1.y) == (entity2.x, entity2.y): if self.player in (entity1, entity2): return 'you los...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def array_from_text(self, msg): """Returns a FSArray of the size of the window containing msg"""
rows, columns = self.t.height, self.t.width return self.array_from_text_rc(msg, rows, columns)
<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_cursor_vertical_diff(self): """Returns the how far down the cursor moved since last render. Note: If another get_cursor_vertical_diff call is already in ...
# Probably called by a SIGWINCH handler, and therefore # will do cursor querying until a SIGWINCH doesn't happen during # the query. Calls to the function from a signal handler COULD STILL # HAPPEN out of order - # they just can't interrupt the actual cursor query. if se...
<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_cursor_vertical_diff_once(self): """Returns the how far down the cursor moved."""
old_top_usable_row = self.top_usable_row row, col = self.get_cursor_position() if self._last_cursor_row is None: cursor_dy = 0 else: cursor_dy = row - self._last_cursor_row logger.info('cursor moved %d lines down' % cursor_dy) while self.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 render_to_terminal(self, array, cursor_pos=(0, 0)): """Renders array to terminal, returns the number of lines scrolled offscreen Returns: Number of times scr...
for_stdout = self.fmtstr_to_stdout_xform() # caching of write and tc (avoiding the self. lookups etc) made # no significant performance difference here if not self.hide_cursor: self.write(self.t.hide_cursor) # TODO race condition here? height, width = self.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 solve(self, solver=None, solverparameters=None): """Call a solver on the SDP relaxation. Upon successful solution, it returns the primal and dual objective v...
if self.F is None: raise Exception("Relaxation is not generated yet. Call " "'SdpRelaxation.get_relaxation' first") solve_sdp(self, solver, solverparameters)
<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_index_of_monomial(self, element, enablesubstitution=True, daggered=False): """Returns the index of a monomial. """
result = [] processed_element, coeff1 = separate_scalar_factor(element) if processed_element in self.moment_substitutions: r = self._get_index_of_monomial(self.moment_substitutions[processed_element], enablesubstitution) return [(k, coeff*coeff1) for k, coeff in r] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __push_facvar_sparse(self, polynomial, block_index, row_offset, i, j): """Calculate the sparse vector representation of a polynomial and pushes it to the F s...
width = self.block_struct[block_index - 1] # Preprocess the polynomial for uniform handling later # DO NOT EXPAND THE POLYNOMIAL HERE!!!!!!!!!!!!!!!!!!! # The simplify_polynomial bypasses the problem. # Simplifying here will trigger a bug in SymPy related to # the powers...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __remove_equalities(self, equalities, momentequalities): """Attempt to remove equalities by solving the linear equations. """
A = self.__process_equalities(equalities, momentequalities) if min(A.shape != np.linalg.matrix_rank(A)): print("Warning: equality constraints are linearly dependent! " "Results might be incorrect.", file=sys.stderr) if A.shape[0] == 0: return 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 process_constraints(self, inequalities=None, equalities=None, momentinequalities=None, momentequalities=None, block_index=0, removeequalities=False): """Proc...
self.status = "unsolved" if block_index == 0: if self._original_F is not None: self.F = self._original_F self.obj_facvar = self._original_obj_facvar self.constant_term = self._original_constant_term self.n_vars = len(self.obj_f...
<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_dual(self, constraint, ymat=None): """Given a solution of the dual problem and a constraint of any type, it returns the corresponding block in the dual s...
if not isinstance(constraint, Expr): raise Exception("Not a monomial or polynomial!") elif self.status == "unsolved" and ymat is None: raise Exception("SDP relaxation is not solved yet!") elif ymat is None: ymat = self.y_mat index = self._constraint_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 get_relaxation(self, level, objective=None, inequalities=None, equalities=None, substitutions=None, momentinequalities=None, momentequalities=None, momentsubs...
if self.level < -1: raise Exception("Invalid level of relaxation") self.level = level if substitutions is None: self.substitutions = {} else: self.substitutions = substitutions for lhs, rhs in substitutions.items(): if not ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten(lol): """Flatten a list of lists to a list. :param lol: A list of lists in arbitrary depth. :type lol: list of list. :returns: flat list of elements....
new_list = [] for element in lol: if element is None: continue elif not isinstance(element, list) and not isinstance(element, tuple): new_list.append(element) elif len(element) > 0: new_list.extend(flatten(element)) return new_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 simplify_polynomial(polynomial, monomial_substitutions): """Simplify a polynomial for uniform handling later. """
if isinstance(polynomial, (int, float, complex)): return polynomial polynomial = (1.0 * polynomial).expand(mul=True, multinomial=True) if is_number_type(polynomial): return polynomial if polynomial.is_Mul: elements = [polynomial] el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __separate_scalar_factor(monomial): """Separate the constant factor from a monomial. """
scalar_factor = 1 if is_number_type(monomial): return S.One, monomial if monomial == 0: return S.One, 0 comm_factors, _ = split_commutative_parts(monomial) if len(comm_factors) > 0: if isinstance(comm_factors[0], Number): scalar_factor = comm_factors[0] if sc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def separate_scalar_factor(element): """Construct a monomial with the coefficient separated from an element in a polynomial. """
coeff = 1.0 monomial = S.One if isinstance(element, (int, float, complex)): coeff *= element return monomial, coeff for var in element.as_coeff_mul()[1]: if not (var.is_Number or var.is_imaginary): monomial = monomial * var else: if var.is_Number:...
<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_ncmonomials(monomials, degree): """Given a list of monomials, it counts those that have a certain degree, or less. The function is useful when certain ...
ncmoncount = 0 for monomial in monomials: if ncdegree(monomial) <= degree: ncmoncount += 1 else: break return ncmoncount
<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_substitutions(monomial, monomial_substitutions, pure=False): """Helper function to remove monomials from the basis."""
if is_number_type(monomial): return monomial original_monomial = monomial changed = True if not pure: substitutions = monomial_substitutions else: substitutions = {} for lhs, rhs in monomial_substitutions.items(): irrelevant = False for atom 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 generate_variables(name, n_vars=1, hermitian=None, commutative=True): """Generates a number of commutative or noncommutative variables :param name: The prefi...
variables = [] for i in range(n_vars): if n_vars > 1: var_name = '%s%s' % (name, i) else: var_name = '%s' % name if commutative: if hermitian is None or hermitian: variables.append(Symbol(var_name, real=True)) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_operators(name, n_vars=1, hermitian=None, commutative=False): """Generates a number of commutative or noncommutative operators :param name: The pref...
variables = [] for i in range(n_vars): if n_vars > 1: var_name = '%s%s' % (name, i) else: var_name = '%s' % name if hermitian is not None and hermitian: variables.append(HermitianOperator(var_name)) else: variables.append(Operator...
<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_monomials(variables, degree): """Generates all noncommutative monomials up to a degree :param variables: The noncommutative variables to generate monomia...
if degree == -1: return [] if not variables: return [S.One] else: _variables = variables[:] _variables.insert(0, 1) ncmonomials = [S.One] ncmonomials.extend(var for var in variables) for var in variables: if not is_hermitian(var): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ncdegree(polynomial): """Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class...
degree = 0 if is_number_type(polynomial): return degree polynomial = polynomial.expand() for monomial in polynomial.as_coefficients_dict(): subdegree = 0 for variable in monomial.as_coeff_mul()[1]: if isinstance(variable, Pow): subdegree += variable.e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iscomplex(polynomial): """Returns whether the polynomial has complex coefficients :param polynomial: Polynomial of noncommutive variables. :type polynomial: ...
if isinstance(polynomial, (int, float)): return False if isinstance(polynomial, complex): return True polynomial = polynomial.expand() for monomial in polynomial.as_coefficients_dict(): for variable in monomial.as_coeff_mul()[1]: if isinstance(variable, complex) or v...
<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_all_monomials(variables, extramonomials, substitutions, degree, removesubstitutions=True): """Return the monomials of a certain degree. """
monomials = get_monomials(variables, degree) if extramonomials is not None: monomials.extend(extramonomials) if removesubstitutions and substitutions is not None: monomials = [monomial for monomial in monomials if monomial not in substitutions] monomials = [remo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pick_monomials_up_to_degree(monomials, degree): """Collect monomials up to a given degree. """
ordered_monomials = [] if degree >= 0: ordered_monomials.append(S.One) for deg in range(1, degree + 1): ordered_monomials.extend(pick_monomials_of_degree(monomials, deg)) return ordered_monomials
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pick_monomials_of_degree(monomials, degree): """Collect all monomials up of a given degree. """
selected_monomials = [] for monomial in monomials: if ncdegree(monomial) == degree: selected_monomials.append(monomial) return selected_monomials
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_monomial_index(filename, monomial_index): """Save a monomial dictionary for debugging purposes. :param filename: The name of the file to save to. :type ...
monomial_translation = [''] * (len(monomial_index) + 1) for key, k in monomial_index.items(): monomial_translation[k] = convert_monomial_to_string(key) file_ = open(filename, 'w') for k in range(len(monomial_translation)): file_.write('%s %s\n' % (k, monomial_translation[k])) 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 unique(seq): """Helper function to include only unique monomials in a basis."""
seen = {} result = [] for item in seq: marker = item if marker in seen: continue seen[marker] = 1 result.append(item) 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 build_permutation_matrix(permutation): """Build a permutation matrix for a permutation. """
matrix = lil_matrix((len(permutation), len(permutation))) column = 0 for row in permutation: matrix[row, column] = 1 column += 1 return matrix
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_relational(relational): """Convert all inequalities to >=0 form. """
rel = relational.rel_op if rel in ['==', '>=', '>']: return relational.lhs-relational.rhs elif rel in ['<=', '<']: return relational.rhs-relational.lhs else: raise Exception("The relational operation ' + rel + ' is not " "implemented!")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ai(board, who='x'): """ Returns best next board < Board |xo.xo.x..| > """
return sorted(board.possible(), key=lambda b: value(b, who))[-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 winner(self): """Returns either x or o if one of them won, otherwise None"""
for c in 'xo': for comb in [(0,3,6), (1,4,7), (2,5,8), (0,1,2), (3,4,5), (6,7,8), (0,4,8), (2,4,6)]: if all(self.spots[p] == c for p in comb): return c 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 get_relaxation(self, A_configuration, B_configuration, I): """Get the sparse SDP relaxation of a Bell inequality. :param A_configuration: The definition of m...
coefficients = collinsgisin_to_faacets(I) M, ncIndices = get_faacets_moment_matrix(A_configuration, B_configuration, coefficients) self.n_vars = M.max() - 1 bs = len(M) # The block size self.block_struct = [bs] self.F = l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def share(track_id=None, url=None, users=None): """ Returns list of users track has been shared with. Either track or url need to be provided. """
client = get_client() if url: track_id = client.get('/resolve', url=url).id if not users: return client.get('/tracks/%d/permissions' % track_id) permissions = {'user_id': []} for username in users: # check cache for user user = settings.users.get(username, 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 solve_with_cvxopt(sdp, solverparameters=None): """Helper function to convert the SDP problem to PICOS and call CVXOPT solver, and parse the output. :param sd...
P = convert_to_picos(sdp) P.set_option("solver", "cvxopt") P.set_option("verbose", sdp.verbose) if solverparameters is not None: for key, value in solverparameters.items(): P.set_option(key, value) solution = P.solve() x_mat = [np.array(P.get_valued_variable('X'))] y_mat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve_with_cvxpy(sdp, solverparameters=None): """Helper function to convert the SDP problem to CVXPY and call the solver, and parse the output. :param sdp: T...
problem = convert_to_cvxpy(sdp) if solverparameters is not None and 'solver' in solverparameters: solver = solverparameters.pop('solver') v = problem.solve(solver=solver, verbose=(sdp.verbose > 0)) else: v = problem.solve(verbose=(sdp.verbose > 0)) if v is None: status =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_to_cvxpy(sdp): """Convert an SDP relaxation to a CVXPY problem. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :retur...
from cvxpy import Minimize, Problem, Variable row_offsets = [0] cumulative_sum = 0 for block_size in sdp.block_struct: cumulative_sum += block_size ** 2 row_offsets.append(cumulative_sum) x = Variable(sdp.n_vars) # The moment matrices are the first blocks of identical size 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_neighbors(index, lattice_length, width=0, periodic=False): """Get the forward neighbors of a site in a lattice. :param index: Linear index of operator. :...
if width == 0: width = lattice_length neighbors = [] coords = divmod(index, width) if coords[1] < width - 1: neighbors.append(index + 1) elif periodic and width > 1: neighbors.append(index - width + 1) if coords[0] < lattice_length - 1: neighbors.append(index + w...
<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_next_neighbors(indices, lattice_length, width=0, distance=1, periodic=False): """Get the forward neighbors at a given distance of a site or set of sites ...
if not isinstance(indices, list): indices = [indices] if distance == 1: return flatten(get_neighbors(index, lattice_length, width, periodic) for index in indices) else: s1 = set(flatten(get_next_neighbors(get_neighbors(index, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pauli_constraints(X, Y, Z): """Return a set of constraints that define Pauli spin operators. :param X: List of Pauli X operator on sites. :type X: list of :c...
substitutions = {} n_vars = len(X) for i in range(n_vars): # They square to the identity substitutions[X[i] * X[i]] = 1 substitutions[Y[i] * Y[i]] = 1 substitutions[Z[i] * Z[i]] = 1 # Anticommutation relations substitutions[Y[i] * X[i]] = - X[i] * Y[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 generate_measurements(party, label): """Generate variables that behave like measurements. :param party: The list of number of measurement outputs a party has...
measurements = [] for i in range(len(party)): measurements.append(generate_operators(label + '%s' % i, party[i] - 1, hermitian=True)) return measurements
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def projective_measurement_constraints(*parties): """Return a set of constraints that define projective measurements. :param parties: Measurements of different p...
substitutions = {} # Idempotency and orthogonality of projectors if isinstance(parties[0][0][0], list): parties = parties[0] for party in parties: for measurement in party: for projector1 in measurement: for projector2 in measurement: if p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def define_objective_with_I(I, *args): """Define a polynomial using measurements and an I matrix describing a Bell inequality. :param I: The I matrix of a Bell i...
objective = I[0][0] if len(args) > 2 or len(args) == 0: raise Exception("Wrong number of arguments!") elif len(args) == 1: A = args[0].parties[0] B = args[0].parties[1] else: A = args[0] B = args[1] i, j = 0, 1 # Row and column index in I for m_Bj in B: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correlator(A, B): """Correlators between the probabilities of two parties. :param A: Measurements of Alice. :type A: list of list of :class:`sympy.physics.qu...
correlators = [] for i in range(len(A)): correlator_row = [] for j in range(len(B)): corr = 0 for k in range(len(A[i])): for l in range(len(B[j])): if k == l: corr += A[i][k] * B[j][l] else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maximum_violation(A_configuration, B_configuration, I, level, extra=None): """Get the maximum violation of a two-party Bell inequality. :param A_configuratio...
P = Probability(A_configuration, B_configuration) objective = define_objective_with_I(I, P) if extra is None: extramonomials = [] else: extramonomials = P.get_extra_monomials(extra) sdpRelaxation = SdpRelaxation(P.get_all_operators(), verbose=0) sdpRelaxation.get_relaxation(leve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interval_overlap(a, b, x, y): """Returns by how much two intervals overlap assumed that a <= b and x <= y"""
if b <= x or a >= y: return 0 elif x <= a <= y: return min(b, y) - a elif x <= b <= y: return b - max(a, x) elif a >= x and b <= y: return b - a else: assert 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 linesplit(string, columns): # type: (Union[Text, FmtStr], int) -> List[FmtStr] """Returns a list of lines, split on the last possible space of each line. Spl...
if not isinstance(string, FmtStr): string = fmtstr(string) string_s = string.s matches = list(re.finditer(r'\s+', string_s)) spaces = [string[m.start():m.end()] for m in matches if m.start() != 0 and m.end() != len(string_s)] words = [string[start:end] for start, end in zip( [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 normalize_slice(length, index): "Fill in the Nones in a slice." is_int = False if isinstance(index, int): is_int = True index = slice(index, index+1) if index.start is None: index = slice(0, index.stop, index.step) if index.stop is None: index = slice(index.start,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_args(args, kwargs): """Returns a kwargs dictionary by turning args into kwargs"""
if 'style' in kwargs: args += (kwargs['style'],) del kwargs['style'] for arg in args: if not isinstance(arg, (bytes, unicode)): raise ValueError("args must be strings:" + repr(args)) if arg.lower() in FG_COLORS: if 'fg' in kwargs: raise ValueError("fg spe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fmtstr(string, *args, **kwargs): # type: (Union[Text, bytes, FmtStr], *Any, **Any) -> FmtStr """ Convenience function for creating a FmtStr on_red(bold(blue(...
atts = parse_args(args, kwargs) if isinstance(string, FmtStr): pass elif isinstance(string, (bytes, unicode)): string = FmtStr.from_str(string) else: raise ValueError("Bad Args: %r (of type %s), %r, %r" % (string, type(string), args, kwargs)) return string.copy_with_new_atts...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def color_str(self): "Return an escape-coded string to write to the terminal." s = self.s for k, v in sorted(self.atts.items()): # (self.atts sorted for the sake of always acting the same.) if k not in xforms: # Unsupported SGR code continu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repr_part(self): """FmtStr repr is build by concatenating these."""
def pp_att(att): if att == 'fg': return FG_NUMBER_TO_COLOR[self.atts[att]] elif att == 'bg': return 'on_' + BG_NUMBER_TO_COLOR[self.atts[att]] else: return att atts_out = dict((k, v) for (k, v) in self.atts.items() if v) return (''.join(pp_att(att)+'(' for at...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, max_width): # type: (int) -> Optional[Tuple[int, Chunk]] """Requests a sub-chunk of max_width or shorter. Returns None if no chunks left."""
if max_width < 1: raise ValueError('requires positive integer max_width') s = self.chunk.s length = len(s) if self.internal_offset == len(s): return None width = 0 start_offset = i = self.internal_offset replacement_char = u' ' ...
<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_str(cls, s): # type: (Union[Text, bytes]) -> FmtStr r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same Fm...
if '\x1b[' in s: try: tokens_and_strings = parse(s) except ValueError: return FmtStr(Chunk(remove_ansi(s))) else: chunks = [] cur_fmt = {} for x in tokens_and_strings: if isi...
<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_with_new_str(self, new_str): """Copies the current FmtStr's attributes while changing its string."""
# What to do when there are multiple Chunks with conflicting atts? old_atts = dict((att, value) for bfs in self.chunks for (att, value) in bfs.atts.items()) return FmtStr(Chunk(new_str, old_atts))
<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_with_new_atts(self, **attributes): """Returns a new FmtStr with the same content but new formatting"""
return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes)) for bfs in self.chunks])
<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, iterable): """Joins an iterable yielding strings or FmtStrs with self as separator"""
before = [] chunks = [] for i, s in enumerate(iterable): chunks.extend(before) before = self.chunks if isinstance(s, FmtStr): chunks.extend(s.chunks) elif isinstance(s, (bytes, unicode)): chunks.extend(fmtstr(s).chu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split(self, sep=None, maxsplit=None, regex=False): """Split based on seperator, optionally using a regex Capture groups are ignored in regex, the whole patte...
if maxsplit is not None: raise NotImplementedError('no maxsplit yet') s = self.s if sep is None: sep = r'\s+' elif not regex: sep = re.escape(sep) matches = list(re.finditer(sep, s)) return [self[start:end] for start, end in zip( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def splitlines(self, keepends=False): """Return a list of lines, split on newline characters, include line boundaries, if keepends is true."""
lines = self.split('\n') return [line+'\n' for line in lines] if keepends else ( lines if lines[-1] else lines[:-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 width(self): """The number of columns it would take to display this string"""
if self._width is not None: return self._width self._width = sum(fs.width for fs in self.chunks) return self._width
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def width_at_offset(self, n): """Returns the horizontal position of character n of the string"""
#TODO make more efficient? width = wcswidth(self.s[:n]) assert width != -1 return width
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shared_atts(self): """Gets atts shared among all nonzero length component Chunk"""
#TODO cache this, could get ugly for large FmtStrs atts = {} first = self.chunks[0] for att in sorted(first.atts): #TODO how to write this without the '???'? if all(fs.atts.get(att, '???') == first.atts[att] for fs in self.chunks if len(fs) > 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 new_with_atts_removed(self, *attributes): """Returns a new FmtStr with the same content but some attributes removed"""
return FmtStr(*[Chunk(bfs.s, bfs.atts.remove(*attributes)) for bfs in self.chunks])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def divides(self): """List of indices of divisions between the constituent chunks."""
acc = [0] for s in self.chunks: acc.append(acc[-1] + len(s)) return acc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def width_aware_slice(self, index): """Slice based on the number of columns it would take to display the substring."""
if wcswidth(self.s) == -1: raise ValueError('bad values for width aware slicing') index = normalize_slice(self.width, index) counter = 0 parts = [] for chunk in self.chunks: if index.start < counter + chunk.width and index.stop > counter: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def width_aware_splitlines(self, columns): # type: (int) -> Iterator[FmtStr] """Split into lines, pushing doublewidth characters at the end of a line to the next...
if columns < 2: raise ValueError("Column width %s is too narrow." % columns) if wcswidth(self.s) == -1: raise ValueError('bad values for width aware slicing') return self._width_aware_splitlines(columns)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def public_api(self,url): ''' template function of public api''' try : url in api_urls return ast.literal_eval(requests.get(base_url + api_urls.get(url)).text) except Exception as e: print(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(s): r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. """
stuff = [] rest = s while True: front, token, rest = peel_off_esc_code(rest) if front: stuff.append(front) if token: try: tok = token_type(token) if tok: stuff.extend(tok) except ValueError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peel_off_esc_code(s): r"""Returns processed text, the next token, and unprocessed text ('some', 'stuff') True """
p = r"""(?P<front>.*?) (?P<seq> (?P<csi> (?:[]\[) | ["""+'\x9b' + r"""]) (?P<private>) (?P<numbers> (?:\d+;)* (?:\d+)?) (?P<intermed>""" +...
<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_key(bytes_, encoding, keynames='curtsies', full=False): """Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete se...
if not all(isinstance(c, type(b'')) for c in bytes_): raise ValueError("get key expects bytes, got %r" % bytes_) # expects raw bytes if keynames not in ['curtsies', 'curses', 'bytes']: raise ValueError("keynames must be one of 'curtsies', 'curses' or 'bytes'") seq = b''.join(bytes_) if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def could_be_unfinished_char(seq, encoding): """Whether seq bytes might create a char in encoding if more bytes were added"""
if decodable(seq, encoding): return False # any sensible encoding surely doesn't require lookahead (right?) # (if seq bytes encoding a character, adding another byte shouldn't also encode something) if encodings.codecs.getdecoder('utf8') is encodings.codecs.getdecoder(encoding): return...