output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def _tidy(self) -> None:
"""
Removes overlaps, etc., and sorts.
"""
if self.no_overlap:
self.remove_overlap(self.no_contiguous) # will sort
else:
self._sort() | Can you write a function in Python 3 where it
removes overlaps etc. and sorts. | You are a Python code generator, capable of creating scripts from specifications. |
Called by _remove_overlap to remove the first overlap found. | Make a summary of the following Python 3 code
def _remove_overlap_sub(self, also_remove_contiguous: bool) -> bool:
# Returns
for i in range(len(self.intervals)):
for j in range(i + 1, len(self.intervals)):
first = self.intervals[i]
second = self.intervals[j]
... | You are a Python code generator, capable of creating scripts from specifications. |
def remove_overlap(self, also_remove_contiguous: bool = False) -> None:
"""
Merges any overlapping intervals.
Args:
also_remove_contiguous: treat contiguous (as well as overlapping)
intervals as worthy of merging?
"""
overlap = True
while over... | How would you code a function in Python 3 to
remove any overlapping intervals. | You are a Python code analyst, evaluating scripts for potential improvements. |
Test if any of the intervals overlap? | Can you generate the documentation for the following Python 3 function
def _any_overlap_or_contiguous(self, test_overlap: bool) -> bool:
for i in range(len(self.intervals)):
for j in range(i + 1, len(self.intervals)):
first = self.intervals[i]
second = self.intervals[... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the start date of the set of intervals or None if there is no start date. | Explain what the following Python 3 code does
def start_datetime(self) -> Optional[datetime.datetime]:
if not self.intervals:
return None
return self.intervals[0].start | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the end date of the set of intervals or None if there is no end date. | Given the following Python 3 function, write the documentation
def end_datetime(self) -> Optional[datetime.datetime]:
if not self.intervals:
return None
return max([x.end for x in self.intervals]) | As a Python code composer, you craft elegant and concise scripts. |
def start_date(self) -> Optional[datetime.date]:
"""
Returns the start date of the set of intervals, or ``None`` if empty.
"""
if not self.intervals:
return None
return self.start_datetime().date() | Create a Python 3 function for
returning the start date of the set of intervals or None if there is no start date. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the end date of the set of intervals or None if there is no end date. | Make a summary of the following Python 3 code
def end_date(self) -> Optional[datetime.date]:
if not self.intervals:
return None
return self.end_datetime().date() | You are a Python code generator, capable of creating scripts from specifications. |
def extent(self) -> Optional[Interval]:
"""
Returns an :class:`Interval` running from the earliest start of an
interval in this list to the latest end. Returns ``None`` if we are
empty.
"""
if not self.intervals:
return None
return Interval(self.start_... | Implement a function in Python 3 to
return the earliest start of an interval running to the latest end of the anatomical set. | You are a Python code analyst, evaluating scripts for potential improvements. |
def total_duration(self) -> datetime.timedelta:
"""
Returns a ``datetime.timedelta`` object with the total sum of
durations. If there is overlap, time will be double-counted, so beware!
"""
total = datetime.timedelta()
for interval in self.intervals:
total += ... | Implement a Python 3 function for
returning the total sum of all the time - counted durations of all the items in the set. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns an intervalList containing intervals representing periods of overlap between intervals in this one. | Make a summary of the following Python 3 code
def get_overlaps(self) -> "IntervalList":
overlaps = IntervalList()
for i in range(len(self.intervals)):
for j in range(i + 1, len(self.intervals)):
first = self.intervals[i]
second = self.intervals[j]
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a list of datetime. timedelta objects representing the durations of each interval in our list. | Can you tell what is the following Python 3 function doing
def durations(self) -> List[datetime.timedelta]:
return [x.duration() for x in self.intervals] | As a Python code analyst, you investigate and solve complex coding mysteries |
def longest_duration(self) -> Optional[datetime.timedelta]:
"""
Returns the duration of the longest interval, or None if none.
"""
if not self.intervals:
return None
return max(self.durations()) | Create a Python 3 function for
returning the duration of the longest interval. | As a python code expert, you are capable of creating scripts from specifications. |
def longest_interval(self) -> Optional[Interval]:
"""
Returns the longest interval, or ``None`` if none.
"""
longest_duration = self.longest_duration()
for i in self.intervals:
if i.duration() == longest_duration:
return i
return None | Can you write a function in Python 3 where it
returns the longest interval in the archive or None if none. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def first_interval_starting(self, start: datetime.datetime) -> \
Optional[Interval]:
"""
Returns our first interval that starts with the ``start`` parameter, or
``None``.
"""
for i in self.intervals:
if i.start == start:
return i
re... | Write a Python 3 script for
returning the first interval that starts with the start parameter or None if no interval is found. | You are a Python code architect, reviewing and designing scalable and efficient code |
def first_interval_ending(self, end: datetime.datetime) \
-> Optional[Interval]:
"""
Returns our first interval that ends with the ``end`` parameter, or
``None``.
"""
for i in self.intervals:
if i.end == end:
return i
return None | Write a Python 3 function that can
return the first interval that ends with the end parameter or None if no interval is found. | You are a Python code architect, reviewing and designing scalable and efficient code |
def gaps(self) -> "IntervalList":
"""
Returns all the gaps between intervals, as an :class:`IntervalList`.
"""
if len(self.intervals) < 2:
return IntervalList(None)
gaps = []
for i in range(len(self.intervals) - 1):
gap = Interval(
... | Implement a Python 3 function for
returning all the gaps between intervals as an : class:`IntervalList. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns an IntervalList that s a subset of this one with only containing intervals that meet the interval criterion. | Can you generate the documentation for the following Python 3 function
def subset(self, interval: Interval,
flexibility: int = 2) -> "IntervalList":
"""
Returns an IntervalList that's a subset of this one, only containing
intervals that meet the "interval" parameter criterion. Wha... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns an IntervalList that s a subset of this one only containing gaps between intervals that meet the interval criterion. | Can you generate a brief explanation for the following Python 3 code
def gap_subset(self, interval: Interval,
flexibility: int = 2) -> "IntervalList":
"""
Returns an IntervalList that's a subset of this one, only containing
*gaps* between intervals that meet the interval crite... | You are a Python code generator, capable of creating scripts from specifications. |
def n_weekends(self) -> int:
"""
Returns the number of weekends that the intervals collectively touch
(where "touching a weekend" means "including time on a Saturday or a
Sunday").
"""
saturdays = set()
for interval in self.intervals:
saturdays.update(... | Create a Python 3 function for
returning the number of weekends that the intervals collectively touch . | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the total duration of the sequence of time intervals that are outside the normal working hours. | Can you tell what is the following Python 3 function doing
def duration_outside_nwh(
self,
starttime: datetime.time = datetime.time(NORMAL_DAY_START_H),
endtime: datetime.time = datetime.time(NORMAL_DAY_END_H)) \
-> datetime.timedelta:
"""
Returns the tota... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the length of the longest sequence of days in which all days include the longest interval. | Make a summary of the following Python 3 code
def max_consecutive_days(self) -> Optional[Tuple[int, Interval]]:
if len(self.intervals) == 0:
return None
startdate = self.start_date()
enddate = self.end_date()
seq = ''
ndays = (enddate - startdate).days + 1
for... | As a Python code composer, you craft elegant and concise scripts. |
This is a worker function for the _sufficient_gaps method. It returns True if there are sufficient gaps in the date range specified? | Explain what the following Python 3 code does
def _sufficient_gaps(self,
startdate: datetime.date,
enddate: datetime.date,
requiredgaps: List[datetime.timedelta],
flexibility: int) -> Tuple[bool, Optional[Interval]]:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check if a set of gaps are present sufficiently often. | Given the following Python 3 function, write the documentation
def sufficient_gaps(self,
every_n_days: int,
requiredgaps: List[datetime.timedelta],
flexibility: int = 2) \
-> Tuple[bool, Optional[Interval]]:
"""
Are gaps... | As a python code expert, you are capable of creating scripts from specifications. |
Returns the cumulative time contained in our intervals up to the given time point. | Here you have a function in Python 3, explain what it does
def cumulative_time_to(self,
when: datetime.datetime) -> datetime.timedelta:
"""
Returns the cumulative time contained in our intervals up to the
specified time point.
"""
assert self.no_overlap... | As a Python code composer, you craft elegant and concise scripts. |
Return the cumulative time within our gaps up to when. | Given the following Python 3 function, write the documentation
def cumulative_gaps_to(self,
when: datetime.datetime) -> datetime.timedelta:
"""
Return the cumulative time within our gaps, up to ``when``.
"""
gaps = self.gaps()
return gaps.cumulative_tim... | You are a Python code analyst, evaluating scripts for potential improvements. |
def time_afterwards_preceding(
self, when: datetime.datetime) -> Optional[datetime.timedelta]:
"""
Returns the time after our last interval, but before ``when``.
If ``self`` is an empty list, returns ``None``.
"""
if self.is_empty():
return None
en... | Create a Python 3 function to
return the time after our last interval but before when. | As a Python code analyst, you investigate and solve complex coding mysteries |
def cumulative_before_during_after(self,
start: datetime.datetime,
when: datetime.datetime) -> \
Tuple[datetime.timedelta,
datetime.timedelta,
datetime.timedelta]:
"""
For a give... | Write a Python 3 script for
returning the cumulative time before and during the given time. | As a Python code composer, you craft elegant and concise scripts. |
Provides a repr - style representation of a function parameter. | Here you have a function in Python 3, explain what it does
def repr_parameter(param: inspect.Parameter) -> str:
return (
"Parameter(name={name}, annotation={annotation}, kind={kind}, "
"default={default}".format(
name=param.name, annotation=param.annotation, kind=param.kind,
... | As a python code expert, you are capable of creating scripts from specifications. |
def get_namespace(fn: Callable, namespace: Optional[str]) -> str:
"""
Returns a representation of a function's name (perhaps within a namespace),
like
.. code-block:: none
mymodule:MyClass.myclassfunc # with no namespace
mymodule:MyClass.myclassfunc|somenamespace # with a namespace
... | Can you create a Python 3 function that
returns a representation of a function s name in a namespace. | You are a Python code generator, capable of creating scripts from specifications. |
A function that allows keyword arguments to be used in a cached function. | Given the following Python 3 function, write the documentation
def kw_fkg_allowing_type_hints(
namespace: Optional[str],
fn: Callable,
to_str: Callable[[Any], str] = repr) -> Callable[[Any], str]:
"""
As for :func:`fkg_allowing_type_hints`, but allowing keyword arguments.
For ``kwar... | You are a Python code analyst, evaluating scripts for potential improvements. |
def gpg_version():
"""Returns the GPG version"""
cmd = flatten([gnupg_bin(), "--version"])
output = stderr_output(cmd)
output = output \
.split('\n')[0] \
.split(" ")[2] \
.split('.')
return tuple([int(x) for x in output]) | Write a Python 3 function for
returning the GPG version | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a string that should work in both Py3 and Py2 | Explain what the following Python 3 code does
def polite_string(a_string):
if is_py3() and hasattr(a_string, 'decode'):
try:
return a_string.decode('utf-8')
except UnicodeDecodeError:
return a_string
return a_string | You are a Python code analyst, evaluating scripts for potential improvements. |
def actually_flatten(iterable):
"""Flatten iterables
This is super ugly. There must be a cleaner py2/3 way
of handling this."""
remainder = iter(iterable)
while True:
first = next(remainder) # pylint: disable=R1708
# Python 2/3 compat
is_iter = isinstance(first, collections.... | Write a Python 3 function that can
flatten iterables This is super ugly. There must be a cleaner py2 / 3 way to handle this. | As a python code expert, you are capable of creating scripts from specifications. |
Read passphrase from a file. | Explain what the following Python 3 code does
def passphrase_file(passphrase=None):
cmd = []
pass_file = None
if not passphrase and 'CRYPTORITO_PASSPHRASE_FILE' in os.environ:
pass_file = os.environ['CRYPTORITO_PASSPHRASE_FILE']
if not os.path.isfile(pass_file):
raise CryptoritoE... | As a Python code analyst, you investigate and solve complex coding mysteries |
def gnupg_home():
"""Returns appropriate arguments if GNUPGHOME is set"""
if 'GNUPGHOME' in os.environ:
gnupghome = os.environ['GNUPGHOME']
if not os.path.isdir(gnupghome):
raise CryptoritoError("Invalid GNUPGHOME directory")
return ["--homedir", gnupghome]
else:
... | Create a Python 3 function for
returning appropriate arguments for GNUPGHOME. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Extracts a key matching a specific fingerprint from a Keybase API response | Make a summary of the following Python 3 code
def fingerprint_from_keybase(fingerprint, kb_obj):
if 'public_keys' in kb_obj and \
'pgp_public_keys' in kb_obj['public_keys']:
for key in kb_obj['public_keys']['pgp_public_keys']:
keyprint = fingerprint_from_var(key).lower()
finge... | As a Python code analyst, you investigate and solve complex coding mysteries |
def key_from_keybase(username, fingerprint=None):
"""Look up a public key from a username"""
url = keybase_lookup_url(username)
resp = requests.get(url)
if resp.status_code == 200:
j_resp = json.loads(polite_string(resp.content))
if 'them' in j_resp and len(j_resp['them']) == 1:
... | Can you write a function in Python 3 where it
looks up a public key from a username | As a Python code analyst, you investigate and solve complex coding mysteries |
Checks to see if we have this gpg key | Make a summary of the following Python 3 code
def has_gpg_key(fingerprint):
if len(fingerprint) > 8:
fingerprint = fingerprint[-8:]
fingerprint = fingerprint.upper()
cmd = flatten([gnupg_bin(), gnupg_home(), "--list-public-keys"])
lines = stderr_output(cmd).split('\n')
return len([key for k... | As a python code expert, you are capable of creating scripts from specifications. |
Extract a fingerprint from a GPG public key | Can you tell what is the following Python 3 function doing
def fingerprint_from_var(var):
vsn = gpg_version()
cmd = flatten([gnupg_bin(), gnupg_home()])
if vsn[0] >= 2 and vsn[1] < 1:
cmd.append("--with-fingerprint")
output = polite_string(stderr_with_input(cmd, var)).split('\n')
if not out... | As a Python code analyst, you investigate and solve complex coding mysteries |
Extract a fingerprint from a GPG public key file | Make a summary of the following Python 3 code
def fingerprint_from_file(filename):
cmd = flatten([gnupg_bin(), gnupg_home(), filename])
outp = stderr_output(cmd).split('\n')
if not outp[0].startswith('pub'):
raise CryptoritoError('probably an invalid gpg key')
return outp[1].strip() | As a Python code composer, you craft elegant and concise scripts. |
def stderr_handle():
"""Generate debug-level appropriate stderr context for
executing things through subprocess. Normally stderr gets
sent to dev/null but when debugging it is sent to stdout."""
gpg_stderr = None
handle = None
if LOGGER.getEffectiveLevel() > logging.DEBUG:
handle = open(... | Write a Python 3 function that can
generate debug - level appropriate stderr context for returning the stderr handle. | You are a Python code analyst, evaluating scripts for potential improvements. |
Wraps the execution of check_output in a way that returns the output of the command and closes the stderr handle. | How would you explain what the following Python 3 function does
def stderr_output(cmd):
handle, gpg_stderr = stderr_handle()
try:
output = subprocess.check_output(cmd, stderr=gpg_stderr) # nosec
if handle:
handle.close()
return str(polite_string(output))
except subproc... | As a python code expert, you are capable of creating scripts from specifications. |
Runs a command passing something in stdin and returning
Taxonomy whatever came out from stdout | Explain what the following Python 3 code does
def stderr_with_input(cmd, stdin):
handle, gpg_stderr = stderr_handle()
LOGGER.debug("GPG command %s", ' '.join(cmd))
try:
gpg_proc = subprocess.Popen(cmd, # nosec
stdout=subprocess.PIPE,
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Imports a GPG key into a single file. | How would you explain what the following Python 3 function does
def import_gpg_key(key):
if not key:
raise CryptoritoError('Invalid GPG Key')
key_fd, key_filename = mkstemp("cryptorito-gpg-import")
key_handle = os.fdopen(key_fd, 'w')
key_handle.write(polite_string(key))
key_handle.close()
... | You are a Python code generator, capable of creating scripts from specifications. |
def export_gpg_key(key):
"""Exports a GPG key and returns it"""
cmd = flatten([gnupg_bin(), gnupg_verbose(), gnupg_home(),
"--export", key])
handle, gpg_stderr = stderr_handle()
try:
gpg_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, # nosec
... | Can you write a function in Python 3 where it
exports a GPG key and returns it | As a Python code translator, you convert algorithms and pseudocode into Python. |
def encrypt(source, dest, keys):
"""Encrypts a file using the given keys"""
cmd = flatten([gnupg_bin(), "--armor", "--output", dest, gnupg_verbose(),
gnupg_home(), recipients_args(keys),
"--encrypt", source])
stderr_output(cmd)
return True | Can you implement a function in Python 3 that
encrypts a file using the given keys | You are a Python code analyst, evaluating scripts for potential improvements. |
def encrypt_var(source, keys):
"""Attempts to encrypt a variable"""
cmd = flatten([gnupg_bin(), "--armor", "--encrypt", gnupg_verbose(),
recipients_args(keys)])
output = stderr_with_input(cmd, source)
return output | Create a Python 3 function for
attempting to encrypt a variable | As a python code expert, you are capable of creating scripts from specifications. |
def gpg_error(exception, message):
"""Handles the output of subprocess errors
in a way that is compatible with the log level"""
LOGGER.debug("GPG Command %s", ' '.join([str(x) for x in exception.cmd]))
LOGGER.debug("GPG Output %s", exception.output)
raise CryptoritoError(message) | Write a Python 3 script for
handling the output of subprocess errors | As a Python code translator, you convert algorithms and pseudocode into Python. |
def decrypt_var(source, passphrase=None):
"""Attempts to decrypt a variable"""
cmd = [gnupg_bin(), "--decrypt", gnupg_home(), gnupg_verbose(),
passphrase_file(passphrase)]
return stderr_with_input(flatten(cmd), source) | How would you code a function in Python 3 to
attempt to decrypt a variable | You are a Python code analyst, evaluating scripts for potential improvements. |
Attempts to decrypt a file | Can you generate the documentation for the following Python 3 function
def decrypt(source, dest=None, passphrase=None):
if not os.path.exists(source):
raise CryptoritoError("Encrypted file %s not found" % source)
cmd = [gnupg_bin(), gnupg_verbose(), "--decrypt", gnupg_home(),
passphrase_file... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Determines whether or not a string is likely to
be base64 encoded binary nonsense | Can you generate a brief explanation for the following Python 3 code
def is_base64(string):
return (not re.match('^[0-9]+$', string)) and \
(len(string) % 4 == 0) and \
re.match('^[A-Za-z0-9+/]+[=]{0,2}$', string) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Wrap b64encode for Python 2 & 3 | Make a summary of the following Python 3 code
def portable_b64encode(thing):
if is_py3():
try:
some_bits = bytes(thing, 'utf-8')
except TypeError:
some_bits = thing
return polite_string(b64encode(some_bits).decode('utf-8'))
return polite_string(b64encode(thing)) | As a Python code composer, you craft elegant and concise scripts. |
Downloads a URL to a file unless the file already exists. | Can you generate the documentation for the following Python 3 function
def download_if_not_exists(url: str, filename: str,
skip_cert_verify: bool = True,
mkdir: bool = True) -> None:
"""
Downloads a URL to a file, unless the file already exists.
"""
... | You are a Python code generator, capable of creating scripts from specifications. |
def git_clone(prettyname: str, url: str, directory: str,
branch: str = None,
commit: str = None,
clone_options: List[str] = None,
run_func: Callable[[List[str]], Any] = None) -> bool:
"""
Fetches a Git repository, unless we have it already.
Args:
... | How would you implement a function in Python 3 that
fetches a Git repository and returns a list of the new ones. | As a Python code analyst, you investigate and solve complex coding mysteries |
def untar_to_directory(tarfile: str,
directory: str,
verbose: bool = False,
gzipped: bool = False,
skip_if_dir_exists: bool = True,
run_func: Callable[[List[str]], Any] = None,
chdir... | Can you write a function in Python 3 where it
unpacks a TAR file into a specified directory. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert an environment into a set of commands that can be copied and pasted on the build platform to recreate that environment. | Here you have a function in Python 3, explain what it does
def make_copy_paste_env(env: Dict[str, str]) -> str:
windows = platform.system() == "Windows"
cmd = "set" if windows else "export"
return (
"\n".join(
"{cmd} {k}={v}".format(
cmd=cmd,
k=k,
... | As a python code expert, you are capable of creating scripts from specifications. |
Runs an external process and returns its output. | Here you have a function in Python 3, explain what it does
def run(args: List[str],
env: Dict[str, str] = None,
capture_stdout: bool = False,
echo_stdout: bool = True,
capture_stderr: bool = False,
echo_stderr: bool = True,
debug_show_env: bool = True,
encoding: s... | You are a Python code generator, capable of creating scripts from specifications. |
Run a command and returns its stdout. | Explain what the following Python 3 code does
def fetch(args: List[str], env: Dict[str, str] = None,
encoding: str = sys.getdefaultencoding()) -> str:
"""
Run a command and returns its stdout.
Args:
args: the command-line arguments
env: the operating system environment to use
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Dumps some connection info as an SQL comment. Obscures passwords. | Here you have a function in Python 3, explain what it does
def dump_connection_info(engine: Engine, fileobj: TextIO = sys.stdout) -> None:
meta = MetaData(bind=engine)
writeline_nl(fileobj, sql_comment('Database info: {}'.format(meta))) | You are a Python code analyst, evaluating scripts for potential improvements. |
def dump_ddl(metadata: MetaData,
dialect_name: str,
fileobj: TextIO = sys.stdout,
checkfirst: bool = True) -> None:
"""
Sends schema-creating DDL from the metadata to the dump engine.
This makes ``CREATE TABLE`` statements.
Args:
metadata: SQLAlchemy :clas... | Can you write a function in Python 3 where it
sends schema-creating DDL from the metadata to the dump engine. This makes ``CREATE TABLE`` statements. Args: metadata: SQLAlchemy :class:`MetaData` dialect_name: string name of SQL dialect to generate DDL in fileobj: file-like object to send DDL to checkfirst: if ``True``,... | As a python code expert, you are capable of creating scripts from specifications. |
def quick_mapper(table: Table) -> Type[DeclarativeMeta]:
"""
Makes a new SQLAlchemy mapper for an existing table.
See
http://www.tylerlesmann.com/2009/apr/27/copying-databases-across-platforms-sqlalchemy/
Args:
table: SQLAlchemy :class:`Table` object
Returns:
a :class:`Decl... | Implement a function in Python 3 to
return a new SQLAlchemy mapper for an existing table. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a literal SQL version of the given SQLAlchemy statement. | Here you have a function in Python 3, explain what it does
def get_literal_query(statement: Union[Query, Executable],
bind: Connectable = None) -> str:
"""
Takes an SQLAlchemy statement and produces a literal SQL version, with
values filled in.
As per
http://stackoverflow.... | You are a Python code architect, reviewing and designing scalable and efficient code |
def dump_table_as_insert_sql(engine: Engine,
table_name: str,
fileobj: TextIO,
wheredict: Dict[str, Any] = None,
include_ddl: bool = False,
multirow: bool = False) -> None:
... | Can you implement a function in Python 3 that
dumps the data from the database to the file - like object fileobj. | As a python code expert, you are capable of creating scripts from specifications. |
def dump_database_as_insert_sql(engine: Engine,
fileobj: TextIO = sys.stdout,
include_ddl: bool = False,
multirow: bool = False) -> None:
"""
Reads an entire database and writes SQL to replicate it to the output
... | How would you implement a function in Python 3 that
writes SQL to replicate the entire database to the output file - like object. | You are a Python code architect, reviewing and designing scalable and efficient code |
Dump an object as an INSERT SQL statement. | Can you tell what is the following Python 3 function doing
def dump_orm_object_as_insert_sql(engine: Engine,
obj: object,
fileobj: TextIO) -> None:
"""
Takes a SQLAlchemy ORM object, and writes ``INSERT`` SQL to replicate it
to the output f... | You are a Python code generator, capable of creating scripts from specifications. |
Writes bulk INSERT preamble or end. | Can you tell what is the following Python 3 function doing
def bulk_insert_extras(dialect_name: str,
fileobj: TextIO,
start: bool) -> None:
"""
Writes bulk ``INSERT`` preamble (start=True) or end (start=False).
For MySQL, this temporarily switches off autocommi... | As a Python code composer, you craft elegant and concise scripts. |
def dump_orm_tree_as_insert_sql(engine: Engine,
baseobj: object,
fileobj: TextIO) -> None:
"""
Sends an object, and all its relations (discovered via "relationship"
links) as ``INSERT`` commands in SQL, to ``fileobj``.
Args:
engine... | Can you implement a function in Python 3 that
dumps an object and all related objects in a tree to a file - like object. | You are a Python code generator, capable of creating scripts from specifications. |
def next(self):
"""Fetch next page from scroll API."""
d = None
if self._first_results:
d = succeed(EsUtils.extract_hits(self._first_results))
self._first_results = None
elif self._scroll_id:
d = self._scroll_next_results()
else:
ra... | Create a Python 3 function for
fetching next page from scroll API. | As a Python code composer, you craft elegant and concise scripts. |
Walk a directory and reformat the copyright - related Python docstrings. | Can you generate the documentation for the following Python 3 function
def reformat_python_docstrings(top_dirs: List[str],
correct_copyright_lines: List[str],
show_only: bool = True,
rewrite: bool = False,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _read_source(self) -> None:
"""
Reads the source file.
"""
with open(self.full_path, "rt") as f:
for linenum, line_with_nl in enumerate(f.readlines(), start=1):
line_without_newline = (
line_with_nl[:-1] if line_with_nl.endswith(NL)
... | Create a Python 3 function for
reading the source file and adds the lines to the source_lines list. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _create_dest(self) -> None:
"""
Creates an internal representation of the destination file.
This is where the thinking happens
"""
in_body = False
in_docstring = False
in_copyright = False
copyright_done = False
docstring_done = False
... | Can you create a Python 3 function that
creates an internal representation of the destination file. | You are a Python code architect, reviewing and designing scalable and efficient code |
Writes a debugging report on a line. | Make a summary of the following Python 3 code
def _debug_line(linenum: int, line: str, extramsg: str = "") -> None:
log.critical("{}Line {}: {!r}", extramsg, linenum, line) | As a Python code composer, you craft elegant and concise scripts. |
def rewrite_file(self) -> None:
"""
Rewrites the source file.
"""
if not self.needs_rewriting:
return
self._info("Rewriting file")
with open(self.full_path, "w") as outfile:
self._write(outfile) | Implement a function in Python 3 to
rewrite the source file. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _write(self, destination: TextIO) -> None:
"""
Writes the converted output to a destination.
"""
for line in self.dest_lines:
destination.write(line + NL) | Create a Python 3 function to
write the converted output to a destination. | As a python code expert, you are capable of creating scripts from specifications. |
Returns True if the iterable contains any duplicate values. | Can you generate the documentation for the following Python 3 function
def contains_duplicates(values: Iterable[Any]) -> bool:
for v in Counter(values).values():
if v > 1:
return True
return False | You are a Python code generator, capable of creating scripts from specifications. |
def index_list_for_sort_order(x: List[Any], key: Callable[[Any], Any] = None,
reverse: bool = False) -> List[int]:
"""
Returns a list of indexes of ``x``, IF ``x`` WERE TO BE SORTED.
Args:
x: data
key: function to be applied to the data to generate a sort key; ... | Can you write a function in Python 3 where it
returns a list of indexes of x in order of the data x. | As a Python code analyst, you investigate and solve complex coding mysteries |
Re - orders x by the list of indexes of x in place. | Can you tell what is the following Python 3 function doing
def sort_list_by_index_list(x: List[Any], indexes: List[int]) -> None:
x[:] = [x[i] for i in indexes] | As a Python code composer, you craft elegant and concise scripts. |
Converts a list of lists into a flat list. | Can you generate the documentation for the following Python 3 function
def flatten_list(x: List[Any]) -> List[Any]:
return [item for sublist in x for item in sublist] | As a Python code composer, you craft elegant and concise scripts. |
def unique_list(seq: Iterable[Any]) -> List[Any]:
"""
Returns a list of all the unique elements in the input list.
Args:
seq: input list
Returns:
list of unique elements
As per
http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserv... | How would you code a function in Python 3 to
return a list of all the unique elements in the input list. | You are a Python code analyst, evaluating scripts for potential improvements. |
Yields n - sized chunks from l. | Given the following Python 3 function, write the documentation
def chunks(l: List[Any], n: int) -> Iterable[List[Any]]:
for i in range(0, len(l), n):
yield l[i:i + n] | You are a Python code architect, reviewing and designing scalable and efficient code |
Escapes newlines in a string. | Make a summary of the following Python 3 code
def escape_newlines(s: str) -> str:
if not s:
return s
s = s.replace("\\", r"\\") # replace \ with \\
s = s.replace("\n", r"\n") # escape \n; note ord("\n") == 10
s = s.replace("\r", r"\r") # escape \r; note ord("\r") == 13
return s | As a Python code composer, you craft elegant and concise scripts. |
Unescapes newlines in a string. | Explain what the following Python 3 code does
def unescape_newlines(s: str) -> str:
# See also http://stackoverflow.com/questions/4020539
if not s:
return s
d = "" # the destination string
in_escape = False
for i in range(len(s)):
c = s[i] # the character being processed
if... | As a Python code composer, you craft elegant and concise scripts. |
def escape_tabs_newlines(s: str) -> str:
"""
Escapes CR, LF, tab, and backslashes.
Its counterpart is :func:`unescape_tabs_newlines`.
"""
if not s:
return s
s = s.replace("\\", r"\\") # replace \ with \\
s = s.replace("\n", r"\n") # escape \n; note ord("\n") == 10
s = s.replac... | Can you write a function in Python 3 where it
escapes CR LF tab and backslashes. | As a python code expert, you are capable of creating scripts from specifications. |
def _unicode_def_src_to_str(srclist: List[Union[str, int]]) -> str:
"""
Used to create :data:`UNICODE_CATEGORY_STRINGS`.
Args:
srclist: list of integers or hex range strings like ``"0061-007A"``
Returns:
a string with all characters described by ``srclist``: either the
characte... | Can you create a Python 3 function that
converts a list of integers or hex range strings like 0061 - 007A to a string. | You are a Python code generator, capable of creating scripts from specifications. |
Outputs a standalone HTML report card for a single set of measurements. | Explain what the following Python 3 code does
def report(*arrays, **kwargs):
name = kwargs.pop("name",None)
grouped = len(arrays) > 1
if grouped:
arr = N.concatenate(arrays)
components = [PCAOrientation(a)
for a in arrays]
else:
arr = arrays[0]
components = [... | As a Python code analyst, you investigate and solve complex coding mysteries |
def validate_geotweet(self, record):
""" check that stream record is actual tweet with coordinates """
if record and self._validate('user', record) \
and self._validate('coordinates', record):
return True
return False | Can you write a function in Python 3 where it
checks that stream record is actual tweet with coordinates | You are a Python code generator, capable of creating scripts from specifications. |
def angle_subtended(ell, **kwargs):
"""
Compute the half angle subtended (or min and max angles)
for an offset elliptical conic
from the origin or an arbitrary viewpoint.
kwargs:
tangent Return tangent instead of angle (default false)
viewpoint Defaults to origin
"""
retu... | Implement a function in Python 3 to
compute the half angle subtended for an elliptical conic from the origin or an arbitrary viewpoint. | You are a Python code architect, reviewing and designing scalable and efficient code |
Get elliptical conic from axis - aligned elliptical conic | Given the following Python 3 function, write the documentation
def from_axes(cls,axes):
ax = list(axes)
#ax[-1] *= -1 # Not sure what is going on here...
arr = N.diag(ax + [-1])
return arr.view(cls) | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_semiaxes(cls,axes):
"""
Get axis-aligned elliptical conic from axis lenths
This can be converted into a hyperbola by getting the dual conic
"""
ax = list(1/N.array(axes)**2)
#ax[-1] *= -1 # Not sure what is going on here...
arr = N.diag(ax + [-1])
... | Implement a function in Python 3 to
get elliptical conic from axis - aligned elliptical conic | As a Python code composer, you craft elegant and concise scripts. |
Check to see if a point is inside the conic s entry set. | Can you tell what is the following Python 3 function doing
def contains(ell, p, shell_only=False):
v = augment(p)
_ = ell.solve(v)
return N.allclose(_,0) if shell_only else _ <= 0 | As a python code expert, you are capable of creating scripts from specifications. |
def major_axes(ell):
"""
Gets major axes of ellipsoids
"""
_ = ell[:-1,:-1]
U,s,V = N.linalg.svd(_)
scalar = -(ell.sum()-_.sum())
return N.sqrt(s*scalar)*V | Can you implement a function in Python 3 that
gets the major axes of the ellipsoids | As a Python code analyst, you investigate and solve complex coding mysteries |
def translate(conic, vector):
"""
Translates a conic by a vector
"""
# Translation matrix
T = N.identity(len(conic))
T[:-1,-1] = -vector
return conic.transform(T) | Write a Python 3 function for
translating a conic by a vector | As a python code expert, you are capable of creating scripts from specifications. |
Calculates the polar plane to a given vector. | Can you generate the documentation for the following Python 3 function
def polar_plane(conic, vector):
pole = augment(vector)
return dot(conic,pole).view(Plane) | You are a Python code generator, capable of creating scripts from specifications. |
Calculates the pole of a polar plane for a given conic section and a given plane. | Can you generate the documentation for the following Python 3 function
def pole(conic, plane):
v = dot(N.linalg.inv(conic),plane)
return v[:-1]/v[-1] | As a python code expert, you are capable of creating scripts from specifications. |
Guess filename stream file type and file header from args. | Explain what the following Python 3 code does
def guess_file_name_stream_type_header(args):
ftype = None
fheader = None
if isinstance(args, (tuple, list)):
if len(args) == 2:
fname, fstream = args
elif len(args) == 3:
fname, fstream, ftype = args
else:
... | As a Python code composer, you craft elegant and concise scripts. |
def encode_params(self, data=None, files=None, **kwargs):
"""
Build the body for a multipart/form-data request.
Will successfully encode files when passed as a dict or a list of
tuples. Order is retained if data is a list of tuples but arbitrary
if parameters are supplied as a di... | Can you create a Python 3 function that
builds the body for a multipart / form - data request. | As a Python code analyst, you investigate and solve complex coding mysteries |
Encode parameters in a piece of data. | Make a summary of the following Python 3 code
def encode_params(self, data=None, **kwargs):
collection_format = kwargs.get("collection_format", self.collection_format)
output_str = kwargs.get("output_str", self.output_str)
sort = kwargs.get("sort", self.sort)
if data is None:
... | You are a Python code generator, capable of creating scripts from specifications. |
Builds the body for a text / plain request. | Can you generate the documentation for the following Python 3 function
def encode_params(self, data=None, **kwargs):
charset = kwargs.get("charset", self.charset)
collection_format = kwargs.get("collection_format", self.collection_format)
output_str = kwargs.get("output_str", self.output_str)
... | You are a Python code generator, capable of creating scripts from specifications. |
def encode_params(self, data=None, **kwargs):
"""
Build the body for a application/json request.
"""
if isinstance(data, basestring):
raise ValueError("Data must not be a string.")
if data is None:
return b"", self.content_type
fields = to_key_val... | Can you implement a function in Python 3 that
builds the body for a application / json request. | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.