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 build_docker_sshd(ctx): """ build docker image sshd-mssh-copy-id """
dinfo = DOCKER_SSHD_IMG ctx.run('docker rmi -f {0}'.format(dinfo['name']), warn=True) ctx.run('docker build -t {0} {1}'.format(dinfo['name'], dinfo['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 build_docker(ctx, image): """ build docker images """
if image not in DOCKER_IMGS: print('Error: unknown docker image "{0}"!'.format(image), file=sys.stderr) sys.exit(1) dinfo = DOCKER_IMGS[image] ctx.run('docker rmi -f {0}'.format(dinfo['name']), warn=True) dinfo_work_dir = os.path.join(dinfo['path'], '_work') ctx.run('mkdir -p {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 build_deb(ctx, target): """ build a deb package """
if target not in ('ubuntu-trusty',): print('Error: unknown target "{0}"!'.format(target), file=sys.stderr) sys.exit(1) os.chdir(PROJECT_DIR) debbuild_dir = os.path.join(DIST_DIR, 'deb') # Create directories layout ctx.run('mkdir -p {0}'.format(debbuild_dir)) # Copy the 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 build_rpm(ctx, target): """ build an RPM package """
if target not in ('centos6', 'centos7'): print('Error: unknown target "{0}"!'.format(target), file=sys.stderr) sys.exit(1) os.chdir(PROJECT_DIR) rpmbuild_dir = os.path.join(DIST_DIR, 'rpmbuild') # Create directories layout ctx.run('mkdir -p {0}'.format(' '.join(os.path.join(rpmbui...
<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_src(ctx, dest=None): """ build source archive """
if dest: if not dest.startswith('/'): # Relative dest = os.path.join(os.getcwd(), dest) os.chdir(PROJECT_DIR) ctx.run('python setup.py sdist --dist-dir {0}'.format(dest)) else: os.chdir(PROJECT_DIR) ctx.run('python setup.py sdist')
<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_gendoc(source, dest, args): """Starts gendoc which reads source and creates rst files in dest with the given args. :param source: The python source direc...
args.insert(0, 'gendoc.py') args.append(dest) args.append(source) print 'Running gendoc.main with: %s' % args gendoc.main(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 main(argv=sys.argv[1:]): """Parse commandline arguments and run the tool :param argv: the commandline arguments. :type argv: list :returns: None :rtype: None...
parser = setup_argparse() args = parser.parse_args(argv) if args.gendochelp: sys.argv[0] = 'gendoc.py' genparser = gendoc.setup_parser() genparser.print_help() sys.exit(0) print 'Preparing output directories' print '='*80 for odir in args.output: prepare_...
<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_migrations(path): ''' In the specified directory, get all the files which match the pattern 0001_migration.py ''' pattern = re.compile(r"\d+_[\w\d]+") modules = [name for _, name, _ in pkgutil.iter_modules([path]) if pattern.match(name) ] return sorted(mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def migrate(engine, database, module, **kwargs): ''' Execute the migrations. Pass in kwargs ''' validate_args(engine, database, module) options = { 'direction': kwargs.get('direction', 'up'), 'fake': kwargs.get('fake', False), 'force': kwargs.get('force', False), 'mi...
<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(engine, database, models, **kwargs): ''' Generate the migrations by introspecting the db ''' validate_args(engine, database, models) generator = Generator(engine, database, models) generator.run()
<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_migration(self, migration, **kwargs): ''' Apply a particular migration ''' cprint("\nAttempting to run %s" % migration, "cyan") # First check if the migration has already been applied exists = Migration.select().where(Migration.name == migration).limit(1).first(...
<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_tables(self, models): ''' Extract all peewee models from the passed in module ''' return { obj._meta.db_table : obj for obj in models.__dict__.itervalues() if isinstance(obj, peewee.BaseModel) and len(obj._meta.fields) > 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 get_pwiz_tables(self, engine, database): ''' Run the pwiz introspector and get the models defined in the DB. ''' introspector = pwiz.make_introspector(engine, database.database, **database.connect_kwargs) out_file = '/tmp/db_models.py' with Captur...
<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_subject_identifier_on_save(self): """Overridden to not set the subject identifier on save. """
if not self.subject_identifier: self.subject_identifier = self.subject_identifier_as_pk.hex elif re.match(UUID_PATTERN, self.subject_identifier): pass return self.subject_identifier
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raise_on_changed_subject_identifier(self): """Raises an exception if there is an attempt to change the subject identifier for an existing instance if the sub...
if self.id and self.subject_identifier_is_set(): with transaction.atomic(): obj = self.__class__.objects.get(pk=self.id) if obj.subject_identifier != self.subject_identifier_as_pk.hex: if self.subject_identifier != obj.subject_identifier: ...
<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(config, default_name = None): """ Resolves a component name from configuration parameters. The name can be stored in "id", "name" fields or inside a ...
name = config.get_as_nullable_string("name") name = name if name != None else config.get_as_nullable_string("id") if name == None: descriptor_str = config.get_as_nullable_string("descriptor") descriptor = Descriptor.from_string(descriptor_str) if descriptor ...
<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_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str: """ Returns the path to the current Python executable. """
return sys.executable
<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_leaves(x): """ Return the number of non-sequence items in a given recursive sequence. """
if hasattr(x, 'keys'): x = list(x.values()) if hasattr(x, '__getitem__'): return sum(map(count_leaves, x)) return 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 reprkwargs(kwargs, sep=', ', fmt="{0!s}={1!r}"): """Display kwargs."""
return sep.join(fmt.format(k, v) for k, v in kwargs.iteritems())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reprcall(name, args=(), kwargs=(), keywords='', sep=', ', argfilter=repr): """Format a function call for display."""
if keywords: keywords = ((', ' if (args or kwargs) else '') + '**' + keywords) argfilter = argfilter or repr return "{name}({args}{sep}{kwargs}{keywords})".format( name=name, args=reprargs(args, filter=argfilter), sep=(args and kwargs) and sep or "", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reprsig(fun, name=None, method=False): """Format a methods signature for display."""
args, varargs, keywords, defs, kwargs = [], [], None, [], {} argspec = fun if callable(fun): name = fun.__name__ if name is None else name argspec = getargspec(fun) try: args = argspec[0] varargs = argspec[1] keywords = argspec[2] defs = argspec[3] ex...
<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_input(input_func, input_str): """ Get input from the user given an input function and an input string """
val = input_func("Please enter your {0}: ".format(input_str)) while not val or not len(val.strip()): val = input_func("You didn't enter a valid {0}, please try again: ".format(input_str)) return val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def working_cycletime(start, end, workday_start=datetime.timedelta(hours=0), workday_end=datetime.timedelta(hours=24)): """ Get the working time between a beginn...
def clamp(t, start, end): "Return 't' clamped to the range ['start', 'end']" return max(start, min(end, t)) def day_part(t): "Return timedelta between midnight and 't'." return t - t.replace(hour=0, minute=0, second=0) if not start: return None if not end: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_definition_expr(expr, default_value=None): """ Parses a definition expression and returns a key-value pair as a tuple. Each definition expression shoul...
try: define, value = expr.split('=', 1) try: value = parse_number_token(value) except ValueError: value = parse_bool_token(value) except ValueError: if expr: define, value = expr, default_value else: raise ValueError("Inval...
<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_definitions(definitions): """ Parses a list of macro definitions and returns a "symbol table" as a dictionary. :params definitions: A list of command l...
defines = {} if definitions: for definition in definitions: define, value = parse_definition_expr(definition, default_value=None) defines[define] = value return defines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_up_logging(logger, level, should_be_quiet): """ Sets up logging for pepe. :param logger: The logger object to update. :param level: Logging level specifi...
LOGGING_LEVELS = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL, 'NONE': None, } logging_level = LOGGING_LEVELS.get(level) if should_be_quiet or logging_level is 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 main(): """ Entry-point function. """
args = parse_command_line() logging_level = set_up_logging(logger, args.logging_level, args.should_be_quiet) defines = parse_definitions(args.definitions) try: content_types_db = ContentTypesDatabase(DEFAULT_CONTENT_TYPES_FILE) for config_file in args.content_types_config_files: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, service, provider, singleton=False): """ Registers a service provider for a given service. @param service A key that identifies the service be...
def get_singleton(*args, **kwargs): result = self._get_singleton(service) if not result: instantiator = self._get_instantiator(provider) result = instantiator(*args, **kwargs) self._set_singleton(service, result) 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 dictionary_based_metrics(metrics): """ Higher order function creating a result type and collection function from the given metrics. Args: metrics (iterable):...
def collect(results, state): """ Measurement collection function for dictionary based metrics. Args: results (dict): Storing results of metrics. state (cipy.algorithms.core.State): Current state of the algorithm. Returns: dict: Updated 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 comparator(objective): """ Higher order function creating a compare function for objectives. Args: objective (cipy.algorithms.core.Objective): The objective...
if isinstance(objective, Minimum): return lambda l, r: l < r else: return lambda l, r: l > 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 _get_jenks_config(): """ retrieve the jenks configuration object """
config_file = (get_configuration_file() or os.path.expanduser(os.path.join("~", CONFIG_FILE_NAME))) if not os.path.exists(config_file): open(config_file, 'w').close() with open(config_file, 'r') as fh: return JenksData( yaml.load(fh.read()), writ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_placeholder(self, text): """Set the placeholder text that will be displayed when the text is empty and the widget is out of focus :param text: The text f...
if self._placeholder != text: self._placeholder = text if not self.hasFocus(): self.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 paintEvent(self, event): """Paint the widget :param event: :type event: :returns: None :rtype: None :raises: None """
if not self.toPlainText() and not self.hasFocus() and self._placeholder: p = QtGui.QPainter(self.viewport()) p.setClipping(False) col = self.palette().text().color() col.setAlpha(128) oldpen = p.pen() p.setPen(col) p.drawText(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 calcEvenAnchors(args): """ Calculates anchor points evenly spaced across the world, given user-specified parameters. Note: May not be exactly even if world s...
anchors = [] dist = int((args.worldSize)/(args.patchesPerSide+1)) for i in range(dist, args.worldSize, dist): for j in range(dist, args.worldSize, dist): anchors.append((i, j)) return anchors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calcRandomAnchors(args, inworld=True): """ Generates a list of random anchor points such that all circles will fit in the world, given the specified radius a...
anchors = [] rng = (args.patchRadius, args.worldSize - args.patchRadius) if not inworld: rng = (0, args.worldSize) for i in range(args.nPatches): anchors.append((random.randrange(rng[0], rng[1]), random.randrange(rng[0], rng[1]))) return anchors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pairwise_point_combinations(xs, ys, anchors): """ Does an in-place addition of the four points that can be composed by combining coordinates from the two lis...
for i in xs: anchors.append((i, max(ys))) anchors.append((i, min(ys))) for i in ys: anchors.append((max(xs), i)) anchors.append((min(xs), 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 calcTightAnchors(args, d, patches): """ Recursively generates the number of anchor points specified in the patches argument, such that all patches are d cell...
centerPoint = (int(args.worldSize/2), int(args.worldSize/2)) anchors = [] if patches == 0: pass elif patches == 1: anchors.append(centerPoint) elif patches % 2 == 0: dsout = int((patches-2)//2) + 1 add_anchors(centerPoint, d, dsout, anchors, True) if d != 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 genRandResources(args, resources): """ Generates a list of the appropriate length containing a roughly equal number of all resources in a random order """
randResources = [] nEach = int(args.nPatches // len(resources)) extras = int(args.nPatches % len(resources)) for i in range(nEach): for res in resources: randResources.append(res + str(i)) additional = random.sample(resources, extras) for res in additional: randReso...
<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_ppas_from_file(file_name, update=True): """Add personal package archive from a file list."""
for ppa in _read_lines_from_file(file_name): add_ppa(ppa, update=False) if update: update_apt_sources()
<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_apt_source(source, key=None, update=True): """Adds source url to apt sources.list. Optional to pass the key url."""
# Make a backup of list source_list = u'/etc/apt/sources.list' sudo("cp %s{,.bak}" % source_list) files.append(source_list, source, use_sudo=True) if key: # Fecth key from url and add sudo(u"wget -q %s -O - | sudo apt-key add -" % key) if update: update_apt_sources()
<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_sources_from_file(file_name, update=True): """ Add source urls from a file list. The file should contain the source line to add followed by the key url, ...
key_regex = re.compile(r'(?P<source>[^()]*)(\s+\((?P<key>.*)\))?$') for line in _read_lines_from_file(file_name): kwargs = key_regex.match(line).groupdict() kwargs['update'] = False add_apt_source(**kwargs) if update: update_apt_sources()
<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_user(name, groups=None, key_file=None): """Create a user. Adds a key file to authorized_keys if given."""
groups = groups or [] if not user_exists(name): for group in groups: if not group_exists(group): sudo(u"addgroup %s" % group) groups = groups and u'-G %s' % u','.join(groups) or '' sudo(u"useradd -m %s -s /bin/bash %s" % (groups, name)) sudo(u"passwd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self, username, password): """ Authenticate the user with a bind on the LDAP server """
if username is None or password is None: return False # check the username if not re.match("^[A-Za-z0-9_-]*$", username): return False user_dn = self.get_user_dn(username) server = ldap3.Server( self.uri, use_ssl=self.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 binary_guesser(handle, num_bytes=512): """Raise error if file not likely binary Guesses if a file is binary, raises error if file is not likely binary, then ...
text_chars = ''.join(map(chr, range(32, 127))) + '\n\r\t\b' byte_chars = text_chars.encode() handle_location = handle.tell() first_block = handle.read(num_bytes) if type(first_block) is str: first_block = first_block.encode() filtered_block = first_block.translate(None, delete=byte_cha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_ui(uifile): """Compile the given Qt designer file. The compiled file will be in the same directory but ends with _ui.py. :param uifile: filepath to t...
print "Compileing: %s" % uifile outputpath = uifile.rsplit(os.path.extsep, 1)[0] + "_ui.py" print "Outputfile: %s" % outputpath outputfile = open(os.path.abspath(outputpath), "w") pysideuic.compileUi(os.path.abspath(uifile), outputfile) print "Done!"
<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(code, filename='<unknown>', mode='exec', tree=None): """Parse the source into an AST node with PyPosAST. Enhance nodes with positions Arguments: code -...
visitor = Visitor(code, filename, mode, tree=tree) return visitor.tree
<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_nodes(code, desired_type, path="__main__", mode="exec", tree=None): """Find all nodes of a given type Arguments: code -- code text desired_type -- ast No...
return _GetVisitor(parse(code, path, mode, tree), desired_type).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 add(self, path): """Add the given path to the decided place in sys.path"""
# sys.path always has absolute paths. path = os.path.abspath(path) # It must exist. if not os.path.exists(path): return # It must not already be in sys.path. if path in sys.path: return if self.index 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 generate(data, algorithms=(DEFAULT_ALOGRITHM,)): """Yields subresource integrity Hash objects for the given data & algorithms sha384 H8BRh8j48O9oYatfu5AZzq6A...
return (Hash.fromresource(data, algorithm) for algorithm in algorithms)
<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(data, algorithms=(DEFAULT_ALOGRITHM,), seperator=' '): """Returns a subresource integrity string for the given data & algorithms 'sha384-H8BRh8j48O9oY...
return seperator.join(str(ihash) for ihash in generate(data, algorithms))
<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(integrity): """Returns a list of subresource integrity Hash objects parsed from a str Hash objects are put in descending order of algorithmic strength ...
matches = _INTEGRITY_PATTERN.findall(integrity) matches.sort(key=lambda t: RECOGNISED_ALGORITHMS.index(t[0])) return [Hash.fromhash(*match) for match in matches]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login(self, username=None, password=None, login_url=None, auth_url=None): """ This will automatically log the user into the pre-defined account Feel free to ...
return super(ConnectionBasic, self).login(username, password, login_url, auth_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def last_change(self): """ queries the database for the most recent time an object was either created or updated returns datetime or None if db is empty """
try: cdt = self.latest('created') udt = self.latest('updated') #print cdt, udt return max(cdt.created, udt.updated) except ObjectDoesNotExist: 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 since(self, timestamp=None, version=None, deleted=False): """ Queries the database for objects updated since timestamp or version Arguments: timestamp <DateT...
qset = self if timestamp is not None: if isinstance(timestamp, numbers.Real): timestamp = datetime.datetime.fromtimestamp(timestamp) qset = qset.filter( models.Q(created__gt=timestamp) | models.Q(updated__gt=timestamp) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fastq_verifier(entries, ambiguous=False): """Raises error if invalid FASTQ format detected Args: entries (list): A list of FastqEntry instances ambiguous (b...
if ambiguous: regex = r'^@.+{0}[ACGTURYKMSWBDHVNX]+{0}' \ r'\+.*{0}[!"#$%&\'()*+,-./0123456' \ r'789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ r'[\]^_`abcdefghijklmnopqrstuvwxyz' \ r'{{|}}~]+{0}$'.format(os.linesep) else: regex = 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 validate_configuration(self): """ Validates the provided settings. * Checks ``inherit_image`` format. * Checks ``use_registry_name`` format. * Checks that ``...
super().validate_configuration() if self.inherit_image is not None: try: assert len(str(self.inherit_image).split(":")) == 2 except (ValueError, AssertionError): raise ArcaMisconfigured(f"Image '{self.inherit_image}' is not a valid value for 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 get_dependencies(self) -> Optional[List[str]]: """ Returns the ``apt_dependencies`` setting to a standardized format. :raise ArcaMisconfigured: if the depende...
if not self.apt_dependencies: return None try: dependencies = list([str(x).strip() for x in self.apt_dependencies]) except (TypeError, ValueError): raise ArcaMisconfigured("Apk dependencies can't be converted into a list of strings") if not len(dep...
<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_image_name(self, repo_path: Path, requirements_option: RequirementsOptions, dependencies: Optional[List[str]]) -> str: """ Returns the name for images wit...
if self.inherit_image is None: return self.get_arca_base_name() else: name, tag = str(self.inherit_image).split(":") return f"arca_{name}_{tag}"
<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_image_tag(self, requirements_option: RequirementsOptions, requirements_hash: Optional[str], dependencies: Optional[List[str]]) -> str: """ Returns the tag...
prefix = "" if self.inherit_image is None: prefix = "{}_{}_".format(arca.__version__, self.get_python_version()) prefix += "i" if self.inherit_image is not None else "a" prefix += "r" if requirements_option != RequirementsOptions.no_requirements else "s" prefix += ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: pull=True, build_context: Optional[Path]=None): """ A proxy for commonly built images, returns them from the local system if they exist, tries to pull them if pu...
if self.image_exists(name, tag): logger.info("Image %s:%s exists", name, tag) return elif pull: logger.info("Trying to pull image %s:%s", name, tag) try: self.client.images.pull(name, tag=tag) logger.info("The image %s:%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 get_inherit_image(self) -> Tuple[str, str]: """ Parses the ``inherit_image`` setting, checks if the image is present locally and pulls it otherwise. :return: ...
name, tag = str(self.inherit_image).split(":") if self.image_exists(name, tag): return name, tag try: self.client.images.pull(name, tag) except docker.errors.APIError: raise ArcaMisconfigured(f"The specified image {self.inherit_image} from which Arca...
<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_image_with_installed_dependencies(self, image_name: str, dependencies: Optional[List[str]]) -> Tuple[str, str]: """ Return name and tag of a image, based ...
python_version = self.get_python_version() if dependencies is not None: def install_dependencies_dockerfile(): python_name, python_tag = self.get_python_base(python_version, pull=not self.disable_pull) ...
<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_image(self, image_name: str, image_tag: str, repo_path: Path, requirements_option: RequirementsOptions, dependencies: Optional[List[str]]): """ Builds ...
if self.inherit_image is not None: return self.build_image_from_inherited_image(image_name, image_tag, repo_path, requirements_option) if requirements_option == RequirementsOptions.no_requirements: python_version = self.get_python_version() # no requirements and n...
<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_to_registry(self, image, image_tag: str): """ Pushes a local image to a registry based on the ``use_registry_name`` setting. :type image: docker.models....
# already tagged, so it's already pushed if f"{self.use_registry_name}:{image_tag}" in image.tags: return image.tag(self.use_registry_name, image_tag) result = self.client.images.push(self.use_registry_name, image_tag) result = result.strip() # remove empty line ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image_exists(self, image_name, image_tag): """ Returns if the image exists locally. """
try: self.get_image(image_name, image_tag) return True except docker.errors.ImageNotFound: 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 container_running(self, container_name): """ Finds out if a container with name ``container_name`` is running. :return: :class:`Container <docker.models.cont...
filters = { "name": container_name, "status": "running", } for container in self.client.containers.list(filters=filters): if container_name == container.name: return container 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 tar_files(self, path: Path) -> bytes: """ Returns a tar with the git repository. """
tarstream = BytesIO() tar = tarfile.TarFile(fileobj=tarstream, mode='w') tar.add(str(path), arcname="data", recursive=True) tar.close() return tarstream.getvalue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tar_runner(self): """ Returns a tar with the runner script. """
script_bytes = self.RUNNER.read_bytes() tarstream = BytesIO() tar = tarfile.TarFile(fileobj=tarstream, mode='w') tarinfo = tarfile.TarInfo(name="runner.py") tarinfo.size = len(script_bytes) tarinfo.mtime = int(time.time()) tar.addfile(tarinfo, BytesIO(script_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 tar_task_definition(self, name: str, contents: str) -> bytes: """ Returns a tar with the task definition. :param name: Name of the file :param contents: Conte...
tarstream = BytesIO() tar = tarfile.TarFile(fileobj=tarstream, mode='w') tarinfo = tarfile.TarInfo(name=name) script_bytes = contents.encode("utf-8") tarinfo.size = len(script_bytes) tarinfo.mtime = int(time.time()) tar.addfile(tarinfo, BytesIO(script_bytes)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_container(self, image, container_name: str, repo_path: Path): """ Starts a container with the image and name ``container_name`` and copies the reposito...
command = "bash -i" if self.inherit_image: command = "sh -i" container = self.client.containers.run(image, command=command, detach=True, tty=True, name=container_name, working_dir=str((Path("/srv/data") / self.cwd).resolve()), ...
<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_container_name(self, repo: str, branch: str, git_repo: Repo): """ Returns the name of the container used for the repo. """
return "arca_{}_{}_{}".format( self._arca.repo_id(repo), branch, self._arca.current_git_hash(repo, branch, git_repo, short=True) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, repo: str, branch: str, task: Task, git_repo: Repo, repo_path: Path) -> Result: """ Gets or builds an image for the repo, gets or starts a container...
self.check_docker_access() container_name = self.get_container_name(repo, branch, git_repo) container = self.container_running(container_name) if container is None: image = self.get_image_for_repo(repo, branch, git_repo, repo_path) container = self.start_conta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_containers(self): """ Stops all containers used by this instance of the backend. """
while len(self._containers): container = self._containers.pop() try: container.kill(signal.SIGKILL) except docker.errors.APIError: # probably doesn't exist anymore pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_install_requirements_dockerfile(self, name: str, tag: str, repo_path: Path, requirements_option: RequirementsOptions) -> str: """ Returns the content of a...
if requirements_option == RequirementsOptions.requirements_txt: target_file = "requirements.txt" requirements_files = [repo_path / self.requirements_location] install_cmd = "pip" cmd_arguments = "install -r /srv/requirements.txt" elif requirements_optio...
<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(): """ Gets the worklog status for the current branch """
import pdb; pdb.set_trace() branch = git.branch issue = jira.get_issue(branch) if not issue: return # Print the title title = issue.fields.summary print "(%s) %s" % (branch, title) # Print the status status = issue.fields.status.name assignee = issue.fields.assignee.na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(duration, message=None, use_last_commit_message=False): """ Log time against the current active issue """
branch = git.branch issue = jira.get_issue(branch) # Create the comment comment = "Working on issue %s" % branch if message: comment = message elif use_last_commit_message: comment = git.get_last_commit_message() if issue: # If the duration is provided use it, other...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mark(): """ Mark the start time for active work on an issue """
branch = git.branch issue = jira.get_issue(branch) if not issue: return worklogs = jira.get_worklog(issue) marked = False if worklogs: # If we have worklogs, change the updated time of the last log to the mark marked = jira.touch_last_worklog(issue) mark_time = ...
<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(): """ Set up the context and connectors """
try: init() except custom_exceptions.NotConfigured: configure() init() # Adding this in case users are trying to run without adding a jira url. # I would like to take this out in a release or two. # TODO: REMOVE except (AttributeError, ConfigParser.NoOptionError): ...
<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_string(cls, contents, **kwargs): """ Given a markdown string, create an Entry object. Usually subclasses will want to customize the parts of the m...
lines = contents.splitlines() title = None description = None line = lines.pop(0) while line != '': if not title and line.startswith('#'): title = line[1:].strip() elif line.startswith('title:'): title = line[6:].strip() elif line.startswith('description:'): description = line[12:].stri...
<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_meta(cls, line, kwargs): """ Process a line of metadata found in the markdown. Lines are usually in the format of "key: value". Modify the kw...
if line.startswith('slug:'): kwargs['slug'] = line[5:].strip() elif line.startswith('public:'): try: kwargs['public'] = _str_to_bool(line[7:]) except ValueError: LOG.warning('invalid boolean value for public', exc_info=True) elif line.startswith('private:'): try: kwargs['public'] = 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 from_file(cls, path, **kwargs): """ Given a markdown file, get an Entry object. """
LOG.debug('creating %s from "%s"', cls, path) # the filename will be the default slug - can be overridden later kwargs['slug'] = os.path.splitext(os.path.basename(path))[0] # TODO: ideally this should be part of the Post class. # if a pubdate isn't explicitly passed, get it from the file metadata # inste...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_tag(cls, tag_name): """ Make a Tag object from a tag name. Registers it with the content manager if possible. """
if cls.cm: return cls.cm.make_tag(tag_name) return Tag(tag_name.strip())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_model(self, m): """Set the model for the level :param m: the model that the level should use :type m: QtCore.QAbstractItemModel :returns: None :rtype: No...
self._model = m self.new_root.emit(QtCore.QModelIndex()) self.model_changed(m)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_model(self, model): """Set all levels\' model to the given one :param m: the model that the levels should use :type m: QtCore.QAbstractItemModel :returns...
# do the set model in reverse! # set model might trigger an update for the lower levels # but the lower ones have a different model, so it will fail anyways # this way the initial state after set_model is correct. self.model = model self._levels[0].set_model(model)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_root(self, depth, index): """Set the level\'s root of the given depth to index :param depth: the depth level :type depth: int :param index: the new root ...
if depth < len(self._levels): self._levels[depth].set_root(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 _new_level(self, depth): """Create a new level and header and connect signals :param depth: the depth level :type depth: int :returns: None :rtype: None :rai...
l = self.create_level(depth) h = self.create_header(depth) self.add_lvl_to_ui(l, h) l.new_root.connect(partial(self.set_root, depth+1)) self._levels.append(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 set_root(self, index): """Set the given index as root index of the combobox :param index: the new root index :type index: QtCore.QModelIndex :returns: None :...
if not index.isValid(): self.setCurrentIndex(-1) return if self.model() != index.model(): self.setModel(index.model()) self.setRootModelIndex(index) if self.model().rowCount(index): self.setCurrentIndex(0) else: self.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 selected_indexes(self, ): """Return the current index :returns: the current index in a list :rtype: list of QtCore.QModelIndex :raises: None """
i = self.model().index(self.currentIndex(), 0, self.rootModelIndex()) return [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 create_header(self, depth): """Create and return a widget that will be used as a header for the given depth Override this method if you want to have header w...
if not (depth >= 0 and depth < len(self._headertexts)): return txt = self._headertexts[depth] if txt is None: return lbl = QtGui.QLabel(txt, self) return lbl
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def model_changed(self, model): """Apply the model to the combobox When a level instance is created, the model is None. So it has to be set afterwards. Then this...
self.setModel(model) # to update all lists belwo # current changed is not triggered by setModel somehow if model is not None: self.setCurrentIndex(self.model().index(0, 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 set_root(self, index): """Set the given index as root index of list :param index: the new root index :type index: QtCore.QModelIndex :returns: None :rtype: N...
if not index.isValid(): self.setModel(None) # so we will not see toplevel stuff self.setCurrentIndex(QtCore.QModelIndex()) self.new_root.emit(QtCore.QModelIndex()) return if self.model() != index.model(): self.setModel(index.model()) 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 set_index(self, index): """Set the current index to the row of the given index :param index: the index to set the level to :type index: QtCore.QModelIndex :r...
self.setCurrentIndex(index) self.new_root.emit(index) self.scrollTo(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 resizeEvent(self, event): """Schedules an item layout if resize mode is \"adjust\". Somehow this is needed for correctly scaling down items. The reason this ...
if self.resizeMode() == self.Adjust: self.scheduleDelayedItemsLayout() return super(ListLevel, self).resizeEvent(event)
<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_level(self, depth): """Create and return a level for the given depth The model and root of the level will be automatically set by the browser. :param ...
ll = ListLevel(parent=self) ll.setEditTriggers(ll.DoubleClicked | ll.SelectedClicked | ll.CurrentChanged) #ll.setSelectionBehavior(ll.SelectRows) ll.setResizeMode(ll.Adjust) self.delegate = CommentDelegate(ll) ll.setItemDelegate(self.delegate) ll.setVerticalScrol...
<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_first_lang(): """Get the first lang of Accept-Language Header. """
request_lang = request.headers.get('Accept-Language').split(',') if request_lang: lang = locale.normalize(request_lang[0]).split('.')[0] else: lang = False return lang
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_dict(dictionary, value, command='set', *keys): """ set_dict takes a dictionary, the value to enter into the dictionary, a command of what to do with the ...
existing = dictionary for i in range(0, len(keys) - 1): if keys[i] in existing: existing = existing[keys[i]] else: existing[keys[i]] = existing.__class__() existing = existing[keys[i]] if command == 'set': existing[keys[len(keys) - 1]] = 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 search_by_re_list(re_list, text): """ Given a list of compiled regular expressions, try to search in text with each matcher until the first match occurs. Ret...
for matcher in re_list: m = matcher.search(text) if m: return m.groupdict() 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 extract_code(lines, node, lstrip="", ljoin="\n", strip=""): """Get corresponding text in the code Arguments: lines -- code splitted by linebreak node -- PyPo...
first_line, first_col = node.first_line - 1, node.first_col last_line, last_col = node.last_line - 1, node.last_col if first_line == last_line: return lines[first_line][first_col:last_col].strip(strip) result = [] # Add first line result.append(lines[first_line][first_col:].strip(lstri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dnode(self, node): """Duplicate node and adjust it for deslocated line and column"""
new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dposition(self, node, dcol=0): """Return deslocated line and column"""
nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol)