output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Returns the discrete linear convolution of a time series with itself optionally using unbiased normalization. | Can you generate the documentation for the following Python 3 function
def autocorrelation(ts, normalized=False, unbiased=False):
ts = np.squeeze(ts)
if ts.ndim <= 1:
if normalized:
ts = (ts - ts.mean())/ts.std()
N = ts.shape[0]
ar = np.asarray(ts)
acf = np.correlate(... | As a Python code composer, you craft elegant and concise scripts. |
Verifies the value is between 1 and 9 inclusively. | Here you have a function in Python 3, explain what it does
def fan_speed(self, value):
if value not in range(1, 10):
raise exceptions.RoasterValueError
self._fan_speed.value = value | As a python code expert, you are capable of creating scripts from specifications. |
Verifies that the heat setting is between 0 and 3. | Explain what the following Python 3 code does
def heat_setting(self, value):
if value not in range(0, 4):
raise exceptions.RoasterValueError
self._heat_setting.value = value | As a Python code composer, you craft elegant and concise scripts. |
Verifies that the heater_level is between 0 and heater_segments. Will throw RoasterValueError otherwise. | How would you explain what the following Python 3 function does
def heater_level(self, value):
if self._ext_sw_heater_drive:
if value not in range(0, self._heater_bangbang_segments+1):
raise exceptions.RoasterValueError
self._heater_level.value = value
else:
... | As a Python code composer, you craft elegant and concise scripts. |
def set_state_transition_func(self, func):
"""THIS FUNCTION MUST BE CALLED BEFORE CALLING
freshroastsr700.auto_connect().
Set, or re-set, the state transition function callback.
The supplied function will be called from a separate thread within
freshroastsr700, triggered by a se... | How would you code a function in Python 3 to
set the state transition function for every available freshroastsr700 state. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This is the main thread that listens to an event from
the comm process to execute the update_data_func callback
in the context of the main process. | Can you tell what is the following Python 3 function doing
def update_data_run(self, event_to_wait_on):
# with the daemon=Turue setting, this thread should
# quit 'automatically'
while event_to_wait_on.wait():
event_to_wait_on.clear()
if self.update_data_callback_kill_eve... | You are a Python code generator, capable of creating scripts from specifications. |
This is the main thread that listens to an event from
the state_transition_func callback
is called when the state_transition_func is called. | Can you generate a brief explanation for the following Python 3 code
def state_transition_run(self, event_to_wait_on):
# with the daemon=Turue setting, this thread should
# quit 'automatically'
while event_to_wait_on.wait():
event_to_wait_on.clear()
if self.state_transiti... | As a python code expert, you are capable of creating scripts from specifications. |
Connect to the roaster and creates a communication thread. | Make a summary of the following Python 3 code
def _connect(self):
# the following call raises a RoasterLookupException when the device
# is not found. It is
port = utils.find_device('1A86:5523')
# on some systems, after the device port is added to the device list,
# it can take u... | You are a Python code architect, reviewing and designing scalable and efficient code |
Sends the initialization packet to the roaster. | Here you have a function in Python 3, explain what it does
def _initialize(self):
self._header.value = b'\xAA\x55'
self._current_state.value = b'\x00\x00'
s = self._generate_packet()
self._ser.write(s)
self._header.value = b'\xAA\xAA'
self._current_state.value = b'\x02\x0... | You are a Python code generator, capable of creating scripts from specifications. |
Attempts to connect to the computer immediately. Will not retry. | Make a summary of the following Python 3 code
def connect(self):
self._start_connect(self.CA_SINGLE_SHOT)
while(self._connect_state.value == self.CS_ATTEMPTING_CONNECT or
self._connect_state.value == self.CS_CONNECTING):
time.sleep(0.1)
if self.CS_CONNECTED != self._con... | You are a Python code generator, capable of creating scripts from specifications. |
Starts the connection process. | Make a summary of the following Python 3 code
def _start_connect(self, connect_type):
if self._connect_state.value != self.CS_NOT_CONNECTED:
# already done or in process, assume success
return
self._connected.value = 0
self._connect_state.value = self.CS_ATTEMPTING_CONNE... | You are a Python code generator, capable of creating scripts from specifications. |
def _auto_connect(self):
"""Attempts to connect to the roaster every quarter of a second."""
while not self._teardown.value:
try:
self._connect()
return True
except exceptions.RoasterLookupError:
time.sleep(.25)
return False | Can you create a Python 3 function that
attempts to connect to the roaster every quarter of a second. Returns True if successful False otherwise. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _comm(self, thermostat=False,
kp=0.06, ki=0.0075, kd=0.01,
heater_segments=8, ext_sw_heater_drive=False,
update_data_event=None):
"""Do not call this directly - call auto_connect(), which will spawn
comm() for you.
This is the main communications lo... | Create a Python 3 function to
do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (bool): thermostat mode. ... | As a Python code analyst, you investigate and solve complex coding mysteries |
This is the main timer loop used to keep track of the time while the roaster is in a cooling state. | Given the following Python 3 function, write the documentation
def _timer(self, state_transition_event=None):
while not self._teardown.value:
state = self.get_roaster_state()
if(state == 'roasting' or state == 'cooling'):
time.sleep(1)
self.total_time += 1... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_roaster_state(self):
"""Returns a string based upon the current state of the roaster. Will
raise an exception if the state is unknown.
Returns:
'idle' if idle,
'sleeping' if sleeping,
'cooling' if cooling,
'roasting' if roasting,
... | How would you implement a function in Python 3 that
returns a string based upon the current state of the roaster. Will throw an exception if the state is unknown. | As a Python code composer, you craft elegant and concise scripts. |
Generates a packet based upon the current class variables. | Given the following Python 3 function, write the documentation
def _generate_packet(self):
roaster_time = utils.seconds_to_float(self._time_remaining.value)
packet = (
self._header.value +
self._temp_unit.value +
self._flags.value +
self._current_state.val... | You are a Python code analyst, evaluating scripts for potential improvements. |
def heat_level(self, value):
"""Set the desired output level. Must be between 0 and
number_of_segments inclusive."""
if value < 0:
self._heat_level = 0
elif round(value) > self._num_segments:
self._heat_level = self._num_segments
else:
self._he... | Create a Python 3 function to
set the desired output level. Must be between 0 and number_of_segments inclusive. | You are a Python code analyst, evaluating scripts for potential improvements. |
Generates the latest on or off pulse in
the string of on or off or off. | How would you explain what the following Python 3 function does
def generate_bangbang_output(self):
if self._current_index >= self._num_segments:
# we're due to switch over to the next
# commanded heat_level
self._heat_level_now = self._heat_level
# reset array in... | As a python code expert, you are capable of creating scripts from specifications. |
This method is called when the time remaining ends. It is a method that will be called when the time remaining ends. | Can you generate a brief explanation for the following Python 3 code
def next_state(self):
self.active_recipe_item += 1
if self.active_recipe_item >= len(self.recipe):
# we're done!
return
# show state step on screen
print("----------------------------------------... | As a Python code composer, you craft elegant and concise scripts. |
Process results by providers and categories. | Make a summary of the following Python 3 code
def process_results(self):
for result in self._results:
provider = result.provider
self.providers.append(provider)
if result.error:
self.failed_providers.append(provider)
continue
if not... | You are a Python code analyst, evaluating scripts for potential improvements. |
async def dnsbl_request(self, addr, provider):
"""
Make lookup to dnsbl provider
Parameters:
* addr (string) - ip address to check
* provider (string) - dnsbl provider
Returns:
* DNSBLResponse object
Raises:
* ValueError
"... | Write a Python 3 script for
making a DNSBL request to check the DNSBL s cache for a specific IP address. | You are a Python code architect, reviewing and designing scalable and efficient code |
A generator that will generate a range of floats. | Explain what the following Python 3 code does
def frange(start, stop, step, precision):
value = start
while round(value, precision) < stop:
yield round(value, precision)
value += step | You are a Python code generator, capable of creating scripts from specifications. |
Finds a connected device with the given VID : PID. Returns the serial
port url. | Can you generate the documentation for the following Python 3 function
def find_device(vidpid):
for port in list_ports.comports():
if re.search(vidpid, port[2], flags=re.IGNORECASE):
return port[0]
raise exceptions.RoasterLookupError | As a Python code analyst, you investigate and solve complex coding mysteries |
Calculate PID output value for given reference input and feedback. | Can you generate the documentation for the following Python 3 function
def update(self, currentTemp, targetTemp):
# in this implementation, ki includes the dt multiplier term,
# and kd includes the dt divisor term. This is typical practice in
# industry.
self.targetTemp = targetTemp
... | You are a Python code generator, capable of creating scripts from specifications. |
def load_nouns(self, file):
"""
Load dict from file for random words.
:param str file: filename
"""
with open(os.path.join(main_dir, file + '.dat'), 'r') as f:
self.nouns = json.load(f) | How would you implement a function in Python 3 that
loads dict from file for random words. | As a Python code composer, you craft elegant and concise scripts. |
Load list of random mails from file for random mails | Make a summary of the following Python 3 code
def load_dmails(self, file):
with open(os.path.join(main_dir, file + '.dat'), 'r') as f:
self.dmails = frozenset(json.load(f)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def load_nicknames(self, file):
"""
Load dict from file for random nicknames.
:param str file: filename
"""
with open(os.path.join(main_dir, file + '.dat'), 'r') as f:
self.nicknames = json.load(f) | Can you write a function in Python 3 where it
loads dict from file for random nicknames. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a list of random words. | Can you generate the documentation for the following Python 3 function
def random_words(self, letter=None, count=1):
self.check_count(count)
words = []
if letter is None:
all_words = list(
chain.from_iterable(self.nouns.values()))
try:
w... | You are a Python code generator, capable of creating scripts from specifications. |
def random_nicks(self, letter=None, gender='u', count=1):
"""
Return list of random nicks.
:param str letter: letter
:param str gender: ``'f'`` for female, ``'m'`` for male and None for both
:param int count: how much nicks
:rtype: list
:returns: list of random n... | How would you code a function in Python 3 to
return a list of random nicks. | You are a Python code analyst, evaluating scripts for potential improvements. |
def randomMails(self, count=1):
"""
Return random e-mails.
:rtype: list
:returns: list of random e-mails
"""
self.check_count(count)
random_nicks = self.rn.random_nicks(count=count)
random_domains = sample(self.dmails, count)
return [
... | Write a Python 3 script to
return random e - mails. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a list of sentences in the language. | Make a summary of the following Python 3 code
def get_sentences_list(self, sentences=1):
if sentences < 1:
raise ValueError('Param "sentences" must be greater than 0.')
sentences_list = []
while sentences:
num_rand_words = random.randint(self.MIN_WORDS, self.MAX_WORDS)
... | As a Python code composer, you craft elegant and concise scripts. |
Return a sentence from list of words. | Can you tell what is the following Python 3 function doing
def make_sentence(list_words):
lw_len = len(list_words)
if lw_len > 6:
list_words.insert(lw_len // 2 + random.choice(range(-2, 2)), ',')
sentence = ' '.join(list_words).replace(' ,', ',')
return sentence.capitalize... | You are a Python code generator, capable of creating scripts from specifications. |
def _discover_cover_image(zf, opf_xmldoc, opf_filepath):
'''
Find the cover image path in the OPF file.
Returns a tuple: (image content in base64, file extension)
'''
content = None
filepath = None
extension = None
# Strategies to discover the cover-image path:
# e.g.: <meta name="... | Can you implement a function in Python 3 that
finds the cover image in the OPF file. | As a Python code composer, you craft elegant and concise scripts. |
Discovers the contents of the OPF file and returns a list of objects. | Can you tell what is the following Python 3 function doing
def _discover_toc(zf, opf_xmldoc, opf_filepath):
'''
Returns a list of objects: {title: str, src: str, level: int, index: int}
'''
toc = None
# ePub 3.x
tag = find_tag(opf_xmldoc, 'item', 'properties', 'nav')
if tag and 'href' in ta... | You are a Python code analyst, evaluating scripts for potential improvements. |
Read the metadata from an ePub file. | Here you have a function in Python 3, explain what it does
def get_epub_metadata(filepath, read_cover_image=True, read_toc=True):
'''
References: http://idpf.org/epub/201 and http://idpf.org/epub/301
1. Parse META-INF/container.xml file and find the .OPF file path.
2. In the .OPF file, find the metadata... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_epub_opf_xml(filepath):
'''
Returns the file.OPF contents of the ePub file
'''
if not zipfile.is_zipfile(filepath):
raise EPubException('Unknown file')
# print('Reading ePub file: {}'.format(filepath))
zf = zipfile.ZipFile(filepath, 'r', compression=zipfile.ZIP_DEFLATED, allowZi... | Write a Python 3 function for
returning the file. OPF contents of the ePub file | As a Python code composer, you craft elegant and concise scripts. |
Падеж для склонение имение класса Case gender Падеж для склонение к | Can you generate the documentation for the following Python 3 function
def firstname(self, value, case, gender=None):
if not value:
raise ValueError('Firstname cannot be empty.')
return self.__inflect(value, case, 'firstname', gender) | You are a Python code analyst, evaluating scripts for potential improvements. |
Падеж для класса Case Lastname | Can you generate the documentation for the following Python 3 function
def lastname(self, value, case, gender=None):
if not value:
raise ValueError('Lastname cannot be empty.')
return self.__inflect(value, case, 'lastname', gender) | You are a Python code architect, reviewing and designing scalable and efficient code |
Падеж для класса Case для класса Case | Can you generate the documentation for the following Python 3 function
def middlename(self, value, case, gender=None):
if not value:
raise ValueError('Middlename cannot be empty.')
return self.__inflect(value, case, 'middlename', gender) | As a Python code composer, you craft elegant and concise scripts. |
def expand(expression):
"""
Expand a reference expression to individual spans.
Also works on space-separated ID lists, although a sequence of space
characters will be considered a delimiter.
>>> expand('a1')
'a1'
>>> expand('a1[3:5]')
'a1[3:5]'
>>> expand('a1[3:5+6:7]')
'a1[3:5]... | Write a Python 3 script for
expanding a reference expression to individual spans. | As a Python code composer, you craft elegant and concise scripts. |
def compress(expression):
"""
Compress a reference expression to group spans on the same id.
Also works on space-separated ID lists, although a sequence of space
characters will be considered a delimiter.
>>> compress('a1')
'a1'
>>> compress('a1[3:5]')
'a1[3:5]'
>>> compress('a1[3:5... | Write a Python 3 script to
compress a reference expression to group spans on the same id. | As a python code expert, you are capable of creating scripts from specifications. |
def selections(expression, keep_delimiters=True):
"""
Split the expression into individual selection expressions. The
delimiters will be kept as separate items if keep_delimters=True.
Also works on space-separated ID lists, although a sequence of space
characters will be considered a delimiter.
... | Create a Python 3 function to
split the expression into individual selection expressions. | As a Python code composer, you craft elegant and concise scripts. |
def resolve(container, expression):
"""
Return the string that is the resolution of the alignment expression
`expression`, which selects ids from `container`.
"""
itemgetter = getattr(container, 'get_item', container.get)
tokens = []
expression = expression.strip()
for sel_delim, _id, _r... | How would you implement a function in Python 3 that
returns the string that is the resolution of the alignment expression expression which selects ids from container. | You are a Python code analyst, evaluating scripts for potential improvements. |
def referents(igt, id, refattrs=None):
"""
Return a list of ids denoting objects (tiers or items) in `igt` that
are referred by the object denoted by `id` using a reference
attribute in `refattrs`. If `refattrs` is None, then consider all
known reference attributes for the type of object denoted by ... | Can you create a Python 3 function that
returns a list of ids denoting objects in igt that are referred by id. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a list of ids denoting objects in igt that refer to the given id. | Here you have a function in Python 3, explain what it does
def referrers(igt, id, refattrs=None):
if refattrs is None:
result = {}
else:
result = {ra: [] for ra in refattrs}
# if the id is a tier, only look at tiers; otherwise only look at items
try:
obj = igt[id]
others... | You are a Python code generator, capable of creating scripts from specifications. |
get ancestors of an item | Here you have a function in Python 3, explain what it does
def ancestors(obj, refattrs=(ALIGNMENT, SEGMENTATION)):
if hasattr(obj, 'tier'):
tier = obj.tier
items = [obj]
else:
tier = obj
items = tier.items
# a tier may be visited twice (e.g. A > B > A), but then it stops;
... | As a Python code composer, you craft elegant and concise scripts. |
def descendants(obj, refattrs=(SEGMENTATION, ALIGNMENT), follow='first'):
"""
>>> for des in query.descendants(igt.get_item('p1'), refattrs=(SEGMENTATION, ALIGNMENT)):
... print(des)
(<Tier object (id: p type: phrases) at ...>, 'segmentation', <Tier object (id: w type: words) at ...>, [<Item object ... | How would you implement a function in Python 3 that
gets the list of descendants of an item | You are a Python code architect, reviewing and designing scalable and efficient code |
def default_decode(events, mode='full'):
"""Decode a XigtCorpus element."""
event, elem = next(events)
root = elem # store root for later instantiation
while (event, elem.tag) not in [('start', 'igt'), ('end', 'xigt-corpus')]:
event, elem = next(events)
igts = None
if event == 'start' a... | Create a Python 3 function to
decode a XigtCorpus element. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a tuple each value being a line of the source file. | Here you have a function in Python 3, explain what it does
def _get_file_content(source):
filepath = os.path.join('siglists', source + '.txt')
lines = []
with resource_stream(__name__, filepath) as f:
for i, line in enumerate(f):
line = line.decode('utf-8', 'strict').strip()
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_rar_version(xfile):
"""Check quickly whether file is rar archive.
"""
buf = xfile.read(len(RAR5_ID))
if buf.startswith(RAR_ID):
return 3
elif buf.startswith(RAR5_ID):
xfile.read(1)
return 5
return 0 | Can you create a Python 3 function that
checks quickly whether file is rar archive. | You are a Python code generator, capable of creating scripts from specifications. |
def _open_next(self):
"""Proceed to next volume."""
# is the file split over archives?
if (self._cur.flags & rarfile.RAR_FILE_SPLIT_AFTER) == 0:
return False
if self._fd:
self._fd.close()
self._fd = None
# open next part
self._volfil... | Can you write a function in Python 3 where it
proceeds to next volume. | You are a Python code analyst, evaluating scripts for potential improvements. |
Check CRC and return code. | Can you generate the documentation for the following Python 3 function
def _check(self): # TODO: fix?
if self._returncode:
rarfile.check_returncode(self, '')
if self._remain != 0:
raise rarfile.BadRarFile("Failed the read enough data") | As a Python code translator, you convert algorithms and pseudocode into Python. |
def to_24bit_gray(mat: np.ndarray):
"""returns a matrix that contains RGB channels, and colors scaled
from 0 to 255"""
return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2) | Can you create a Python 3 function that
returns a matrix that contains RGB channels and colors scaled by 0 to 255 | You are a Python code analyst, evaluating scripts for potential improvements. |
returns an RGB matrix scaled by a matplotlib color map | How would you explain what the following Python 3 function does
def apply_color_map(name: str, mat: np.ndarray = None):
def apply_map(mat):
return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8)
return apply_map if mat is None else apply_map(mat) | You are a Python code generator, capable of creating scripts from specifications. |
def mat_to_surface(mat: np.ndarray, transformer=to_24bit_gray):
"""Can be used to create a pygame.Surface from a 2d numpy array.
By default a grey image with scaled colors is returned, but using the
transformer argument any transformation can be used.
:param mat: the matrix to create the surface of.
... | How would you implement a function in Python 3 that
converts a 2d numpy array to a pygame. Surface | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates a random id with the given length and charset. | Make a summary of the following Python 3 code
def random_id(length=16, charset=alphanum_chars, first_charset=alpha_chars, sep='', group=0):
t = []
first_chars = list(set(charset).intersection(first_charset))
if len(first_chars) == 0:
first_chars = charset
t.append(first_chars[random.ran... | As a python code expert, you are capable of creating scripts from specifications. |
def merge_dict(data, *args):
"""Merge any number of dictionaries
"""
results = {}
for current in (data,) + args:
results.update(current)
return results | Can you implement a function in Python 3 that
merges any number of dictionaries with the given ones. | As a Python code analyst, you investigate and solve complex coding mysteries |
def make_url(url, *paths):
"""Joins individual URL strings together, and returns a single string.
"""
for path in paths:
url = re.sub(r'/?$', re.sub(r'^/?', '/', path), url)
return url | Write a Python 3 function that can
join individual URL strings together and returns a single string. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def aggregate_result(self, return_code, output, service_description='', specific_servers=None):
'''
aggregate result
'''
if specific_servers == None:
specific_servers = self.servers
else:
specific_servers = set(self.servers).intersection(specific_servers)
... | Can you implement a function in Python 3 that
aggregates result for all servers. | You are a Python code analyst, evaluating scripts for potential improvements. |
def send_results(self):
'''
send results
'''
for server in self.servers:
if self.servers[server]['results']:
if len(self.servers[server]['results']) == 1:
msg = MIMEText('')
msg['Subject'] = '[%(custom_fqdn)s] [%(servic... | Write a Python 3 script for
sending results to all servers | You are a Python code analyst, evaluating scripts for potential improvements. |
Main function for the main function of the main function. | Can you generate the documentation for the following Python 3 function
def main():
config = {
"api": {
"services": [
{
"name": "my_api",
"testkey": "testval",
},
],
"calls": {
"hello_w... | You are a Python code architect, reviewing and designing scalable and efficient code |
def make_request(self, data):
"""Parse the outgoing schema"""
sch = MockItemSchema()
return Request(**{
"callname": self.context.get("callname"),
"payload": sch.dump(data),
}) | How would you code a function in Python 3 to
make a request from the incoming data | As a Python code composer, you craft elegant and concise scripts. |
def populate_data(self, data):
"""Parse the outgoing schema"""
sch = MockItemSchema()
return Result(**{
"callname": self.context.get("callname"),
"result": sch.dump(data),
}) | How would you code a function in Python 3 to
populate the result with the data from the incoming data. | As a python code expert, you are capable of creating scripts from specifications. |
returns a handler that can be used with EventListener. listen()
| Can you generate the documentation for the following Python 3 function
def key_press(keys):
return lambda e: e.key if e.type == pygame.KEYDOWN \
and e.key in keys else EventConsumerInfo.DONT_CARE | As a Python code composer, you craft elegant and concise scripts. |
returns a handler that listens for unicode characters | Here you have a function in Python 3, explain what it does
def unicode_char(ignored_chars=None):
return lambda e: e.unicode if e.type == pygame.KEYDOWN \
and ((ignored_chars is None)
or (e.unicode not in ignored_chars))\
else EventConsumerInfo.DONT_CARE | You are a Python code analyst, evaluating scripts for potential improvements. |
Adds a new MouseProxy for the given group to the
EventListener. mouse_proxies dict. | Here you have a function in Python 3, explain what it does
def mouse_area(self, handler, group=0, ident=None):
key = ident or id(handler)
if key not in self.mouse_proxies[group]:
self.mouse_proxies[group][key] = MouseProxy(handler, ident)
return self.mouse_proxies[group][key] | You are a Python code architect, reviewing and designing scalable and efficient code |
def listen_until_return(self, *temporary_handlers, timeout=0):
"""Calls listen repeatedly until listen returns something else than None.
Then returns listen's result. If timeout is not zero listen_until_return
stops after timeout seconds and returns None."""
start = time.time()
w... | Write a Python 3 script for
calling listen repeatedly until listen returns something else than None. Then returns None. | As a Python code composer, you craft elegant and concise scripts. |
def wait_for_n_keypresses(self, key, n=1):
"""Waits till one key was pressed n times.
:param key: the key to be pressed as defined by pygame. E.g.
pygame.K_LEFT for the left arrow key
:type key: int
:param n: number of repetitions till the function returns
:type n: i... | Write a Python 3 script to
wait till one key was pressed n times. | You are a Python code architect, reviewing and designing scalable and efficient code |
Waits until one of the specified keys was pressed and returns
which key was pressed. | Can you generate the documentation for the following Python 3 function
def wait_for_keys(self, *keys, timeout=0):
if len(keys) == 1 and _is_iterable(keys[0]):
keys = keys[0]
return self.listen_until_return(Handler.key_press(keys), timeout=timeout) | As a Python code composer, you craft elegant and concise scripts. |
def wait_for_unicode_char(self, ignored_chars=None, timeout=0):
"""Returns a str that contains the single character that was pressed.
This already respects modifier keys and keyboard layouts. If timeout is
not none and no key is pressed within the specified timeout, None is
returned. If ... | How would you implement a function in Python 3 that
waits until a single character is pressed in the specified list of ignored_chars. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Yields all the first files in the item. | Can you generate a brief explanation for the following Python 3 code
def _find_all_first_files(self, item):
for listed_item in item.list():
new_style = re.findall(r'(?i)\.part(\d+)\.rar^', listed_item.id)
if new_style:
if int(new_style[0]) == 1:
yield ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def find_datafile(name, search_path, codecs=get_codecs()):
"""
find all matching data files in search_path
search_path: path of directories to load from
codecs: allow to override from list of installed
returns array of tuples (codec_object, filename)
"""
return munge.find_datafile(name, sear... | Implement a function in Python 3 to
find all matching data files in search_path | As a Python code translator, you convert algorithms and pseudocode into Python. |
load datafile from codec
| Here you have a function in Python 3, explain what it does
def load_datafile(name, search_path, codecs=get_codecs(), **kwargs):
return munge.load_datafile(name, search_path, codecs, **kwargs) | As a Python code composer, you craft elegant and concise scripts. |
Initialize what requires credentials and secret files. | Make a summary of the following Python 3 code
def cred_init(
self,
*,
secrets_dir: str,
log: Logger,
bot_name: str,
) -> None:
"""
Initialize what requires credentials/secret files.
:param secrets_dir: dir to expect credentials in ... | You are a Python code generator, capable of creating scripts from specifications. |
Send a message to a specific birdsite. | Explain what the following Python 3 code does
def send(
self,
*,
text: str,
) -> List[OutputRecord]:
"""
Send birdsite message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single ... | As a Python code composer, you craft elegant and concise scripts. |
Uploads media to birdsite and sends status and media and captions to post. | Make a summary of the following Python 3 code
def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[]
) -> List[OutputRecord]:
"""
Upload media to birdsite,
and send status and media,
and captions i... | As a Python code composer, you craft elegant and concise scripts. |
def perform_batch_reply(
self,
*,
callback: Callable[..., str],
lookback_limit: int,
target_handle: str,
) -> List[OutputRecord]:
"""
Performs batch reply on target account.
Looks up the recent messages of the target user,
a... | How would you code a function in Python 3 to
perform a batch reply on the target account. | You are a Python code architect, reviewing and designing scalable and efficient code |
def send_dm_sos(self, message: str) -> None:
"""
Send DM to owner if something happens.
:param message: message to send to owner.
:returns: None.
"""
if self.owner_handle:
try:
# twitter changed the DM API and tweepy (as of 2019-03-08)
... | Implement a function in Python 3 to
send DM to owner if something happens. | You are a Python code analyst, evaluating scripts for potential improvements. |
Handle an error while trying to do something. | Can you generate the documentation for the following Python 3 function
def handle_error(
self,
*,
message: str,
error: tweepy.TweepError,
) -> OutputRecord:
"""
Handle error while trying to do something.
:param message: message to send in DM r... | You are a Python code architect, reviewing and designing scalable and efficient code |
Handle uploading all captions.
:param media_ids: media ids of uploads to attach captions to.
:param captions: captions to be attached to those media ids.
:returns: None. | How would you explain what the following Python 3 function does
def _handle_caption_upload(
self,
*,
media_ids: List[str],
captions: Optional[List[str]],
) -> None:
"""
Handle uploading all captions.
:param media_ids: media ids of uploads to a... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _send_direct_message_new(self, messageobject: Dict[str, Dict]) -> Any:
"""
:reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event.html
"""
headers, post_data = _buildmessageobject(messageobject)
newdm_path = "/direct_me... | Implement a Python 3 function for
sending a new message to the direct message queue. | As a python code expert, you are capable of creating scripts from specifications. |
Takes crash data via stdin and generates a Socorro signature | Can you tell what is the following Python 3 function doing
def main():
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
args = parser.parse_args()
generator = SignatureGenerator(debug=ar... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add a configuration dict to the internal configuration dict. | How would you explain what the following Python 3 function does
def add_config(self, config):
for attr in self.__fixed_attrs:
if attr in config:
raise Exception("cannot set '%s' outside of init", attr)
# pre checkout
stages = config.get('stages', None)
if st... | You are a Python code architect, reviewing and designing scalable and efficient code |
check the config for sanity checks | Can you generate the documentation for the following Python 3 function
def check_config(self):
# sanity checks - no config access past here
if not getattr(self, 'stages', None):
raise NotImplementedError("member variable 'stages' must be defined")
# start at stage
if self.__... | You are a Python code analyst, evaluating scripts for potential improvements. |
def check_definition(self):
"""
called after Defintion was loaded to sanity check
raises on error
"""
if not self.write_codec:
self.__write_codec = self.defined.data_ext
# TODO need to add back a class scope target limited for subprojects with sub target sets... | Can you implement a function in Python 3 that
checks if the definition of a class is valid | As a Python code translator, you convert algorithms and pseudocode into Python. |
def find_datafile(self, name, search_path=None):
"""
find all matching data files in search_path
returns array of tuples (codec_object, filename)
"""
if not search_path:
search_path = self.define_dir
return codec.find_datafile(name, search_path) | How would you implement a function in Python 3 that
finds all matching data files in search_path returns array of tuples | As a Python code translator, you convert algorithms and pseudocode into Python. |
def load_datafile(self, name, search_path=None, **kwargs):
"""
find datafile and load them from codec
"""
if not search_path:
search_path = self.define_dir
self.debug_msg('loading datafile %s from %s' % (name, str(search_path)))
return codec.load_datafile(nam... | Write a Python 3 script to
load a datafile from the codec | As a Python code composer, you craft elegant and concise scripts. |
def run(self):
""" run all configured stages """
self.sanity_check()
# TODO - check for devel
# if not self.version:
# raise Exception("no version")
# XXX check attr exist
if not self.release_environment:
raise Exception("no instance name")
time_start = t... | How would you implement a function in Python 3 that
runs all configured stages | As a Python code analyst, you investigate and solve complex coding mysteries |
Return POSIX timestamp as float. | Given the following Python 3 function, write the documentation
def timestamp(dt):
if dt.tzinfo is None:
return time.mktime((
dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
-1, -1, -1)) + dt.microsecond / 1e6
else:
return (dt - _EPOCH).total_seconds() | You are a Python code generator, capable of creating scripts from specifications. |
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
"""Rate limit a function."""
return util.rate_limited(max_per_hour, *args) | Can you implement a function in Python 3 that
rates limit a function. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _repair(record: Dict[str, Any]) -> Dict[str, Any]:
"""Repair a corrupted IterationRecord with a specific known issue."""
output_records = record.get("output_records")
if record.get("_type", None) == "IterationRecord" and output_records is not None:
birdsite_record = output_records.get("birdsite"... | Write a Python 3 script to
repair a corrupted IterationRecord with a specific known issue. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get object back from dict. | Make a summary of the following Python 3 code
def from_dict(cls, obj_dict: Dict[str, Any]) -> "IterationRecord":
obj = cls()
for key, item in obj_dict.items():
obj.__dict__[key] = item
return obj | As a Python code composer, you craft elegant and concise scripts. |
Send a message to all outputs. | Explain what the following Python 3 code does
def send(
self,
*args: str,
text: str=None,
) -> IterationRecord:
"""
Post text-only to all outputs.
:param args: positional arguments.
expected: text to send as message in post.
keywor... | You are a Python code analyst, evaluating scripts for potential improvements. |
Post with one media item to all outputs. | Here you have a function in Python 3, explain what it does
def send_with_one_media(
self,
*args: str,
text: str=None,
file: str=None,
caption: str=None,
) -> IterationRecord:
"""
Post with one media item to all outputs.
Provide file... | As a Python code analyst, you investigate and solve complex coding mysteries |
Post with several media. | Explain what the following Python 3 code does
def send_with_many_media(
self,
*args: str,
text: str=None,
files: List[str]=None,
captions: List[str]=[],
) -> IterationRecord:
"""
Post with several media.
Provide filenames so outputs... | You are a Python code analyst, evaluating scripts for potential improvements. |
Performs a batch reply on the target accounts. | Can you generate a brief explanation for the following Python 3 code
def perform_batch_reply(
self,
*,
callback: Callable[..., str]=None,
target_handles: Dict[str, str]=None,
lookback_limit: int=20,
per_service_lookback_limit: Dict[str, int]=None,
... | As a python code expert, you are capable of creating scripts from specifications. |
def nap(self) -> None:
"""
Go to sleep for the duration of self.delay.
:returns: None
"""
self.log.info(f"Sleeping for {self.delay} seconds.")
for _ in progress.bar(range(self.delay)):
time.sleep(1) | Write a Python 3 function for
going to sleep for the duration of self. delay seconds. | You are a Python code analyst, evaluating scripts for potential improvements. |
Store some extra info in the messaging storage. | Here you have a function in Python 3, explain what it does
def store_extra_info(self, key: str, value: Any) -> None:
self.extra_keys[key] = value | You are a Python code architect, reviewing and designing scalable and efficient code |
def store_extra_keys(self, d: Dict[str, Any]) -> None:
"""
Store several extra values in the messaging storage.
:param d: dictionary entry to merge with current self.extra_keys.
:returns: None
"""
new_dict = dict(self.extra_keys, **d)
self.extra_keys = new_dict.c... | Create a Python 3 function to
store several extra keys in the messaging storage. | You are a Python code generator, capable of creating scripts from specifications. |
def update_history(self) -> None:
"""
Update messaging history on disk.
:returns: None
"""
self.log.debug(f"Saving history. History is: \n{self.history}")
jsons = []
for item in self.history:
json_item = item.__dict__
# Convert sub-entri... | Write a Python 3 function that can
update the history of the current message. | As a python code expert, you are 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.