output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Determines whether an OpenXML file appears to be good. | Can you generate the documentation for the following Python 3 function
def is_openxml_good(filename: str) -> bool:
try:
log.debug("Trying: {}", filename)
with ZipFile(filename, 'r') as zip_ref:
namelist = zip_ref.namelist() # type: List[str]
# log.critical("\n{}", pformat(na... | As a python code expert, you are capable of creating scripts from specifications. |
def process_openxml_file(filename: str,
print_good: bool,
delete_if_bad: bool) -> None:
"""
Prints the filename of, or deletes, an OpenXML file depending on whether
it is corrupt or not.
Args:
filename: filename to check
print_good: if `... | How would you code a function in Python 3 to
process an OpenXML file based on whether it is good or not. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function is called by the command line interface to find bad OpenXML files. | How would you explain what the following Python 3 function does
def main() -> None:
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
description="""
Tool to scan rescued Microsoft Office OpenXML files (produced by the
find_recovered_openxml.py tool in this kit; q.v.) and detect ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Open the SMTP connection to the email server. | Can you tell what is the following Python 3 function doing
def open(self) -> bool:
if self.connection:
# Nothing to do if the connection is already open.
return False
connection_params = {'local_hostname': DNS_NAME.get_fqdn()}
if self.timeout is not None:
con... | As a Python code analyst, you investigate and solve complex coding mysteries |
A measure of the distance between two probability distributions
| Explain what the following Python 3 code does
def bhattacharyya_distance(pca1,pca2):
u1 = pca1.coefficients
s1 = pca1.covariance_matrix
u2 = pca2.coefficients
s2 = pca2.covariance_matrix
sigma = (s1+s2)/2
assert all(u1 > 0)
assert all(u2 > 0)
assert all(s1.sum(axis=1) > 0)
assert a... | As a Python code composer, you craft elegant and concise scripts. |
Produce CSV output for the current language. | Can you tell what is the following Python 3 function doing
def produce_csv_output(filehandle: TextIO,
fields: Sequence[str],
values: Iterable[str]) -> None:
"""
Produce CSV output, without using ``csv.writer``, so the log can be used
for lots of things.
- .... | As a python code expert, you are capable of creating scripts from specifications. |
def output_csv(filehandle: TextIO, values: Iterable[str]) -> None:
"""
Write a line of CSV. POOR; does not escape things properly. DEPRECATED.
Args:
filehandle: file to write to
values: values
"""
line = ",".join(values)
filehandle.write(line + "\n") | How would you implement a function in Python 3 that
writes a line of CSV. POOR does not escape things properly. DEPRECATED. | As a Python code composer, you craft elegant and concise scripts. |
Find the part of s that is after prefix. | Can you generate a brief explanation for the following Python 3 code
def get_what_follows_raw(s: str,
prefix: str,
onlyatstart: bool = True,
stripwhitespace: bool = True) -> Tuple[bool, str]:
"""
Find the part of ``s`` that is after ``pr... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the string that follows the prefix. | Can you generate a brief explanation for the following Python 3 code
def get_what_follows(strings: Sequence[str],
prefix: str,
onlyatstart: bool = True,
stripwhitespace: bool = True,
precedingline: str = "") -> str:
"""
Find a s... | You are a Python code analyst, evaluating scripts for potential improvements. |
Find a string as per get_what_follows. | Can you generate the documentation for the following Python 3 function
def get_string(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[str]:
"""
Find a string as per :func:`get_what_follows`.
Args:
... | As a python code expert, you are capable of creating scripts from specifications. |
Returns the string that is relative to the first line in the sequence of strings. | Make a summary of the following Python 3 code
def get_string_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False,
stripwhitespace: bool = True) ->... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_int(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[int]:
"""
Fetches an integer parameter via :func:`get_string`.
"""
return get_int_raw(get_string(strings, prefix,
... | Can you implement a function in Python 3 that
retrieves an integer parameter from a sequence of strings. | You are a Python code analyst, evaluating scripts for potential improvements. |
Retrieves a float parameter from a sequence of strings. | Can you tell what is the following Python 3 function doing
def get_float(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[float]:
"""
Fetches a float parameter via :func:`get_string`.
"""
return get_floa... | You are a Python code generator, capable of creating scripts from specifications. |
Maps Y to True and N to False. | How would you explain what the following Python 3 function does
def get_bool_raw(s: str) -> Optional[bool]:
if s == "Y" or s == "y":
return True
elif s == "N" or s == "n":
return False
return None | You are a Python code generator, capable of creating scripts from specifications. |
def get_bool(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[bool]:
"""
Fetches a boolean parameter via :func:`get_string`.
"""
return get_bool_raw(get_string(strings, prefix,
... | Implement a function in Python 3 to
fetch a boolean parameter from a sequence of strings. | You are a Python code analyst, evaluating scripts for potential improvements. |
Gets a boolean parameter from a sequence of strings relative to a given base. | How would you explain what the following Python 3 function does
def get_bool_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[bool]:
"""
Fetches a boolean... | As a python code expert, you are capable of creating scripts from specifications. |
Gets a float parameter from a sequence of strings relative to a given prefix. | Can you tell what is the following Python 3 function doing
def get_float_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[float]:
"""
Fetches a float ... | As a python code expert, you are capable of creating scripts from specifications. |
def get_int_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[int]:
"""
Fetches an int parameter via :func:`get_string_relative`.
"""
return get_int_ra... | Can you write a function in Python 3 where it
gets an integer parameter from a sequence of strings relative to another string. | As a Python code composer, you craft elegant and concise scripts. |
def get_datetime(strings: Sequence[str],
prefix: str,
datetime_format_string: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[datetime.datetime]:
"""
Fetches a ``datetime.datetime`` parameter via :func:`get_string`.
... | Can you create a Python 3 function that
retrieves a datetime. datetime parameter from a sequence of strings. | You are a Python code architect, reviewing and designing scalable and efficient code |
def find_line_beginning(strings: Sequence[str],
linestart: Optional[str]) -> int:
"""
Finds the index of the line in ``strings`` that begins with ``linestart``,
or ``-1`` if none is found.
If ``linestart is None``, match an empty line.
"""
if linestart is None: # match ... | Write a Python 3 function that can
find the index of the line in strings that begins with linestart. | You are a Python code generator, capable of creating scripts from specifications. |
def find_line_containing(strings: Sequence[str], contents: str) -> int:
"""
Finds the index of the line in ``strings`` that contains ``contents``,
or ``-1`` if none is found.
"""
for i in range(len(strings)):
if strings[i].find(contents) != -1:
return i
return -1 | Can you implement a function in Python 3 that
finds the index of the line in strings that contains contents. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Takes a list of strings and returns a list of strings FROM firstlinestart TO lastline_starts. | Given the following Python 3 function, write the documentation
def get_lines_from_to(strings: List[str],
firstlinestart: str,
list_of_lastline_starts: Iterable[Optional[str]]) \
-> List[str]:
"""
Takes a list of ``strings``. Returns a list of strings FROM
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def csv_to_list_of_fields(lines: List[str],
csvheader: str,
quotechar: str = '"') -> List[str]:
"""
Extracts data from a list of CSV lines (starting with a defined header
line) embedded in a longer text block but ending with a blank line.
Used for... | Write a Python 3 script to
return a list of fields from a CSV file. | As a python code expert, you are capable of creating scripts from specifications. |
Extracts data from a list of CSV lines starting with a defined header line and ending with a blank line. | Can you generate the documentation for the following Python 3 function
def csv_to_list_of_dicts(lines: List[str],
csvheader: str,
quotechar: str = '"') -> List[Dict[str, str]]:
"""
Extracts data from a list of CSV lines (starting with a defined header
line) ... | You are a Python code generator, capable of creating scripts from specifications. |
Converts a list of dictionaries to a string form. | Can you generate the documentation for the following Python 3 function
def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None:
for d in dict_list:
d[key] = str(d[key])
if d[key] == "":
d[key] = None | You are a Python code architect, reviewing and designing scalable and efficient code |
Converts a list of dictionaries into a datetime. datetime object. | Explain what the following Python 3 code does
def dictlist_convert_to_datetime(dict_list: Iterable[Dict],
key: str,
datetime_format_string: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) `... | As a python code expert, you are capable of creating scripts from specifications. |
Converts each dictionary d [ key ] to an integer. | Can you generate the documentation for the following Python 3 function
def dictlist_convert_to_int(dict_list: Iterable[Dict], key: str) -> None:
for d in dict_list:
try:
d[key] = int(d[key])
except ValueError:
d[key] = None | As a Python code analyst, you investigate and solve complex coding mysteries |
Converts each dictionary in dict_list to a float. | Can you generate a brief explanation for the following Python 3 code
def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None:
for d in dict_list:
try:
d[key] = float(d[key])
except ValueError:
d[key] = None | As a Python code composer, you craft elegant and concise scripts. |
Convert a list of dictionaries to a bool. | Can you generate the documentation for the following Python 3 function
def dictlist_convert_to_bool(dict_list: Iterable[Dict], key: str) -> None:
for d in dict_list:
# d[key] = True if d[key] == "Y" else False
d[key] = 1 if d[key] == "Y" else 0 | As a Python code composer, you craft elegant and concise scripts. |
def dictlist_replace(dict_list: Iterable[Dict], key: str, value: Any) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, change
(in place) ``d[key]`` to ``value``.
"""
for d in dict_list:
d[key] = value | Implement a Python 3 function for
replacing a key with value in a list of dictionaries. | As a Python code composer, you craft elegant and concise scripts. |
def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, delete
``d[key]`` if it exists.
"""
for d in dict_list:
d.pop(key, None) | Write a Python 3 script to
remove a key from a list of dictionaries. | As a Python code composer, you craft elegant and concise scripts. |
Returns a string that can be used to generate a cache key for the function call. | Can you tell what is the following Python 3 function doing
def get_call_signature(fn: FunctionType,
args: ArgsType,
kwargs: KwargsType,
debug_cache: bool = False) -> str:
"""
Takes a function and its args/kwargs, and produces a string descript... | As a Python code analyst, you investigate and solve complex coding mysteries |
Generates a unique cache key for the given function call signature. | Explain what the following Python 3 code does
def make_cache_key(call_signature: str,
debug_cache: bool = False) -> str:
"""
Takes a function and its args/kwargs, and produces a string description
of the function call (the call signature) suitable for use as a cache key.
The string is... | As a python code expert, you are capable of creating scripts from specifications. |
A decorator that returns a function that caches the result of the function in Django s cache. | Can you tell what is the following Python 3 function doing
def django_cache_function(timeout: int = 5 * 60,
cache_key: str = '',
debug_cache: bool = False):
"""
Decorator to add caching to a function in Django.
Uses the Django default cache.
Args:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def transform(v1, v2):
"""
Create an affine transformation matrix that maps vector 1
onto vector 2
https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another
"""
theta = angle(v1,v2)
x = N.cross(v1,v2)
x = x / N.linalg.norm(x)
A = N.array([
[0, -x[2],... | Can you implement a function in Python 3 that
creates an affine transformation matrix that maps vector 1 onto vector 2. | As a Python code composer, you craft elegant and concise scripts. |
Converts spherical positions in ( lon lat ) to cartesian coordiantes [ x y z ) | How would you explain what the following Python 3 function does
def cartesian(lon, lat):
return N.array([
N.cos(lat)*N.cos(lon),
N.cos(lat)*N.sin(lon),
N.sin(lat)
]) | You are a Python code generator, capable of creating scripts from specifications. |
Calculate the authentication headers needed to send a request to the Latch API. | Explain what the following Python 3 code does
def x_11paths_authorization(app_id, secret, context, utc=None):
utc = utc or context.headers[X_11PATHS_DATE_HEADER_NAME]
url_path = ensure_url_path_starts_with_slash(context.url_path)
url_path_query = url_path
if context.query_params:
url_path_query... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _sign_data(secret, data):
"""
Sign data.
:param data: the string to sign
:return: string base64 encoding of the HMAC-SHA1 hash of the data parameter using {@code secretKey} as cipher key.
"""
sha1_hash = hmac.new(secret.encode(), data.encode(), sha1)
return binascii.b2a_base64(sha1_hash... | How would you implement a function in Python 3 that
signs data using the secret as cipher key. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a string ready to be signed from the 11 - paths specific HTTP headers received. | Here you have a function in Python 3, explain what it does
def _get_11paths_serialized_headers(x_headers):
if x_headers:
headers = to_key_val_list(x_headers, sort=True, insensitive=True)
serialized_headers = ""
for key, value in headers:
if key.lower().startswith(X_11PATHS_HEADER... | As a Python code analyst, you investigate and solve complex coding mysteries |
def rotate_2D(angle):
"""
Returns a 2x2 transformation matrix to rotate
by an angle in two dimensions
"""
return N.array([[N.cos(angle),-N.sin(angle)],
[N.sin(angle),N.cos(angle)]]) | Can you implement a function in Python 3 that
returns a 2x2 transformation matrix to rotate the sequence element by an angle in two dimensions. | You are a Python code analyst, evaluating scripts for potential improvements. |
Generates a two - dimensional rotation matrix that rotates a projected dataset to correct for apparent dip
| Can you tell what is the following Python 3 function doing
def apparent_dip_correction(axes):
a1 = axes[0].copy()
a1[-1] = 0
cosa = angle(axes[0],a1,cos=True)
_ = 1-cosa**2
if _ > 1e-12:
sina = N.sqrt(_)
if cosa < 0:
sina *= -1
# Construct rotation matrix
... | You are a Python code generator, capable of creating scripts from specifications. |
Create a function that can be used to create a view of a hyperbolic error ellipse from a specific direction. | Explain what the following Python 3 code does
def hyperbolic_errors(hyp_axes, xvals,
transformation=None, axes=None,
means=None, correct_apparent_dip=True,
reverse=False):
"""
Returns a function that can be used to create a view of the
hyperb... | As a Python code composer, you craft elegant and concise scripts. |
def hyperbola_values(hyp_axes, xvals):
"""
kwargs:
transformation rotation to apply to quadric prior to slicing
(e.g. transformation into 'world' coordinates
axes axes on which to slice the data
"""
A = N.sqrt(hyp_axes)
return A[1]*N.cosh(N.arcsinh... | Can you implement a function in Python 3 that
computes hyperbola values for the given set of values. | As a python code expert, you are capable of creating scripts from specifications. |
def sizeof_fmt(num: float, suffix: str = 'B') -> str:
"""
Formats a number of bytes in a human-readable binary format (e.g. ``2048``
becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841.
"""
for unit in ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'):
if abs(num) < 1024.0:
... | Can you implement a function in Python 3 that
formats a number of bytes in a human - readable binary format. | You are a Python code analyst, evaluating scripts for potential improvements. |
def bytes2human(n: Union[int, float],
format: str = '%(value).1f %(symbol)s',
symbols: str = 'customary') -> str:
"""
Converts a number of bytes into a human-readable format.
From http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/.
Ar... | Can you create a Python 3 function that
returns a human - readable version of the number of bytes in a format specification string. | You are a Python code architect, reviewing and designing scalable and efficient code |
def human2bytes(s: str) -> int:
"""
Modified from
http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/.
Attempts to guess the string format based on default symbols
set and return the corresponding bytes as an integer.
When unable to recognize the format, :exc... | Implement a function in Python 3 to
convert a human - readable string to bytes. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_all_dependencies(metadata: MetaData,
extra_dependencies: List[TableDependency] = None,
sort: bool = True) \
-> List[TableDependency]:
"""
Describes how the tables found in the metadata depend on each other.
(If table B contains a foreign key ... | Can you implement a function in Python 3 that
returns a list of all tables that depend on each other. | As a Python code analyst, you investigate and solve complex coding mysteries |
def classify_tables_by_dependency_type(
metadata: MetaData,
extra_dependencies: List[TableDependency] = None,
sort: bool = True) \
-> List[TableDependencyClassification]:
"""
Inspects a metadata object (optionally adding other specified dependencies)
and returns a list of obj... | How would you code a function in Python 3 to
classify a metadata object by their dependencies. | You are a Python code architect, reviewing and designing scalable and efficient code |
Merges the SQLAlchemy database with another SQLAlchemy database. | Explain what the following Python 3 code does
def merge_db(base_class: Type,
src_engine: Engine,
dst_session: Session,
allow_missing_src_tables: bool = True,
allow_missing_src_columns: bool = True,
translate_fn: Callable[[TranslationContext], None] = None... | You are a Python code architect, reviewing and designing scalable and efficient code |
def set_metadata(self, metadata: MetaData) -> None:
"""
Sets the metadata for the parent and child tables.
"""
self._parent.set_metadata(metadata)
self._child.set_metadata(metadata) | Can you implement a function in Python 3 that
sets the metadata for the parent and child tables. | You are a Python code architect, reviewing and designing scalable and efficient code |
Sets the metadata for the parent and child tables unless they were set already. | Here you have a function in Python 3, explain what it does
def set_metadata_if_none(self, metadata: MetaData) -> None:
self._parent.set_metadata_if_none(metadata)
self._child.set_metadata_if_none(metadata) | As a Python code analyst, you investigate and solve complex coding mysteries |
def set_circular(self, circular: bool, chain: List[Table] = None) -> None:
"""
Mark this table as circular (or not).
Args:
circular: is it circular?
chain: if it's circular, this should be the list of tables
participating in the circular chain
"""... | Create a Python 3 function to
mark this table as circular. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Short description of the current object. | Here you have a function in Python 3, explain what it does
def description(self) -> str:
if self.is_parent and self.is_child:
desc = "parent+child"
elif self.is_parent:
desc = "parent"
elif self.is_child:
desc = "child"
else:
desc = "standa... | You are a Python code generator, capable of creating scripts from specifications. |
def excel_to_bytes(wb: Workbook) -> bytes:
"""
Obtain a binary version of an :class:`openpyxl.Workbook` representation of
an Excel file.
"""
memfile = io.BytesIO()
wb.save(memfile)
return memfile.getvalue() | Write a Python 3 script for
returning a binary version of an openpyxl. Workbook representation of an Excel file. | As a Python code composer, you craft elegant and concise scripts. |
Returns a spherical formula from a list of coordinates. | Can you generate a brief explanation for the following Python 3 code
def spherical(coordinates):
c = coordinates
r = N.linalg.norm(c,axis=0)
theta = N.arccos(c[2]/r)
phi = N.arctan2(c[1],c[0])
return N.column_stack((r,theta,phi)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the center of the given coordinates. | Here you have a function in Python 3, explain what it does
def centered(coordinates):
coordinates = N.array(coordinates)
means = N.mean(coordinates,axis=0)
return coordinates - means | You are a Python code generator, capable of creating scripts from specifications. |
def add_http_headers_for_attachment(response: HttpResponse,
offered_filename: str = None,
content_type: str = None,
as_attachment: bool = False,
as_inline: bool = False,
... | Can you write a function in Python 3 where it
adds HTTP headers to a Django response class object. | As a Python code analyst, you investigate and solve complex coding mysteries |
def serve_file(path_to_file: str,
offered_filename: str = None,
content_type: str = None,
as_attachment: bool = False,
as_inline: bool = False) -> HttpResponseBase:
"""
Serve up a file from disk.
Two methods (chosen by ``settings.XSENDFILE``):
... | How would you code a function in Python 3 to
serve up a file from disk. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Serve up binary data from a buffer. | Given the following Python 3 function, write the documentation
def serve_buffer(data: bytes,
offered_filename: str = None,
content_type: str = None,
as_attachment: bool = True,
as_inline: bool = False) -> HttpResponse:
"""
Serve up binary data ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_download_filename(response: HttpResponse, filename: str) -> None:
"""
Adds a ``Content-Disposition`` header to the HTTP response to say that
there is an attachment with the specified filename.
"""
# https://docs.djangoproject.com/en/1.9/howto/outputting-csv/
add_http_headers_for_attachme... | Write a Python 3 script for
adding a Content - Disposition header to the HTTP response to say that there is an attachment with the specified filename. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns an HttpResponse with an attachment containing the specified data with the specified content type and filename as an attachment. | Explain what the following Python 3 code does
def file_response(data: Union[bytes, str], # HttpResponse encodes str if req'd
content_type: str,
filename: str) -> HttpResponse:
"""
Returns an ``HttpResponse`` with an attachment containing the specified
data with the speci... | You are a Python code architect, reviewing and designing scalable and efficient code |
def serve_concatenated_pdf_from_disk(
filenames: Iterable[str],
offered_filename: str = "crate_download.pdf",
**kwargs) -> HttpResponse:
"""
Concatenates PDFs from disk and serves them.
"""
pdf = get_concatenated_pdf_from_disk(filenames, **kwargs)
return serve_buffer(pdf,
... | Can you implement a function in Python 3 that
serves a single PDF from disk. | You are a Python code generator, capable of creating scripts from specifications. |
Serve a PDF from a HTML page. | Can you tell what is the following Python 3 function doing
def serve_pdf_from_html(html: str,
offered_filename: str = "test.pdf",
**kwargs) -> HttpResponse:
"""
Same args as ``pdf_from_html()``.
WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish.
... | As a Python code composer, you craft elegant and concise scripts. |
def serve_concatenated_pdf_from_memory(
pdf_plans: Iterable[PdfPlan],
start_recto: bool = True,
offered_filename: str = "crate_download.pdf") -> HttpResponse:
"""
Concatenates PDFs into memory and serves it.
WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish.
"""
... | Implement a Python 3 function for
serving a single PDF from a list of PDFs into memory and serve it. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def auto_delete_files_on_instance_delete(instance: Any,
fieldnames: Iterable[str]) -> None:
"""
Deletes files from filesystem when object is deleted.
"""
for fieldname in fieldnames:
filefield = getattr(instance, fieldname, None)
if filefield:
... | Can you create a Python 3 function that
deletes files from filesystem when object is deleted. | As a Python code analyst, you investigate and solve complex coding mysteries |
Deletes files from filesystem when instance is changed. | Can you generate the documentation for the following Python 3 function
def auto_delete_files_on_instance_change(
instance: Any,
fieldnames: Iterable[str],
model_class) -> None:
"""
Deletes files from filesystem when object is changed.
model_class: ``Type[Model]``
... only the t... | As a python code expert, you are capable of creating scripts from specifications. |
Creates an affine transformation matrix to rotate data in PCA axes into Cartesian plane. | Can you generate the documentation for the following Python 3 function
def axis_transform(pca_axes):
from_ = N.identity(3)
to_ = pca_axes
# Find inverse transform for forward transform
# y = M x -> M = y (x)^(-1)
# We don't need to do least-squares since
# there is a simple transformation
t... | You are a Python code generator, capable of creating scripts from specifications. |
def covariance_matrix(self):
"""
Constructs the covariance matrix of
input data from
the singular value decomposition. Note
that this is different than a covariance
matrix of residuals, which is what we want
for calculating fit errors.
Using SVD output to compute covariance matrix
X... | Write a Python 3 script for
constructing the covariance matrix of the input data from the singular value decomposition. | You are a Python code architect, reviewing and designing scalable and efficient code |
Property to support lazy evaluation of residuals
| Explain what the following Python 3 code does
def U(self):
if self._U is None:
sinv = N.diag(1/self.singular_values)
self._U = dot(self.arr,self.V.T,sinv)
return self._U | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns residuals of fit against all
| Make a summary of the following Python 3 code
def residuals(self):
_ = self.rotated()
_[:,-1] = 0
_ = N.dot(_,self.axes)
return self.arr - _ | As a Python code composer, you craft elegant and concise scripts. |
Returns the angular error for an in - plane axis of
given length. | How would you explain what the following Python 3 function does
def angular_error(self, axis_length):
hyp_axes = self.method(self)
return N.arctan2(hyp_axes[-1],axis_length) | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the minimum and maximum angular errors of the current class. | Here you have a function in Python 3, explain what it does
def angular_errors(self, degrees=True):
hyp_axes = self.method(self)
v = angular_errors(hyp_axes)
if degrees:
v = N.degrees(v)
return tuple(v) | As a python code expert, you are capable of creating scripts from specifications. |
Constructs the covariance matrix from PCA
residuals. | Make a summary of the following Python 3 code
def _covariance_matrix(self, type='noise'):
if type == 'sampling':
return self.sigma**2/(self.n-1)
elif type == 'noise':
return 4*self.sigma*N.var(self.rotated(), axis=0) | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the explained variance of the log - likelihood of the current cluster entry. | How would you explain what the following Python 3 function does
def explained_variance(self):
v = N.diagonal(self.covariance_matrix)
return v[0:2].sum()/v.sum() | You are a Python code generator, capable of creating scripts from specifications. |
def strike_dip(self, degrees=True):
"""
Computes strike and dip from a normal vector.
Results are usually the same as LLSQ
in strike (to a few decimal places) and close in dip.
Sometimes, dips are greater by as much as 45 degrees,
reflecting inclusion of errors in x-y pla... | Implement a Python 3 function for
computing strike and dip from a normal vector. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the hyperbolic error area of the current object. | Explain what the following Python 3 code does
def as_hyperbola(self, rotated=False):
idx = N.diag_indices(3)
_ = 1/self.covariance_matrix[idx]
d = list(_)
d[-1] *= -1
arr = N.identity(4)*-1
arr[idx] = d
hyp = conic(arr)
if rotated:
R = augment... | As a python code expert, you are capable of creating scripts from specifications. |
def run(self, line):
"""
Extract words from tweet
1. Remove non-ascii characters
2. Split line into individual words
3. Clean up puncuation characters
"""
words = []
for word in self.clean_unicode(line.lower()).split():
if word.starts... | Write a Python 3 script for
extracting words from tweet 69. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the rows and column names from a SQLAlchemy query. | How would you explain what the following Python 3 function does
def get_rows_fieldnames_from_query(
session: Union[Session, Engine, Connection],
query: Query) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]:
"""
Returns results and column names from a query.
Args:
session: SQLAlche... | As a python code expert, you are capable of creating scripts from specifications. |
def bool_from_exists_clause(session: Session,
exists_clause: Exists) -> bool:
"""
Database dialects are not consistent in how ``EXISTS`` clauses can be
converted to a boolean answer. This function manages the inconsistencies.
See:
- https://bitbucket.org/zzzeek/sqla... | Write a Python 3 function for
converting a SQLAlchemy Exists clause to a boolean answer. | You are a Python code generator, capable of creating scripts from specifications. |
def exists_orm(session: Session,
ormclass: DeclarativeMeta,
*criteria: Any) -> bool:
"""
Detects whether a database record exists for the specified ``ormclass``
and ``criteria``.
Example usage:
.. code-block:: python
bool_exists = exists_orm(session, MyClass,... | Implement a function in Python 3 to
determine whether a database record exists for the specified ormclass and criteria. | You are a Python code analyst, evaluating scripts for potential improvements. |
Fetches an ORM object from the database or creates one if none existed. | Can you tell what is the following Python 3 function doing
def get_or_create(session: Session,
model: DeclarativeMeta,
defaults: Dict[str, Any] = None,
**kwargs: Any) -> Tuple[Any, bool]:
"""
Fetches an ORM object from the database, or creates one if none ex... | As a Python code composer, you craft elegant and concise scripts. |
def count_star(self) -> int:
"""
Implements the ``COUNT(*)`` specialization.
"""
count_query = (self.statement.with_only_columns([func.count()])
.order_by(None))
return self.session.execute(count_query).scalar() | Can you create a Python 3 function that
returns the number of starred entries in the database. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def read(self, src):
""" Download GeoJSON file of US counties from url (S3 bucket) """
geojson = None
if not self.is_valid_src(src):
error = "File < {0} > does not exists or does start with 'http'."
raise ValueError(error.format(src))
if not self.is_url(src):
... | Write a Python 3 script to
download GeoJSON file of US counties from url and return it as string. | You are a Python code architect, reviewing and designing scalable and efficient code |
Create and return num_bytes of random data. | Can you generate a brief explanation for the following Python 3 code
def create_base64encoded_randomness(num_bytes: int) -> str:
randbytes = os.urandom(num_bytes) # YES
return base64.urlsafe_b64encode(randbytes).decode('ascii') | You are a Python code generator, capable of creating scripts from specifications. |
def table(self) -> Table:
"""
Returns a SQLAlchemy :class:`Table` object. This is either the
:class:`Table` object that was used for initialization, or one that
was constructed from the ``tablename`` plus the ``metadata``.
"""
if self._table is not None:
retur... | Write a Python 3 script to
return a SQLAlchemy Table object that is used for initialization. | As a Python code analyst, you investigate and solve complex coding mysteries |
def tablename(self) -> str:
"""
Returns the string name of the table.
"""
if self._tablename:
return self._tablename
return self.table.name | Can you create a Python 3 function that
returns the string name of the table. | You are a Python code generator, capable of creating scripts from specifications. |
Checks if a process is running. | Can you generate the documentation for the following Python 3 function
def is_running(process_id: int) -> bool:
pstr = str(process_id)
encoding = sys.getdefaultencoding()
s = subprocess.Popen(["ps", "-p", pstr], stdout=subprocess.PIPE)
for line in s.stdout:
strline = line.decode(encoding)
... | You are a Python code generator, capable of creating scripts from specifications. |
Main function for the pause_process_by_disk_space tool. | Explain what the following Python 3 code does
def main() -> None:
parser = ArgumentParser(
description="Pauses and resumes a process by disk space; LINUX ONLY."
)
parser.add_argument(
"process_id", type=int,
help="Process ID."
)
parser.add_argument(
"--path", required... | As a python code expert, you are capable of creating scripts from specifications. |
def bootstrap_noise(data, func, n=10000, std=1, symmetric=True):
"""
Bootstrap by adding noise
"""
boot_dist = []
arr = N.zeros(data.shape)
for i in range(n):
if symmetric:
# Noise on all three axes
arr = N.random.randn(*data.shape)*std
else:
#... | Create a Python 3 function to
bootstrap noise on the data. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def modelrepr(instance) -> str:
"""
Default ``repr`` version of a Django model object, for debugging.
"""
elements = []
# noinspection PyProtectedMember
for f in instance._meta.get_fields():
# https://docs.djangoproject.com/en/2.0/ref/models/meta/
if f.auto_created:
c... | Write a Python 3 script for
returning a string representation of a Django model object. | You are a Python code analyst, evaluating scripts for potential improvements. |
Assert that a specific PDF processor is available. | Can you generate the documentation for the following Python 3 function
def assert_processor_available(processor: str) -> None:
if processor not in [Processors.XHTML2PDF,
Processors.WEASYPRINT,
Processors.PDFKIT]:
raise AssertionError("rnc_pdf.set_pdf_process... | You are a Python code architect, reviewing and designing scalable and efficient code |
def make_pdf_from_html(
# Mandatory parameters:
on_disk: bool,
html: str,
# Disk options:
output_path: str = None,
# Shared options:
header_html: str = None,
footer_html: str = None,
wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME,
wkhtml... | Can you write a function in Python 3 where it
makes a PDF from HTML. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_pdf_from_html(html: str,
header_html: str = None,
footer_html: str = None,
wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME,
wkhtmltopdf_options: Dict[str, Any] = None,
file_encoding: str = "utf-8",
... | How would you code a function in Python 3 to
take a HTML string and returns a PDF. | You are a Python code analyst, evaluating scripts for potential improvements. |
def pdf_from_writer(writer: Union[PdfFileWriter, PdfFileMerger]) -> bytes:
"""
Extracts a PDF (as binary data) from a PyPDF2 writer or merger object.
"""
memfile = io.BytesIO()
writer.write(memfile)
memfile.seek(0)
return memfile.read() | How would you code a function in Python 3 to
extract a PDF from a PyPDF2 writer or merger object. | As a python code expert, you are capable of creating scripts from specifications. |
def append_memory_pdf_to_writer(input_pdf: bytes,
writer: PdfFileWriter,
start_recto: bool = True) -> None:
"""
Appends a PDF (as bytes in memory) to a PyPDF2 writer.
Args:
input_pdf: the PDF, as ``bytes``
writer: the writer
... | Write a Python 3 script for
appending a PDF to a PyPDF2 writer. | As a python code expert, you are capable of creating scripts from specifications. |
Append a PDF to a pyPDF writer. | Given the following Python 3 function, write the documentation
def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):
append_memory_pdf_to_writer(input_pdf=input_pdf,
writer=output_writer) | As a python code expert, you are capable of creating scripts from specifications. |
Returns a PDF that is concatenated from the given files. | Can you generate a brief explanation for the following Python 3 code
def get_concatenated_pdf_from_disk(filenames: Iterable[str],
start_recto: bool = True) -> bytes:
"""
Concatenates PDFs from disk and returns them as an in-memory binary PDF.
Args:
filenames: iter... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_concatenated_pdf_in_memory(
pdf_plans: Iterable[PdfPlan],
start_recto: bool = True) -> bytes:
"""
Concatenates PDFs and returns them as an in-memory binary PDF.
Args:
pdf_plans: iterable of :class:`PdfPlan` objects
start_recto: start a new right-hand page for each ne... | Implement a function in Python 3 to
return a concatenation of the PDFs in - memory. | As a Python code composer, you craft elegant and concise scripts. |
def add_to_writer(self,
writer: PdfFileWriter,
start_recto: bool = True) -> None:
"""
Add the PDF described by this class to a PDF writer.
Args:
writer: a :class:`PyPDF2.PdfFileWriter`
start_recto: start a new right-hand page?
... | Create a Python 3 function for
adding the PDF described by this class to a PDF writer. | As a Python code analyst, you investigate and solve complex coding mysteries |
def trunc_if_integer(n: Any) -> Any:
"""
Truncates floats that are integers to their integer representation.
That is, converts ``1.0`` to ``1``, etc.
Otherwise, returns the starting value.
Will raise an exception if the input cannot be converted to ``int``.
"""
if n == int(n):
return... | Implement a function in Python 3 to
truncate a number to its integer representation. | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.