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 pp_event(seq): """Returns pretty representation of an Event or keypress"""
if isinstance(seq, Event): return str(seq) # Get the original sequence back if seq is a pretty name already rev_curses = dict((v, k) for k, v in CURSES_NAMES.items()) rev_curtsies = dict((v, k) for k, v in CURTSIES_NAMES.items()) if seq in rev_curses: seq = rev_curses[seq] eli...
<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_nouns(max=2): """ Return a string of random nouns up to max number """
nouns = [] for noun in range(0, max): nouns.append(random.choice(noun_list)) return " ".join(nouns)
<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_date(past=False, max_years_future=10, max_years_past=10): """ Create a random valid date If past, then dates can be in the past If into the future, th...
if past: start = datetime.datetime.today() - datetime.timedelta(days=max_years_past * 365) #Anywhere between 1980 and today plus max_ears num_days = (max_years_future * 365) + start.day else: start = datetime.datetime.today() num_days = max_years_future * 365 random...
<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_birthday(min_age=18, max_age=80): """ Create a random birthday fomr someone between the ages of min_age and max_age """
age = random.randint(min_age, max_age) start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365)) return start - datetime.timedelta(days=age * 365)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_examples(): """ Run through some simple examples """
first, last = create_name() add = create_street() zip, city, state = create_city_state_zip() phone = create_phone(zip) print(first, last) print(add) print("{0:s} {1:s} {2:s}".format(city, state, zip)) print(phone) print(create_sentence()) print(create_paragraphs(num=3)) prin...
<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_mosek_index(block_struct, row_offsets, block_offsets, row): """MOSEK requires a specific sparse format to define the lower-triangular part of a sy...
block_index, i, j = convert_row_to_sdpa_index(block_struct, row_offsets, row) offset = block_offsets[block_index] ci = offset + i cj = offset + j return cj, ci
<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_mosek_matrix(sdp): """Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices. """
barci = [] barcj = [] barcval = [] barai = [] baraj = [] baraval = [] for k in range(sdp.n_vars): barai.append([]) baraj.append([]) baraval.append([]) row_offsets = [0] block_offsets = [0] cumulative_sum = 0 cumulative_square_sum = 0 for block_siz...
<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_mosek(sdp): """Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns:...
import mosek # Cheat when variables are complex and convert with PICOS if sdp.complex_matrix: from .picos_utils import convert_to_picos Problem = convert_to_picos(sdp).to_real() Problem._make_mosek_instance() task = Problem.msk_task if sdp.verbose > 0: ta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_text(self, text): """ If ``text`` is not empty, append a new Text node to the most recent pending node, if there is any, or to the new nodes, if there a...
if text: if self.pending_nodes: self.pending_nodes[-1].append(nodes.Text(text)) else: self.new_nodes.append(nodes.Text(text))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff(cls, a, b, ignore_formatting=False): """Returns two FSArrays with differences underlined"""
def underline(x): return u'\x1b[4m%s\x1b[0m' % (x,) def blink(x): return u'\x1b[5m%s\x1b[0m' % (x,) a_rows = [] b_rows = [] max_width = max([len(row) for row in a] + [len(row) for row in b]) a_lengths = [] b_lengths = [] for a_row, b_row in zip(a, 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 history(self): ''' show payment history ''' url= 'https://coincheck.com/api/exchange/orders/transactions' headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.get(url,headers=headers) return json.loads(r.text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pager(text, color=None): """Decide what method to use for paging through text."""
stdout = _default_text_stdout() if not isatty(sys.stdin) or not isatty(stdout): return _nullpager(stdout, text, color) if 'PAGER' in os.environ: if WIN: return _tempfilepager(text, os.environ['PAGER'], color) return _pipepager(text, os.environ['PAGER'], color) if os....
<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_int(cls, retries, redirect=True, default=None): """ Backwards-compatibility for the old retries format."""
if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redirect) and None new_retries = cls(retries, redirect=redirect) log.debug("Converted retries value: %r -> %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 convert_type(ty, default=None): """Converts a callable or python ty into the most appropriate param ty. """
if isinstance(ty, tuple): return Tuple(ty) if isinstance(ty, ParamType): return ty guessed_type = False if ty is None and default is not None: ty = type(default) guessed_type = True if ty is text_type or ty is str or ty is None: return STRING if ty is int...
<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(preset, name, silent, update): """Create new default preset \b Usage: $ be new ad "blue_unicorn" created $ be new film --name spiderman "spiderman" creat...
if self.isactive(): lib.echo("Please exit current preset before starting a new") sys.exit(lib.USER_ERROR) if not name: count = 0 name = lib.random_name() while name in _extern.projects(): if count > 10: lib.echo("ERROR: Couldn't come up with...
<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(preset, clean): """Update a local preset This command will cause `be` to pull a preset already available locally. \b Usage: $ be update ad Updating "a...
if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) presets = _extern.github_presets() if preset not in presets: sys.stdout.write("\"%s\" not found" % preset) sys.exit(lib.USER_ERROR) lib.echo("Are you sure you want to update \"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tab(topics, complete): """Utility sub-command for tabcompletion This command is meant to be called by a tab completion function and is given a the currently ...
# Discard `be tab` topics = list(topics)[2:] # When given an incomplete argument, # the argument is *sometimes* returned twice (?) # .. note:: Seen in Git Bash on Windows # $ be in giant [TAB] # -> ['giant'] # $ be in gi[TAB] # -> ['gi', 'gi'] if len(topics) > 1 and topics[-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 activate(): """Enter into an environment with support for tab-completion This command drops you into a subshell, similar to the one instead it enables tab-co...
parent = lib.parent() try: cmd = lib.cmd(parent) except SystemError as exc: lib.echo(exc) sys.exit(lib.PROGRAM_ERROR) # Store reference to calling shell context = lib.context(root=_extern.cwd()) context["BE_SHELL"] = parent if lib.platform() == "unix": co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ls(topics): """List contents of current context \b Usage: $ be ls - spiderman - hulk $ be ls spiderman - peter - mjay $ be ls spiderman seq01 - 1000 - 2000 -...
if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) # List projects if len(topics) == 0: for project in lib.list_projects(root=_extern.cwd()): lib.echo("- %s (project)" % project) sys.exit(lib.NORMAL) # List inventory...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mkdir(dir, enter): """Create directory with template for topic of the current environment """
if not os.path.exists(dir): os.makedirs(dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def preset_find(query): """Find preset from hub \b $ be find ad https://github.com/mottosso/be-ad.git """
if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USER_ERROR) found = _extern.github_presets().get(query) if found: lib.echo(found) else: lib.echo("Unable to locate preset \"%s\"" % query)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(): """Print current environment Environment is outputted in a YAML-friendly format \b Usage: $ be dump Prefixed: - BE_TOPICS=hulk bruce animation """
if not self.isactive(): lib.echo("ERROR: Enter a project first") sys.exit(lib.USER_ERROR) # Print custom environment variables first custom = sorted(os.environ.get("BE_ENVIRONMENT", "").split()) if custom: lib.echo("Custom:") for key in custom: lib.echo("- ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def what(): """Print current topics"""
if not self.isactive(): lib.echo("No topic") sys.exit(lib.USER_ERROR) lib.echo(os.environ.get("BE_TOPICS", "This is a bug"))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_user_agent(name="python-requests"): """Return a string representing the default user agent."""
_implementation = platform.python_implementation() if _implementation == 'CPython': _implementation_version = platform.python_version() elif _implementation == 'PyPy': _implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.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 to_native_string(string, encoding='ascii'): """ Given a string object, regardless of type, returns a representation of that string in the native string type,...
out = None if isinstance(string, builtin_str): out = string else: if is_py2: out = string.encode(encoding) else: out = string.decode(encoding) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ls(*topic, **kwargs): """List topic from external datastore Arguments: topic (str): One or more topics, e.g. ("project", "item", "task") root (str, optional...
context = dump() root = kwargs.get("root") or context.get("cwd") or os.getcwd() backend = kwargs.get("backend", os.listdir) absolute = kwargs.get("absolute", True) content = { 0: "projects", 1: "inventory", 2: "template" }[min(2, len(topic))] # List projects ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(context=os.environ): """Dump current environment as a dictionary Arguments: context (dict, optional): Current context, defaults to the current environm...
output = {} for key, value in context.iteritems(): if not key.startswith("BE_"): continue output[key[3:].lower()] = value return 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 cwd(): """Return the be current working directory"""
cwd = os.environ.get("BE_CWD") if cwd and not os.path.isdir(cwd): sys.stderr.write("ERROR: %s is not a directory" % cwd) sys.exit(lib.USER_ERROR) return cwd or os.getcwd().replace("\\", "/")
<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_script(script, tempdir): """Write script to a temporary directory Arguments: script (list): Commands which to put into a file Returns: Absolute path t...
name = "script" + self.suffix path = os.path.join(tempdir, name) with open(path, "w") as f: f.write("\n".join(script)) return path
<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_aliases(aliases, tempdir): """Write aliases to temporary directory Arguments: aliases (dict): {name: value} dict of aliases tempdir (str): Absolute p...
platform = lib.platform() if platform == "unix": home_alias = "cd $BE_DEVELOPMENTDIR" else: home_alias = "cd %BE_DEVELOPMENTDIR%" aliases["home"] = home_alias tempdir = os.path.join(tempdir, "aliases") os.makedirs(tempdir) for alias, cmd in aliases.iteritems(): 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 presets_dir(): """Return presets directory"""
default_presets_dir = os.path.join( os.path.expanduser("~"), ".be", "presets") presets_dir = os.environ.get(BE_PRESETSDIR) or default_presets_dir if not os.path.exists(presets_dir): os.makedirs(presets_dir) return presets_dir
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_preset(preset): """Physically delete local preset Arguments: preset (str): Name of preset """
preset_dir = os.path.join(presets_dir(), preset) try: shutil.rmtree(preset_dir) except IOError: lib.echo("\"%s\" did not exist" % preset)
<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(path, **kwargs): """requests.get wrapper"""
token = os.environ.get(BE_GITHUB_API_TOKEN) if token: kwargs["headers"] = { "Authorization": "token %s" % token } try: response = requests.get(path, verify=False, **kwargs) if response.status_code == 403: lib.echo("Patience: You can't pull more than ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gist_is_preset(repo): """Evaluate whether gist is a be package Arguments: gist (str): username/id pair e.g. mottosso/2bb4651a05af85711cde """
_, gistid = repo.split("/") gist_template = "https://api.github.com/gists/{}" gist_path = gist_template.format(gistid) response = get(gist_path) if response.status_code == 404: return False try: data = response.json() except: return False files = data.get("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 _repo_is_preset(repo): """Evaluate whether GitHub repository is a be package Arguments: gist (str): username/id pair e.g. mottosso/be-ad """
package_template = "https://raw.githubusercontent.com" package_template += "/{repo}/master/package.json" package_path = package_template.format(repo=repo) response = get(package_path) if response.status_code == 404: return False try: data = response.json() except: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def github_presets(): """Return remote presets hosted on GitHub"""
addr = ("https://raw.githubusercontent.com" "/mottosso/be-presets/master/presets.json") response = get(addr) if response.status_code == 404: lib.echo("Could not connect with preset database") sys.exit(lib.PROGRAM_ERROR) return dict((package["name"], package["repository"]) ...
<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_preset(preset_dir, project_dir): """Copy contents of preset into new project If package.json contains the key "contents", limit the files copied to thos...
os.makedirs(project_dir) package_file = os.path.join(preset_dir, "package.json") with open(package_file) as f: package = json.load(f) for fname in os.listdir(preset_dir): src = os.path.join(preset_dir, fname) contents = package.get("contents") or [] if fname not 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 echo(message=None, file=None, nl=True, err=False, color=None): """Prints a message plus a newline to the given file or stdout. On first sight, this looks lik...
if file is None: if err: file = _default_text_stderr() else: file = _default_text_stdout() # Convert non bytes/text into the native string type. if message is not None and not isinstance(message, echo_native_types): message = text_type(message) # If the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parent(): """Determine subshell matching the currently running shell The shell is determined by either a pre-defined BE_SHELL environment variable, or, if no...
if self._parent: return self._parent if "BE_SHELL" in os.environ: self._parent = os.environ["BE_SHELL"] else: # If a shell is not provided, rely on `psutil` # to look at the calling process name. try: import psutil except ImportError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmd(parent): """Determine subshell command for subprocess.call Arguments: parent (str): Absolute path to parent shell executable """
shell_name = os.path.basename(parent).rsplit(".", 1)[0] dirname = os.path.dirname(__file__) # Support for Bash if shell_name in ("bash", "sh"): shell = os.path.join(dirname, "_shell.sh").replace("\\", "/") cmd = [parent.replace("\\", "/"), shell] # Support for Cmd elif shell...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def context(root, project=""): """Produce the be environment The environment is an exact replica of the active environment of the current process, with a few add...
environment = os.environ.copy() environment.update({ "BE_PROJECT": project, "BE_PROJECTROOT": ( os.path.join(root, project).replace("\\", "/") if project else ""), "BE_PROJECTSROOT": root, "BE_ALIASDIR": "", "BE_CWD": root, "BE_CD": "", ...
<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_name(): """Return a random name Example: >> random_name() dizzy_badge >> random_name() evasive_cactus """
adj = _data.adjectives[random.randint(0, len(_data.adjectives) - 1)] noun = _data.nouns[random.randint(0, len(_data.nouns) - 1)] return "%s_%s" % (adj, noun)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isproject(path): """Return whether or not `path` is a project Arguments: path (str): Absolute path """
try: if os.path.basename(path)[0] in (".", "_"): return False if not os.path.isdir(path): return False if not any(fname in os.listdir(path) for fname in ("templates.yaml", "inventory.yaml")): return Fal...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def echo(text, silent=False, newline=True): """Print to the console Arguments: text (str): Text to print to the console silen (bool, optional): Whether or not ...
if silent: return print(text) if newline else sys.stdout.write(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_projects(root, backend=os.listdir): """List projects at `root` Arguments: root (str): Absolute path to the `be` root directory, typically the current w...
projects = list() for project in sorted(backend(root)): abspath = os.path.join(root, project) if not isproject(abspath): continue projects.append(project) return projects
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_inventory(inventory): """List a projects inventory Given a project, simply list the contents of `inventory.yaml` Arguments: root (str): Absolute path t...
inverted = invert_inventory(inventory) items = list() for item in sorted(inverted, key=lambda a: (inverted[a], a)): items.append((item, inverted[item])) return items
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_template(root, topics, templates, inventory, be, absolute=False): """List contents for resolved template Resolve a template as far as possible via the g...
project = topics[0] # Get item try: key = be.get("templates", {}).get("key") or "{1}" item = item_from_topics(key, topics) binding = binding_from_item(inventory, item) except KeyError: return [] except IndexError as exc: raise IndexError("At least %s topi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replacement_fields_from_context(context): """Convert context replacement fields Example: BE_KEY=value -> {"key": "value} Arguments: context (dict): The curr...
return dict((k[3:].lower(), context[k]) for k in context if k.startswith("BE_"))
<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_from_topics(key, topics): """Get binding from `topics` via `key` Example: {0} == hello --> be in hello world {1} == world --> be in hello world Returns:...
if re.match("{\d+}", key): pos = int(key.strip("{}")) try: binding = topics[pos] except IndexError: raise IndexError(pos + 1) else: echo("be.yaml template key not recognised") sys.exit(PROJECT_ERROR) return binding
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pattern_from_template(templates, name): """Return pattern for name Arguments: templates (dict): Current templates name (str): Name of name """
if name not in templates: echo("No template named \"%s\"" % name) sys.exit(1) return templates[name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def binding_from_item(inventory, item): """Return binding for `item` Example: asset: - myasset The binding is "asset" Arguments: project: Name of project item (s...
if item in self.bindings: return self.bindings[item] bindings = invert_inventory(inventory) try: self.bindings[item] = bindings[item] return bindings[item] except KeyError as exc: exc.bindings = bindings raise exc
<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_environment(fields, context, topics): """Resolve the be.yaml environment key Features: - Lists, e.g. ["/path1", "/path2"] - Environment variable refere...
def _resolve_environment_lists(context): """Concatenate environment lists""" for key, value in context.copy().iteritems(): if isinstance(value, list): context[key] = os.pathsep.join(value) return context def _resolve_environment_references(fields, context):...
<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_redirect(redirect, topics, context): """Resolve the be.yaml redirect key Arguments: redirect (dict): Source/destination pairs, e.g. {BE_ACTIVE: ACTIVE...
for map_source, map_dest in redirect.items(): if re.match("{\d+}", map_source): topics_index = int(map_source.strip("{}")) topics_value = topics[topics_index] context[map_dest] = topics_value continue context[map_dest] = context[map_source]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slice(index, template): """Slice a template based on it's positional argument Arguments: index (int): Position at which to slice template (str): Template t...
try: return re.match("^.*{[%i]}" % index, template).group() except AttributeError: raise ValueError("Index %i not found in template: %s" % (index, template))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def proxy_headers(self, proxy): """Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that t...
headers = {} username, password = get_auth_from_url(proxy) if username and password: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return headers
<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_dict(self, domain=None, path=None): """Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookie...
dictionary = {} for cookie in iter(self): if (domain is None or cookie.domain == domain) and (path is None or cookie.path == path): dictionary[cookie.name] = cookie.value return dictionary
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_stderr_logger(level=logging.DEBUG): """ Helper for quickly adding a StreamHandler to the logger. Useful for debugging. Returns the handler after adding i...
# This method needs to be in this __init__.py to get the __name__ correct # even if urllib3 is vendored within another package. logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) logger.addHandl...
<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_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED, options=None, ciphers=None): """All arguments have the same meaning as ``ssl_wrap_socke...
context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23) if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _put_conn(self, conn): """ Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn...
try: self.pool.put(conn, block=False) return # Everything is dandy, done. except AttributeError: # self.pool is None. pass except Full: # This should never happen if self.block == True log.warning( "Connect...
<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_conn(self, conn): """ Called right before a request is made, after the socket is created. """
super(HTTPSConnectionPool, self)._validate_conn(conn) # Force connect early to allow us to validate the connection. if not getattr(conn, 'sock', None): # AppEngine might not have `.sock` conn.connect() if not conn.is_verified: warnings.warn(( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def main(argv=None): ''' Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str ''' # Get command line arguments parser = argparse.Argume...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def style(text, fg=None, bg=None, bold=None, dim=None, underline=None, blink=None, reverse=None, reset=True): """Styles a text with ANSI styles and returns the n...
bits = [] if fg: try: bits.append('\033[%dm' % (_ansi_colors.index(fg) + 30)) except ValueError: raise TypeError('Unknown color %r' % fg) if bg: try: bits.append('\033[%dm' % (_ansi_colors.index(bg) + 40)) except ValueError: ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_setting(request_setting, session_setting, dict_class=OrderedDict): """ Determines appropriate setting for a given request, taking into account the expl...
if session_setting is None: return request_setting if request_setting is None: return session_setting # Bypass if not a dictionary (e.g. verify) if not ( isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) ): return reques...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Receives a Response. Returns a generator of Response...
i = 0 hist = [] # keep track of history while resp.is_redirect: prepared_request = req.copy() if i > 0: # Update history and keep track of redirects. hist.append(resp) new_hist = list(hist) resp.history =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_method(self, method): """Prepares the given HTTP method."""
self.method = method if self.method is not None: self.method = self.method.upper()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_headers(self, headers): """Prepares the given HTTP headers."""
if headers: self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items()) else: self.headers = CaseInsensitiveDict()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the c...
def generate(): try: # Special case for urllib3. try: for chunk in self.raw.stream(chunk_size, decode_content=True): yield chunk except ProtocolError as e: raise ChunkedEncodingError(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 command(name=None): """A decorator to register a subcommand with the global `Subcommands` instance. """
def decorator(f): _commands.append((name, f)) return f return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(program=None, version=None, doc_template=None, commands=None, argv=None, exit_at_end=True): """Top-level driver for creating subcommand-based programs. ...
if commands is None: if program is None: raise ValueError( '`program` required if subcommand object not provided') if version is None: raise ValueError( '`version` required if subcommand object not provided') commands = Subcommands(pro...
<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, spider): """Overridden process_response would "pipe" response.body through BeautifulSoup."""
return response.replace(body=str(BeautifulSoup(response.body, self.parser)))
<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_datasets(test_functions): """ Generator producing test_methods, with an optional dataset. :param test_functions: Iterator over tuples of test name an...
for name, func in test_functions: dataset_tuples = chain( [(None, getattr(func, 'genty_datasets', {}))], getattr(func, 'genty_dataproviders', []), ) no_datasets = True for dataprovider, datasets in dataset_tuples: for dataset_name, dataset in si...
<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_repeats(test_functions): """ Generator producing test_methods, with any repeat count unrolled. :param test_functions: Sequence of tuples of - method_...
for name, func, dataset_name, dataset, dataprovider in test_functions: repeat_count = getattr(func, 'genty_repeat_count', 0) if repeat_count: for i in range(1, repeat_count + 1): repeat_suffix = _build_repeat_suffix(i, repeat_count) yield ( ...
<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_repeat_suffix(iteration, count): """ Return the suffix string to identify iteration X out of Y. For example, with a count of 100, this will build stri...
format_width = int(math.ceil(math.log(count + 1, 10))) new_suffix = 'iteration_{0:0{width}d}'.format( iteration, width=format_width ) return new_suffix
<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_final_method_name( method_name, dataset_name, dataprovider_name, repeat_suffix, ): """ Return a nice human friendly name, that almost looks like code....
# For tests using a dataprovider, append "_<dataprovider_name>" to # the test method name suffix = '' if dataprovider_name: suffix = '_{0}'.format(dataprovider_name) if not dataset_name and not repeat_suffix: return '{0}{1}'.format(method_name, suffix) if dataset_name: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_method_to_class( target_cls, method_name, func, dataset_name, dataset, dataprovider, repeat_suffix, ): """ Add the described method to the given class. ...
# pylint: disable=too-many-arguments test_method_name_for_dataset = _build_final_method_name( method_name, dataset_name, dataprovider.__name__ if dataprovider else None, repeat_suffix, ) test_method_for_dataset = _build_test_method(func, dataset, dataprovider) test...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Close any open window. Note that this only works with non-blocking methods. """
if self._process: # Be nice first. self._process.send_signal(signal.SIGINT) # If it doesn't close itself promptly, be brutal. # Python 3.2+ added the timeout option to wait() and the # corresponding TimeoutExpired exception. If they exist, use them. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error(self, message, rofi_args=None, **kwargs): """Show an error window. This method blocks until the user presses a key. Fullscreen mode is not supported fo...
rofi_args = rofi_args or [] # Generate arguments list. args = ['rofi', '-e', message] args.extend(self._common_args(allow_fullscreen=False, **kwargs)) args.extend(rofi_args) # Close any existing window and show the error. self._run_blocking(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 status(self, message, rofi_args=None, **kwargs): """Show a status message. This method is non-blocking, and intended to give a status update to the user whil...
rofi_args = rofi_args or [] # Generate arguments list. args = ['rofi', '-e', message] args.extend(self._common_args(allow_fullscreen=False, **kwargs)) args.extend(rofi_args) # Update the status. self._run_nonblocking(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 select(self, prompt, options, rofi_args=None, message="", select=None, **kwargs): """Show a list of options and return user selection. This method blocks unt...
rofi_args = rofi_args or [] # Replace newlines and turn the options into a single string. optionstr = '\n'.join(option.replace('\n', ' ') for option in options) # Set up arguments. args = ['rofi', '-dmenu', '-p', prompt, '-format', 'i'] if select is not None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generic_entry(self, prompt, validator=None, message=None, rofi_args=None, **kwargs): """A generic entry box. Parameters prompt: string Text prompt for the en...
error = "" rofi_args = rofi_args or [] # Keep going until we get something valid. while True: args = ['rofi', '-dmenu', '-p', prompt, '-format', 's'] # Add any error to the given message. msg = message or "" if error: msg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text_entry(self, prompt, message=None, allow_blank=False, strip=True, rofi_args=None, **kwargs): """Prompt the user to enter a piece of text. Parameters prom...
def text_validator(text): if strip: text = text.strip() if not allow_blank: if not text: return None, "A value is required." return text, None return self.generic_entry(prompt, text_validator, message, rofi_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 integer_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs): """Prompt the user to enter an integer. Parameters prompt: string Pr...
# Sanity check. if (min is not None) and (max is not None) and not (max > min): raise ValueError("Maximum limit has to be more than the minimum limit.") def integer_validator(text): error = None # Attempt to convert to integer. 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 float_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs): """Prompt the user to enter a floating point number. Parameters prompt...
# Sanity check. if (min is not None) and (max is not None) and not (max > min): raise ValueError("Maximum limit has to be more than the minimum limit.") def float_validator(text): error = None # Attempt to convert to float. 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 decimal_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs): """Prompt the user to enter a decimal number. Parameters prompt: str...
# Sanity check. if (min is not None) and (max is not None) and not (max > min): raise ValueError("Maximum limit has to be more than the minimum limit.") def decimal_validator(text): error = None # Attempt to convert to decimal. 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 date_entry(self, prompt, message=None, formats=['%x', '%d/%m/%Y'], show_example=False, rofi_args=None, **kwargs): """Prompt the user to enter a date. Paramet...
def date_validator(text): # Try them in order. for format in formats: try: dt = datetime.strptime(text, format) except ValueError: continue else: # This one worked; good enough fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_entry(self, prompt, message=None, formats=['%X', '%H:%M', '%I:%M', '%H.%M', '%I.%M'], show_example=False, rofi_args=None, **kwargs): """Prompt the user ...
def time_validator(text): # Try them in order. for format in formats: try: dt = datetime.strptime(text, format) except ValueError: continue else: # This one worked; good enough fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def datetime_entry(self, prompt, message=None, formats=['%x %X'], show_example=False, rofi_args=None, **kwargs): """Prompt the user to enter a date and time. Par...
def datetime_validator(text): # Try them in order. for format in formats: try: dt = datetime.strptime(text, format) except ValueError: continue else: # This one worked; good enoug...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exit_with_error(self, error, **kwargs): """Report an error and exit. This raises a SystemExit exception to ask the interpreter to quit. Parameters error: str...
self.error(error, **kwargs) raise SystemExit(error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genty_dataprovider(builder_function): """Decorator defining that this test gets parameters from the given build_function. :param builder_function: A callable...
datasets = getattr(builder_function, 'genty_datasets', {None: ()}) def wrap(test_method): # Save the data providers in the test method. This data will be # consumed by the @genty decorator. if not hasattr(test_method, 'genty_dataproviders'): test_method.genty_dataproviders ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genty_dataset(*args, **kwargs): """Decorator defining data sets to provide to a test. Inspired by http://sebastian-bergmann.de/archives/ 702-Data-Providers-i...
datasets = _build_datasets(*args, **kwargs) def wrap(test_method): # Save the datasets in the test method. This data will be consumed # by the @genty decorator. if not hasattr(test_method, 'genty_datasets'): test_method.genty_datasets = OrderedDict() test_method.ge...
<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_datasets(*args, **kwargs): """Build the datasets into a dict, where the keys are the name of the data set and the values are the data sets themselves....
datasets = OrderedDict() _add_arg_datasets(datasets, args) _add_kwarg_datasets(datasets, kwargs) return datasets
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_arg_datasets(datasets, args): """Add data sets of the given args. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param...
for dataset in args: # turn a value into a 1-tuple. if not isinstance(dataset, (tuple, GentyArgs)): dataset = (dataset,) # Create a test_name_suffix - basically the parameter list if isinstance(dataset, GentyArgs): dataset_strings = dataset # GentyArgs 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 _add_kwarg_datasets(datasets, kwargs): """Add data sets of the given kwargs. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` ...
for test_method_suffix, dataset in six.iteritems(kwargs): datasets[test_method_suffix] = dataset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dedent(s): """Removes the hanging dedent from all the first line of a string."""
head, _, tail = s.partition('\n') dedented_tail = textwrap.dedent(tail) result = "{head}\n{tail}".format( head=head, tail=dedented_tail) 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 top_level_doc(self): """The top-level documentation string for the program. """
return self._doc_template.format( available_commands='\n '.join(sorted(self._commands)), program=self.program)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command(self, name=None): """A decorator to add subcommands. """
def decorator(f): self.add_command(f, name) return f return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_command(self, handler, name=None): """Add a subcommand `name` which invokes `handler`. """
if name is None: name = docstring_to_subcommand(handler.__doc__) # TODO: Prevent overwriting 'help'? self._commands[name] = handler
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def f2p_word(word, max_word_size=15, cutoff=3): """Convert a single word from Finglish to Persian. max_word_size: Maximum size of the words to consider. Words la...
original_word = word word = word.lower() c = dictionary.get(word) if c: return [(c, 1.0)] if word == '': return [] elif len(word) > max_word_size: return [(original_word, 1.0)] results = [] for w in variations(word): results.extend(f2p_word_internal(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 f2p_list(phrase, max_word_size=15, cutoff=3): """Convert a phrase from Finglish to Persian. phrase: The phrase to convert. max_word_size: Maximum size of the...
# split the phrase into words results = [w for w in sep_regex.split(phrase) if w] # return an empty list if no words if results == []: return [] # convert each word separately results = [f2p_word(w, max_word_size, cutoff) for w in results] return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def f2p(phrase, max_word_size=15, cutoff=3): """Convert a Finglish phrase to the most probable Persian phrase. """
results = f2p_list(phrase, max_word_size, cutoff) return ' '.join(i[0][0] for i in results)