output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def plotF0(fromTuple, toTuple, mergeTupleList, fnFullPath):
'''
Plots the original data in a graph above the plot of the dtw'ed data
'''
_matplotlibCheck()
plt.hold(True)
fig, (ax0) = plt.subplots(nrows=1)
# Old data
plot1 = ax0.plot(fromTuple[0], fromTuple[1], color='red',
... | Write a Python 3 script to
plot the original data in a graph above the plot of the dtwed data | As a Python code translator, you convert algorithms and pseudocode into Python. |
def getPitchForIntervals(data, tgFN, tierName):
'''
Preps data for use in f0Morph
'''
tg = tgio.openTextgrid(tgFN)
data = tg.tierDict[tierName].getValuesInIntervals(data)
data = [dataList for _, dataList in data]
return data | Can you create a Python 3 function that
returns the pitch for the given data for the given tier | As a python code expert, you are capable of creating scripts from specifications. |
def decode(s):
"""
Converts text in the numbering format of pinyin ("ni3hao3") to text with the
appropriate tone marks ("nǐhǎo").
"""
s = s.lower()
r = ""
t = ""
for c in s:
if c >= 'a' and c <= 'z':
t += c
elif c == ':':
try:
if ... | Can you create a Python 3 function that
decodes a string in the numbering format of pinyin to text with the appropriate tone marks ("nǐhǎo"). | You are a Python code generator, capable of creating scripts from specifications. |
def adjustPeakHeight(self, heightAmount):
'''
Adjust peak height
The foot of the accent is left unchanged and intermediate
values are linearly scaled
'''
if heightAmount == 0:
return
pitchList = [f0V for _, f0V in self.pointList]
... | Write a Python 3 script to
adjust peak height of the peak. | You are a Python code analyst, evaluating scripts for potential improvements. |
def addPlateau(self, plateauAmount, pitchSampFreq=None):
'''
Add a plateau
A negative plateauAmount will move the peak backwards.
A positive plateauAmount will move the peak forwards.
All points on the side of the peak growth will also get moved.
i.e. th... | Write a Python 3 script to
add a plateau to the current object. | You are a Python code architect, reviewing and designing scalable and efficient code |
def shiftAccent(self, shiftAmount):
'''
Move the whole accent earlier or later
'''
if shiftAmount == 0:
return
self.pointList = [(time + shiftAmount, pitch)
for time, pitch in self.pointList]
# Update shift amounts
... | Can you implement a function in Python 3 that
moves the whole accent earlier or later or later AttributeNames | You are a Python code architect, reviewing and designing scalable and efficient code |
def deleteOverlapping(self, targetList):
'''
Erase points from another list that overlap with points in this list
'''
start = self.pointList[0][0]
stop = self.pointList[-1][0]
if self.netLeftShift < 0:
start += self.netLeftShift
i... | Can you write a function in Python 3 where it
deletes points from another list that overlap with points in this list. | As a python code expert, you are capable of creating scripts from specifications. |
def reintegrate(self, fullPointList):
'''
Integrates the pitch values of the accent into a larger pitch contour
'''
# Erase the original region of the accent
fullPointList = _deletePoints(fullPointList, self.minT, self.maxT)
# Erase the new region of the accent
... | Can you write a function in Python 3 where it
integrates the pitch values of the accent into a larger pitch contour | You are a Python code architect, reviewing and designing scalable and efficient code |
def convert(filename, new_filename=None, overwrite=False, to_encoding='utf-8', force=True):
""" Convert file with crappy encoding to a new proper encoding (or vice versa if you wish).
filename -- the name, partial path or full path of the file you want to encode to a new encoding
new_filename -- (optional)... | How would you implement a function in Python 3 that
converts a file with crappy encoding to a new file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def detect(filename, include_confidence=False):
"""
Detect the encoding of a file.
Returns only the predicted current encoding as a string.
If `include_confidence` is True,
Returns tuple containing: (str encoding, float confidence)
"""
f = open(filename)
detection = chardet.detect(f.r... | Can you write a function in Python 3 where it
detects the encoding of a file. | As a Python code composer, you craft elegant and concise scripts. |
This function is a unexposed function is responsibility for translation internal. | Make a summary of the following Python 3 code
def _t(unistr, charset_from, charset_to):
# if type(unistr) is str:
# try:
# unistr = unistr.decode('utf-8')
# # Python 3 returns AttributeError when .decode() is called on a str
# # This means it is already unicode.
# except ... | As a python code expert, you are capable of creating scripts from specifications. |
Identify whether a string is simplified or traditional Chinese. | How would you explain what the following Python 3 function does
def identify(text):
filtered_text = set(list(text)).intersection(ALL_CHARS)
if len(filtered_text) is 0:
return None
if filtered_text.issubset(SHARED_CHARS):
return EITHER
if filtered_text.issubset(TRAD_CHARS):
return... | You are a Python code generator, capable of creating scripts from specifications. |
def makeSequenceRelative(absVSequence):
'''
Puts every value in a list on a continuum between 0 and 1
Also returns the min and max values (to reverse the process)
'''
if len(absVSequence) < 2 or len(set(absVSequence)) == 1:
raise RelativizeSequenceException(absVSequence)
minV = min(ab... | How would you code a function in Python 3 to
make a sequence relative to the main sequence | You are a Python code analyst, evaluating scripts for potential improvements. |
def makeSequenceAbsolute(relVSequence, minV, maxV):
'''
Makes every value in a sequence absolute
'''
return [(value * (maxV - minV)) + minV for value in relVSequence] | How would you implement a function in Python 3 that
makes every value in a sequence absolute | You are a Python code generator, capable of creating scripts from specifications. |
def _makeTimingRelative(absoluteDataList):
'''
Given normal pitch tier data, puts the times on a scale from 0 to 1
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
Also returns the start and end time so that the process can be reversed
'''
timingSeq = [row[0] ... | Write a Python 3 function for
giving normal pitch tier data puts the times on a scale from 0 to 1 Returns the start and end times of the process | You are a Python code architect, reviewing and designing scalable and efficient code |
Make a list of tuples of the form time1 pitch1 time2 pitch3... | How would you explain what the following Python 3 function does
def _makeTimingAbsolute(relativeDataList, startTime, endTime):
'''
Maps values from 0 to 1 to the provided start and end time
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
'''
timingSeq = [row[0] fo... | You are a Python code generator, capable of creating scripts from specifications. |
Returns the value in inputList that is closest to targetVal Iteratively splits the dataset in two so it should be pretty fast | Can you generate a brief explanation for the following Python 3 code
def _getSmallestDifference(inputList, targetVal):
'''
Returns the value in inputList that is closest to targetVal
Iteratively splits the dataset in two, so it should be pretty fast
'''
targetList = inputList[:]
retVal = No... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the list of indices that are closest to each other in the input list. | Explain what the following Python 3 code does
def _getNearestMappingIndexList(fromValList, toValList):
'''
Finds the indicies for data points that are closest to each other.
The inputs should be in relative time, scaled from 0 to 1
e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1]
will output [0... | You are a Python code generator, capable of creating scripts from specifications. |
def morphDataLists(fromList, toList, stepList):
'''
Iteratively morph fromList into toList using the values 0 to 1 in stepList
stepList: a value of 0 means no change and a value of 1 means a complete
change to the other value
'''
# If there are more than 1 pitch value, then we align the da... | Create a Python 3 function for
yielding the data points from fromList into toList using the values 0 to 1 in stepList. | As a Python code composer, you craft elegant and concise scripts. |
def morphAveragePitch(fromDataList, toDataList):
'''
Adjusts the values in fromPitchList to have the same average as toPitchList
Because other manipulations can alter the average pitch, morphing the pitch
is the last pitch manipulation that should be done
After the morphing, the code remov... | Create a Python 3 function for
adjusting the values in fromPitchList to have the same average as toPitchList Because other manipulations can alter the average pitch, morphing the pitch is the last pitch manipulation that should be done After the morphing, the code removes any values below zero, thus the final average m... | As a Python code composer, you craft elegant and concise scripts. |
This function morphs two sets of values in one distribution to that of another. | Explain what the following Python 3 code does
def morphRange(fromDataList, toDataList):
'''
Changes the scale of values in one distribution to that of another
ie The maximum value in fromDataList will be set to the maximum value in
toDataList. The 75% largest value in fromDataList will be set to t... | You are a Python code generator, capable of creating scripts from specifications. |
This function generates a series of points on a smooth curve that crosses the given valueList2d. | Can you tell what is the following Python 3 function doing
def quadraticInterpolation(valueList2d, numDegrees, n,
startTime=None, endTime=None):
'''
Generates a series of points on a smooth curve that cross the given points
numDegrees - the degrees of the fitted polynomial
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get information about the extract tier used by several merge scripts
| Can you generate the documentation for the following Python 3 function
def getIntervals(fn, tierName, filterFunc=None,
includeUnlabeledRegions=False):
'''
Get information about the 'extract' tier, used by several merge scripts
'''
tg = tgio.openTextgrid(fn)
tier = tg.tierDict[... | As a Python code composer, you craft elegant and concise scripts. |
def changeDuration(fromWavFN, durationParameters, stepList, outputName,
outputMinPitch, outputMaxPitch, praatEXE):
'''
Uses praat to morph duration in one file to duration in another
Praat uses the PSOLA algorithm
'''
rootPath = os.path.split(fromWavFN)[0]
# Prep output dir... | Implement a Python 3 function for
using praat to morph duration in one file to duration in another Praat uses the PSOLA algorithm | You are a Python code architect, reviewing and designing scalable and efficient code |
def getMorphParameters(fromTGFN, toTGFN, tierName,
filterFunc=None, useBlanks=False):
'''
Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on the contents of ... | Write a Python 3 script for
getting intervals for source audio files and target audio files and return the duration parameters of the morphological audio files. | You are a Python code analyst, evaluating scripts for potential improvements. |
def getManipulatedParamaters(tgFN, tierName, modFunc,
filterFunc=None, useBlanks=False):
'''
Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on modfunc... | Write a Python 3 script to
get the list of parameters that can be used to calculate the duration of the audio files in a tier. | You are a Python code analyst, evaluating scripts for potential improvements. |
A convenience function that returns a new tg that is a copy of the fromTGFN and toTGFN. | Given the following Python 3 function, write the documentation
def textgridMorphDuration(fromTGFN, toTGFN):
'''
A convenience function. Morphs interval durations of one tg to another.
This assumes the two textgrids have the same number of segments.
'''
fromTG = tgio.openTextgrid(fromTGFN)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def getSoundFileDuration(fn):
'''
Returns the duration of a wav file (in seconds)
'''
audiofile = wave.open(fn, "r")
params = audiofile.getparams()
framerate = params[2]
nframes = params[3]
duration = float(nframes) / framerate
return duration | Implement a function in Python 3 to
return the duration of a wav file in seconds | As a python code expert, you are capable of creating scripts from specifications. |
u Split Chinese text at word boundaries. | Can you generate the documentation for the following Python 3 function
def split_text(text, include_part_of_speech=False, strip_english=False, strip_numbers=False):
if not include_part_of_speech:
seg_list = pseg.cut(text)
if strip_english:
seg_list = filter(lambda x: not contains_englis... | As a python code expert, you are capable of creating scripts from specifications. |
def is_special_atom(cron_atom, span):
"""
Returns a boolean indicating whether or not the string can be parsed by
parse_atom to produce a static set. In the process of examining the
string, the syntax of any special character uses is also checked.
"""
for special_char in ('%', '#', 'L', 'W'):
... | Write a Python 3 script for
checking if a string contains a special character. | As a python code expert, you are capable of creating scripts from specifications. |
def parse_atom(parse, minmax):
"""
Returns a set containing valid values for a given cron-style range of
numbers. The 'minmax' arguments is a two element iterable containing the
inclusive upper and lower limits of the expression.
Examples:
>>> parse_atom("1-5",(0,6))
set([1, 2, 3, 4, 5])
... | Write a Python 3 function for
parsing a cron - style range of the internal list of the available cron - tables. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Recomputes the sets for the static ranges of the trigger time. | How would you explain what the following Python 3 function does
def compute_numtab(self):
self.numerical_tab = []
for field_str, span in zip(self.string_tab, FIELD_RANGES):
split_field_str = field_str.split(',')
if len(split_field_str) > 1 and "*" in split_field_str:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Checks if the trigger is active at the given time. | Can you generate a brief explanation for the following Python 3 code
def check_trigger(self, date_tuple, utc_offset=0):
year, month, day, hour, mins = date_tuple
given_date = datetime.date(year, month, day)
zeroday = datetime.date(*self.epoch[:3])
last_dom = calendar.monthrange(year, mon... | You are a Python code analyst, evaluating scripts for potential improvements. |
Show the structure of self. rules_list only for debug. | Make a summary of the following Python 3 code
def show(self):
for rule in self.rules_list:
result = ", ".join([str(check) for check, deny in rule])
print(result) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Run self. rules_list.
Return True if one rule channel has been passed otherwise return False and the deny method of the last failed rule. | Can you generate a brief explanation for the following Python 3 code
def run(self):
failed_result = None
for rule in self.rules_list:
for check, deny in rule:
if not check():
failed_result = (False, deny)
break
else:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Set the meter indicator. Value should be between 0 and 1. | Can you generate the documentation for the following Python 3 function
def set_fraction(self, value):
if value < 0:
value *= -1
value = min(value, 1)
if self.horizontal:
width = int(self.width * value)
height = self.height
else:
width = sel... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Update status informations in tkinter window. | Can you tell what is the following Python 3 function doing
def update_status(self):
try:
# all this may fail if the connection to the fritzbox is down
self.update_connection_status()
self.max_stream_rate.set(self.get_stream_rate_str())
self.ip.set(self.status.exte... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a human readable string of a byte - value. | Here you have a function in Python 3, explain what it does
def format_num(num, unit='bytes'):
if unit == 'bytes':
extension = 'B'
else:
# if it's not bytes, it's bits
extension = 'Bit'
for dimension in (unit, 'K', 'M', 'G', 'T'):
if num < 1024:
if dimension == uni... | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse a Content - Disposition header value. | Can you generate the documentation for the following Python 3 function
def parse_headers(content_disposition, location=None, relaxed=False):
LOGGER.debug(
'Content-Disposition %r, Location %r', content_disposition, location)
if content_disposition is None:
return ContentDisposition(location=lo... | As a python code expert, you are capable of creating scripts from specifications. |
def parse_requests_response(response, **kwargs):
"""Build a ContentDisposition from a requests (PyPI) response.
"""
return parse_headers(
response.headers.get('content-disposition'), response.url, **kwargs) | Write a Python 3 function that can
build a ContentDisposition from a requests response. | As a python code expert, you are capable of creating scripts from specifications. |
def build_header(
filename, disposition='attachment', filename_compat=None
):
"""Generate a Content-Disposition header for a given filename.
For legacy clients that don't understand the filename* parameter,
a filename_compat value may be given.
It should either be ascii-only (recommended) or iso-88... | How would you implement a function in Python 3 that
generates a Content - Disposition header for a given filename. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a filename that is safer to use on the filesystem. | Here you have a function in Python 3, explain what it does
def filename_sanitized(self, extension, default_filename='file'):
assert extension
assert extension[0] != '.'
assert default_filename
assert '.' not in default_filename
extension = '.' + extension
fname = self.f... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the upstream downstream values as a tuple in bytes per
second. Use this for periodical calling. | Here you have a function in Python 3, explain what it does
def transmission_rate(self):
sent = self.bytes_sent
received = self.bytes_received
traffic_call = time.time()
time_delta = traffic_call - self.last_traffic_call
upstream = int(1.0 * (sent - self.last_bytes_sent)/time_delt... | You are a Python code architect, reviewing and designing scalable and efficient code |
def str_transmission_rate(self):
"""Returns a tuple of human readable transmission rates in bytes."""
upstream, downstream = self.transmission_rate
return (
fritztools.format_num(upstream),
fritztools.format_num(downstream)
) | Write a Python 3 function that can
return a tuple of human readable transmission rates in bytes. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a tuple with the maximun upstream - and downstream - rate of the given connection. | Make a summary of the following Python 3 code
def max_bit_rate(self):
status = self.fc.call_action('WANCommonInterfaceConfig',
'GetCommonLinkProperties')
downstream = status['NewLayer1DownstreamMaxBitRate']
upstream = status['NewLayer1UpstreamMaxBitRate']
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def str_max_bit_rate(self):
"""
Returns a human readable maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec.
"""
upstream, downstream = self.max_bit_rate
return (
fritztools.format_rate(upstream, unit='bits'),
... | How would you code a function in Python 3 to
return a human readable max bit rate of the given connection. | You are a Python code generator, capable of creating scripts from specifications. |
Helper method to construct the appropriate SOAP - body to call a
FritzBox - Service. | Can you generate a brief explanation for the following Python 3 code
def _body_builder(self, kwargs):
p = {
'action_name': self.name,
'service_type': self.service_type,
'arguments': '',
}
if kwargs:
arguments = [
self.argument_t... | You are a Python code analyst, evaluating scripts for potential improvements. |
Calls the FritzBox action and returns a dictionary with the arguments. | How would you explain what the following Python 3 function does
def execute(self, **kwargs):
headers = self.header.copy()
headers['soapaction'] = '%s#%s' % (self.service_type, self.name)
data = self.envelope.strip() % self._body_builder(kwargs)
url = 'http://%s:%s%s' % (self.address, sel... | As a Python code analyst, you investigate and solve complex coding mysteries |
Parses the response from a FritzBox action - call into a dictionary with the received arguments - value pairs. | How would you explain what the following Python 3 function does
def parse_response(self, response):
result = {}
root = etree.fromstring(response)
for argument in self.arguments.values():
try:
value = root.find('.//%s' % argument.name).text
except Attribute... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the FritzBox model name. | Here you have a function in Python 3, explain what it does
def get_modelname(self):
xpath = '%s/%s' % (self.nodename('device'), self.nodename('modelName'))
return self.root.find(xpath).text | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a list of FritzService - objects. | Given the following Python 3 function, write the documentation
def get_services(self):
result = []
nodes = self.root.iterfind(
'.//ns:service', namespaces={'ns': self.namespace})
for node in nodes:
result.append(FritzService(
node.find(self.nodename('servi... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Reads the stateVariable information from the xml - file. | Can you generate the documentation for the following Python 3 function
def _read_state_variables(self):
nodes = self.root.iterfind(
'.//ns:stateVariable', namespaces={'ns': self.namespace})
for node in nodes:
key = node.find(self.nodename('name')).text
value = node.fi... | As a python code expert, you are capable of creating scripts from specifications. |
def get_actions(self):
"""Returns a list of FritzAction instances."""
self._read_state_variables()
actions = []
nodes = self.root.iterfind(
'.//ns:action', namespaces={'ns': self.namespace})
for node in nodes:
action = FritzAction(self.service.service_type... | Create a Python 3 function to
return a list of FritzAction instances. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _get_arguments(self, action_node):
"""
Returns a dictionary of arguments for the given action_node.
"""
arguments = {}
argument_nodes = action_node.iterfind(
r'./ns:argumentList/ns:argument', namespaces={'ns': self.namespace})
for argument_node in argument... | Implement a function in Python 3 to
return a dictionary of arguments for the given action_node. | You are a Python code generator, capable of creating scripts from specifications. |
def _get_argument(self, argument_node):
"""
Returns a FritzActionArgument instance for the given argument_node.
"""
argument = FritzActionArgument()
argument.name = argument_node.find(self.nodename('name')).text
argument.direction = argument_node.find(self.nodename('direc... | Can you implement a function in Python 3 that
returns a FritzActionArgument instance for the given argument_node. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _read_descriptions(self, password):
"""
Read and evaluate the igddesc.xml file
and the tr64desc.xml file if a password is given.
"""
descfiles = [FRITZ_IGD_DESC_FILE]
if password:
descfiles.append(FRITZ_TR64_DESC_FILE)
for descfile in descfiles:
... | Can you implement a function in Python 3 that
reads and evaluate the igddesc. xml file and the tr64desc. xml file. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get actions from services. | How would you explain what the following Python 3 function does
def _read_services(self, services):
for service in services:
parser = FritzSCDPParser(self.address, self.port, service)
actions = parser.get_actions()
service.actions = {action.name: action for action in actions}... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a alphabetical sorted list of tuples with all known
service - and action - names. | Here you have a function in Python 3, explain what it does
def actionnames(self):
actions = []
for service_name in sorted(self.services.keys()):
action_names = self.services[service_name].actions.keys()
for action_name in sorted(action_names):
actions.append((serv... | As a Python code composer, you craft elegant and concise scripts. |
def get_action_arguments(self, service_name, action_name):
"""
Returns a list of tuples with all known arguments for the given
service- and action-name combination. The tuples contain the
argument-name, direction and data_type.
"""
return self.services[service_name].actio... | Can you write a function in Python 3 where it
returns a list of tuples with all known arguments for the given service and action. | You are a Python code generator, capable of creating scripts from specifications. |
Executes the given action. Raise a KeyError on unkown actions. | Can you generate a brief explanation for the following Python 3 code
def call_action(self, service_name, action_name, **kwargs):
action = self.services[service_name].actions[action_name]
return action.execute(**kwargs) | You are a Python code generator, capable of creating scripts from specifications. |
Returns a list of dicts with information about the known hosts. | Can you tell what is the following Python 3 function doing
def get_hosts_info(self):
result = []
index = 0
while index < self.host_numbers:
host = self.get_generic_host_entry(index)
result.append({
'ip': host['NewIPAddress'],
'name': host['... | You are a Python code architect, reviewing and designing scalable and efficient code |
Finds executable in PATH and returns the path to the executable. | Can you tell what is the following Python 3 function doing
def find_executable(executable):
'''
Finds executable in PATH
Returns:
string or None
'''
logger = logging.getLogger(__name__)
logger.debug("Checking executable '%s'...", executable)
executable_path = _find_executable(execut... | As a Python code composer, you craft elegant and concise scripts. |
Checks if jasper can connect to a network server. | Here you have a function in Python 3, explain what it does
def check_network_connection(server, port):
'''
Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False
''... | As a Python code composer, you craft elegant and concise scripts. |
def check_python_import(package_or_module):
'''
Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False
'''
logger = logging.getLogger(__name__)
logger.debug("Checking python import '%s'...... | Write a Python 3 function that can
check if a python package or module is importable. | As a Python code composer, you craft elegant and concise scripts. |
Recursively injects aXe into all iframes and the top level document. | Explain what the following Python 3 code does
def inject(self):
with open(self.script_url, "r", encoding="utf8") as f:
self.selenium.execute_script(f.read()) | You are a Python code architect, reviewing and designing scalable and efficient code |
Run axe against the current page. | Explain what the following Python 3 code does
def run(self, context=None, options=None):
template = (
"var callback = arguments[arguments.length - 1];"
+ "axe.run(%s).then(results => callback(results))"
)
args = ""
# If context parameter is passed, add to args
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a readable string of accessibility violations found. | Explain what the following Python 3 code does
def report(self, violations):
string = ""
string += "Found " + str(len(violations)) + " accessibility violations:"
for violation in violations:
string += (
"\n\n\nRule Violated:\n"
+ violation["id"]
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Write JSON to file with the specified name. | Given the following Python 3 function, write the documentation
def write_results(self, data, name=None):
if name:
filepath = os.path.abspath(name)
else:
filepath = os.path.join(os.path.getcwd(), "results.json")
with open(filepath, "w", encoding="utf8") as f:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def create_engine(engine, options=None, defaults=None):
'''
Creates an instance of an engine.
There is a two-stage instantiation process with engines.
1. ``options``:
The keyword options to instantiate the engine class
2. ``defaults``:
The default configuration for the engine (optio... | Implement a Python 3 function for
creating an instance of an engine. | As a python code expert, you are capable of creating scripts from specifications. |
Classifies text by language. Uses preferred_languages weighting. | Can you generate the documentation for the following Python 3 function
def classify(self, txt):
'''
Classifies text by language. Uses preferred_languages weighting.
'''
ranks = []
for lang, score in langid.rank(txt):
if lang in self.preferred_languages:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_engine_for_lang(self, lang):
'''
Determines the preferred engine/voice for a language.
'''
for eng in self.engines:
if lang in eng.languages.keys():
return eng
raise TTSError('Could not match language') | Can you write a function in Python 3 where it
determines the preferred engine for a language. | As a python code expert, you are capable of creating scripts from specifications. |
Says the text.
if ``lang`` is ``None``, then uses ``classify()`` to detect language. | How would you explain what the following Python 3 function does
def say(self, txt, lang=None):
'''
Says the text.
if ``lang`` is ``None``, then uses ``classify()`` to detect language.
'''
lang = lang or self.classify(txt)
self.get_engine_for_lang(lang).say(txt, language=... | As a Python code analyst, you investigate and solve complex coding mysteries |
def configure_default(self, **_options):
'''
Sets default configuration.
Raises TTSError on error.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self.languages_options[language] = (voice, options)
self.default_language = language
s... | Implement a Python 3 function for
setting default configuration. Raises TTSError on error. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def configure(self, **_options):
'''
Sets language-specific configuration.
Raises TTSError on error.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self.languages_options[language] = (voice, options) | How would you implement a function in Python 3 that
sets language - specific configuration. | You are a Python code generator, capable of creating scripts from specifications. |
Says the phrase with the specified options. | How would you explain what the following Python 3 function does
def say(self, phrase, **_options):
'''
Says the phrase, optionally allows to select/override any voice options.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self._logger.debug("Saying '%s' wi... | As a Python code analyst, you investigate and solve complex coding mysteries |
Plays the sounds.
:filename: The input file name
:translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV. | Here you have a function in Python 3, explain what it does
def play(self, filename, translate=False): # pragma: no cover
'''
Plays the sounds.
:filename: The input file name
:translate: If True, it runs it through audioread which will translate from common compression formats to raw WA... | You are a Python code architect, reviewing and designing scalable and efficient code |
def getCollectDServer(queue, cfg):
"""Get the appropriate collectd server (multi processed or not)"""
server = CollectDServerMP if cfg.collectd_workers > 1 else CollectDServer
return server(queue, cfg) | How would you code a function in Python 3 to
get the appropriate collectd server. | You are a Python code architect, reviewing and designing scalable and efficient code |
Constant time comparison of bytes for py3 strings for py2 | Can you generate the documentation for the following Python 3 function
def _hashes_match(self, a, b):
if len(a) != len(b):
return False
diff = 0
if six.PY2:
a = bytearray(a)
b = bytearray(b)
for x, y in zip(a, b):
diff |= x ^ y
retu... | You are a Python code analyst, evaluating scripts for potential improvements. |
Load metadata for all sites in basin_ids. | Make a summary of the following Python 3 code
def load_sites(*basin_ids):
# Resolve basin ids to HUC8s if needed
basins = []
for basin in basin_ids:
if basin.isdigit() and len(basin) == 8:
basins.append(basin)
else:
from climata.huc8 import get_huc8
basin... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_huc8(prefix):
"""
Return all HUC8s matching the given prefix (e.g. 1801) or basin name
(e.g. Klamath)
"""
if not prefix.isdigit():
# Look up hucs by name
name = prefix
prefix = None
for row in hucs:
if row.basin.lower() == name.lower():
... | Write a Python 3 script to
return all 8 - digit HUCs matching the given prefix | As a Python code analyst, you investigate and solve complex coding mysteries |
def parse(self):
"""
Convert ACIS 'll' value into separate latitude and longitude.
"""
super(AcisIO, self).parse()
# This is more of a "mapping" step than a "parsing" step, but mappers
# only allow one-to-one mapping from input fields to output fields.
for row in... | How would you code a function in Python 3 to
convert ACIS 'll' value into separate latitude and longitude. | You are a Python code architect, reviewing and designing scalable and efficient code |
def map_value(self, field, value):
"""
Clean up some values returned from the web service.
(overrides wq.io.mappers.BaseMapper)
"""
if field == 'sids':
# Site identifiers are returned as "[id] [auth_id]";
# Map to auth name for easier usability
... | Can you implement a function in Python 3 that
maps the value of a resource field to a dictionary of values. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_field_names(self):
"""
ACIS web service returns "meta" and "data" for each station;
Use meta attributes as field names
"""
field_names = super(StationDataIO, self).get_field_names()
if set(field_names) == set(['meta', 'data']):
meta_fields = list(self.... | Can you create a Python 3 function that
returns the list of fields that are used for each station in the data IO. | As a Python code composer, you craft elegant and concise scripts. |
Use meta and data attributes as item values and add nested IOs for iterating over data | Here you have a function in Python 3, explain what it does
def usable_item(self, data):
# Use metadata as item
item = data['meta']
# Add nested IO for data
elems, elems_is_complex = self.getlist('parameter')
if elems_is_complex:
elems = [elem['name'] for elem in ele... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def load_data(self, data):
"""
MultiStnData data results are arrays without explicit dates;
Infer time series based on start date.
"""
dates = fill_date_range(self.start_date, self.end_date)
for row, date in zip(data, dates):
data = {'date': date}
... | How would you implement a function in Python 3 that
loads MultiStnData data from a list of dictionaries. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_field_names(self):
"""
Different field names depending on self.add setting (see load_data)
For BaseIO
"""
if self.add:
return ['date', 'elem', 'value'] + [flag for flag in self.add]
else:
field_names = ['date']
for elem in self.... | Can you write a function in Python 3 where it
returns a list of field names depending on self. add setting. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def fill_date_range(start_date, end_date, date_format=None):
"""
Function accepts start date, end date, and format (if dates are strings)
and returns a list of Python dates.
"""
if date_format:
start_date = datetime.strptime(start_date, date_format).date()
end_date = datetime.strpti... | Implement a Python 3 function for
functioning fills the date_list with the dates in the given date range. | As a Python code analyst, you investigate and solve complex coding mysteries |
def parse(self, value):
"""
Enforce rules and return parsed value
"""
if self.required and value is None:
raise ValueError("%s is required!" % self.name)
elif self.ignored and value is not None:
warn("%s is ignored for this class!" % self.name)
eli... | Create a Python 3 function for
enforcing rules and return parsed value | As a Python code analyst, you investigate and solve complex coding mysteries |
def parse(self, value):
"""
Parse date
"""
value = super(DateOpt, self).parse(value)
if value is None:
return None
if isinstance(value, str):
value = self.parse_date(value)
if isinstance(value, datetime) and self.date_only:
valu... | Write a Python 3 function for
parsing value into a base - 10 value. | As a python code expert, you are capable of creating scripts from specifications. |
Get all filter options defined on class and superclasses. | Make a summary of the following Python 3 code
def get_filter_options(cls):
attr = '_filter_options_%s' % id(cls)
options = getattr(cls, attr, {})
if options:
return options
for key in dir(cls):
val = getattr(cls, key)
if isinstance(val, FilterOpt):
... | As a Python code composer, you craft elegant and concise scripts. |
def getlist(self, name):
"""
Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list)
"""
value = self.getvalue(name)
complex = {}
def... | Can you write a function in Python 3 where it
retrieves given property from class or instance ensuring it is a list. | As a python code expert, you are capable of creating scripts from specifications. |
def set_param(self, into, name):
"""
Set parameter key, noting whether list value is "complex"
"""
value, complex = self.getlist(name)
if value is not None:
into[name] = value
return complex | Can you implement a function in Python 3 that
sets the value of a parameter in a dictionary into. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get parameters for web service noting whether any are complex | Can you tell what is the following Python 3 function doing
def get_params(self):
params = {}
complex = False
for name, opt in self.filter_options.items():
if opt.ignored:
continue
if self.set_param(params, name):
complex = True
ret... | You are a Python code generator, capable of creating scripts from specifications. |
def params(self):
"""
URL parameters for wq.io.loaders.NetLoader
"""
params, complex = self.get_params()
url_params = self.default_params.copy()
url_params.update(self.serialize_params(params, complex))
return url_params | How would you implement a function in Python 3 that
returns a dictionary of all parameters for this loader. | As a python code expert, you are capable of creating scripts from specifications. |
Serialize parameter names and values to a dict ready for urlencode | Explain what the following Python 3 code does
def serialize_params(self, params, complex=False):
if complex:
# See climata.acis for an example implementation
raise NotImplementedError("Cannot serialize %s!" % params)
else:
# Simpler queries can use traditional URL par... | You are a Python code generator, capable of creating scripts from specifications. |
convert the measurement to inches | Can you generate the documentation for the following Python 3 function
def get_inches(self):
''' convert the measurement to inches '''
if self._obs_value in self.MISSING:
return 'MISSING'
if self._obs_units == self.MILLIMETERS:
return round(self.INCH_CONVERSION_FACTOR * self._obs_value, 4) | As a python code expert, you are capable of creating scripts from specifications. |
print a nicely formatted output of this report | Make a summary of the following Python 3 code
def formatted(self):
''' print a nicely formatted output of this report '''
return """
Weather Station: %s (%s, %s)
Elevation: %s m
Time: %s UTC
Air Temperature: %s C (%s F)
Wind Speed: %s m/s (%s mph)
Wind Direction: %s
Present Weather Obs: %s
Precipitation: %s
Cl... | As a python code expert, you are capable of creating scripts from specifications. |
loads in a report from a string | Can you generate the documentation for the following Python 3 function
def loads(self, noaa_string):
''' load in a report (or set) from a string '''
self.raw = noaa_string
self.weather_station = noaa_string[4:10]
self.wban = noaa_string[10:15]
expected_length = int(noaa_string[0:4]) + self.PREAMBLE_... | As a Python code composer, you craft elegant and concise scripts. |
def _get_remarks_component(self, string, initial_pos):
''' Parse the remarks into the _remarks dict '''
remarks_code = string[initial_pos:initial_pos + self.ADDR_CODE_LENGTH]
if remarks_code != 'REM':
raise ish_reportException("Parsing remarks. Expected REM but got %s." % (remarks_code,))
expecte... | How would you code a function in Python 3 to
parse the remarks from the string into the _remarks dict. | You are a Python code generator, capable of creating scripts from specifications. |
given a string and a position return both an updated position and a Component Object or a String back to the caller | How would you explain what the following Python 3 function does
def _get_component(self, string, initial_pos):
''' given a string and a position, return both an updated position and
either a Component Object or a String back to the caller '''
add_code = string[initial_pos:initial_pos + self.ADDR_CODE_LENGTH... | 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.