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 string_avg(strings, binary=True):
""" Takes a list of strings of equal length and returns a string containing the most common value from each index in the st... |
if binary: # Assume this is a binary number and fill leading zeros
strings = deepcopy(strings)
longest = len(max(strings, key=len))
for i in range(len(strings)):
while len(strings[i]) < longest:
split_string = strings[i].split("b")
strings[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 get_world_dimensions(gridfile, delim=" "):
""" This function takes the name of a file in grid_task format and returns the dimensions of the world it represen... |
infile = open(gridfile)
lines = infile.readlines()
infile.close()
world_x = len(lines[0].strip().split(delim))
world_y = len(lines)
return (world_x, world_y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modify_config(path):
""" Context manager to modify a flit config file. Will read the config file, validate the config, yield the config object, validate and ... |
if isinstance(path, str):
path = Path(path)
config = _read_pkg_ini(path)
_validate_config(config, path)
# don't catch exception, we won't write the new config.
yield config
_validate_config(config, path)
with path.open('w') as f:
config.write(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 pformat(self):
''' | and supress escaping apostrophe
'''
result = "{\n"
indent1 = " " * 4
indent2 = " " * 8
for line_no, code_objects in sorted(self.items()):
result += '%s%i: [\n' % (indent1, line_no)
for code_object in code_objects:
result += '%s"""<%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 _parse_string(self, line):
""" Consume the complete string until next " or \n """ |
log.debug("*** parse STRING: >>>%r<<<", line)
parts = self.regex_split_string.split(line, maxsplit=1)
if len(parts) == 1: # end
return parts[0], None
pre, match, post = parts
log.debug("\tpre: >>>%r<<<", pre)
log.debug("\tmatch: >>>%r<<<", match)
lo... |
<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(self, line):
""" parse the given BASIC line and branch into DATA, String and consume a complete Comment """ |
log.debug("*** parse CODE: >>>%r<<<", line)
parts = self.regex_split_all.split(line, maxsplit=1)
if len(parts) == 1: # end
self.line_data.append(BASIC_Code(parts[0]))
return
pre, match, post = parts
log.debug("\tpre: >>>%r<<<", pre)
log.debug("\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 close(correlation_id, components):
""" Closes multiple components. To be closed components must implement [[ICloseable]] interface. If they don't the call to... |
if components == None:
return
for component in components:
Closer.close_one(correlation_id, component) |
<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(app, url = None, path = None, endpoint=None, decorate=None, index='index.html', **options):
"""Adds static files endpoint with optional directory index."... |
url = url or app.static_url_path or ''
path = os.path.abspath(path or app.static_folder or '.')
endpoint = endpoint or 'static_' + os.path.basename(path)
decorate = decorate or (lambda f: f)
endpoints = {}
if path == app.static_folder:
raise ValueError('Files in `{}` path are already ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def program_dump2ascii_lines(self, dump, program_start=None):
""" convert a memory dump of a tokensized BASIC listing into ASCII listing list. """ |
dump = bytearray(dump)
# assert isinstance(dump, bytearray)
if program_start is None:
program_start = self.DEFAULT_PROGRAM_START
return self.listing.program_dump2ascii_lines(dump, program_start) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ascii_listing2program_dump(self, basic_program_ascii, program_start=None):
""" convert a ASCII BASIC program listing into tokens. This tokens list can be use... |
if program_start is None:
program_start = self.DEFAULT_PROGRAM_START
basic_lines = self.ascii_listing2basic_lines(basic_program_ascii, program_start)
program_dump=self.listing.basic_lines2program_dump(basic_lines, program_start)
assert isinstance(program_dump, bytearray), ... |
<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_gaf_format(self):
"""Return a GAF 2.0-compatible string representation of the annotation. Parameters Returns ------- str The formatted string. """ |
sep = '\t'
return sep.join(
[self.gene, self.db_ref, self.term.id, self.evidence,
'|'.join(self.db_ref), '|'.join(self.with_)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def ahead(self, i, j=None):
'''Raising stopiteration with end the parse.
'''
if j is None:
return self._stream[self.i + i]
else:
return self._stream[self.i + i: self.i + j] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def method_name(func):
"""Method wrapper that adds the name of the method being called to its arguments list in Pascal case """ |
@wraps(func)
def _method_name(*args, **kwargs):
name = to_pascal_case(func.__name__)
return func(name=name, *args, **kwargs)
return _method_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 to_pascal_case(s):
"""Transform underscore separated string to pascal case """ |
return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_underscore(s):
"""Transform camel or pascal case to underscore separated string """ |
return re.sub(
r'(?!^)([A-Z]+)',
lambda m: "_{0}".format(m.group(1).lower()),
re.sub(r'(?!^)([A-Z]{1}[a-z]{1})', lambda m: "_{0}".format(m.group(1).lower()), s)
).lower() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notify(self, correlation_id, args):
""" Fires this event and notifies all registred listeners. :param correlation_id: (optional) transaction id to trace exec... |
for listener in self._listeners:
try:
listener.on_event(correlation_id, self, args)
except Exception as ex:
raise InvocationException(
correlation_id,
"EXEC_FAILED",
"Raising event " + self._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 _parseIsTag(self):
""" Detect whether the element is HTML tag or not. Result is saved to the :attr:`_istag` property. """ |
el = self._element
self._istag = el and el[0] == "<" and el[-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 _parseIsComment(self):
""" Detect whether the element is HTML comment or not. Result is saved to the :attr:`_iscomment` property. """ |
self._iscomment = (
self._element.startswith("<!--") and self._element.endswith("-->")
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parseTagName(self):
""" Parse name of the tag. Result is saved to the :attr:`_tagname` property. """ |
for el in self._element.split():
el = el.replace("/", "").replace("<", "").replace(">", "")
if el.strip():
self._tagname = el.rstrip()
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parseParams(self):
""" Parse parameters from their string HTML representation to dictionary. Result is saved to the :attr:`params` property. """ |
# check if there are any parameters
if " " not in self._element or "=" not in self._element:
return
# remove '<' & '>'
params = self._element.strip()[1:-1].strip()
# remove tagname
offset = params.find(self.getTagName()) + len(self.getTagName())
par... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isOpeningTag(self):
""" Detect whether this tag is opening or not. Returns: bool: True if it is opening. """ |
if self.isTag() and \
not self.isComment() and \
not self.isEndTag() and \
not self.isNonPairTag():
return True
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 entropy(dictionary):
""" Helper function for entropy calculations. Takes a frequency dictionary and calculates entropy of the keys. """ |
total = 0.0
entropy = 0
for key in dictionary.keys():
total += dictionary[key]
for key in dictionary.keys():
entropy += dictionary[key]/total * log(1.0/(dictionary[key]/total), 2)
return entropy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sqrt_shannon_entropy(filename):
""" Calculates Shannon entropy based on square root of phenotype count. This might account for relationship between populatio... |
data = load_grid_data(filename, "int")
data = agg_grid(data, mode)
phenotypes = {}
for r in data:
for c in r:
if c in phenotypes:
phenotypes[c] += 1
else:
phenotypes[c] = 1
for key in phenotypes.keys():
phenotypes[key] = sqrt(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _composed_doc(fs):
""" Generate a docstring for the composition of fs. """ |
if not fs:
# Argument name for the docstring.
return 'n'
return '{f}({g})'.format(f=fs[0].__name__, g=_composed_doc(fs[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 update_model(self, idx=None):
"""Updates the value of property at given index. If idx is None, all controlled indices will be updated. This method should be ... |
if idx is None:
for w in self._widgets:
idx = self._get_idx_from_widget(w)
try: val = self._read_widget(idx)
except ValueError: pass
else: self._write_property(val, idx)
pass
pass
else:
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 update_widget(self, idx=None):
"""Forces the widget at given index to be updated from the property value. If index is not given, all controlled widgets will ... |
if idx is None:
for w in self._widgets:
idx = self._get_idx_from_widget(w)
self._write_widget(self._read_property(idx), idx)
pass
else: self._write_widget(self._read_property(idx), idx)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _on_wid_changed(self, wid):
"""Called when the widget is changed""" |
if self._itsme: return
self.update_model(self._get_idx_from_widget(wid))
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_url(url):
""" Fetch the given url, strip formfeeds and decode it into the defined encoding """ |
with closing(urllib.urlopen(url)) as f:
if f.code is 200:
response = f.read()
return strip_formfeeds(response).decode(ENCODING) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_entry_line(str_to_match, regex_obj=MAIN_REGEX_OBJ):
"""Does a regex match of the mount entry string""" |
match_obj = regex_obj.match(str_to_match)
if not match_obj:
error_message = ('Line "%s" is unrecognized by overlay4u. '
'This is only meant for use with Ubuntu Linux.')
raise UnrecognizedMountEntry(error_message % str_to_match)
return match_obj.groupdict() |
<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_list(self, fs_type=None):
"""List mount entries""" |
entries = self._entries
if fs_type:
entries = filter(lambda a: a.fs_type == fs_type, entries)
return entries |
<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(self, f_buf=None):
""" Definitely render the workbook :param obj f_buf: A file buffer supporting the write and seek methods """ |
if f_buf is None:
f_buf = StringIO.StringIO()
with odswriter.writer(f_buf) as writer:
default_sheet = writer.new_sheet(self.title)
self._render_headers(default_sheet)
self._render_rows(default_sheet)
# abstract_sheet require the same attribut... |
<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_related_exporter(self, related_obj, column):
""" returns an SqlaOdsExporter for the given related object and stores it in the column object as a cache "... |
result = column.get('sqla_ods_exporter')
if result is None:
result = column['sqla_ods_exporter'] = SqlaOdsExporter(
related_obj.__class__,
is_root=False,
title=column.get('label', column['key']),
)
self.add_sheet(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 _get_relationship_cell_val(self, obj, column):
""" Return the value to insert in a relationship cell Handle the case of complex related datas we want to hand... |
val = SqlaExporter._get_relationship_cell_val(self, obj, column)
if val == "":
related_key = column.get('related_key', None)
if column['__col__'].uselist and related_key is None and \
self.is_root:
# on récupère les objets lié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 raster(times, indices, max_time=None, max_index=None, x_label="Timestep", y_label="Index", **kwargs):
"""Plots a raster plot given times and indices of event... |
# set default size to 1
if 's' not in kwargs:
kwargs['s'] = 1
scatter(times, indices, **kwargs)
if max_time is None:
max_time = max(times)
if max_index is None:
max_index = max(indices)
axis((0, max_time, 0, max_index))
if x_label is not None: xlabel(x_label)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def query(query):
'''
Send an ADQL query to the Gaia archive,
wait for a response,
and hang on to the results.
'''
# send the query to the Gaia archive
with warnings.catch_warnings() :
warnings.filterwarnings("ignore")
_gaia_job = astroquery.gaia.Gaia.launch_job(query)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connectionMade(self):
""" Initializes the protocol. """ |
self._buffer = b''
self._queue = {}
self._stopped = None
self._tag = 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 dataReceived(self, data):
""" Parses chunks of bytes into responses. Whenever a complete response is received, this method extracts its payload and calls L{r... |
size = len(self._buffer) + len(data)
if size > self.MAX_LENGTH:
self.lengthLimitExceeded(size)
self._buffer += data
start = 0
for match in self._pattern.finditer(self._buffer):
# The start of the sentinel marks the end of the response.
end = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def responseReceived(self, response, tag):
""" Receives some characters of a netstring. Whenever a complete response is received, this method calls the deferred ... |
self._queue.pop(tag).callback(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 execute(self, *args):
""" Pass one command to exiftool and return a deferred which is fired as soon as the command completes. @param *args: Command line argu... |
result = defer.Deferred()
if self.connected and not self._stopped:
self._tag += 1
args = tuple(args) + ('-execute{:d}'.format(self._tag), '')
safe_args = [fsencode(arg) for arg in args]
self.transport.write(b'\n'.join(safe_args))
result = d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loseConnection(self):
""" Close the connection and terminate the exiftool process. @rtype: C{Deferred} @return: A deferred whose callback will be invoked whe... |
if self._stopped:
result = self._stopped
elif self.connected:
result = defer.Deferred()
self._stopped = result
self.transport.write(b'\n'.join((b'-stay_open', b'False', b'')))
else:
# Already disconnected.
result = defer.su... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connectionLost(self, reason=protocol.connectionDone):
""" Check whether termination was intended and invoke the deferred. If the connection terminated unexpe... |
self.connected = 0
for pending in self._queue.values():
pending.errback(reason)
self._queue.clear()
if self._stopped:
result = self if reason.check(error.ConnectionDone) else reason
self._stopped.callback(result)
self._stopped = 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 find_next_character(code, position, char):
"""Find next char and return its first and last positions""" |
end = LineCol(code, *position)
while not end.eof and end.char() in WHITESPACE:
end.inc()
if not end.eof and end.char() == char:
return end.tuple(), inc_tuple(end.tuple())
return None, 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 from_value(value = None):
""" Converts specified value into ProjectionParams. :param value: value to be converted :return: a newly created ProjectionParams. ... |
if isinstance(value, ProjectionParams):
return value
array = AnyValueArray.from_value(value) if value != None else AnyValueArray()
return ProjectionParams(array) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_string(self):
""" Gets a string representation of the object. The result is a comma-separated list of projection fields "field1,field2.field21,field2.fiel... |
builder = ""
index = 0
while index < self.__len__():
if index > 0:
builder = builder + ','
builder = builder + super(ProjectionParams, self).__getitem__(index)
index = index + 1
return builder |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def snake_case_backend_name(self):
""" CamelCase -> camel_case """ |
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', type(self).__name__)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() |
<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_setting(self, key, default=NOT_SET):
""" Gets a setting for the key. :raise KeyError: If the key is not set and default isn't provided. """ |
if self._arca is None:
raise LazySettingProperty.SettingsNotReady
return self._arca.settings.get(*self.get_settings_keys(key), default=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 hash_file_contents(requirements_option: RequirementsOptions, path: Path) -> str: """ Returns a SHA256 hash of the contents of ``path`` combined with the Arca ... |
return hashlib.sha256(path.read_bytes() + bytes(
requirements_option.name + arca.__version__, "utf-8"
)).hexdigest() |
<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_requirements_information(self, path: Path) -> Tuple[RequirementsOptions, Optional[str]]: """ Returns the information needed to install requirements for a ... |
if self.pipfile_location is not None:
pipfile = path / self.pipfile_location / "Pipfile"
pipfile_lock = path / self.pipfile_location / "Pipfile.lock"
pipfile_exists = pipfile.exists()
pipfile_lock_exists = pipfile_lock.exists()
if pipfile_exists and... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialized_task(self, task: Task) -> Tuple[str, str]: """ Returns the name of the task definition file and its contents. """ |
return f"{task.hash}.json", task.json |
<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: # pragma: no cover """ Executes the script and returns the result. M... |
raise NotImplementedError |
<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: # pragma: no cover """ Abstract method which must be implemen... |
raise NotImplementedError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quote_names(db, names):
"""psycopg2 doesn't know how to quote identifier names, so we ask the server""" |
c = db.cursor()
c.execute("SELECT pg_catalog.quote_ident(n) FROM pg_catalog.unnest(%s::text[]) n", [list(names)])
return [name for (name,) in c] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_catch(c, sql, vars=None):
"""Run a query, but ignore any errors. For error recovery paths where the error handler should not raise another.""" |
try:
c.execute(sql, vars)
except Exception as err:
cmd = sql.split(' ', 1)[0]
log.error("Error executing %s: %s", cmd, err) |
<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_copy():
settings. When used with --force, an existing database with the same name as DEST is replaced, the original is renamed out of place in the form D... |
db = connect()
if args.force and db_exists(db, args.dest):
tmp_db = generate_alt_dbname(db, args.dest, 'tmp')
pg_copy(db, args.src, tmp_db)
pg_move_extended(db, tmp_db, args.dest)
else:
pg_copy(db, args.src, args.dest) |
<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_move(db=None):
"""Rename a database within a server. When used with --force, an existing database with the same name as DEST is replaced, the original is... |
if db is None:
db = connect()
pg_move_extended(db, args.src, args.dest) |
<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_reindex():
"""Uses CREATE INDEX CONCURRENTLY to create a duplicate index, then tries to swap the new index for the original. The index swap is done using... |
db = connect(args.database)
for idx in args.indexes:
pg_reindex(db, idx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def align(s1, s2, gap=' ', eq=operator.eq):
'''aligns two strings
>>> print(*align('pharmacy', 'farmácia', gap='_'), sep='\\n')
pharmac_y
_farmácia
>>> print(*align('advantage', 'vantagem', gap='_'), sep='\\n')
advantage_
__vantagem
'''
# first we compute the dynamic programming 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 mismatches(s1, s2, context=0, eq=operator.eq):
'''extract mismatched segments from aligned strings
>>> list(mismatches(*align('pharmacy', 'farmácia'), context=1))
[('pha', ' fa'), ('mac', 'mác'), ('c y', 'cia')]
>>> list(mismatches(*align('constitution', 'constituição'), context=1))
[('ution',... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init():
""" build connection and init it""" |
connection.connect()
# start track
# all services were provided here:
# https://android.googlesource.com/platform/system/core/+/jb-dev/adb/SERVICES.TXT
ready_data = utils.encode_data('host:track-devices')
connection.adb_socket.send(ready_data)
# get status
status = connection.adb_sock... |
<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_comment_group_for_path(self, pathname, default_content_type=None):
""" Obtains the comment group for a specified pathname. :param pathname: The path for ... |
content_type = self.guess_content_type(pathname)
if not content_type:
# Content type is not found.
if default_content_type:
content_type = default_content_type
return self.get_comment_group(content_type)
else:
raise 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 add_config_file(self, config_filename):
""" Parses the content.types file and updates the content types database. :param config_filename: The path to the con... |
with open(config_filename, 'rb') as f:
content = f.read()
config = yaml.load(content)
self.add_config(config, config_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 guess_content_type(self, pathname):
"""Guess the content type for the given path. :param path: The path of file for which to guess the content type. :return:... |
file_basename = os.path.basename(pathname)
content_type = None
# Try to determine from the path.
if not content_type and self._filename_map.has_key(file_basename):
content_type = self._filename_map[file_basename]
#logger.debug("Content type of '%s' is '%s' (dete... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect():
""" create socket and connect to adb server """ |
global adb_socket
if adb_socket is not None:
raise RuntimeError('connection already existed')
host, port = config.HOST, config.PORT
connection = socket.socket()
try:
connection.connect((host, port))
except ConnectionError as _:
warn_msg = 'failed when connecting to adb... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reboot_adb_server():
""" execute 'adb devices' to start adb server """ |
_reboot_count = 0
_max_retry = 1
def _reboot():
nonlocal _reboot_count
if _reboot_count >= _max_retry:
raise RuntimeError('fail after retry {} times'.format(_max_retry))
_reboot_count += 1
return_code = subprocess.call(['adb', 'devices'], stdout=subprocess.DEVN... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def escape_string(value):
"""Converts a string to its S-expression representation, adding quotes and escaping funny characters. """ |
res = StringIO()
res.write('"')
for c in value:
if c in CHAR_TO_ESCAPE:
res.write(f'\\{CHAR_TO_ESCAPE[c]}')
elif c.isprintable():
res.write(c)
elif ord(c) < 0x100:
res.write(f'\\x{ord(c):02x}')
elif ord(c) < 0x10000:
res.write(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare(value1, operation, value2):
""" Perform comparison operation over two arguments. The operation can be performed over values of any type. :param value... |
if operation == None:
return False
operation = operation.upper()
if operation in ["=", "==", "EQ"]:
return ObjectComparator.are_equal(value1, value2)
if operation in ["!=", "<>", "NE"]:
return ObjectComparator.are_not_equal(value1, value2)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def are_equal(value1, value2):
""" Checks if two values are equal. The operation can be performed over values of any type. :param value1: the first value to comp... |
if value1 == None or value2 == None:
return True
if value1 == None or value2 == None:
return False
return value1 == value2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def less(value1, value2):
""" Checks if first value is less than the second one. The operation can be performed over numbers or strings. :param value1: the first... |
number1 = FloatConverter.to_nullable_float(value1)
number2 = FloatConverter.to_nullable_float(value2)
if number1 == None or number2 == None:
return False
return number1 < number2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def more(value1, value2):
""" Checks if first value is greater than the second one. The operation can be performed over numbers or strings. :param value1: the fi... |
number1 = FloatConverter.to_nullable_float(value1)
number2 = FloatConverter.to_nullable_float(value2)
if number1 == None or number2 == None:
return False
return number1 > number2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(value1, value2):
""" Checks if string matches a regular expression :param value1: a string value to match :param value2: a regular expression string :r... |
if value1 == None and value2 == None:
return True
if value1 == None or value2 == None:
return False
string1 = str(value1)
string2 = str(value2)
return re.match(string2, string1) != 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 register_view(self, view):
"""Loads the text taking it from the model, then starts a timer to scroll it.""" |
self.view.set_text(self.model.credits)
gobject.timeout_add(1500, self.on_begin_scroll)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_scroll(self):
"""Called to scroll text""" |
try:
sw = self.view['sw_scroller']
except KeyError:
return False # destroyed!
vadj = sw.get_vadjustment()
if vadj is None: return False
val = vadj.get_value()
# is scrolling over?
if val >= vadj.upper - vadj.page_size:
... |
<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_token(self, *, holder_name, card_number, credit_card_cvv, expiration_date, token_type='credit_card', identity_document=None, billing_address=None, addi... |
headers = self.client._get_public_headers()
payload = {
"token_type": token_type,
"credit_card_cvv": credit_card_cvv,
"card_number": card_number,
"expiration_date": expiration_date,
"holder_name": holder_name,
"identity_document": ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retrieve_token(self, token):
""" Retrieve Token details for a specific Token. Args: token: The identifier of the token. Returns: """ |
headers = self.client._get_private_headers()
endpoint = '/tokens/{}'.format(token)
return self.client._get(self.client.URL_BASE + endpoint, headers=headers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prj_created_data(project, role):
"""Return the data for created :param project: the project that holds the data :type project: :class:`jukeboxcore.djadapter.... |
if role == QtCore.Qt.DisplayRole:
return project.date_created.isoformat(' ') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prj_fps_data(project, role):
"""Return the data for fps :param project: the project that holds the data :type project: :class:`jukeboxcore.djadapter.models.P... |
if role == QtCore.Qt.DisplayRole:
return str(project.framerate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prj_resolution_data(project, role):
"""Return the data for resolution :param project: the project that holds the data :type project: :class:`jukeboxcore.djad... |
if role == QtCore.Qt.DisplayRole:
return '%s x %s' % (project.resx, project.resy) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shot_duration_data(shot, role):
"""Return the data for duration :param shot: the shot that holds the data :type shot: :class:`jukeboxcore.djadapter.models.Sh... |
if role == QtCore.Qt.DisplayRole:
return str(shot.duration) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shot_start_data(shot, role):
"""Return the data for startframe :param shot: the shot that holds the data :type shot: :class:`jukeboxcore.djadapter.models.Sho... |
if role == QtCore.Qt.DisplayRole:
return str(shot.startframe) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shot_end_data(shot, role):
"""Return the data for endframe :param shot: the shot that holds the data :type shot: :class:`jukeboxcore.djadapter.models.Shot` :... |
if role == QtCore.Qt.DisplayRole:
return str(shot.endframe) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def note_content_data(note, role):
"""Return the data for content :param note: the note that holds the data :type note: :class:`jukeboxcore.djadapter.models.Note... |
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return note.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 remove_adapter(widget_class, flavour=None):
"""Removes the given widget class information from the default set of adapters. If widget_class had been previous... |
for it,tu in enumerate(__def_adapter):
if (widget_class == tu[WIDGET] and flavour == tu[FLAVOUR]):
del __def_adapter[it]
return True
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 get(self, key):
""" Gets a map element specified by its key. The key can be defined using dot notation and allows to recursively access elements of elements.... |
if key == None or key == '':
return None
elif key.find('.') > 0:
return RecursiveObjectReader.get_property(self, key)
else:
return super(Parameters, self).get(key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, key, value):
""" Puts a new value into map element specified by its key. The key can be defined using dot notation and allows to recursively access... |
if key == None or key == '':
return None
elif key.find('.') > 0:
RecursiveObjectWriter.set_property(self, key, value)
return value
else:
self[key] = value
return 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 get_as_nullable_parameters(self, key):
""" Converts map element into an Parameters or returns null if conversion is not possible. :param key: a key of elemen... |
value = self.get_as_nullable_map(key)
return Parameters(value) if value != None else None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_as_parameters_with_default(self, key, default_value):
""" Converts map element into an Parameters or returns default value if conversion is not possible.... |
result = self.get_as_nullable_parameters(key)
return result if result != None else default_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 override(self, parameters, recursive = False):
""" Overrides parameters with new values from specified Parameters and returns a new Parameters object. :param... |
result = Parameters()
if recursive:
RecursiveObjectWriter.copy_properties(result, self)
RecursiveObjectWriter.copy_properties(result, parameters)
else:
ObjectWriter.set_properties(result, self)
ObjectWriter.set_properties(result, parameters)
... |
<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, default_values, recursive = False):
""" Set default values from specified Parameters and returns a new Parameters object. :param default_v... |
result = Parameters()
if recursive:
RecursiveObjectWriter.copy_properties(result, default_values)
RecursiveObjectWriter.copy_properties(result, self)
else:
ObjectWriter.set_properties(result, default_values)
ObjectWriter.set_properties(result, 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 pick(self, *props):
""" Picks select parameters from this Parameters and returns them as a new Parameters object. :param props: keys to be picked and copied ... |
result = Parameters()
for prop in props:
if self.contains_key(prop):
result.put(prop, self.get(prop))
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 omit(self, *props):
""" Omits selected parameters from this Parameters and returns the rest as a new Parameters object. :param props: keys to be omitted from... |
result = Parameters(self)
for prop in props:
del result[prop]
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 from_value(value):
""" Creates a new Parameters object filled with key-value pairs from specified object. :param value: an object with key-value pairs used t... |
map = value if isinstance(value, dict) else RecursiveObjectReader.get_properties(value)
return Parameters(map) |
<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_config(config):
""" Creates new Parameters from ConfigMap object. :param config: a ConfigParams that contain parameters. :return: a new Parameters objec... |
result = Parameters()
if config == None or len(config) == 0:
return result
for (key, value) in config.items():
result.put(key, value)
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 execute(correlation_id, components, args = None):
""" Executes multiple components. To be executed components must implement [[IExecutable]] interface. If th... |
results = []
if components == None:
return
args = args if args != None else Parameters()
for component in components:
result = Executor.execute_one(correlation_id, component, args)
results.append(result)
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decorator(func):
"""A function timer decorator.""" |
def function_timer(*args, **kwargs):
"""A nested function for timing other functions."""
# Capture start time
start = time.time()
# Execute function with arguments
value = func(*args, **kwargs)
# Capture end time
end = 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 populateImagesFromSurveys(self, surveys=dss2 + twomass):
'''
Load images from archives.
'''
# what's the coordinate center?
coordinatetosearch = '{0.ra.deg} {0.dec.deg}'.format(self.center)
# query sky view for those images
paths = astroquery.skyview.SkyView... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def global_instance(cls):
"""Return a per-thread global batcher instance.""" |
try:
return GLOBAL_BATCHER.instance
except AttributeError:
instance = PrioritizedBatcher(
**getattr(settings, 'PRIORITIZED_BATCHER', {})
)
GLOBAL_BATCHER.instance = instance
return instance |
<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 a batch.""" |
assert self.batch is not None, "No active batch, call start() first"
logger.debug("Comitting batch from %d sources...", len(self.batch))
# Determine item priority.
by_priority = []
for name in self.batch.keys():
priority = self.priorities.get(name, self.default_pri... |
<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, name, handler, group_by=None, aggregator=None):
"""Add a new handler to the current batch.""" |
assert self.batch is not None, "No active batch, call start() first"
items = self.batch.setdefault(name, collections.OrderedDict())
if group_by is None:
# None is special as it means no grouping. In this case we must store all
# the different handlers and call them all.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(name, path=None):
""" Configure logging and return a logger and the location of its logging configuration file. This function expects: + A Splunk a... |
app_directory = os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0])))
if path is None:
probing_path = [
'local/%s.logging.conf' % name,
'default/%s.logging.conf' % name,
'local/logging.conf',
'default/logging.conf']
for relative_path in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand_user(path, user=None):
"""Roughly the same as os.path.expanduser, but you can pass a default user.""" |
def _replace(m):
m_user = m.group(1) or user
return pwd.getpwnam(m_user).pw_dir if m_user else pwd.getpwuid(os.getuid()).pw_dir
return re.sub(r'~(\w*)', _replace, path) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.