output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Initialize websockets in a thread with channels and subscriptions | Can you generate a brief explanation for the following Python 3 code
def run(self):
self.api = self.context.get("cls")(self.context)
self.context["inst"].append(self) # Adapters used by strategies
def on_ws_connect(*args, **kwargs):
"""Callback on connect hook to set is_connected_w... | You are a Python code generator, capable of creating scripts from specifications. |
def add_channels(self, channels):
"""
Take a list of SockChannel objects and extend the websock listener
"""
chans = [
SockChannel(chan, res, self._generate_result)
for chan, res in channels.items()
]
self.api.channels.extend(chans)
self.ap... | Create a Python 3 function to
add the given channels to the websock listener and connect them to the websock listener | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate the result object | Explain what the following Python 3 code does
def _generate_result(self, res_type, channel, result):
schema = self.api.ws_result_schema()
schema.context['channel'] = channel
schema.context['response_type'] = res_type
self.callback(schema.load(result), self.context) | You are a Python code architect, reviewing and designing scalable and efficient code |
def rand_elem(seq, n=None):
"""returns a random element from seq n times. If n is None, it continues indefinitly"""
return map(random.choice, repeat(seq, n) if n is not None else repeat(seq)) | Create a Python 3 function to
return a random element from seq n times. | You are a Python code analyst, evaluating scripts for potential improvements. |
def first_paragraph(multiline_str, without_trailing_dot=True, maxlength=None):
'''Return first paragraph of multiline_str as a oneliner.
When without_trailing_dot is True, the last char of the first paragraph
will be removed, if it is a dot ('.').
Examples:
>>> multiline_str = 'first line\\nse... | Can you implement a function in Python 3 that
returns first paragraph of multiline_str as a oneliner. | As a Python code analyst, you investigate and solve complex coding mysteries |
def print_doc1(*args, **kwargs):
'''Print the first paragraph of the docstring of the decorated function.
The paragraph will be printed as a oneliner.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, ``prefix`` of ``tail``
(eg.... | Can you create a Python 3 function that
prints the first paragraph of the docstring of the decorated function. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return str template with applied substitutions. | Can you tell what is the following Python 3 function doing
def filled_out_template_str(template, **substitutions):
'''Return str template with applied substitutions.
Example:
>>> template = 'Asyl for {{name}} {{surname}}!'
>>> filled_out_template_str(template, name='Edward', surname='Snowden')
... | As a python code expert, you are capable of creating scripts from specifications. |
def filled_out_template(filename, **substitutions):
'''Return content of file filename with applied substitutions.'''
res = None
with open(filename, 'r') as fp:
template = fp.read()
res = filled_out_template_str(template, **substitutions)
return res | How would you implement a function in Python 3 that
returns content of file filename with applied substitutions. | As a Python code composer, you craft elegant and concise scripts. |
Search in file filename for a line starting with prefix and replace the line by new_line. Return True if the line was updated False if the line was not appended True if the line was not found. | Here you have a function in Python 3, explain what it does
def update_or_append_line(filename, prefix, new_line, keep_backup=True,
append=True):
'''Search in file 'filename' for a line starting with 'prefix' and replace
the line by 'new_line'.
If a line starting with 'prefix' not ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def comment_out_line(filename, line, comment='#',
update_or_append_line=update_or_append_line):
'''Comment line out by putting a comment sign in front of the line.
If the file does not contain the line, the files content will not be
changed (but the file will be touched in every case).... | Write a Python 3 script for
commenting out a line in a file. | You are a Python code architect, reviewing and designing scalable and efficient code |
def uncomment_or_update_or_append_line(filename, prefix, new_line, comment='#',
keep_backup=True,
update_or_append_line=update_or_append_line):
'''Remove the comment of an commented out line and make the line "active".
If such an com... | Can you write a function in Python 3 where it
removes the comment of an existing line and make the line active. | As a python code expert, you are capable of creating scripts from specifications. |
Return a copy of input with every str component encoded from unicode to
utf - 8. | Can you generate a brief explanation for the following Python 3 code
def convert_unicode_2_utf8(input):
'''Return a copy of `input` with every str component encoded from unicode to
utf-8.
'''
if isinstance(input, dict):
try:
# python-2.6
return dict((convert_unicode_2_utf... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the json - file data with all strings utf - 8 encoded. | Given the following Python 3 function, write the documentation
def load_json(filename, gzip_mode=False):
'''Return the json-file data, with all strings utf-8 encoded.'''
open_file = open
if gzip_mode:
open_file = gzip.open
try:
with open_file(filename, 'rt') as fh:
data = j... | You are a Python code generator, capable of creating scripts from specifications. |
def write_json(data, filename, gzip_mode=False):
'''Write the python data structure as a json-Object to filename.'''
open_file = open
if gzip_mode:
open_file = gzip.open
try:
with open_file(filename, 'wt') as fh:
json.dump(obj=data, fp=fh, sort_keys=True)
except Attribu... | Implement a function in Python 3 to
write the python data structure as a json - Object to filename. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return text with a newline inserted after each line_length char. | Given the following Python 3 function, write the documentation
def text_with_newlines(text, line_length=78, newline='\n'):
'''Return text with a `newline` inserted after each `line_length` char.
Return `text` unchanged if line_length == 0.
'''
if line_length > 0:
if len(text) <= line_length:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
A memoize decorator for class properties. | Make a summary of the following Python 3 code
def lazy_val(func, with_del_hook=False):
'''A memoize decorator for class properties.
Return a cached property that is calculated by function `func` on first
access.
'''
def hook_for(that):
try:
orig_del = that.__del__
excep... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _readlines(fname, fpointer1=open, fpointer2=open): # pragma: no cover
"""Read all lines from file."""
# fpointer1, fpointer2 arguments to ease testing
try:
with fpointer1(fname, "r") as fobj:
return fobj.readlines()
except UnicodeDecodeError: # pragma: no cover
with fpo... | How would you implement a function in Python 3 that
reads all lines from file. | As a python code expert, you are capable of creating scripts from specifications. |
def match(Class, path, pattern, flags=re.I, sortkey=None, ext=None):
"""for a given path and regexp pattern, return the files that match"""
return sorted(
[
Class(fn=fn)
for fn in rglob(path, f"*{ext or ''}")
if re.search(pattern, os.path.basen... | How would you implement a function in Python 3 that
returns the files that match a given path and regexp pattern | You are a Python code analyst, evaluating scripts for potential improvements. |
def copy(self, new_fn):
"""copy the file to the new_fn, preserving atime and mtime"""
new_file = self.__class__(fn=str(new_fn))
new_file.write(data=self.read())
new_file.utime(self.atime, self.mtime)
return new_file | Write a Python 3 script to
copy the file to the new_fn preserving atime and mtime | As a Python code translator, you convert algorithms and pseudocode into Python. |
def make_basename(self, fn=None, ext=None):
"""make a filesystem-compliant basename for this file"""
fb, oldext = os.path.splitext(os.path.basename(fn or self.fn))
ext = ext or oldext.lower()
fb = String(fb).hyphenify(ascii=True)
return ''.join([fb, ext]) | Create a Python 3 function to
make a filesystem - compliant basename for this file | As a python code expert, you are capable of creating scripts from specifications. |
def tempfile(self, mode='wb', **args):
"write the contents of the file to a tempfile and return the tempfile filename"
tf = tempfile.NamedTemporaryFile(mode=mode)
self.write(tf.name, mode=mode, **args)
return tfn | Can you implement a function in Python 3 that
writes the contents of the file to a tempfile and return the tempfile filename | You are a Python code architect, reviewing and designing scalable and efficient code |
delete the file from the filesystem. | Given the following Python 3 function, write the documentation
def delete(self):
if self.isfile:
os.remove(self.fn)
elif self.isdir:
shutil.rmtree(self.fn) | You are a Python code architect, reviewing and designing scalable and efficient code |
given a number of bytes return the file size in readable units | How would you explain what the following Python 3 function does
def readable_size(C, bytes, suffix='B', decimals=1, sep='\u00a0'):
if bytes is None:
return
size = float(bytes)
for unit in C.SIZE_UNITS:
if abs(size) < 1024 or unit == C.SIZE_UNITS[-1]:
retur... | You are a Python code analyst, evaluating scripts for potential improvements. |
def bytes_from_readable_size(C, size, suffix='B'):
"""given a readable_size (as produced by File.readable_size()), return the number of bytes."""
s = re.split("^([0-9\.]+)\s*([%s]?)%s?" % (''.join(C.SIZE_UNITS), suffix), size, flags=re.I)
bytes, unit = round(float(s[1])), s[2].upper()
wh... | How would you code a function in Python 3 to
give a readable_size returns the number of bytes. | You are a Python code analyst, evaluating scripts for potential improvements. |
def run(self):
"""Executed on startup of application"""
for wsock in self.wsocks:
wsock.run()
for api in self.apis:
api.run() | Write a Python 3 script to
execute on startup of application | As a Python code translator, you convert algorithms and pseudocode into Python. |
Executed on shutdown of application | Can you tell what is the following Python 3 function doing
def shutdown(self):
for wsock in self.wsocks:
wsock.shutdown()
for api in self.apis:
api.shutdown() | As a Python code analyst, you investigate and solve complex coding mysteries |
def request(self, url, method, data=None, headers=None):
"""Makes a HTTP call, formats response and does error handling.
"""
http_headers = merge_dict(self.default_headers, headers or {})
request_data = merge_dict({'api_key': self.apikey}, data or {})
logger.info('HTTP %s REQUES... | Implement a Python 3 function for
making a HTTP call and formats response and does error handling. | As a Python code analyst, you investigate and solve complex coding mysteries |
Makes a GET request on the object with the given action. | Given the following Python 3 function, write the documentation
def get(self, action, params=None, headers=None):
return self.request(make_url(self.endpoint, action), method='GET', data=params,
headers=headers) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def post(self, action, data=None, headers=None):
"""Makes a GET request
"""
return self.request(make_url(self.endpoint, action), method='POST', data=data,
headers=headers) | Implement a function in Python 3 to
make a POST request | You are a Python code architect, reviewing and designing scalable and efficient code |
def delete(self, action, headers=None):
"""Makes a GET request
"""
return self.request(make_url(self.endpoint, action), method='DELETE',
headers=headers) | Can you implement a function in Python 3 that
makes a DELETE request returning the response. | You are a Python code generator, capable of creating scripts from specifications. |
def calc_piece_size(size, min_piece_size=20, max_piece_size=29, max_piece_count=1000):
"""
Calculates a good piece size for a size
"""
logger.debug('Calculating piece size for %i' % size)
for i in range(min_piece_size, max_piece_size): # 20 = 1MB
if size / (2**i) < max_piece_count:
... | Can you implement a function in Python 3 that
calculates a good piece size for a size. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Prepare a list of all pieces grouped together together | Given the following Python 3 function, write the documentation
def split_pieces(piece_list, segments, num):
piece_groups = []
pieces = list(piece_list)
while pieces:
for i in range(segments):
p = pieces[i::segments][:num]
if not p:
break
piece_grou... | As a Python code composer, you craft elegant and concise scripts. |
def after(parents, func=None):
'''Create a new Future whose completion depends on parent futures
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in which the dependent future's
... | Write a Python 3 function for
creating a new future whose completion depends on parent futures | As a Python code analyst, you investigate and solve complex coding mysteries |
def wait_any(futures, timeout=None):
'''Wait for the completion of any (the first) one of multiple futures
:param list futures: A list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, will block indefinitely.
:type timeout: float or None
:returns:
One o... | How would you code a function in Python 3 to
wait for the completion of any of the provided futures. | You are a Python code generator, capable of creating scripts from specifications. |
Wait for the completion of all futures in a list of : class : Future \ s
. | Here you have a function in Python 3, explain what it does
def wait_all(futures, timeout=None):
'''Wait for the completion of all futures in a list
:param list future: a list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, can block indefinitely.
:type timeout: flo... | You are a Python code analyst, evaluating scripts for potential improvements. |
def finish(self, value):
'''Give the future it's value and trigger any associated callbacks
:param value: the new value for the future
:raises:
:class:`AlreadyComplete <junction.errors.AlreadyComplete>` if
already complete
'''
if self._done.is_set():
... | Can you create a Python 3 function that
gives the future it s value and trigger any associated callbacks is set to None. | You are a Python code analyst, evaluating scripts for potential improvements. |
Finish this future in an error state. | Can you generate the documentation for the following Python 3 function
def abort(self, klass, exc, tb=None):
'''Finish this future (maybe early) in an error state
Takes a standard exception triple as arguments (like returned by
``sys.exc_info``) and will re-raise them as the value.
Any... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Assign a callback function to be run when successfully complete
| Given the following Python 3 function, write the documentation
def on_finish(self, func):
'''Assign a callback function to be run when successfully complete
:param function func:
A callback to run when complete. It will be given one argument (the
value that has arrived), and it'... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def on_abort(self, func):
'''Assign a callback function to be run when :meth:`abort`\ed
:param function func:
A callback to run when aborted. It will be given three arguments:
- ``klass``: the exception class
- ``exc``: the exception instance
... | Write a Python 3 function for
assigning a callback function to be run when abort \ ed is set | As a python code expert, you are capable of creating scripts from specifications. |
Create a new future whose completion depends on this one and the function func will be called with the return value of which the future s result is set to the final value of that one s parents. | Explain what the following Python 3 code does
def after(self, func=None, other_parents=None):
'''Create a new Future whose completion depends on this one
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
... | As a Python code composer, you craft elegant and concise scripts. |
transforms any os path into unix style | Here you have a function in Python 3, explain what it does
def os_path_transform(self, s, sep=os.path.sep):
if sep == '/':
return s
else:
return s.replace(sep, '/') | As a python code expert, you are capable of creating scripts from specifications. |
Transform a list of files into a list of config files. | Explain what the following Python 3 code does
def transform(self, tr_list, files):
singular = False
if not isinstance(files, list) and not isinstance(files, tuple):
singular = True
files = [files]
for _find, _replace in tr_list:
files = [opt.replace(_find, _r... | As a python code expert, you are capable of creating scripts from specifications. |
def resolve_dst(self, dst_dir, src):
"""
finds the destination based on source
if source is an absolute path, and there's no pattern, it copies the file to base dst_dir
"""
if os.path.isabs(src):
return os.path.join(dst_dir, os.path.basename(src))
return os.pa... | Write a Python 3 function for
resolving the destination based on source and returns the file name. | As a Python code composer, you craft elegant and concise scripts. |
def write(self, fn=None):
"""copy the zip file from its filename to the given filename."""
fn = fn or self.fn
if not os.path.exists(os.path.dirname(fn)):
os.makedirs(os.path.dirname(fn))
f = open(self.fn, 'rb')
b = f.read()
f.close()
f = open(fn, 'wb')... | How would you code a function in Python 3 to
copy the zip file from its filename to the given filename. | You are a Python code generator, capable of creating scripts from specifications. |
Assign attributes to the current instance. | How would you explain what the following Python 3 function does
def assign(self, attrs):
for k, v in attrs.items():
setattr(self, k, v) | You are a Python code architect, reviewing and designing scalable and efficient code |
def normalize_rust_function(self, function, line):
"""Normalizes a single rust frame with a function"""
# Drop the prefix and return type if there is any
function = drop_prefix_and_return_type(function)
# Collapse types
function = collapse(
function,
open... | Write a Python 3 function that can
normalize a single rust frame with a function | As a Python code analyst, you investigate and solve complex coding mysteries |
Normalizes a single cpp frame with a function | Here you have a function in Python 3, explain what it does
def normalize_cpp_function(self, function, line):
# Drop member function cv/ref qualifiers like const, const&, &, and &&
for ref in ('const', 'const&', '&&', '&'):
if function.endswith(ref):
function = function[:-len(... | You are a Python code architect, reviewing and designing scalable and efficient code |
Normalizes a single frame by using the specified function and line number. | Make a summary of the following Python 3 code
def normalize_frame(
self,
module=None,
function=None,
file=None,
line=None,
module_offset=None,
offset=None,
normalized=None,
**kwargs # eat any extra kwargs passed in
):
"""Normalizes a s... | You are a Python code architect, reviewing and designing scalable and efficient code |
Generate the list of relevant frame names. | Given the following Python 3 function, write the documentation
def _do_generate(self, source_list, hang_type, crashed_thread, delimiter=' | '):
notes = []
debug_notes = []
# shorten source_list to the first signatureSentinel
sentinel_locations = []
for a_sentinel in self.signatu... | You are a Python code architect, reviewing and designing scalable and efficient code |
Fix up some garbage errors. | Can you generate the documentation for the following Python 3 function
def _clean_tag(t):
# TODO: when score present, include info.
t = _scored_patt.sub(string=t, repl='')
if t == '_country_' or t.startswith('_country:'):
t = 'nnp_country'
elif t == 'vpb':
t = 'vb' # "carjack" is listed... | As a Python code composer, you craft elegant and concise scripts. |
def local_settings(settings, prefix):
"""Localizes the settings for the dotted prefix.
For example, if the prefix where 'xyz'::
{'xyz.foo': 'bar', 'other': 'something'}
Would become::
{'foo': 'bar'}
Note, that non-prefixed items are left out and the prefix is dropped.
"""
pre... | How would you code a function in Python 3 to
localize the settings for the dotted prefix. | As a python code expert, you are capable of creating scripts from specifications. |
Return a humanized string representation of a number of bytes. | Here you have a function in Python 3, explain what it does
def humanize_bytes(bytes, precision=1):
abbrevs = (
(1<<50, 'PB'),
(1<<40, 'TB'),
(1<<30, 'GB'),
(1<<20, 'MB'),
(1<<10, 'kB'),
(1, 'bytes')
)
if bytes == 1:
return '1 byte'
for factor, suff... | You are a Python code analyst, evaluating scripts for potential improvements. |
return the parent URL with params query and fragment in place | Here you have a function in Python 3, explain what it does
def parent(self):
path = '/'.join(self.path.split('/')[:-1])
s = path.strip('/').split(':')
if len(s)==2 and s[1]=='':
return None
else:
return self.__class__(self, path=path) | As a Python code translator, you convert algorithms and pseudocode into Python. |
join a list of url elements and include any keyword arguments as a new URL | Can you generate a brief explanation for the following Python 3 code
def join(C, *args, **kwargs):
u = C('/'.join([str(arg).strip('/') for arg in args]), **kwargs)
return u | As a Python code translator, you convert algorithms and pseudocode into Python. |
def select_peer(peer_addrs, service, routing_id, method):
'''Choose a target from the available peers for a singular message
:param peer_addrs:
the ``(host, port)``s of the peers eligible to handle the RPC, and
possibly a ``None`` entry if this hub can handle it locally
:type peer_addrs: li... | Write a Python 3 script for
choosing a target from the available peers for a singular message. | As a Python code composer, you craft elegant and concise scripts. |
initialize process timing for the current stack | Given the following Python 3 function, write the documentation
def start(self, key=None, **params):
self.params.update(**params)
key = key or self.stack_key
if key is not None:
self.current_times[key] = time() | You are a Python code analyst, evaluating scripts for potential improvements. |
def report(self, fraction=None):
"""report the total progress for the current stack, optionally given the local fraction completed.
fraction=None: if given, used as the fraction of the local method so far completed.
runtimes=None: if given, used as the expected runtimes for the current stack.
"""
r = Dict()
... | Can you create a Python 3 function that
reports the total progress for the current stack optionally given the local fraction completed. | You are a Python code analyst, evaluating scripts for potential improvements. |
record the current stack process as finished | Can you generate a brief explanation for the following Python 3 code
def finish(self):
self.report(fraction=1.0)
key = self.stack_key
if key is not None:
if self.data.get(key) is None:
self.data[key] = []
start_time = self.current_times.get(key) or time()
self.data[key].append(Dict(runtime=time()-sta... | As a python code expert, you are capable of creating scripts from specifications. |
Add the directive header and options to the generated content. | Can you generate the documentation for the following Python 3 function
def add_directive_header(self, sig):
domain = getattr(self, 'domain', 'py')
directive = getattr(self, 'directivetype', "module")
name = self.format_name()
self.add_line(u'.. %s:%s:: %s%s' % (domain, directive, name, s... | As a Python code analyst, you investigate and solve complex coding mysteries |
def connect(self):
"Initiate the connection to a proxying hub"
log.info("connecting")
# don't have the connection attempt reconnects, because when it goes
# down we are going to cycle to the next potential peer from the Client
self._peer = connection.Peer(
None, ... | Create a Python 3 function to
initiate the connection to a proxying hub | You are a Python code architect, reviewing and designing scalable and efficient code |
def wait_connected(self, timeout=None):
'''Wait for connections to be made and their handshakes to finish
:param timeout:
maximum time to wait in seconds. with None, there is no timeout.
:type timeout: float or None
:returns:
``True`` if all connections were mad... | Implement a function in Python 3 to
wait for all the active connection and their handshakes to finish. | You are a Python code analyst, evaluating scripts for potential improvements. |
def reset(self):
"Close the current failed connection and prepare for a new one"
log.info("resetting client")
rpc_client = self._rpc_client
self._addrs.append(self._peer.addr)
self.__init__(self._addrs)
self._rpc_client = rpc_client
self._dispatcher.rpc_client = r... | Implement a Python 3 function for
closing the current failed connection and prepare for a new one | As a Python code analyst, you investigate and solve complex coding mysteries |
Close the hub connection | Can you tell what is the following Python 3 function doing
def shutdown(self):
'Close the hub connection'
log.info("shutting down")
self._peer.go_down(reconnect=False, expected=True) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def publish(self, service, routing_id, method, args=None, kwargs=None,
broadcast=False):
'''Send a 1-way message
:param service: the service name (the routing top level)
:type service: anything hash-able
:param routing_id:
The id used for routing within the regis... | Can you implement a function in Python 3 that
sends a 1 - way message to the hub. | As a Python code composer, you craft elegant and concise scripts. |
def publish_receiver_count(
self, service, routing_id, method, timeout=None):
'''Get the number of peers that would handle a particular publish
This method will block until a response arrives
:param service: the service name
:type service: anything hash-able
:param ... | Write a Python 3 script for
getting the number of peers that would handle a particular publish | You are a Python code analyst, evaluating scripts for potential improvements. |
Send out an RPC request to all connected peers. | Can you generate the documentation for the following Python 3 function
def send_rpc(self, service, routing_id, method, args=None, kwargs=None,
broadcast=False):
'''Send out an RPC request
:param service: the service name (the routing top level)
:type service: anything hash-able
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the number of peers that would handle a particular RPC message. This method blocks until a response arrives. | Can you generate the documentation for the following Python 3 function
def rpc_receiver_count(self, service, routing_id, method, timeout=None):
'''Get the number of peers that would handle a particular RPC
This method will block until a response arrives
:param service: the service name
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the default headers and others as necessary | Can you tell what is the following Python 3 function doing
def _headers(self, others={}):
headers = {
'Content-Type': 'application/json'
}
for p in others.keys():
headers[p] = others[p]
return headers | As a Python code composer, you craft elegant and concise scripts. |
Read the config file with spec validation
| Make a summary of the following Python 3 code
def read(config_file, configspec, server_mode=False, default_section='default_settings', list_values=True):
'''
Read the config file with spec validation
'''
# configspec = ConfigObj(path.join(path.abspath(path.dirname(__file__)), configspec),
# ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Colorize a string. | Given the following Python 3 function, write the documentation
def pcolor(text, color, indent=0):
esc_dict = {
"black": 30,
"red": 31,
"green": 32,
"yellow": 33,
"blue": 34,
"magenta": 35,
"cyan": 36,
"white": 37,
"none": -1,
}
if not i... | As a Python code analyst, you investigate and solve complex coding mysteries |
def strframe(obj, extended=False):
"""
Return a string with a frame record pretty-formatted.
The record is typically an item in a list generated by `inspect.stack()
<https://docs.python.org/3/library/inspect.html#inspect.stack>`_).
:param obj: Frame record
:type obj: tuple
:param extende... | How would you code a function in Python 3 to
return a string with a frame record pretty - formatted. | You are a Python code analyst, evaluating scripts for potential improvements. |
def set(self, x):
"""
Set variable values via a dictionary mapping name to value.
"""
for name, value in iter(x.items()):
if hasattr(value, "ndim"):
if self[name].value.ndim < value.ndim:
self[name].value.itemset(value.squeeze())
... | How would you implement a function in Python 3 that
sets variable values via a dictionary mapping name to value. | You are a Python code generator, capable of creating scripts from specifications. |
def select(self, fixed):
"""
Return a subset of variables according to ``fixed``.
"""
names = [n for n in self.names() if self[n].isfixed == fixed]
return Variables({n: self[n] for n in names}) | Can you write a function in Python 3 where it
returns a subset of variables according to fixed. | As a Python code analyst, you investigate and solve complex coding mysteries |
def validate(self, tracking_number):
"Return True if this is a valid USPS tracking number."
tracking_num = tracking_number[:-1].replace(' ', '')
odd_total = 0
even_total = 0
for ii, digit in enumerate(tracking_num):
if ii % 2:
odd_total += int(digit)
... | Write a Python 3 function that can
return True if this is a valid USPS tracking number. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return True if this is a valid UPS tracking number. | Given the following Python 3 function, write the documentation
def validate(self, tracking_number):
"Return True if this is a valid UPS tracking number."
tracking_num = tracking_number[2:-1]
odd_total = 0
even_total = 0
for ii, digit in enumerate(tracking_num.upper()):
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Track a UPS package by number. Returns just a delivery date. | Here you have a function in Python 3, explain what it does
def track(self, tracking_number):
"Track a UPS package by number. Returns just a delivery date."
resp = self.send_request(tracking_number)
return self.parse_response(resp) | You are a Python code generator, capable of creating scripts from specifications. |
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)... | Write a Python 3 script for
loading a matrix and wordlist from a. vec file. | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a BOW representation of a list of items. | Can you generate the documentation for the following Python 3 function
def bow(self, tokens, remove_oov=False):
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
i... | As a python code expert, you are capable of creating scripts from specifications. |
Transform a corpus by repeated calls to vectorize. | Given the following Python 3 function, write the documentation
def transform(self, corpus, remove_oov=False, norm=False):
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus] | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the num most similar items to a given list of items. | Here you have a function in Python 3, explain what it does
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a... | As a python code expert, you are capable of creating scripts from specifications. |
This function returns all items whose similarity is higher than threshold. | Can you generate a brief explanation for the following Python 3 code
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is hig... | As a python code expert, you are capable of creating scripts from specifications. |
This function returns the list of tuples that are the nearest neighbors to some arbitrary vector. | How would you explain what the following Python 3 function does
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find th... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function returns the list of items that are nearest neighbors to some arbitrary vector. | Given the following Python 3 function, write the documentation
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Yields the batched cosine distance of the given set of entries. | Can you generate the documentation for the following Python 3 function
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distan... | As a Python code composer, you craft elegant and concise scripts. |
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np... | How would you code a function in Python 3 to
normalize a matrix of row vectors to unit length. | You are a Python code generator, capable of creating scripts from specifications. |
Compute the similarity between a vector and a set of items. | Here you have a function in Python 3, explain what it does
def vector_similarity(self, vector, items):
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T) | As a python code expert, you are capable of creating scripts from specifications. |
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
... | Write a Python 3 script for
computing the similarity between two sets of items. | You are a Python code architect, reviewing and designing scalable and efficient code |
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
... | Write a Python 3 function for
pruning the current reach instance by removing items. | You are a Python code architect, reviewing and designing scalable and efficient code |
Save the current vector space in word2vec format. | Make a summary of the following Python 3 code
def save(self, path, write_header=True):
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)... | As a Python code analyst, you investigate and solve complex coding mysteries |
Save a Reach instance in a fast format. | Make a summary of the following Python 3 code
def save_fast_format(self, filename):
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".fo... | You are a Python code generator, capable of creating scripts from specifications. |
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
fil... | Implement a function in Python 3 to
load a reach instance in fast format. | You are a Python code architect, reviewing and designing scalable and efficient code |
Sub for fast loader. | Can you generate a brief explanation for the following Python 3 code
def _load_fast(filename):
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def demo_usage(n_data=50, n_fit=537, nhead=5, ntail=5, plot=False, alt=0):
"""
Plots a noisy sine curve and the fitting to it.
Also presents the error and the error in the
approximation of its first derivative (cosine curve)
Usage example for benchmarking:
$ time python sine.py --nhead 3 --nta... | Implement a Python 3 function for
plotting a noisy sine curve and the fitting to it. Also presents the error and the error in the approximation of its first derivative (cosine curve) Usage example for benchmarking: $ time python sine.py --nhead 3 --ntail 3 --n-fit 500000 --n-data 50000 Usage example for plotting: $ pyt... | You are a Python code generator, capable of creating scripts from specifications. |
Display the results of the contributors and the number of contributors in the repository. | Explain what the following Python 3 code does
def display_results(repo_name, contributors, api_len):
print("\n")
print("All Contributors:")
# Sort and consolidate on Name
seen = []
for user in sorted(contributors, key=_sort_by_name):
if user.get("name"):
key = user["name"]
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get a JSON object from GitHub. | Explain what the following Python 3 code does
def get_json(uri):
response = requests.get(API + uri, headers=HEADERS)
limit = int(response.headers.get("x-ratelimit-remaining"))
if limit == 0:
sys.stdout.write("\n")
message = "You have run out of GitHub request tokens. "
if int(respo... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function walks all the pages until there s no more content | Can you tell what is the following Python 3 function doing
def api_walk(uri, per_page=100, key="login"):
page = 1
result = []
while True:
response = get_json(uri + "?page=%d&per_page=%d" % (page, per_page))
if len(response) == 0:
break
else:
page += 1
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Reduce the JSON structure of a single object into a single object. | Given the following Python 3 function, write the documentation
def reducejson(j):
authors = []
for key in j["data"]["repository"]["commitComments"]["edges"]:
authors.append(key["node"]["author"])
for key in j["data"]["repository"]["issues"]["nodes"]:
authors.append(key["author"])
... | As a Python code composer, you craft elegant and concise scripts. |
def stringify_with_dot_if_path(x):
'''Pathlib never renders a leading './' in front of a local path. That's an
issue because on POSIX subprocess.py (like bash) won't execute scripts in
the current directory without it. In the same vein, we also don't want
Path('echo') to match '/usr/bin/echo' from the $... | Write a Python 3 script for
converting a path to a dotted path. | As a Python code composer, you craft elegant and concise scripts. |
Wrapper for subprocess. Popen that does not lock popen_lock. | Here you have a function in Python 3, explain what it does
def safe_popen(*args, **kwargs):
'''This wrapper works around two major deadlock issues to do with pipes.
The first is that, before Python 3.2 on POSIX systems, os.pipe() creates
inheritable file descriptors, which leak to all child processes and pr... | You are a Python code generator, capable of creating scripts from specifications. |
Execute the expression and return a Result which includes the exitStatus status and any captured output. Raise an exception if the status is
non - zero. | Can you generate the documentation for the following Python 3 function
def run(self):
'''Execute the expression and return a Result, which includes the exit
status and any captured output. Raise an exception if the status is
non-zero.'''
with spawn_output_reader() as (stdout_capture, std... | You are a Python code architect, reviewing and designing scalable and efficient code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.