output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def cmdline_split(s: str, platform: Union[int, str] = 'this') -> List[str]:
"""
As per
https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex.
Multi-platform variant of ``shlex.split()`` for command-line splitting.
For use with ``subprocess``, for ``argv`` inje... | Create a Python 3 function for
splitting command - line into pieces. | You are a Python code generator, capable of creating scripts from specifications. |
def percentiles(a, pcts, axis=None):
"""Like scoreatpercentile but can take and return array of percentiles.
Parameters
----------
a : array
data
pcts : sequence of percentile values
percentile or percentiles to find score at
axis : int or None
if not None, computes score... | Create a Python 3 function to
like scoreatpercentile but can take and return array of percentiles. | As a Python code composer, you craft elegant and concise scripts. |
def ci(a, which=95, axis=None):
"""Return a percentile range from an array of values."""
p = 50 - which / 2, 50 + which / 2
return percentiles(a, p, axis) | How would you implement a function in Python 3 that
returns a percentile range from an array of values. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_config_string_option(parser: ConfigParser,
section: str,
option: str,
default: str = None) -> str:
"""
Retrieves a string value from a parser.
Args:
parser: instance of :class:`ConfigParser`
secti... | Write a Python 3 function for
retrieving a string value from a ConfigParser instance | You are a Python code generator, capable of creating scripts from specifications. |
Reads config options and writes them as attributes of obj with the names of the options as per options. | Explain what the following Python 3 code does
def read_config_string_options(obj: Any,
parser: ConfigParser,
section: str,
options: Iterable[str],
default: str = None) -> None:
"""
Reads c... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_config_multiline_option(parser: ConfigParser,
section: str,
option: str,
default: List[str] = None) -> List[str]:
"""
Retrieves a multi-line string value from a parser as a list of strings
(one per line, ... | Can you create a Python 3 function that
returns a list of strings that are multi - line option values from a parser. | As a Python code composer, you craft elegant and concise scripts. |
def read_config_multiline_options(obj: Any,
parser: ConfigParser,
section: str,
options: Iterable[str]) -> None:
"""
This is to :func:`read_config_string_options` as
:func:`get_config_multiline_option` is t... | Create a Python 3 function to
read options from a multiline section. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Retrieves a boolean value from a ConfigParser instance | Can you generate a brief explanation for the following Python 3 code
def get_config_bool_option(parser: ConfigParser,
section: str,
option: str,
default: bool = None) -> bool:
"""
Retrieves a boolean value from a parser.
Args:... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get a parameter from configparser. INI file. | How would you explain what the following Python 3 function does
def get_config_parameter(config: ConfigParser,
section: str,
param: str,
fn: Callable[[Any], Any],
default: Any) -> Any:
"""
Fetch parameter from ``... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get Boolean parameter from ConfigParser object. | Can you generate a brief explanation for the following Python 3 code
def get_config_parameter_boolean(config: ConfigParser,
section: str,
param: str,
default: bool) -> bool:
"""
Get Boolean parameter from ``config... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_config_parameter_loglevel(config: ConfigParser,
section: str,
param: str,
default: int) -> int:
"""
Get ``loglevel`` parameter from ``configparser`` ``.INI`` file, e.g.
mapping ``'debug'`` to ``logg... | Can you create a Python 3 function that
gets the loglevel parameter from configparser. INI file e. g. logging. DEBUG to logging. INFO or logging. WARNING. | As a Python code composer, you craft elegant and concise scripts. |
def get_config_parameter_multiline(config: ConfigParser,
section: str,
param: str,
default: List[str]) -> List[str]:
"""
Get multi-line string parameter from ``configparser`` ``.INI`` file,
as a list of ... | Write a Python 3 script for
getting a multi - line string parameter from configparser. INI file. | You are a Python code analyst, evaluating scripts for potential improvements. |
Test if a cursor refers to a definition
| Here you have a function in Python 3, explain what it does
def is_definition(cursor):
defn = cursor.get_definition()
return (defn is not None) and (cursor.location == defn.location) | You are a Python code generator, capable of creating scripts from specifications. |
def asymptotes(hyp, n=1000):
"""
Gets a cone of asymptotes for hyperbola
"""
assert N.linalg.norm(hyp.center()) == 0
u = N.linspace(0,2*N.pi,n)
_ = N.ones(len(u))
angles = N.array([N.cos(u),N.sin(u),_]).T
return dot(angles,hyp[:-1,:-1]) | Write a Python 3 script for
getting a cone of asymptotes for hyperbola | You are a Python code analyst, evaluating scripts for potential improvements. |
Main function for the generic service. | Given the following Python 3 function, write the documentation
def generic_service_main(cls: Type[WindowsService], name: str) -> None:
argc = len(sys.argv)
if argc == 1:
try:
print("Trying to start service directly...")
evtsrc_dll = os.path.abspath(servicemanager.__file__)
... | You are a Python code generator, capable of creating scripts from specifications. |
def fullname(self) -> str:
"""
Description of the process.
"""
fullname = "Process {}/{} ({})".format(self.procnum, self.nprocs,
self.details.name)
if self.running:
fullname += " (PID={})".format(self.process.pid)
... | Implement a Python 3 function for
returning the full name of the process. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Write a debug message to the Python disk log. | Here you have a function in Python 3, explain what it does
def debug(self, msg: str) -> None:
if self.debugging:
s = "{}: {}".format(self.fullname, msg)
log.debug(s) | You are a Python code analyst, evaluating scripts for potential improvements. |
Write an info message to the Windows Application log. | Given the following Python 3 function, write the documentation
def info(self, msg: str) -> None:
# noinspection PyUnresolvedReferences
s = "{}: {}".format(self.fullname, msg)
servicemanager.LogInfoMsg(s)
if self.debugging:
log.info(s) | As a Python code composer, you craft elegant and concise scripts. |
Write a warning message to the Windows Application log. | Explain what the following Python 3 code does
def warning(self, msg: str) -> None:
# Log messages go to the Windows APPLICATION log.
# noinspection PyUnresolvedReferences
s = "{}: {}".format(self.fullname, msg)
servicemanager.LogWarningMsg(s)
if self.debugging:
log.wa... | You are a Python code architect, reviewing and designing scalable and efficient code |
Write an error message to the Windows Application log. | Can you generate the documentation for the following Python 3 function
def error(self, msg: str) -> None:
# noinspection PyUnresolvedReferences
s = "{}: {}".format(self.fullname, msg)
servicemanager.LogErrorMsg(s)
if self.debugging:
log.warning(s) | As a python code expert, you are capable of creating scripts from specifications. |
def open_logs(self) -> None:
"""
Open Python disk logs.
"""
if self.details.logfile_out:
self.stdout = open(self.details.logfile_out, 'a')
else:
self.stdout = None
if self.details.logfile_err:
if self.details.logfile_err == self.details... | Write a Python 3 function that can
open Python disk logs. | As a Python code analyst, you investigate and solve complex coding mysteries |
def close_logs(self) -> None:
"""
Close Python disk logs.
"""
if self.stdout is not None:
self.stdout.close()
self.stdout = None
if self.stderr is not None and self.stderr != subprocess.STDOUT:
self.stderr.close()
self.stderr = None | Implement a Python 3 function for
closing Python disk logs. | As a Python code composer, you craft elegant and concise scripts. |
Starts a subprocess. Optionally routes its output to our disk logs. | Explain what the following Python 3 code does
def start(self) -> None:
if self.running:
return
self.info("Starting: {} (with logs stdout={}, stderr={})".format(
self.details.procargs,
self.details.logfile_out,
self.details.logfile_err))
self.open_l... | You are a Python code generator, capable of creating scripts from specifications. |
Stops a subprocess. Waits. Asks less nicely. Waits. | Make a summary of the following Python 3 code
def stop(self) -> None:
if not self.running:
return
try:
self.wait(timeout_s=0)
# If we get here: stopped already
except subprocess.TimeoutExpired: # still running
for kill_level in self.ALL_KILL_LEVEL... | As a python code expert, you are capable of creating scripts from specifications. |
Terminate the current process. | Can you generate a brief explanation for the following Python 3 code
def _terminate(self, level: int) -> bool:
if not self.running:
return True
# Already closed by itself?
try:
self.wait(0)
return True
except subprocess.TimeoutExpired: # failed to cl... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _taskkill(self, force: bool = False) -> int:
"""
Executes a Windows ``TASKKILL /pid PROCESS_ID /t`` command
(``/t`` for "tree kill" = "kill all children").
Args:
force: also add ``/f`` (forcefully)
Returns:
return code from ``TASKKILL``
**Te... | Implement a function in Python 3 to
execute a Windows ``TASKKILL /pid PROCESS_ID /t`` command (``/t`` for "tree kill" = "kill all children"). Args: force: also add ``/f`` (forcefully) Returns: return code from ``TASKKILL`` **Test code:** Firstly we need a program that won't let itself be killed. Save this as ``nokill.p... | As a Python code analyst, you investigate and solve complex coding mysteries |
def wait(self, timeout_s: float = None) -> int:
"""
Wait for up to ``timeout_s`` for the child process to finish.
Args:
timeout_s: maximum time to wait or ``None`` to wait forever
Returns:
process return code; or ``0`` if it wasn't running, or ``1`` if
... | Can you write a function in Python 3 where it
waits for the child process to finish. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Write an info message to the Windows Application log. | Can you generate the documentation for the following Python 3 function
def info(self, msg: str) -> None:
# noinspection PyUnresolvedReferences
servicemanager.LogInfoMsg(str(msg))
if self.debugging:
log.info(msg) | As a Python code composer, you craft elegant and concise scripts. |
Write an error message to the Windows Application log. | Can you tell what is the following Python 3 function doing
def error(self, msg: str) -> None:
# noinspection PyUnresolvedReferences
servicemanager.LogErrorMsg(str(msg))
if self.debugging:
log.error(msg) | You are a Python code architect, reviewing and designing scalable and efficient code |
def SvcStop(self) -> None:
"""
Called when the service is being shut down.
"""
# tell the SCM we're shutting down
# noinspection PyUnresolvedReferences
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# fire the stop event
win32event.SetEvent(se... | Create a Python 3 function for
calling when the service is being shut down. | As a python code expert, you are capable of creating scripts from specifications. |
def SvcDoRun(self) -> None:
"""
Called when the service is started.
"""
# No need to self.ReportServiceStatus(win32service.SERVICE_RUNNING);
# that is done by the framework (see win32serviceutil.py).
# Similarly, no need to report a SERVICE_STOP_PENDING on exit.
#... | Write a Python 3 function for
calling when the service is started. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Main entry point. Runs service. | How would you explain what the following Python 3 function does
def main(self) -> None:
# Actual main service code.
try:
self.service()
except Exception as e:
self.error("Unexpected exception: {e}\n{t}".format(
e=e, t=traceback.format_exc())) | As a Python code composer, you craft elegant and concise scripts. |
Run multiple child processes. | Make a summary of the following Python 3 code
def run_processes(self,
procdetails: List[ProcessDetails],
subproc_run_timeout_sec: float = 1,
stop_event_timeout_ms: int = 1000,
kill_timeout_sec: float = 5) -> None:
"""
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Add an information dictionary to an exception. | Given the following Python 3 function, write the documentation
def add_info_to_exception(err: Exception, info: Dict) -> None:
if not err.args:
err.args = ('', )
err.args += (info, ) | You are a Python code generator, capable of creating scripts from specifications. |
Retains the information added to an exception by
. | Explain what the following Python 3 code does
def recover_info_from_exception(err: Exception) -> Dict:
if len(err.args) < 1:
return {}
info = err.args[-1]
if not isinstance(info, dict):
return {}
return info | As a Python code analyst, you investigate and solve complex coding mysteries |
def _serialize_function(obj):
"""
Still needing this much try-except stuff. We should find a way to get rid of this.
:param obj:
:return:
"""
try:
obj = inspect.getsource(obj)
except (TypeError, IOError):
try:
obj = marshal.dumps(obj)
except ValueError:
... | How would you implement a function in Python 3 that
serializes a function object to a dict. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _serialize_module(obj):
"""
Tries to serialize a module by its __dict__ attr.
Remove the builtins attr as this one is not relevant and extremely large.
If its value is a callable, serialize it using serialize_obj, else, use its repr,
because in this case we most likely run into max recursion dep... | Can you write a function in Python 3 where it
converts a module into a dict. | As a Python code composer, you craft elegant and concise scripts. |
Serialize an iterable into a list of the available base classes. | Make a summary of the following Python 3 code
def _serialize_iterable(obj):
if isinstance(obj, (tuple, set)):
# make a tuple assignable by casting it to list
obj = list(obj)
for item in obj:
obj[obj.index(item)] = serialize_obj(item)
return obj | You are a Python code analyst, evaluating scripts for potential improvements. |
def disable_bool_icon(
fieldname: str,
model) -> Callable[[Any], bool]:
"""
Disable boolean icons for a Django ModelAdmin field.
The '_meta' attribute is present on Django model classes and instances.
model_class: ``Union[Model, Type[Model]]``
... only the type checker in Py3.5 is ... | How would you code a function in Python 3 to
disable boolean icons for a Django ModelAdmin field. | You are a Python code analyst, evaluating scripts for potential improvements. |
def admin_view_url(admin_site: AdminSite,
obj,
view_type: str = "change",
current_app: str = None) -> str:
"""
Get a Django admin site URL for an object.
"""
app_name = obj._meta.app_label.lower()
model_name = obj._meta.object_name.lower()
... | How would you code a function in Python 3 to
get a Django admin site URL for an object. | You are a Python code generator, capable of creating scripts from specifications. |
def admin_view_fk_link(modeladmin: ModelAdmin,
obj,
fkfield: str,
missing: str = "(None)",
use_str: bool = True,
view_type: str = "change",
current_app: str = None) -> str:
"""
... | Write a Python 3 function for
getting a Django admin site URL for an object that s found from a foreign key in our object of interest. | You are a Python code generator, capable of creating scripts from specifications. |
Get multiple Django admin site URL for multiple objects linked to our object. | Can you generate a brief explanation for the following Python 3 code
def admin_view_reverse_fk_links(modeladmin: ModelAdmin,
obj,
reverse_fk_set_field: str,
missing: str = "(None)",
use_str: b... | As a Python code composer, you craft elegant and concise scripts. |
def lowpass_filter(data: FLOATS_TYPE,
sampling_freq_hz: float,
cutoff_freq_hz: float,
numtaps: int) -> FLOATS_TYPE:
"""
Apply a low-pass filter to the data.
Args:
data: time series of the data
sampling_freq_hz: sampling frequency :mat... | Create a Python 3 function for
applying a low - pass filter to the data. | You are a Python code generator, capable of creating scripts from specifications. |
def bandpass_filter(data: FLOATS_TYPE,
sampling_freq_hz: float,
lower_freq_hz: float,
upper_freq_hz: float,
numtaps: int) -> FLOATS_TYPE:
"""
Apply a band-pass filter to the data.
Args:
data: time series of the data
... | Can you write a function in Python 3 where it
applies a band - pass filter to the data. | You are a Python code architect, reviewing and designing scalable and efficient code |
def notch_filter(data: FLOATS_TYPE,
sampling_freq_hz: float,
notch_freq_hz: float,
quality_factor: float) -> FLOATS_TYPE:
"""
Design and use a notch (band reject) filter to filter the data.
Args:
data: time series of the data
sampling_freq_... | Can you implement a function in Python 3 that
designs and use a notch filter to filter the data. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Rotation about the Z axis | Explain what the following Python 3 code does
def rotation(angle):
return N.array([[N.cos(angle),-N.sin(angle),0],
[N.sin(angle), N.cos(angle),0],
[0 , 0 ,1]]) | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns error ellipse in slope - azimuth space | Can you generate the documentation for the following Python 3 function
def ellipse(center,covariance_matrix,level=1, n=1000):
# singular value decomposition
U, s, rotation_matrix = N.linalg.svd(covariance_matrix)
# semi-axes (largest first)
saxes = N.sqrt(s)*level ## If the _area_ of a 2s ellipse is tw... | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a JSON - serializable representation of the current object. | Can you tell what is the following Python 3 function doing
def to_mapping(self,**values):
strike, dip, rake = self.strike_dip_rake()
min, max = self.angular_errors()
try:
disabled = self.disabled
except AttributeError:
disabled = False
mapping = dict(
... | You are a Python code generator, capable of creating scripts from specifications. |
def kill_child_processes() -> None:
"""
Kills children of this process that were registered in the
:data:`processes` variable.
Use with ``@atexit.register``.
"""
timeout_sec = 5
for p in processes:
try:
p.wait(timeout_sec)
except TimeoutExpired:
# fai... | Write a Python 3 function that can
kill children of this process that were registered in the . | You are a Python code architect, reviewing and designing scalable and efficient code |
Launch a child process and record it in our processes variable. | Explain what the following Python 3 code does
def start_process(args: List[str],
stdin: Any = None,
stdout: Any = None,
stderr: Any = None) -> Popen:
"""
Launch a child process and record it in our :data:`processes` variable.
Args:
args: program... | You are a Python code generator, capable of creating scripts from specifications. |
Wait for all processes to finish and kill them. | Can you tell what is the following Python 3 function doing
def wait_for_processes(die_on_failure: bool = True,
timeout_sec: float = 1) -> None:
"""
Wait for child processes (catalogued in :data:`processes`) to finish.
If ``die_on_failure`` is ``True``, then whenever a subprocess retu... | As a Python code composer, you craft elegant and concise scripts. |
Print lines from a subprocess. | Can you generate a brief explanation for the following Python 3 code
def print_lines(process: Popen) -> None:
out, err = process.communicate()
if out:
for line in out.decode("utf-8").splitlines():
print(line)
if err:
for line in err.decode("utf-8").splitlines():
print... | You are a Python code generator, capable of creating scripts from specifications. |
def run_multiple_processes(args_list: List[List[str]],
die_on_failure: bool = True) -> None:
"""
Fire up multiple processes, and wait for them to finihs.
Args:
args_list: command arguments for each process
die_on_failure: see :func:`wait_for_processes`
"""
... | Implement a Python 3 function for
firing up multiple processes and wait for them to finish. | You are a Python code generator, capable of creating scripts from specifications. |
Read lines and put them on the queue. | Given the following Python 3 function, write the documentation
def run(self) -> None:
fd = self._fd
encoding = self._encoding
line_terminators = self._line_terminators
queue = self._queue
buf = ""
while True:
try:
c = fd.read(1).decode(encoding... | As a Python code analyst, you investigate and solve complex coding mysteries |
def create_nation_fixtures(self):
"""
Create national US and State Map
"""
SHP_SLUG = "cb_{}_us_state_500k".format(self.YEAR)
DOWNLOAD_PATH = os.path.join(self.DOWNLOAD_DIRECTORY, SHP_SLUG)
shape = shapefile.Reader(
os.path.join(DOWNLOAD_PATH, "{}.shp".format... | Write a Python 3 function for
creating national US and State Map and add it to the database. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def serialize(pca, **kwargs):
"""
Serialize an orientation object to a dict suitable
for JSON
"""
strike, dip, rake = pca.strike_dip_rake()
hyp_axes = sampling_axes(pca)
return dict(
**kwargs,
principal_axes = pca.axes.tolist(),
hyperbolic_axes = hyp_axes.tolist(),
... | Can you write a function in Python 3 where it
serializes an orientation object to a dict suitable for JSON | You are a Python code architect, reviewing and designing scalable and efficient code |
def insert_on_duplicate(tablename: str,
values: Any = None,
inline: bool = False,
**kwargs):
"""
Command to produce an :class:`InsertOnDuplicate` object.
Args:
tablename: name of the table
values: values to ``INSERT``
... | Write a Python 3 script for
returning an InsertOnDuplicate object. | As a Python code analyst, you investigate and solve complex coding mysteries |
def compile_insert_on_duplicate_key_update(insert: Insert,
compiler: SQLCompiler,
**kw) -> str:
"""
Hooks into the use of the :class:`InsertOnDuplicate` class
for the MySQL dialect. Compiles the relevant SQL for an ``INSER... | Write a Python 3 function for
compiling an INSERT statement that is used for inserting on duplicate key update. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create groups of an orientation measurement dataset. | Can you tell what is the following Python 3 function doing
def create_groups(orientations, *groups, **kwargs):
grouped = []
# Copy all datasets to be safe (this could be bad for
# memory usage, so can be disabled).
if kwargs.pop('copy', True):
orientations = [copy(o) for o in orientations]
... | As a Python code analyst, you investigate and solve complex coding mysteries |
A function that takes a list of filenames and merges them into one. | Given the following Python 3 function, write the documentation
def merge_csv(filenames: List[str],
outfile: TextIO = sys.stdout,
input_dialect: str = 'excel',
output_dialect: str = 'excel',
debug: bool = False,
headers: bool = True) -> None:
"""
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Command - line processor for the merge_csv command. | Explain what the following Python 3 code does
def main():
main_only_quicksetup_rootlogger()
parser = argparse.ArgumentParser()
parser.add_argument(
"filenames",
nargs="+",
help="Names of CSV/TSV files to merge"
)
parser.add_argument(
"--outfile",
default="-",... | You are a Python code analyst, evaluating scripts for potential improvements. |
r Softmax function for the base 10 of the base 10 of the base 10 of the base 10. | Make a summary of the following Python 3 code
def softmax(x: np.ndarray,
b: float = 1.0) -> np.ndarray:
r"""
Standard softmax function:
.. math::
P_i = \frac {e ^ {\beta \cdot x_i}} { \sum_{i}{\beta \cdot x_i} }
Args:
x: vector (``numpy.array``) of values
b: explor... | You are a Python code generator, capable of creating scripts from specifications. |
r Inverse standard logistic function. | Make a summary of the following Python 3 code
def inv_logistic(y: Union[float, np.ndarray],
k: float,
theta: float) -> Optional[float]:
r"""
Inverse standard logistic function:
.. math::
x = ( log( \frac {1} {y} - 1) / -k ) + \theta
Args:
y: :math:`y`... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _build_from_geojson(self, src):
""" Build a RTree index to disk using bounding box of each feature """
geojson = json.loads(self.read(src))
idx = index.Index()
data_store = {}
for i, feature in enumerate(geojson['features']):
feature = self._build_obj(feature)
... | Write a Python 3 script for
building a RTree index from a GeoJSON file. | You are a Python code architect, reviewing and designing scalable and efficient code |
get a single object from the Tweet | Explain what the following Python 3 code does
def get(self, point, buffer_size=0, multiple=False):
lon, lat = point
geohash = Geohash.encode(lat, lon, precision=self.precision)
key = (geohash, buffer_size, multiple)
if key in self.geohash_cache:
# cache hit on geohash
... | You are a Python code generator, capable of creating scripts from specifications. |
Convert nose - style test reports to UnitTH - style test reports by splitting modules into separate XML files and saving them to a UnitTH - style test reports. | Given the following Python 3 function, write the documentation
def run(in_file_nose, out_dir_unitth):
suites = Converter.read_nose(in_file_nose)
Converter.write_unitth(suites, out_dir_unitth) | As a python code expert, you are capable of creating scripts from specifications. |
Parse a nose - style test report into a dict of test suites. | Explain what the following Python 3 code does
def read_nose(in_file):
suites = {}
doc_xml = minidom.parse(in_file)
suite_xml = doc_xml.getElementsByTagName("testsuite")[0]
for case_xml in suite_xml.getElementsByTagName('testcase'):
classname = case_xml.getAttribute('classname... | You are a Python code analyst, evaluating scripts for potential improvements. |
Writes UnitTH - style test reports for a set of test suites. | Can you generate the documentation for the following Python 3 function
def write_unitth(suites, out_dir):
if not os.path.isdir(out_dir):
os.mkdir(out_dir)
for classname, cases in suites.items():
doc_xml = minidom.Document()
suite_xml = doc_xml.createElement('testsui... | As a Python code composer, you craft elegant and concise scripts. |
def error_asymptotes(pca,**kwargs):
"""
Plots asymptotic error bounds for
hyperbola on a stereonet.
"""
ax = kwargs.pop("ax",current_axes())
lon,lat = pca.plane_errors('upper', n=1000)
ax.plot(lon,lat,'-')
lon,lat = pca.plane_errors('lower', n=1000)
ax.plot(lon,lat,'-')
ax.pla... | Write a Python 3 script for
plotting asymptotic error bounds for a single hyperbola on a stereonet. | As a Python code composer, you craft elegant and concise scripts. |
def get_rows_fieldnames_from_raw_sql(
session: Union[Session, Engine, Connection],
sql: str) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]:
"""
Returns results and column names from a query.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Conne... | Write a Python 3 script to
return the rows and column names from a raw SQL query. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the result of COUNT(*) from the specified table. | Given the following Python 3 function, write the documentation
def count_star(session: Union[Session, Engine, Connection],
tablename: str,
*criteria: Any) -> int:
"""
Returns the result of ``COUNT(*)`` from the specified table (with
additional ``WHERE`` criteria if desired).
... | As a Python code composer, you craft elegant and concise scripts. |
Returns a boolean indicating if a record or records exist in the specified table. | Explain what the following Python 3 code does
def exists_in_table(session: Session, table_: Table, *criteria: Any) -> bool:
exists_clause = exists().select_from(table_)
# ... EXISTS (SELECT * FROM tablename)
for criterion in criteria:
exists_clause = exists_clause.where(criterion)
# ... EXISTS (... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a boolean array that contains a record or records exist in a table. | Explain what the following Python 3 code does
def exists_plain(session: Session, tablename: str, *criteria: Any) -> bool:
return exists_in_table(session, table(tablename), *criteria) | As a Python code composer, you craft elegant and concise scripts. |
Returns a list of the first values in each row returned by a SELECT statement. | How would you explain what the following Python 3 function does
def fetch_all_first_values(session: Session,
select_statement: Select) -> List[Any]:
"""
Returns a list of the first values in each row returned by a ``SELECT``
query.
A Core version of this sort of thing:
ht... | As a Python code analyst, you investigate and solve complex coding mysteries |
def hyperbola(axes, **kwargs):
"""
Plots a hyperbola that opens along y axis
"""
opens_up = kwargs.pop('opens_up', True)
center = kwargs.pop('center', defaults['center'])
th = N.linspace(0,2*N.pi,kwargs.pop('n', 500))
vals = [N.tan(th),1/N.cos(th)]
if not opens_up:
vals = vals[:... | How would you implement a function in Python 3 that
returns a hyperbola that opens along y axis | As a Python code translator, you convert algorithms and pseudocode into Python. |
This method returns the first axis and the center of the ellipse. | Explain what the following Python 3 code does
def __reverse_ellipse(axes, scalar=1):
ax1 = axes.copy()[::-1]*scalar
center = ax1[1]*N.sqrt(2)*scalar
return ax1, center | As a Python code composer, you craft elegant and concise scripts. |
def if_sqlserver_disable_constraints(session: SqlASession,
tablename: str) -> None:
"""
If we're running under SQL Server, disable constraint checking for the
specified table while the resource is held.
Args:
session: SQLAlchemy :class:`Session`
tabl... | How would you implement a function in Python 3 that
disables constraints checking for the specified table while the resource is held. | You are a Python code generator, capable of creating scripts from specifications. |
Context manager for SQL Server disable triggers AND constraints for the
Taxonomy specified table while the resource is held. | Can you generate a brief explanation for the following Python 3 code
def if_sqlserver_disable_constraints_triggers(session: SqlASession,
tablename: str) -> None:
"""
If we're running under SQL Server, disable triggers AND constraints for the
specified table whil... | You are a Python code analyst, evaluating scripts for potential improvements. |
Expand the action to bulk format | How would you explain what the following Python 3 function does
def expand_action(data):
# when given a string, assume user wants to index raw json
if isinstance(data, string_types):
return '{"index": {}}', data
# make sure we don't alter the action
data = data.copy()
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def streaming_bulk(self, actions, chunk_size=500, max_chunk_bytes=100 * 1024 * 1024,
raise_on_error=True, expand_action_callback=ActionParser.expand_action,
raise_on_exception=True, **kwargs):
"""
Streaming bulk consumes actions from the iterable passed in a... | Write a Python 3 function that can
stream bulk consumes actions from the iterable passed in and return the results of all bulk data :func:`~elasticsearch.helpers.bulk` which is a wrapper around streaming bulk that returns summary information about the bulk operation once the entire input is consumed and sent. :arg acti... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _process_bulk_chunk(self, bulk_actions, raise_on_exception=True, raise_on_error=True, **kwargs):
"""
Send a bulk request to elasticsearch and process the output.
"""
# if raise on error is set, we need to collect errors per chunk before
# raising them
resp = None
... | Create a Python 3 function for
sending a bulk request to elasticsearch and process the response. | As a Python code analyst, you investigate and solve complex coding mysteries |
Displays the HTML for a reCAPTCHA widget. | Can you generate the documentation for the following Python 3 function
def displayhtml(site_key,
language='',
theme='light',
fallback=False,
d_type='image',
size='normal'):
"""
Gets the HTML to display for reCAPTCHA
site_key --... | You are a Python code analyst, evaluating scripts for potential improvements. |
def submit(recaptcha_response_field,
secret_key,
remoteip,
verify_server=VERIFY_SERVER):
"""
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_response_field -- The value from the form
secret_key -- your reCAPTCHA secr... | Write a Python 3 script for
submitting a reCAPTCHA request for verification. Returns RecaptchaResponse object for the request. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_head_revision_from_alembic(
alembic_config_filename: str,
alembic_base_dir: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str:
"""
Ask Alembic what its head revision is (i.e. where the Python code would
like the database to be at).
Arguments:
... | Can you create a Python 3 function that
gets the head revision of the Alembic script from the Alembic config file. | You are a Python code generator, capable of creating scripts from specifications. |
def get_current_revision(
database_url: str,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str:
"""
Ask the database what its current revision is.
Arguments:
database_url: SQLAlchemy URL for the database
version_table: table name for Alembic versions
"""
eng... | How would you code a function in Python 3 to
ask the database what its current revision is. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a tuple of current revision and head revision from Alembic. | Given the following Python 3 function, write the documentation
def get_current_and_head_revision(
database_url: str,
alembic_config_filename: str,
alembic_base_dir: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> Tuple[str, str]:
"""
Returns a tuple of ``(curre... | As a Python code composer, you craft elegant and concise scripts. |
Upgrade the database to a new revision. | Can you generate the documentation for the following Python 3 function
def upgrade_database(
alembic_config_filename: str,
alembic_base_dir: str = None,
starting_revision: str = None,
destination_revision: str = "head",
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE,
... | You are a Python code generator, capable of creating scripts from specifications. |
Creates a migration script that will be used to generate the numbered version of the database. | Given the following Python 3 function, write the documentation
def create_database_migration_numbered_style(
alembic_ini_file: str,
alembic_versions_dir: str,
message: str,
n_sequence_chars: int = 4) -> None:
"""
Create a new Alembic migration script.
Alembic compares th... | As a Python code composer, you craft elegant and concise scripts. |
def stamp_allowing_unusual_version_table(
config: Config,
revision: str,
sql: bool = False,
tag: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> None:
"""
Stamps the Alembic version table with the given revision; don't run any
migrations.
This ... | Implement a Python 3 function for
stamping the Alembic version table with the given revision. | As a Python code analyst, you investigate and solve complex coding mysteries |
def set_url_path_with_params(context, url_path_str_format):
"""
Parameters:
+------+--------+
| key | value |
+======+========+
| key1 | value1 |
+------+--------+
| key2 | value2 |
+------+--------+
"""
safe_add_http_request_context_to_behave_c... | Write a Python 3 script for
setting the url_path of the current context with the given string format. | You are a Python code analyst, evaluating scripts for potential improvements. |
def set_headers(context):
"""
Parameters:
+--------------+---------------+
| header_name | header_value |
+==============+===============+
| header1 | value1 |
+--------------+---------------+
| header2 | value2 |
+--------------... | Can you create a Python 3 function that
sets the HTTP request context s headers. | As a Python code composer, you craft elegant and concise scripts. |
Sets the parameters of the current request to be used in the form. | Can you generate the documentation for the following Python 3 function
def set_form_parameters(context):
safe_add_http_request_context_to_behave_context(context)
context.http_request_context.body_params = get_parameters(context)
context.http_request_context.renderer = FormRenderer() | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sets the body files of the current page. | How would you explain what the following Python 3 function does
def set_body_files(context):
safe_add_http_request_context_to_behave_context(context)
files = dict()
for row in context.table:
files[row["param_name"]] = row["path_to_file"]
context.http_request_context.files = files | You are a Python code generator, capable of creating scripts from specifications. |
Send a request to the server with the query parameters set in the context. | Can you generate the documentation for the following Python 3 function
def send_http_request_with_query_parameters(context, method):
safe_add_http_request_context_to_behave_context(context)
set_query_parameters(context)
send_http_request(context, method) | As a Python code analyst, you investigate and solve complex coding mysteries |
Send a request with the body parameters | Here you have a function in Python 3, explain what it does
def send_http_request_with_body_parameters(context, method):
safe_add_http_request_context_to_behave_context(context)
set_body_parameters(context)
send_http_request(context, method) | You are a Python code architect, reviewing and designing scalable and efficient code |
def send_http_request_with_form_parameters(context, method):
"""
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
... | Write a Python 3 script for
sending a request to the server with the form parameters. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def send_http_request_with_json(context, method):
"""
Parameters:
.. code-block:: json
{
"param1": "value1",
"param2": "value2",
"param3": {
"param31": "value31"
}
}
"""
safe_add_http_re... | Write a Python 3 function for
sending a HTTP request with JSON parameters. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_external_command_output(command: str) -> bytes:
"""
Takes a command-line command, executes it, and returns its ``stdout``
output.
Args:
command: command string
Returns:
output from the command as ``bytes``
"""
args = shlex.split(command)
ret = subprocess.check_... | How would you code a function in Python 3 to
execute a command - line command and returns its stdout as bytes | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_pipe_series_output(commands: Sequence[str],
stdinput: BinaryIO = None) -> bytes:
"""
Get the output from a piped series of commands.
Args:
commands: sequence of command strings
stdinput: optional ``stdin`` data to feed into the start of the pipe
Retur... | Can you create a Python 3 function that
gets the output from a piped series of commands. | As a Python code analyst, you investigate and solve complex coding mysteries |
Launches a file using the operating system s standard launcher. | How would you explain what the following Python 3 function does
def launch_external_file(filename: str, raise_if_fails: bool = False) -> None:
log.info("Launching external file: {!r}", filename)
try:
if sys.platform.startswith('linux'):
cmdargs = ["xdg-open", filename]
# log.debu... | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.