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 write_debug_log(self, file_path):
""" Write the debug log to a file """ |
with open(file_path, "wb+") as fh:
fh.write(system.get_system_info().encode('utf-8'))
# writing to debug stream
self._debug_stream.seek(0)
fh.write(self._debug_stream.read().encode('utf-8'))
fh.write("The following errors occured:\n".encode('utf-8'))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_manifest(self):
""" Write the manifest to the file """ |
if os.path.exists(self.directory.manifest_path):
self.main_manifest.write(open(self.directory.manifest_path, "w+")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def message_failure(self):
""" return a failure message, if one exists """ |
if not isinstance(self.main_manifest, Manifest):
return None
return self.main_manifest.get('config', 'message_failure', default=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 warmup(self):
""" initialize variables necessary to perform a sprinter action """ |
self.logger.debug("Warming up...")
try:
if not isinstance(self.source, Manifest) and self.source:
self.source = load_manifest(self.source)
if not isinstance(self.target, Manifest) and self.target:
self.target = load_manifest(self.target)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _inject_config_source(self, source_filename, files_to_inject):
""" Inject existing environmental config with namespace sourcing. Returns a tuple of the first... |
# src_path = os.path.join(self.directory.root_dir, source_filename)
# src_exec = "[ -r %s ] && . %s" % (src_path, src_path)
src_exec = "[ -r {0} ] && . {0}".format(os.path.join(self.directory.root_dir, source_filename))
# The ridiculous construction above is necessary to avoid failing t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _finalize(self):
""" command to run at the end of sprinter's run """ |
self.logger.info("Finalizing...")
self.write_manifest()
if self.directory.rewrite_config:
# always ensure .rc is written (sourcing .env)
self.directory.add_to_rc('')
# prepend brew for global installs
if system.is_osx() and self.main_manifest.is_... |
<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_logger(self, level=logging.INFO):
""" return a logger. if logger is none, generate a logger from stdout """ |
self._debug_stream = StringIO()
logger = logging.getLogger('sprinter')
# stdout log
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setLevel(level)
logger.addHandler(out_hdlr)
# debug log
debug_hdlr = logging.StreamHandler(self._debug_stream)
... |
<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_action(self, feature, action, run_if_error=False, raise_exception=True):
""" Run an action, and log it's output in case of errors """ |
if len(self._error_dict[feature]) > 0 and not run_if_error:
return
error = None
instance = self.features[feature]
try:
getattr(instance, action)()
# catch a generic exception within a feature
except Exception as e:
e = sys.exc_info()[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _specialize(self, reconfigure=False):
""" Add variables and specialize contexts """ |
# add in the 'root_dir' directories to the context dictionaries
for manifest in [self.source, self.target]:
context_dict = {}
if manifest:
for s in manifest.formula_sections():
context_dict["%s:root_dir" % s] = self.directory.install_directory... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _copy_source_to_target(self):
""" copy source user configuration to target """ |
if self.source and self.target:
for k, v in self.source.items('config'):
# always have source override target.
self.target.set_input(k, v) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grab_inputs(self, reconfigure=False):
""" Resolve the source and target config section """ |
self._copy_source_to_target()
if self.target:
self.target.grab_inputs(force=reconfigure) |
<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_domain(url):
""" parse the domain from the url """ |
domain_match = lib.DOMAIN_REGEX.match(url)
if domain_match:
return domain_match.group() |
<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_credentials(options, environment):
""" Get credentials or prompt for them from options """ |
if options['--username'] or options['--auth']:
if not options['--username']:
options['<username>'] = lib.prompt("Please enter the username for %s..." % environment)
if not options['--password']:
options['<password>'] = lib.prompt("Please enter the password for %s..." % envir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def full_name(self):
""" The full name of the field. This is the field's entities name concatenated with the field's name. If the field is unnamed or not bound t... |
entity = self.entity.__name__ if self.entity is not None else None
name = self.name if self.name is not None else None
if entity and name:
return entity + '.' + name
elif entity:
return entity + '.<unnamed>'
elif name:
return '<unbound>.' + name
else:
return '<unbound>.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def type_name(self):
""" Returns the full type identifier of the field. """ |
res = self.type.__name__
if self.type.__module__ not in ('__builtin__', 'builtins'):
res = self.type.__module__ + '.' + res
return res |
<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_subclass_from_module(module, parent_class):
""" Get a subclass of parent_class from the module at module get_subclass_from_module performs reflection to ... |
try:
r = __recursive_import(module)
member_dict = dict(inspect.getmembers(r))
sprinter_class = parent_class
for v in member_dict.values():
if inspect.isclass(v) and issubclass(v, parent_class) and v != parent_class:
if sprinter_class is parent_class:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __recursive_import(module_name):
""" Recursively looks for and imports the names, returning the module desired currently module with relative imports don't w... |
names = module_name.split(".")
path = None
module = None
while len(names) > 0:
if module:
path = module.__path__
name = names.pop(0)
(module_file, pathname, description) = imp.find_module(name, path)
module = imp.load_module(name, module_file, pathname, descr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def err_exit(msg, rc=1):
"""Print msg to stderr and exit with rc. """ |
print(msg, file=sys.stderr)
sys.exit(rc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_file(self, infile):
"""Read a reST file into a string. """ |
try:
with open(infile, 'rt') as file:
return file.read()
except UnicodeDecodeError as e:
err_exit('Error reading %s: %s' % (infile, e))
except (IOError, OSError) as e:
err_exit('Error reading %s: %s' % (infile, e.strerror or e)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_file(self, html, outfile):
"""Write an HTML string to a file. """ |
try:
with open(outfile, 'wt') as file:
file.write(html)
except (IOError, OSError) as e:
err_exit('Error writing %s: %s' % (outfile, e.strerror or e)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_string(self, rest):
"""Convert a reST string to an HTML string. """ |
try:
html = publish_string(rest, writer_name='html')
except SystemExit as e:
err_exit('HTML conversion failed with error: %s' % e.code)
else:
if sys.version_info[0] >= 3:
return html.decode('utf-8')
return html |
<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_styles(self, html, styles):
"""Insert style information into the HTML string. """ |
index = html.find('</head>')
if index >= 0:
return ''.join((html[:index], styles, html[index:]))
return html |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish_string(self, rest, outfile, styles=''):
"""Render a reST string as HTML. """ |
html = self.convert_string(rest)
html = self.strip_xml_header(html)
html = self.apply_styles(html, styles)
self.write_file(html, outfile)
return outfile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish_file(self, infile, outfile, styles=''):
"""Render a reST file as HTML. """ |
rest = self.read_file(infile)
return self.publish_string(rest, outfile, styles) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upgrade(self):
"""Upgrade the config file. """ |
warn('Upgrading ' + self.filename)
if self.backup_config(self.filename):
return self.write_default_config(self.filename)
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 backup_config(self, filename):
"""Backup the current config file. """ |
backup_name = filename + '-' + self.version
warn('Moving current configuration to ' + backup_name)
try:
shutil.copy2(filename, backup_name)
return True
except (IOError, OSError) as e:
print('Error copying %s: %s' % (filename, e.strerror or e), file=sy... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_default_config(self, filename):
"""Write the default config file. """ |
try:
with open(filename, 'wt') as file:
file.write(DEFAULT_CONFIG)
return True
except (IOError, OSError) as e:
print('Error writing %s: %s' % (filename, e.strerror or e), file=sys.stderr)
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 reset_defaults(self, config_file):
"""Reset defaults. """ |
if not exists(config_file):
err_exit('No such file: %(config_file)s' % locals())
if not isfile(config_file):
err_exit('Not a file: %(config_file)s' % locals())
if not os.access(config_file, os.R_OK):
err_exit('File cannot be read: %(config_file)s' % locals())... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_defaults(self):
"""Create default config file and reload. """ |
self.defaults.write()
self.reset_defaults(self.defaults.filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upgrade_defaults(self):
"""Upgrade config file and reload. """ |
self.defaults.upgrade()
self.reset_defaults(self.defaults.filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_styles(self):
"""Print available styles and exit. """ |
known = sorted(self.defaults.known_styles)
if not known:
err_exit('No styles', 0)
for style in known:
if style == self.defaults.default_style:
print(style, '(default)')
else:
print(style)
sys.exit(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 render_file(self, filename):
"""Convert a reST file to HTML. """ |
dirname, basename = split(filename)
with changedir(dirname):
infile = abspath(basename)
outfile = abspath('.%s.html' % basename)
self.docutils.publish_file(infile, outfile, self.styles)
return outfile |
<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_long_description(self, dirname):
"""Convert a package's long description to HTML. """ |
with changedir(dirname):
self.setuptools.check_valid_package()
long_description = self.setuptools.get_long_description()
outfile = abspath('.long-description.html')
self.docutils.publish_string(long_description, outfile, self.styles)
return outfile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_in_browser(self, outfile):
"""Open the given HTML file in a browser. """ |
if self.browser == 'default':
webbrowser.open('file://%s' % outfile)
else:
browser = webbrowser.get(self.browser)
browser.open('file://%s' % outfile) |
<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):
"""Render and display Python package documentation. """ |
os.environ['JARN_RUN'] = '1'
self.python.check_valid_python()
args = self.parse_options(self.args)
if args:
arg = args[0]
else:
arg = os.curdir
if arg:
arg = expanduser(arg)
if isfile(arg):
outfile = self.render_f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preprocess_cell( self, cell: "NotebookNode", resources: dict, cell_index: int ) -> Tuple["NotebookNode", dict]: """Apply a transformation on each cell. Parame... |
# Get files directory if it has been specified
output_files_dir = resources.get("output_files_dir", None)
# Make sure outputs key exists
if not isinstance(resources["outputs"], dict):
resources["outputs"] = {}
# Loop through all of the attachments in the cell
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def combine_pdf_as_bytes(pdfs: List[BytesIO]) -> bytes: """Combine PDFs and return a byte-string with the result. Arguments --------- pdfs A list of BytesIO repre... |
writer = PdfWriter()
for pdf in pdfs:
writer.addpages(PdfReader(pdf).pages)
bio = BytesIO()
writer.write(bio)
bio.seek(0)
output = bio.read()
bio.close()
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split(self, granularity_after_split, exclude_partial=True):
""" Split a period into a given granularity. Optionally include partial periods at the start and ... |
if granularity_after_split == Granularity.DAY:
return self.get_days()
elif granularity_after_split == Granularity.WEEK:
return self.get_weeks(exclude_partial)
elif granularity_after_split == Granularity.MONTH:
return self.get_months(exclude_partial)
... |
<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_calibration(df, calibration_df, calibration):
'''
Apply calibration values from `fit_fb_calibration` result to `calibration`
object.
'''
from dmf_control_board_firmware import FeedbackResults
for i, (fb_resistor, R_fb, C_fb) in calibration_df[['fb_resistor', 'R_fb', 'C_fb']].iterrows(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config_dict(config):
""" Given a Sphinx config object, return a dictionary of config values. """ |
return dict(
(key, getattr(config, key))
for key in config.values
) |
<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_defn(cls, defn):
"Return the first Repl subclass that works with this"
instances = (subcl(defn) for subcl in cls.__subclasses__())
return next(filter(None, instances)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_colormap(cls, names=[], N=10, show=True, *args, **kwargs):
"""Show a colormap dialog Parameters %(show_colormaps.parameters.no_use_qt)s""" |
names = safe_list(names)
obj = cls(names, N, *args, **kwargs)
vbox = obj.layout()
buttons = QDialogButtonBox(QDialogButtonBox.Close, parent=obj)
buttons.rejected.connect(obj.close)
vbox.addWidget(buttons)
if show:
obj.show()
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_list(args):
"""List all element in pen""" |
for penlist in penStore.data:
puts(penlist + " (" + str(len(penStore.data[penlist])) + ")") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_all(args):
"""List everything recursively""" |
for penlist in penStore.data:
puts(penlist)
with indent(4, ' -'):
for penfile in penStore.data[penlist]:
puts(penfile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_create(args):
"""Creates a list""" |
name = args.get(0)
if name:
penStore.createList(name)
else:
puts("not valid") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_touch_note(args):
"""Create a note""" |
major = args.get(0)
minor = args.get(1)
if major in penStore.data:
if minor is None: # show items in list
for note in penStore.data[major]:
puts(note)
elif minor in penStore.data[major]:
penStore.openNote(major, minor)
else:
penSt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_delete(args):
"""Deletes a node""" |
major = args.get(0)
minor = args.get(1)
if major is not None:
if major in penStore.data:
if minor is None:
if len(penStore.data[major]) > 0:
if raw_input("are you sure (y/n)? ") not in ['y', 'Y', 'yes', 'Yes']:
return ExitStatu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restclient_admin_required(view_func):
""" View decorator that checks whether the user is permitted to view proxy restclients. Calls login_required in case th... |
def wrapper(request, *args, **kwargs):
template = 'access_denied.html'
if hasattr(settings, 'RESTCLIENTS_ADMIN_AUTH_MODULE'):
auth_func = import_string(settings.RESTCLIENTS_ADMIN_AUTH_MODULE)
else:
context = {'error_msg': (
"Your application must defi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def destination_heuristic(data):
""" A heuristic to get the folder with all other files from bib, using majority vote. """ |
counter = collections.Counter()
for entry in data:
file_field = entry['fields'].get('file')
if not file_field:
continue
path = os.path.dirname(file_field)
counter[path] += 1
if not counter: # No paths found
raise click.ClickException(
'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 remove_entry(data, entry):
'''
Remove an entry in place.
'''
file_field = entry['fields'].get('file')
if file_field:
try:
os.remove(file_field)
except IOError:
click.echo('This entry\'s file was missing')
data.remove(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 string_to_basename(s):
'''
Converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
'''
s = s.strip().lower()
s = re.sub(r'[^\w\s-]', '', s)
return re.sub(r'[\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 editor(*args, **kwargs):
'''
Wrapper for `click.edit` that raises an error when None is returned.
'''
result = click.edit(*args, **kwargs)
if result is None:
msg = 'Editor exited without saving, command aborted'
raise click.ClickException(msg)
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 terms(self, facet_name, field, size=10, order=None, all_terms=False, exclude=[], regex='', regex_flags=''):
'''
Allow to specify field facets that return the N most frequent terms.
Ordering: Allow to control the ordering of the terms facets, to be ordered by count, term, reverse_count or re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def backup_file(filename):
""" create a backup of the file desired """ |
if not os.path.exists(filename):
return
BACKUP_SUFFIX = ".sprinter.bak"
backup_filename = filename + BACKUP_SUFFIX
shutil.copyfile(filename, backup_filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inject(self, filename, content):
""" add the injection content to the dictionary """ |
# ensure content always has one trailing newline
content = _unicode(content).rstrip() + "\n"
if filename not in self.inject_dict:
self.inject_dict[filename] = ""
self.inject_dict[filename] += content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit(self):
""" commit the injections desired, overwriting any previous injections in the file. """ |
self.logger.debug("Starting injections...")
self.logger.debug("Injections dict is:")
self.logger.debug(self.inject_dict)
self.logger.debug("Clear list is:")
self.logger.debug(self.clear_set)
for filename, content in self.inject_dict.items():
content = _unicod... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def injected(self, filename):
""" Return true if the file has already been injected before. """ |
full_path = os.path.expanduser(filename)
if not os.path.exists(full_path):
return False
with codecs.open(full_path, 'r+', encoding="utf-8") as fh:
contents = fh.read()
return self.wrapper_match.search(contents) 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 destructive_inject(self, filename, content):
""" Injects the injections desired immediately. This should generally be run only during the commit phase, when ... |
content = _unicode(content)
backup_file(filename)
full_path = self.__generate_file(filename)
with codecs.open(full_path, 'r', encoding="utf-8") as f:
new_content = self.inject_content(f.read(), content)
with codecs.open(full_path, 'w+', encoding="utf-8") as f:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __generate_file(self, file_path):
""" Generate the file at the file_path desired. Creates any needed directories on the way. returns the absolute path of the... |
file_path = os.path.expanduser(file_path)
if not os.path.exists(os.path.dirname(file_path)):
self.logger.debug("Directories missing! Creating directories for %s..." % file_path)
os.makedirs(os.path.dirname(file_path))
if not os.path.exists(file_path):
open(fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_noninjected_file(self, file_path, content):
""" Checks if a string exists in the file, sans the injected """ |
if os.path.exists(file_path):
file_content = codecs.open(file_path, encoding="utf-8").read()
file_content = self.wrapper_match.sub(u"", file_content)
else:
file_content = ""
return file_content.find(content) != -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 clear_content(self, content):
""" Clear the injected content from the content buffer, and return the results """ |
content = _unicode(content)
return self.wrapper_match.sub("", content) |
<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_order(self, order):
""" Adds a MarketOrder instance to the list of market orders contained within this order list. Does some behind-the-scenes magic to g... |
# This key is used to group the orders based on region.
key = '%s_%s' % (order.region_id, order.type_id)
if not self._orders.has_key(key):
# We don't have any orders for this yet. Prep the region+item
# combo by instantiating a new MarketItemsInRegionList for
... |
<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_entry(self, entry):
""" Adds a MarketHistoryEntry instance to the list of market history entries contained within this instance. Does some behind-the-sce... |
# This key is used to group the orders based on region.
key = '%s_%s' % (entry.region_id, entry.type_id)
if not self._history.has_key(key):
# We don't have any orders for this yet. Prep the region+item
# combo by instantiating a new MarketItemsInRegionList for
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _find_file(self, file_name: str, lookup_dir: Path) -> Path or None:
'''Find a file in a directory by name. Check subdirectories recursively.
:param file_name: Name of the file
:lookup_dir: Starting directory
:returns: Path to the found file or None if the file was not found
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _sync_repo(self, repo_url: str, revision: str or None = None) -> Path:
'''Clone a Git repository to the cache dir. If it has been cloned before, update it.
:param repo_url: Repository URL
:param revision: Revision: branch, commit hash, or tag
:returns: Path to the cloned repository... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _shift_headings(self, content: str, shift: int) -> str:
'''Shift Markdown headings in a string by a given value. The shift can
be positive or negative.
:param content: Markdown content
:param shift: Heading shift
:returns: Markdown content with headings shifted by ``shift``... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _cut_from_heading_to_heading(
self,
content: str,
from_heading: str,
to_heading: str or None = None,
options={}
) -> str:
'''Cut part of Markdown string between two headings, set internal heading level,
and remove top heading.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _cut_to_heading(
self,
content: str,
to_heading: str or None = None,
options={}
) -> str:
'''Cut part of Markdown string from the start to a certain heading,
set internal heading level, and remove top heading.
If not heading is defined... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _adjust_image_paths(self, content: str, md_file_path: Path) -> str:
'''Locate images referenced in a Markdown string and replace their paths
with the absolute ones.
:param content: Markdown content
:param md_file_path: Path to the Markdown file containing the content
:retur... |
<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_src_file_path(self, markdown_file_path: Path) -> Path:
'''Translate the path of Markdown file that is located inside the temporary working directory
into the path of the corresponding Markdown file that is located inside the source directory
of Foliant project.
:param markdown_... |
<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_included_file_path(self, user_specified_path: str, current_processed_file_path: Path) -> Path:
'''Resolve user specified path to the local included file.
:param user_specified_path: User specified string that represents
the path to a local file
:param current_processed_fil... |
<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_includes(self, markdown_file_path: Path, content: str) -> str:
'''Replace all include statements with the respective file contents.
:param markdown_file_path: Path to curently processed Markdown file
:param content: Markdown content
:returns: Markdown content with resolved ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_logger(name, CFG=None):
"""set up logging for a service using the py 2.7 dictConfig """ |
logger = logging.getLogger(name)
if CFG:
# Make log directory if it doesn't exist
for handler in CFG.get('handlers', {}).itervalues():
if 'filename' in handler:
log_dir = os.path.dirname(handler['filename'])
if not os.path.exists(log_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 t_trailingwhitespace(self, token):
ur'.+? \n'
print "Error: trailing whitespace at line %s in text '%s'" % (token.lexer.lineno + 1, token.value[:-1])
token.lexer.lexerror = True
token.lexer.skip(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 exec_before_request_actions(actions, **kwargs):
"""Execute actions in the "before" and "before_METHOD" groups """ |
groups = ("before", "before_" + flask.request.method.lower())
return execute_actions(actions, limit_groups=groups, **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 exec_after_request_actions(actions, response, **kwargs):
"""Executes actions of the "after" and "after_METHOD" groups. A "response" var will be injected in t... |
current_context["response"] = response
groups = ("after_" + flask.request.method.lower(), "after")
try:
rv = execute_actions(actions, limit_groups=groups, **kwargs)
except ReturnValueException as e:
rv = e.value
if rv:
return rv
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_view(url=None, methods=None, view_class=ActionsView, name=None, url_rules=None, **kwargs):
"""Decorator to transform a function into a view class. Be warn... |
def decorator(f):
if url is not None:
f = expose(url, methods=methods)(f)
clsdict = {"name": name or f.__name__,
"actions": getattr(f, "actions", None),
"url_rules": url_rules or getattr(f, "urls", None)}
if isinstance(f, WithActionsDecora... |
<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, target):
"""Registers url_rules on the blueprint """ |
for rule, options in self.url_rules:
target.add_url_rule(rule, self.name, self.dispatch_request, **options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def view(self, *args, **kwargs):
"""Decorator to automatically apply as_view decorator and register it. """ |
def decorator(f):
kwargs.setdefault("view_class", self.view_class)
return self.add_view(as_view(*args, **kwargs)(f))
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_action_view(self, name, url, actions, **kwargs):
"""Creates an ActionsView instance and registers it. """ |
view = ActionsView(name, url=url, self_var=self, **kwargs)
if isinstance(actions, dict):
for group, actions in actions.iteritems():
view.actions.extend(load_actions(actions, group=group or None))
else:
view.actions.extend(load_actions(actions))
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 process(exam_num: int, time: str, date: str) -> None: """Process the exams in the exam_num folder for the time.""" |
prefix = Path(f"exams/exam-{exam_num}")
problems = list(prefix.glob(f"exam-{exam_num}-{time}-[0-9].ipynb"))
problems = sorted(problems, key=lambda k: k.stem[-1])
output_directory = (prefix / "output").resolve()
fw = FilesWriter(build_directory=str(output_directory))
assignment_zip_name = out... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(argv: Optional[Sequence[str]] = None) -> None: """Parse arguments and process the exam assignment.""" |
parser = ArgumentParser(description="Convert Jupyter Notebook exams to PDFs")
parser.add_argument(
"--exam",
type=int,
required=True,
help="Exam number to convert",
dest="exam_num",
)
parser.add_argument(
"--time", type=str, required=True, help="Time of e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_meta(self, text):
""" Takes input as the entire file. Reads the first yaml document as metadata. and the rest of the document as text """ |
first_line = True
metadata = []
content = []
metadata_parsed = False
for line in text.split('\n'):
if first_line:
first_line = False
if line.strip() != '---':
raise MetaParseException('Invalid metadata')
... |
<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_defaults(self):
""" Add each model entry with it's default """ |
for key, value in self.spec.items():
setattr(self, key.upper(), value.get("default", 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 load_env(self):
""" Load the model fron environment variables """ |
for key, value in self.spec.items():
if value['type'] in (dict, list):
envar = (self.env_prefix + "_" + key).upper()
try:
envvar = env.json(envar,
default=getattr(self, key.upper(), value.get('default')))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_args(self):
""" Parse the cli args Returns: args (namespace):
The args """ |
parser = ArgumentParser(description='',
formatter_class=RawTextHelpFormatter)
parser.add_argument("--generate", action="store", dest='generate',
choices=['command', 'docker-run', 'docker-compose',
'ini', 'e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_args(self, args):
""" Add the args Args: args (namespace):
The commandline args """ |
for key, value in vars(args).items():
if value is not None:
setattr(self, key.upper(), 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 load_ini(self, ini_file):
""" Load the contents from the ini file Args: ini_file (str):
The file from which the settings should be loaded """ |
if ini_file and not os.path.exists(ini_file):
self.log.critical(f"Settings file specified but not found. {ini_file}")
sys.exit(1)
if not ini_file:
ini_file = f"{self.cwd}/settings.ini"
if os.path.exists(ini_file):
config = configparser.RawConfigPa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_required(self):
""" Check all required settings have been provided """ |
die = False
for key, value in self.spec.items():
if not getattr(self, key.upper()) and value['required']:
print(f"{key} is a required setting. "
"Set via command-line params, env or file. "
"For examples, try '--generate' or '--hel... |
<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(self):
""" Generate sample settings """ |
otype = getattr(self, 'GENERATE')
if otype:
if otype == 'env':
self.generate_env()
elif otype == "command":
self.generate_command()
elif otype == "docker-run":
self.generate_docker_run()
elif otype == "docke... |
<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_env(self):
""" Generate sample environment variables """ |
for key in sorted(list(self.spec.keys())):
if self.spec[key]['type'] in (dict, list):
value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'"
else:
value = f"{self.spec[key].get('example', '')}"
print(f"export {self.env_prefix}_{key.upp... |
<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_command(self):
""" Generate a sample command """ |
example = []
example.append(f"{sys.argv[0]}")
for key in sorted(list(self.spec.keys())):
if self.spec[key]['type'] == list:
value = " ".join(self.spec[key].get('example', ''))
elif self.spec[key]['type'] == dict:
value = f"\'{json.dumps(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 generate_docker_run(self):
""" Generate a sample docker run """ |
example = []
example.append("docker run -it")
for key in sorted(list(self.spec.keys())):
if self.spec[key]['type'] in (dict, list):
value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'"
else:
value = f"{self.spec[key].get('example... |
<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_docker_compose(self):
""" Generate a sample docker compose """ |
example = {}
example['app'] = {}
example['app']['environment'] = []
for key in sorted(list(self.spec.keys())):
if self.spec[key]['type'] in (dict, list):
value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'"
else:
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 generate_ini(self):
""" Generate a sample ini """ |
example = []
example.append("[settings]")
for key in sorted(list(self.spec.keys())):
if self.spec[key]['type'] in [list, dict]:
value = json.dumps(self.spec[key].get('example', ''))
else:
value = self.spec[key].get('example', '')
... |
<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_kubernetes(self):
""" Generate a sample kubernetes """ |
example = {}
example['spec'] = {}
example['spec']['containers'] = []
example['spec']['containers'].append({"name": '', "image": '', "env": []})
for key, value in self.spec.items():
if value['type'] in (dict, list):
kvalue = f"\'{json.dumps(value.get('... |
<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_drone_plugin(self):
""" Generate a sample drone plugin configuration """ |
example = {}
example['pipeline'] = {}
example['pipeline']['appname'] = {}
example['pipeline']['appname']['image'] = ""
example['pipeline']['appname']['secrets'] = ""
for key, value in self.spec.items():
if value['type'] in (dict, list):
kvalue... |
<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_readme(self):
""" Generate a readme with all the generators """ |
print("## Examples of settings runtime params")
print("### Command-line parameters")
print("```")
self.generate_command()
print("```")
print("### Environment variables")
print("```")
self.generate_env()
print("```")
print("### ini 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 file_exists(self, subdir, prefix, suffix):
"""Returns true if the resource file exists, else False. Positional arguments: subdir -- sub directory name under ... |
real_path = os.path.join(self.STATIC_DIR, self.DIR, subdir, prefix + suffix)
return os.path.exists(real_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 add_css(self, subdir, file_name_prefix):
"""Add a css file for this resource. If self.minify is True, checks if the .min.css file exists. If not, falls back ... |
suffix_maxify = '.css'
suffix_minify = '.min.css'
if self.minify and self.file_exists(subdir, file_name_prefix, suffix_minify):
self.resources_css.append(posixpath.join(self.DIR, subdir, file_name_prefix + suffix_minify))
elif self.file_exists(subdir, file_name_prefix, suffi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.