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}'.format(dinfo_work_dir))
ctx.run('cp {0} {1}'.format(os.path.join(DOCKER_COMMON_DIR, 'sudo-as-user.sh'), dinfo_work_dir))
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_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 sources
build_src(ctx, dest=debbuild_dir)
src_archive = glob.glob(os.path.join(debbuild_dir, 'mssh-copy-id-*.tar.gz'))[0]
ctx.run('tar -xvf {0} -C {1}'.format(src_archive, debbuild_dir))
src_dir = src_archive[:-7] # uncompressed directory
ctx.run('cp -r {0} {1}'.format(os.path.join(PROJECT_DIR, 'deb/debian'), src_dir))
# Build the deb
ctx.run('docker run -e LOCAL_USER_ID={local_user_id} -v {local}:{cont} {img}'
.format(local_user_id=os.getuid(),
local=debbuild_dir,
cont='/deb',
img=DOCKER_IMGS[target]['name']))
ctx.run('mv -f {0} {1}'.format(os.path.join(debbuild_dir, 'mssh-copy-id_*.deb'), DIST_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 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(rpmbuild_dir, d)
for d in ('BUILD', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS'))))
# Copy the sources & spec file
build_src(ctx, dest=os.path.join(rpmbuild_dir, 'SOURCES'))
ctx.run('cp -f {0} {1}'.format(os.path.join(PROJECT_DIR, 'rpm/centos/mssh-copy-id.spec'),
os.path.join(rpmbuild_dir, 'SPECS')))
# Build the RPM
ctx.run('docker run -e LOCAL_USER_ID={local_user_id} -v {local}:{cont} {img}'
.format(local_user_id=os.getuid(),
local=rpmbuild_dir,
cont='/rpmbuild',
img=DOCKER_IMGS[target]['name']))
ctx.run('mv -f {0} {1}'.format(os.path.join(rpmbuild_dir, 'RPMS/noarch/mssh-copy-id-*.rpm'), DIST_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 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 directory for gendoc. Can be a relative path. :type source: str :param dest: The destination for the rst files. Can be a relative path. :type dest: str :param args: Arguments for gendoc. See gendoc for more information. :type args: list :returns: None :rtype: None :raises: SystemExit """ |
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 :raises: 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_dir(odir, not args.nodelete)
print '\nRunning gendoc'
print '='*80
for i, idir in enumerate(args.input):
if i >= len(args.output):
odir = args.output[-1]
else:
odir = args.output[i]
run_gendoc(idir, odir, args.gendocargs) |
<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(modules, key=lambda name: int(name.split("_")[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 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),
'migration': kwargs.get('migration', None),
'transaction': kwargs.get('transaction', True),
}
Migration._meta.database = database
migrator = DATABASE_MAP[engine](database, module, **options)
migrator.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 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()
if exists and self.direction == 'up':
cprint("This migration has already been run on this server", "red")
if not self.force or self.fake:
return False
else:
cprint("Force running this migration again", "yellow")
# Load the module
module_name = "%s.%s" % (self.module_name, migration)
try:
module = importlib.import_module(module_name)
if not hasattr(module, self.direction):
raise MigrationException("%s doesn't have %s migration defined" %
(migration, self.direction)
)
# Actually execute the direction method
# Note that this doesn't actually run the migrations in the DB yet.
# This merely collects the steps in the migration, so that if needed
# we can just fake it and print out the SQL query as well.
getattr(module, self.direction)(self)
# Print out each migration and execute it
for op in self.operations:
self.execute_operation(op)
if not self.fake:
# If successful, create the entry in our log
if self.direction == 'up' and not exists:
Migration.create(name=migration)
elif self.direction == 'down' and exists:
exists.delete_instance()
cprint("Done", "green")
except ImportError:
raise MigrationException("%s migration not found" % migration) |
<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 Capturing() as code:
pwiz.print_models(introspector)
code = '\n'.join(code)
# Unfortunately, introspect.getsource doesn't seem to work
# with dynamically created classes unless it is written out
# to a file. So write it out to a temporary file
with open(out_file, 'w') as file_:
file_.write(code)
# Load up the DB models as a new module so that we can
# compare them with those in the model definition
return imp.load_source('db_models', out_file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 subject identifier is already set. """ |
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:
raise RegisteredSubjectError(
'Subject identifier cannot be changed for '
'existing registered subject. Got {} <> {}.'.format(
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 component descriptor. If name cannot be determined it returns a defaultName. :param config: configuration parameters that may contain a component name. :param default_name: (optional) a default component name. :return: resolved name or default name if the name cannot be determined. """ |
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 != None:
name = descriptor.get_name()
return name if name != None else default_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 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 "",
kwargs=reprkwargs(kwargs, sep), keywords=keywords 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]
except IndexError:
pass
if defs:
args, kwkeys = args[:-len(defs)], args[-len(defs):]
kwargs = dict(zip(kwkeys, defs))
if varargs:
args.append('*' + varargs)
if method:
args.insert(0, 'self')
return reprcall(name, map(str, args), kwargs, keywords,
argfilter=str) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 beginning and an end point subtracting out non-office time """ |
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:
end = datetime.datetime.now()
zero = datetime.timedelta(0)
# Make sure that the work day is valid
assert(zero <= workday_start <= workday_end <= datetime.timedelta(1))
# Get the workday delta
workday = workday_end - workday_start
# Get the number of days it took
days = (end - start).days + 1
# Number of weeks
weeks = days // 7
# Get the number of days in addition to weeks
extra = (max(0, 5 - start.weekday()) + min(5, 1 + end.weekday())) % 5
# Get the number of working days
weekdays = weeks * 5 + extra
# Get the total time spent accounting for the workday
total = workday * weekdays
if start.weekday() < 5:
# Figuring out how much time it wasn't being worked on and subtracting
total -= clamp(day_part(start) - workday_start, zero, workday)
if end.weekday() < 5:
# Figuring out how much time it wasn't being worked on and subtracting
total -= clamp(workday_end - day_part(end), zero, workday)
cycle_time = timedelta_total_seconds(total) / timedelta_total_seconds(workday)
return cycle_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 parse_definition_expr(expr, default_value=None):
""" Parses a definition expression and returns a key-value pair as a tuple. Each definition expression should be in one of these two formats: * <variable>=<value> * <variable> :param expr: String expression to be parsed. :param default_value: (Default None) When a definition is encountered that has no value, this will be used as its value. :return: A (define, value) tuple or raises a ``ValueError`` if an invalid definition expression is provided. or raises ``AttributeError`` if None is provided for ``expr``. Usage: ('DEBUG', 1) ('FOOBAR', 64) ('FOOBAR', 'whatever') ('FOOBAR', False) ('FOOBAR', True) ('FOOBAR', None) ('FOOBAR', 1) ('FOOBAR', 'ah=3') ('FOOBAR', 'ah=3 ') ('FOOBAR', 'ah=3 ') ('FOOBAR', ' ah=3 ') Traceback (most recent call last):
ValueError: Invalid definition symbol ` ` Traceback (most recent call last):
AttributeError: 'NoneType' object has no attribute 'split' """ |
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("Invalid definition expression `%s`" % str(expr))
d = define.strip()
if d:
return d, value
else:
raise ValueError("Invalid definition symbol `%s`" % str(define)) |
<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 line macro definitions. Each item in the list should be in one of these two formats: * <variable>=<value> * <variable> :return: ``dict`` as symbol table or raises an exception thrown by :func:``parse_definition_expr``. Usage:: {'DEBUG': 1} {'DEBUG': False, 'FOOBAR': 64} {'FOOBAR': 'whatever'} {'FOOBAR': None} {'FOOBAR': 'ah=3'} {} {} """ |
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 specified at command line. :param should_be_quiet: Boolean value for the -q option. :return: logging level ``int`` or None """ |
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:
logging_handler = NullLoggingHandler()
else:
logger.setLevel(logging_level)
logging_handler = logging.StreamHandler()
logging_handler.setLevel(logging_level)
logging_handler.setFormatter(
logging.Formatter(
"%(asctime)s:%(name)s:%(levelname)s: %(message)s"
)
)
logger.addHandler(logging_handler)
return logging_level |
<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:
content_types_db.add_config_file(config_file)
output_filename = args.output_filename
with open(args.input_filename, 'rb') as input_file:
if output_filename is None:
# No output file specified. Will output to stdout.
preprocess(input_file=input_file,
output_file=sys.stdout,
defines=defines,
options=args,
content_types_db=content_types_db)
else:
if os.path.exists(output_filename):
if args.should_force_overwrite:
# Overwrite existing file.
with open(output_filename, 'wb') as output_file:
preprocess(input_file=input_file,
output_file=output_file,
defines=defines,
options=args,
content_types_db=content_types_db)
else:
raise IOError("File `%s` exists - cannot overwrite. (Use -f to force overwrite.)" % args.output_filename)
else:
# File doesn't exist and output file is provided, so write.
with open(output_filename, 'wb') as output_file:
preprocess(input_file=input_file,
output_file=output_file,
defines=defines,
options=args,
content_types_db=content_types_db)
except PreprocessorError, ex:
if logging_level == logging.DEBUG:
import traceback
traceback.print_exc(file=sys.stderr)
else:
sys.stderr.write("pepe: error: %s\n" % str(ex))
return 1
return 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 register(self, service, provider, singleton=False):
""" Registers a service provider for a given service. @param service A key that identifies the service being registered. @param provider This is either the service being registered, or a callable that will either instantiate it or return it. @param singleton Indicates that the service is to be registered as a singleton. This is only relevant if the provider is a callable. Services that are not callable will always be registered as singletons. """ |
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
# Providers are always registered in self.providers as callable methods
if not callable(provider):
self._set_provider(service, lambda *args, **kwargs: provider)
elif singleton:
self._set_provider(service, get_singleton)
else:
self._set_provider(service, self._get_instantiator(provider)) |
<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):
Sequence of callable metrics, each accepting the algorithm state as parameter and returning the measured value with its label: measurement(state) -> (label, value). Returns: tuple(dict, callable):
dictionary result type and a collection function accepting the current results and the state as arguments and returning updated result. Examples: """ |
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 containing new metrics.
"""
for measurement in metrics:
(label, value) = measurement(state)
iteration_dict = results.get(state.iterations, {})
iteration_dict[label] = str(value)
results[state.iterations] = iteration_dict
return results
return {}, collect |
<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 to create a compare for. Returns: callable: Function accepting two objectives to compare. Examples: """ |
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()),
write_method=generate_write_yaml_to_file(config_file)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 for the placeholder :type text: str :raises: None """ |
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(self.viewport().geometry(), QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop, self._placeholder)
p.setPen(oldpen)
else:
return super(JB_PlainTextEdit, self).paintEvent(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 calcEvenAnchors(args):
""" Calculates anchor points evenly spaced across the world, given user-specified parameters. Note: May not be exactly even if world size is not divisible by patches+1. Note: Eveness is based on bounded world, not toroidal. """ |
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 and worldsize. The number of anchors to generate is given by nPatches """ |
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 lists to the given list of anchors """ |
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 cells away from their nearest neighbors. """ |
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:
anchors = list(set(anchors))
anchors.sort()
if dsout != 1:
return (anchors +
calcTightAnchors(args, d, patches-2)
)[:patches*patches]
# to cut off the extras in the case where d=0
else:
# Note - an odd number of args.patchesPerSide requires that there be
# a patch at the centerpoint
dsout = int((patches-1)//2)
add_anchors(centerPoint, d, dsout, anchors, False)
if dsout != 1:
return anchors + calcTightAnchors(d, patches-2)
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 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:
randResources.append(res + str(nEach))
random.shuffle(randResources)
return randResources |
<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, if any, enclosed in parentheses. Ex: deb http://example.com/deb lucid main (http://example.com/key) """ |
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 -d %s" % name)
if key_file:
sudo(u"mkdir -p /home/%s/.ssh" % name)
put(key_file, u"/home/%s/.ssh/authorized_keys" % name, use_sudo=True)
sudo(u"chown -R %(name)s:%(name)s /home/%(name)s/.ssh" % {'name': 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 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.use_ssl
)
connection = ldap3.Connection(server, user=user_dn, password=password)
return connection.bind() |
<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 returns to location in file when handle passed to binary_guesser. Args: handle (file):
File handle of file thought to be binary num_bytes (int):
Bytes of file to read to guess binary, more bytes is often better but takes longer Raises: FormatError: Error raised if file is not likely binary Example: The following example demonstrate how to use binary_guesser. Note: These doctests will not pass, examples are only in doctest format as per convention. bio_utils uses pytests for testing. """ |
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_chars)
handle.seek(handle_location) # Return to original handle location
if float(len(filtered_block)) / float(len(first_block)) > 0.30:
pass # File is likely binary
else:
msg = '{0} is probably not a binary file'.format(handle.name)
raise FormatError(message=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 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 the uifile :type uifile: str :returns: None :rtype: None :raises: None """ |
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 -- code text Keyword Arguments: filename -- code path mode -- execution mode (exec, eval, single) tree -- current tree, if it was optimized """ |
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 Node or tuple Keyword Arguments: path -- code path mode -- execution mode (exec, eval, single) tree -- current tree, if it was optimized """ |
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:
sys.path.insert(self.index, path)
self.index += 1
else:
sys.path.append(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 generate(data, algorithms=(DEFAULT_ALOGRITHM,)):
"""Yields subresource integrity Hash objects for the given data & algorithms sha384 H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO """ |
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-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO' sha256-qznLcsROx4GACP2dm0UCKCzCG+HiZ1guq6ZZDob/Tng= sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO """ |
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 Unrecognised hash algorithms are discarded [] """ |
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 overwrite this with an endpoint on endpoint load :param username: str of the user name to login in as :param password: str of the password to login as :param login_url: str of the url for the server's login :param auth_url: str of the url for the server's authorization login :return: str of self._status """ |
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 <DateTime=None|int=None> if specified return all objects modified since that specified time. If integer is submitted it is treated like a unix timestamp version <int=None> if specified return all objects with a version greater then the one specified deleted <bool=False> if true include soft-deleted objects in the result Either timestamp or version needs to be provided """ |
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)
)
if version is not None:
qset = qset.filter(version__gt=version)
if not deleted:
qset = qset.undeleted()
return qset |
<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 (bool):
Permit ambiguous bases, i.e. permit non-ACGTU bases Raises: FormatError: Error when FASTQ format incorrect with descriptive message Example: """ |
if ambiguous:
regex = r'^@.+{0}[ACGTURYKMSWBDHVNX]+{0}' \
r'\+.*{0}[!"#$%&\'()*+,-./0123456' \
r'789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
r'[\]^_`abcdefghijklmnopqrstuvwxyz' \
r'{{|}}~]+{0}$'.format(os.linesep)
else:
regex = r'^@.+{0}[ACGTU]+{0}' \
r'\+.*{0}[!-~]+{0}$'.format(os.linesep)
delimiter = r'{0}'.format(os.linesep)
for entry in entries:
if len(entry.sequence) != len(entry.quality):
msg = 'The number of bases in {0} does not match the number ' \
'of quality scores'.format(entry.id)
raise FormatError(message=msg)
try:
entry_verifier([entry.write()], regex, delimiter)
except FormatError as error:
if error.part == 0:
msg = 'Unknown Header Error with {0}'.format(entry.id)
raise FormatError(message=msg)
elif error.part == 1 and ambiguous:
msg = '{0} contains a base not in ' \
'[ACGTURYKMSWBDHVNX]'.format(entry.id)
raise FormatError(message=msg)
elif error.part == 1 and not ambiguous:
msg = '{0} contains a base not in ' \
'[ACGTU]'.format(entry.id)
raise FormatError(message=msg)
elif error.part == 2:
msg = 'Unknown error with line 3 of {0}'.format(entry.id)
raise FormatError(message=msg)
elif error.part == 3:
msg = r'{0} contains a quality score not in ' \
r'[!-~]'.format(entry.id)
raise FormatError(message=msg)
else:
msg = '{0}: Unknown Error: Likely a Bug'.format(entry.id)
raise FormatError(message=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 validate_configuration(self):
""" Validates the provided settings. * Checks ``inherit_image`` format. * Checks ``use_registry_name`` format. * Checks that ``apt_dependencies`` is not set when ``inherit_image`` is set. :raise ArcaMisconfigured: If some of the settings aren't valid. """ |
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 'inherit_image'"
f"setting")
if self.inherit_image is not None and self.get_dependencies() is not None:
raise ArcaMisconfigured("An external image is used as a base image, "
"therefore Arca can't install dependencies.")
if self.use_registry_name is not None:
try:
assert 2 >= len(str(self.inherit_image).split("/")) <= 3
except ValueError:
raise ArcaMisconfigured(f"Registry '{self.use_registry_name}' is not valid value for the "
f"'use_registry_name' setting.") |
<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 dependencies can't be converted into a list of strings :return: List of dependencies, ``None`` if there are none. """ |
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(dependencies):
return None
dependencies.sort()
return dependencies |
<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 with installed requirements and dependencies. """ |
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 for images with the dependencies and requirements installed. 64-byte hexadecimal strings cannot be used as docker tags, so the prefixes are necessary. Double hashing the dependencies and requirements hash to make the final tag shorter. Prefixes: * Image type: * i – Inherited image * a – Arca base image * Requirements: * r – Does have some kind of requirements * s – Doesn't have requirements * Dependencies: * d – Does have dependencies * e – Doesn't have dependencies Possible outputs: * Inherited images: * `ise` – no requirements * `ide_<hash(requirements)>` – with requirements * From Arca base image: * `<Arca version>_<Python version>_ase` – no requirements and no dependencies * `<Arca version>_<Python version>_asd_<hash(dependencies)>` – only dependencies * `<Arca version>_<Python version>_are_<hash(requirements)>` – only requirements * `<Arca version>_<Python version>_ard_<hash(hash(dependencies) + hash(requirements))>` – both requirements and dependencies """ |
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 += "d" if dependencies is not None else "e"
if self.inherit_image is not None:
if requirements_hash:
return prefix + "_" + requirements_hash
return prefix
if dependencies is None:
dependencies_hash = ""
else:
dependencies_hash = self.get_dependencies_hash(dependencies)
if requirements_hash and dependencies_hash:
return prefix + "_" + hashlib.sha256(bytes(requirements_hash + dependencies_hash, "utf-8")).hexdigest()
elif requirements_hash:
return f"{prefix}_{requirements_hash}"
elif dependencies_hash:
return f"{prefix}_{dependencies_hash}"
else:
return 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 pull isn't disabled, otherwise builds them by the definition in ``dockerfile``. :param name: Name of the image :param tag: Image tag :param dockerfile: Dockerfile text or a callable (no arguments) that produces Dockerfile text :param pull: If the image is not present locally, allow pulling from registry (default is ``True``) :param build_context: A path to a folder. If it's provided, docker will build the image in the context of this folder. (eg. if ``ADD`` is needed) """ |
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 was pulled from registry", name, tag)
return
except docker.errors.APIError:
logger.info("The image %s:%s can't be pulled, building locally.", name, tag)
if callable(dockerfile):
dockerfile = dockerfile()
try:
if build_context is None:
fileobj = BytesIO(bytes(dockerfile, "utf-8")) # required by the docker library
self.client.images.build(
fileobj=fileobj,
tag=f"{name}:{tag}"
)
else:
dockerfile_file = build_context / "dockerfile"
dockerfile_file.write_text(dockerfile)
self.client.images.build(
path=str(build_context.resolve()),
dockerfile=dockerfile_file.name,
tag=f"{name}:{tag}"
)
dockerfile_file.unlink()
except docker.errors.BuildError as e:
for line in e.build_log:
if isinstance(line, dict) and line.get("errorDetail") and line["errorDetail"].get("code") in {124, 143}:
raise BuildTimeoutError(f"Installing of requirements timeouted after "
f"{self.requirements_timeout} seconds.")
logger.exception(e)
raise BuildError("Building docker image failed, see extra info for details.", extra_info={
"build_log": e.build_log
}) |
<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: Returns the name and the tag of the image. :raise ArcaMisconfiguration: If the image can't be pulled from registries. """ |
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 should inherit "
f"can't be pulled")
return 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_with_installed_dependencies(self, image_name: str, dependencies: Optional[List[str]]) -> Tuple[str, str]: """ Return name and tag of a image, based on the Arca python image, with installed dependencies defined by ``apt_dependencies``. :param image_name: Name of the image which will be ultimately used for the image. :param dependencies: List of dependencies in the standardized format. """ |
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)
return self.INSTALL_DEPENDENCIES.format(
name=python_name,
tag=python_tag,
dependencies=" ".join(self.get_dependencies())
)
image_tag = self.get_image_tag(RequirementsOptions.no_requirements, None, dependencies)
self.get_or_build_image(image_name, image_tag, install_dependencies_dockerfile,
pull=not self.disable_pull)
return image_name, image_tag
else:
return 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 an image for specific requirements and dependencies, based on the settings. :param image_name: How the image should be named :param image_tag: And what tag it should have. :param repo_path: Path to the cloned repository. :param requirements_option: How requirements are set in the repository. :param dependencies: List of dependencies (in the formalized format) :return: The Image instance. :rtype: docker.models.images.Image """ |
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 no dependencies, just return the basic image with the correct python installed
if dependencies is None:
base_name, base_tag = self.get_python_base(python_version, pull=not self.disable_pull)
image = self.get_image(base_name, base_tag)
# tag the image so ``build_image`` doesn't have to be called next time
image.tag(image_name, image_tag)
return image
# extend the image with correct python by installing the dependencies
def install_dependencies_dockerfile():
base_name, base_tag = self.get_python_base(python_version, pull=not self.disable_pull)
return self.INSTALL_DEPENDENCIES.format(
name=base_name,
tag=base_tag,
dependencies=" ".join(dependencies)
)
self.get_or_build_image(image_name, image_tag, install_dependencies_dockerfile)
return self.get_image(image_name, image_tag)
else: # doesn't have to be here, but the return right above was confusing
def install_requirements_dockerfile():
""" Returns a Dockerfile for installing pip requirements,
based on a image with installed dependencies (or no extra dependencies)
"""
dependencies_name, dependencies_tag = self.get_image_with_installed_dependencies(image_name,
dependencies)
return self.get_install_requirements_dockerfile(
name=dependencies_name,
tag=dependencies_tag,
repo_path=repo_path,
requirements_option=requirements_option,
)
self.get_or_build_image(image_name, image_tag, install_requirements_dockerfile,
build_context=repo_path.parent, pull=False)
return self.get_image(image_name, image_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 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.images.Image :raise PushToRegistryError: If the push fails. """ |
# 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 at the end of output
# the last can have one of two outputs, either
# {"progressDetail":{},"aux":{"Tag":"<tag>","Digest":"sha256:<hash>","Size":<size>}}
# when the push is successful, or
# {"errorDetail": {"message":"<error_msg>"},"error":"<error_msg>"}
# when the push is not successful
last_line = json.loads(result.split("\n")[-1])
if "error" in last_line:
self.client.images.remove(f"{self.use_registry_name}:{image_tag}")
raise PushToRegistryError(f"Push of the image failed because of: {last_line['error']}", full_output=result)
logger.info("Pushed image to registry %s:%s", self.use_registry_name, image_tag)
logger.debug("Info:\n%s", 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 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.containers.Container>` if it's running, ``None`` otherwise. :rtype: Optional[docker.models.container.Container] """ |
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_bytes))
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_task_definition(self, name: str, contents: str) -> bytes: """ Returns a tar with the task definition. :param name: Name of the file :param contents: Contens of the definition, utf-8 """ |
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))
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 start_container(self, image, container_name: str, repo_path: Path):
""" Starts a container with the image and name ``container_name`` and copies the repository into the container. :type image: docker.models.images.Image :rtype: docker.models.container.Container """ |
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()),
auto_remove=True)
container.exec_run(["mkdir", "-p", "/srv/scripts"])
container.put_archive("/srv", self.tar_files(repo_path))
container.put_archive("/srv/scripts", self.tar_runner())
return container |
<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 for the image and runs the script. :param repo: Repository URL :param branch: Branch ane :param task: :class:`Task` to run. :param git_repo: :class:`Repo <git.repo.base.Repo>` of the cloned repository. :param repo_path: :class:`Path <pathlib.Path>` to the cloned location. """ |
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_container(image, container_name, repo_path)
task_filename, task_json = self.serialized_task(task)
container.put_archive("/srv/scripts", self.tar_task_definition(task_filename, task_json))
res = None
try:
command = ["timeout"]
if self.inherit_image:
if self.alpine_inherited or b"Alpine" in container.exec_run(["cat", "/etc/issue"], tty=True).output:
self.alpine_inherited = True
command = ["timeout", "-t"]
command += [str(task.timeout),
"python",
"/srv/scripts/runner.py",
f"/srv/scripts/{task_filename}"]
logger.debug("Running command %s", " ".join(command))
res = container.exec_run(command, tty=True)
# 124 is the standard, 143 on alpine
if res.exit_code in {124, 143}:
raise BuildTimeoutError(f"The task timeouted after {task.timeout} seconds.")
return Result(res.output)
except BuildError: # can be raised by :meth:`Result.__init__`
raise
except Exception as e:
logger.exception(e)
if res is not None:
logger.warning(res.output)
raise BuildError("The build failed", extra_info={
"exception": e,
"output": res if res is None else res.output
})
finally:
if not self.keep_container_running:
container.kill(signal.SIGKILL)
else:
self._containers.add(container) |
<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 Dockerfile that will install requirements based on the repository, prioritizing Pipfile or Pipfile.lock and falling back on requirements.txt files """ |
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_option == RequirementsOptions.pipfile:
target_file = ""
requirements_files = [repo_path / self.pipfile_location / "Pipfile",
repo_path / self.pipfile_location / "Pipfile.lock"]
install_cmd = "pipenv"
cmd_arguments = "install --system --ignore-pipfile --deploy"
else:
raise ValueError("Invalid requirements_option")
dockerfile = self.INSTALL_REQUIREMENTS.format(
name=name,
tag=tag,
timeout=self.requirements_timeout,
target_file=target_file,
requirements_files=" ".join(str(x.relative_to(repo_path.parent)) for x in requirements_files),
cmd_arguments=cmd_arguments,
install_cmd=install_cmd
)
logger.debug("Installing Python requirements with Dockerfile: %s", dockerfile)
return dockerfile |
<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.name
in_progress = jira.get_datetime_issue_in_progress(issue)
if in_progress:
in_progress_string = in_progress.strftime("%a %x %I:%M %p")
print ' Status: %s as of %s' % (status, in_progress_string)
else:
print ' Status: %s' % status
print ' Assignee: %s' % assignee
# Print the worklogs
# Get the timespent and return 0m if it does not exist
time_spent = '0m'
try:
time_spent = issue.fields.timetracking.timeSpent
except:
pass
worklogs = jira.get_worklog(issue)
print "\nTime logged (%s):" % time_spent
if worklogs:
for worklog in worklogs:
worklog_hash = worklog.raw
author = worklog_hash['author']['name']
time_spent = worklog_hash.get('timeSpent', '0m')
created = dateutil.parser.parse(worklog_hash['started'])
created_pattern = '%a %x ' # Adding extra space for formatting
if not created.hour == created.minute == created.second == 0:
created = created.astimezone(tzlocal())
created_pattern = '%a %x %I:%M %p'
comment = worklog_hash.get('comment', '<no comment>')
updated_string = created.strftime(created_pattern)
print " %s - %s (%s): %s" % (updated_string, author, time_spent, comment)
else:
print " No worklogs"
cycle_time = jira.get_cycle_time(issue)
if cycle_time:
print '\nCycle Time: %.1f days' % cycle_time
# Print the time elapsed since the last mark
elapsed_time = jira.get_elapsed_time(issue)
if elapsed_time:
print '\n\033[0;32m%s elapsed\033[00m (use "jtime log ." to log elapsed time or "jtime log <duration> (ex. 30m, 1h etc.)" to log a specific amount of time)' % (elapsed_time)
else:
print '\n\033[0;32m0m elapsed\033[00m' |
<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, otherwise use the elapsed time since the last mark
duration = jira.get_elapsed_time(issue) if duration == '.' else duration
if duration:
# Add the worklog
jira.add_worklog(issue, timeSpent=duration, adjustEstimate=None, newEstimate=None, reduceBy=None,
comment=comment)
print "Logged %s against issue %s (%s)" % (duration, branch, comment)
else:
print "No time logged, less than 0m elapsed." |
<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 = datetime.datetime.now(dateutil.tz.tzlocal()).strftime("%I:%M %p")
print "Set mark at %s on %s by touching last work log" % (mark_time, branch)
else:
# If we don't have worklogs, mark the issue as in progress if that is an available transition
jira.workflow_transition(issue, 'Open')
marked = jira.workflow_transition(issue, 'In Progress')
mark_time = datetime.datetime.now(dateutil.tz.tzlocal()).strftime("%I:%M %p")
print 'Set mark at %s on %s by changing status to "In Progress"' % (mark_time, branch)
if not marked:
print "ERROR: Issue %s is has a status of %s and has no worklogs. You must log some time or re-open the issue to proceed." % \
(branch, issue.fields.status.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 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):
logging.error('It appears that your configuration is invalid, please reconfigure the app and try again.')
configure()
init()
parser = argparse.ArgumentParser()
# Now simply auto-discovering the methods listed in this module
current_module = sys.modules[__name__]
module_methods = [getattr(current_module, a, None) for a in dir(current_module)
if isinstance(getattr(current_module, a, None), types.FunctionType)
and a != 'main']
argh.add_commands(parser, module_methods)
# Putting the error logging after the app is initialized because
# we want to adhere to the user's preferences
try:
argh.dispatch(parser)
# We don't want to report keyboard interrupts to rollbar
except (KeyboardInterrupt, SystemExit):
raise
except Exception as e:
if isinstance(e, jira.exceptions.JIRAError) and "HTTP 400" in e:
logging.warning('It appears that your authentication with {0} is invalid. Please re-configure jtime: `jtime configure` with the correct credentials'.format(configuration.load_config['jira'].get('url')))
elif configured.get('jira').get('error_reporting', True):
# Configure rollbar so that we report errors
import rollbar
from . import __version__ as version
root_path = os.path.dirname(os.path.realpath(__file__))
rollbar.init('7541b8e188044831b6728fa8475eab9f', 'v%s' % version, root=root_path)
logging.error('Sorry. It appears that there was an error when handling your command. '
'This error has been reported to our error tracking system. To disable '
'this reporting, please re-configure the app: `jtime config`.')
extra_data = {
# grab the command that we're running
'cmd': sys.argv[1],
# we really don't want to see jtime in the args
'args': sys.argv[2:],
# lets grab anything useful, python version?
'python': str(sys.version),
}
# We really shouldn't thit this line of code when running tests, so let's not cover it.
rollbar.report_exc_info(extra_data=extra_data) # pragma: no cover
else:
logging.error('It appears that there was an error when handling your command.')
raise |
<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 markdown where you provide values for attributes like public - this can be done by overriding the process_meta method. """ |
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:].strip()
elif line.startswith('subtitle:'):
kwargs['subtitle'] = line[9:].strip()
elif line.startswith('comments:'):
try:
kwargs['allow_comments'] = _str_to_bool(line[9:])
except ValueError:
LOG.warning('invalid boolean value for comments', exc_info=True)
cls.process_meta(line, kwargs)
line = lines.pop(0)
# the only lines left should be the actual contents
body = '\n'.join(lines).strip()
excerpt = _get_excerpt(body)
if description is None:
description = _get_description(excerpt, 160)
if issubclass(cls, Post):
kwargs['excerpt'] = render_markdown(excerpt)
body = render_markdown(body)
return cls(title=title, body=body, description=description, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 kwargs dict in order to change or add new kwargs that should be passed to the class's constructor. """ |
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 _str_to_bool(line[8:])
except ValueError:
LOG.warning('invalid boolean value for private', exc_info=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 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
# instead. note that it might still be overriden later on while reading
# the file contents.
if issubclass(cls, Post) and not kwargs.get('pubdate'):
# you would think creation always comes before modification, but you
# can manually modify a file's modification date to one earlier than
# the creation date. this lets you set a post's pubdate by running
# the command `touch`. we support this behaviour by simply finding
# the chronologically earliest date of creation and modification.
timestamp = min(os.path.getctime(path), os.path.getmtime(path))
kwargs['pubdate'] = datetime.fromtimestamp(timestamp)
with open(path, 'r') as file:
entry = cls.from_string(file.read(), **kwargs)
return entry |
<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: None :raises: None """ |
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: None :rtype: None :raises: None """ |
# 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 index :type index: QtCore.QModelIndex :returns: None :rtype: None :raises: None """ |
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 :raises: None """ |
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 :rtype: None :raises: 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.setCurrentIndex(-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 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 widgets. The default implementation returns None. You can return None if you do not want a header for the given depth :param depth: the depth level :type depth: int :returns: a Widget that is used for the header or None :rtype: QtGui.QWidget|None :raises: None """ |
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 method will be called and your level should somehow use the model :param model: the model that the level should use :type model: QtCore.QAbstractItemModel :returns: None :rtype: None :raises: None """ |
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: None :raises: None """ |
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())
self.setRootIndex(index)
if self.model().hasChildren(index):
self.setCurrentIndex(self.model().index(0, 0, index))
self.new_root.emit(self.model().index(0, 0, index))
else:
self.new_root.emit(QtCore.QModelIndex()) |
<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 :returns: None :rtype: None :raises: None """ |
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 was reimplemented was the CommentDelegate. :param event: the resize event :type event: QtCore.QEvent :returns: None :rtype: None :raises: None """ |
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 depth: the depth level that the level should handle :type depth: int :returns: a new level for the given depth :rtype: :class:`jukeboxcore.gui.widgets.browser.AbstractLevel` :raises: None """ |
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.setVerticalScrollMode(ll.ScrollPerPixel)
return ll |
<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 value, and a sequence of keys. d = {} set_dict(d,1,'append','level 1','level 2') -> d['level 1']['level 2'] = [1] set_dict(d,2,'append','level 1','level 2') -> d['level 1']['level 2'] = [1,2] """ |
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
elif command == 'append':
if keys[len(keys) - 1] in existing:
existing[keys[len(keys) - 1]].append(value)
else:
existing[keys[len(keys) - 1]] = [value]
elif command == 'set_or_append':
if keys[len(keys) - 1] in existing:
if type(keys[len(keys) - 1]) == type([]):
existing[keys[len(keys) - 1]].append(value)
else:
existing[keys[len(keys) - 1]] = [existing[keys[len(keys) - 1]], value]
else:
existing[keys[len(keys) - 1]] = value
elif command == 'insert':
if keys[len(keys) - 1] in existing:
if not value in existing[keys[len(keys) - 1]]:
existing[keys[len(keys) - 1]].append(value)
else:
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. Return the group-dict for that first match. """ |
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 -- PyPosAST enhanced node Keyword Arguments: lstrip -- During extraction, strip lines with this arg (default="") ljoin -- During extraction, join lines with this arg (default="\n") strip -- After extraction, strip all code with this arg (default="") """ |
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(lstrip))
# Add middle lines
if first_line + 1 != last_line:
for line in range(first_line + 1, last_line):
result.append(lines[line].strip(lstrip))
# Add last line
result.append(lines[last_line][:last_col].strip(lstrip))
return ljoin.join(result).strip(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 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) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.