output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def getconfigvar_escaped(config: configparser.ConfigParser, section: str, key: str) -> Optional[str]: """ Returns a CGI-escaped version of the value read from an INI file using :class:`ConfigParser`, or ``None``. """ value = config.get(section, key) ...
Write a Python 3 script for returning a CGI - escaped version of the value read from an INI file using .
As a Python code composer, you craft elegant and concise scripts.
Returns a cgi. FieldStorage object from the WSGI environment.
Can you generate the documentation for the following Python 3 function def get_cgi_fieldstorage_from_wsgi_env( env: Dict[str, str], include_query_string: bool = True) -> cgi.FieldStorage: """ Returns a :class:`cgi.FieldStorage` object from the WSGI environment. """ # http://stackoverflow...
As a Python code composer, you craft elegant and concise scripts.
def get_png_data_url(blob: Optional[bytes]) -> str: """ Converts a PNG blob into a local URL encapsulating the PNG. """ return BASE64_PNG_URL_PREFIX + base64.b64encode(blob).decode('ascii')
Write a Python 3 function that can convert a PNG blob into a local URL encapsulating the PNG.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_png_img_html(blob: Union[bytes, memoryview], extra_html_class: str = None) -> str: """ Converts a PNG blob to an HTML IMG tag with embedded data. """ return """<img {}src="{}" />""".format( 'class="{}" '.format(extra_html_class) if extra_html_class else "", g...
Can you implement a function in Python 3 that converts a PNG blob to an HTML IMG tag with embedded data.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a WSGI response object for a PDF.
How would you explain what the following Python 3 function does def pdf_result(pdf_binary: bytes, extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None, filename: str = None) -> WSGI_TUPLE_TYPE: """ Returns ``(contenttype, extraheaders, data)`` tuple for a PDF. """ extraheaders =...
As a Python code composer, you craft elegant and concise scripts.
Returns a WSGI response body for a ZIP file.
Given the following Python 3 function, write the documentation def zip_result(zip_binary: bytes, extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None, filename: str = None) -> WSGI_TUPLE_TYPE: """ Returns ``(contenttype, extraheaders, data)`` tuple for a ZIP. """ extraheaders = ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def html_result(html: str, extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None) \ -> WSGI_TUPLE_TYPE: """ Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 HTML. """ extraheaders = extraheaders or [] return 'text/html; charset=utf-8', extraheaders, html.encode("utf-8"...
How would you code a function in Python 3 to return a WSGI response tuple for UTF - 8 HTML.
As a Python code composer, you craft elegant and concise scripts.
def xml_result(xml: str, extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None) \ -> WSGI_TUPLE_TYPE: """ Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 XML. """ extraheaders = extraheaders or [] return 'text/xml; charset=utf-8', extraheaders, xml.encode("utf-8")
Write a Python 3 function that can return a WSGI response object for the XML.
You are a Python code analyst, evaluating scripts for potential improvements.
def text_result(text: str, extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None, filename: str = None) -> WSGI_TUPLE_TYPE: """ Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 text. """ extraheaders = extraheaders or [] if filename: extraheaders.append...
Can you create a Python 3 function that returns WSGI response body for UTF - 8 text.
As a python code expert, you are capable of creating scripts from specifications.
def print_result_for_plain_cgi_script_from_tuple( contenttype_headers_content: WSGI_TUPLE_TYPE, status: str = '200 OK') -> None: """ Writes HTTP result to stdout. Args: contenttype_headers_content: the tuple ``(contenttype, extraheaders, data)`` status: ...
How would you implement a function in Python 3 that prints the result of a CGI - script to stdout.
You are a Python code generator, capable of creating scripts from specifications.
Writes HTTP request result to stdout.
Can you generate the documentation for the following Python 3 function def print_result_for_plain_cgi_script(contenttype: str, headers: TYPE_WSGI_RESPONSE_HEADERS, content: bytes, status: str = '200 OK') ->...
As a python code expert, you are capable of creating scripts from specifications.
Simple WSGI response handler.
Can you tell what is the following Python 3 function doing def wsgi_simple_responder( result: Union[str, bytes], handler: Callable[[Union[str, bytes]], WSGI_TUPLE_TYPE], start_response: TYPE_WSGI_START_RESPONSE, status: str = '200 OK', extraheaders: TYPE_WSGI_RESPONSE_HEADERS = N...
As a Python code composer, you craft elegant and concise scripts.
Converts a value into an HTML - safe string.
Can you generate the documentation for the following Python 3 function def webify(v: Any, preserve_newlines: bool = True) -> str: nl = "<br>" if preserve_newlines else " " if v is None: return "" if not isinstance(v, str): v = str(v) # noinspection PyDeprecation return cgi.escape(v)....
As a Python code analyst, you investigate and solve complex coding mysteries
def bold_if_not_blank(x: Optional[str]) -> str: """ HTML-emboldens content, unless blank. """ if x is None: return u"{}".format(x) return u"<b>{}</b>".format(x)
Write a Python 3 function for returning a HTML - emboldens content unless blank.
You are a Python code architect, reviewing and designing scalable and efficient code
Makes hyperlinks to the text that appears to contain URLs.
Here you have a function in Python 3, explain what it does def make_urls_hyperlinks(text: str) -> str: find_url = r''' (?x)( # verbose identify URLs within text (http|ftp|gopher) # make sure we find a resource type :// # ...needs to be followed by colon-slash-sla...
You are a Python code analyst, evaluating scripts for potential improvements.
Converts rows from an SQL query result to an HTML table.
Can you generate a brief explanation for the following Python 3 code def html_table_from_query(rows: Iterable[Iterable[Optional[str]]], descriptions: Iterable[Optional[str]]) -> str: """ Converts rows from an SQL query result to an HTML table. Suitable for processing output from th...
As a Python code analyst, you investigate and solve complex coding mysteries
def rst_underline(heading: str, underline_char: str) -> str: """ Underlines a heading for RST files. Args: heading: text to underline underline_char: character to use Returns: underlined heading, over two lines (without a final terminating newline) """ assert "\...
Can you implement a function in Python 3 that underlines a heading for RST files.
You are a Python code architect, reviewing and designing scalable and efficient code
def write_if_allowed(filename: str, content: str, overwrite: bool = False, mock: bool = False) -> None: """ Writes the contents to a file, if permitted. Args: filename: filename to write content: contents to write overwr...
Write a Python 3 function for writing the contents to a file if permitted.
As a Python code translator, you convert algorithms and pseudocode into Python.
def rst_filename_rel_autodoc_index(self, index_filename: str) -> str: """ Returns the filename of the target RST file, relative to a specified index file. Used to make the index refer to the RST. """ index_dir = dirname(abspath(expanduser(index_filename))) return relpath(...
Can you write a function in Python 3 where it returns the filename of the target RST file relative to a specified index file. Used to make the index refer to the RST.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the name of the Python module that this instance refers to.
Given the following Python 3 function, write the documentation def python_module_name(self) -> str: if not self.is_python: return "" filepath = self.source_filename_rel_python_root dirs_and_base = splitext(filepath)[0] dir_and_file_parts = dirs_and_base.split(sep) ret...
You are a Python code generator, capable of creating scripts from specifications.
def pygments_language(self) -> str: """ Returns the code type annotation for Pygments; e.g. ``python`` for Python, ``cpp`` for C++, etc. """ extension = splitext(self.source_filename)[1] if extension in self.pygments_language_override: return self.pygments_lan...
How would you code a function in Python 3 to return the code type annotation for Pygments ; e. g. python for Python cpp for C ++ etc.
As a Python code composer, you craft elegant and concise scripts.
Returns the contents of an RST file that will automatically create a new object.
Make a summary of the following Python 3 code def rst_content(self, prefix: str = "", suffix: str = "", heading_underline_char: str = "=", method: AutodocMethod = None) -> str: """ Returns the text contents of an RST file th...
You are a Python code architect, reviewing and designing scalable and efficient code
def write_rst(self, prefix: str = "", suffix: str = "", heading_underline_char: str = "=", method: AutodocMethod = None, overwrite: bool = False, mock: bool = False) -> None: """ Writes the RST fi...
Implement a function in Python 3 to write the RST file to our destination RST filename.
As a python code expert, you are capable of creating scripts from specifications.
def add_source_files( self, source_filenames_or_globs: Union[str, List[str]], method: AutodocMethod = None, recursive: bool = None, source_rst_title_style_python: bool = None, pygments_language_override: Dict[str, str] = None) -> None: """ ...
How would you implement a function in Python 3 that adds source files to the index.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_sorted_source_files( self, source_filenames_or_globs: Union[str, List[str]], recursive: bool = True) -> List[str]: """ Returns a sorted list of filenames to process, from a filename, a glob string, or a list of filenames/globs. Args: ...
Write a Python 3 function that can return a sorted list of filenames to process from a filename glob string or a list of filenames or globs.
As a Python code composer, you craft elegant and concise scripts.
def filename_matches_glob(filename: str, globtext: str) -> bool: """ The ``glob.glob`` function doesn't do exclusion very well. We don't want to have to specify root directories for exclusion patterns. We don't want to have to trawl a massive set of files to find exclusion files....
Write a Python 3 function that can return True if the filename matches the globtext.
You are a Python code generator, capable of creating scripts from specifications.
Returns True if this file should be excluded.
Explain what the following Python 3 code does def should_exclude(self, filename) -> bool: for skip_glob in self.skip_globs: if self.filename_matches_glob(filename, skip_glob): return True return False
As a Python code composer, you craft elegant and concise scripts.
def specific_file_rst_filename(self, source_filename: str) -> str: """ Gets the RST filename corresponding to a source filename. See the help for the constructor for more details. Args: source_filename: source filename within current project Returns: RST...
How would you code a function in Python 3 to return the RST filename corresponding to a source filename.
As a Python code composer, you craft elegant and concise scripts.
def write_index_and_rst_files(self, overwrite: bool = False, mock: bool = False) -> None: """ Writes both the individual RST files and the index. Args: overwrite: allow existing files to be overwritten? mock: pretend to write, but don't ...
Implement a function in Python 3 to write both the individual RST files and the index.
As a python code expert, you are capable of creating scripts from specifications.
Returns the filename of this index relative to the director of another index.
Here you have a function in Python 3, explain what it does def index_filename_rel_other_index(self, other: str) -> str: return relpath(self.index_filename, start=dirname(other))
As a Python code translator, you convert algorithms and pseudocode into Python.
def index_content(self) -> str: """ Returns the contents of the index RST file. """ # Build the toctree command index_filename = self.index_filename spacer = " " toctree_lines = [ ".. toctree::", spacer + ":maxdepth: {}".format(self.toc...
Write a Python 3 function for returning the contents of the index RST file.
You are a Python code analyst, evaluating scripts for potential improvements.
def write_index(self, overwrite: bool = False, mock: bool = False) -> None: """ Writes the index file, if permitted. Args: overwrite: allow existing files to be overwritten? mock: pretend to write, but don't """ write_if_allowed(self.index_filename, self....
Write a Python 3 function that can write the index file if permitted.
As a python code expert, you are capable of creating scripts from specifications.
def parse_host(hosts): """ Parsing the hosts parameter, * currently support only one host :param hosts: the hosts json to parse :return: the full host and the authentication if exists """ hosts = EsParser._normalize_hosts(hosts) host = hosts[0] ho...
Create a Python 3 function to parse the hosts parameter and return the full host and authentication if exists
You are a Python code analyst, evaluating scripts for potential improvements.
def _update_ssl_params(host): """ Update the host ssl params (port or scheme) if needed. :param host: :return: """ if host[HostParsing.HOST] \ and EsParser._is_secure_connection_type(host): host[HostParsing.PORT] = EsParser.SSL_DEFAULT_PORT ...
Can you create a Python 3 function that updates the host ssl params if needed.
You are a Python code analyst, evaluating scripts for potential improvements.
def _parse_string_host(host_str): """ Parse host string into a dictionary host :param host_str: :return: """ host_str = EsParser._fix_host_prefix(host_str) parsed_url = urlparse(host_str) host = {HostParsing.HOST: parsed_url.hostname} if parsed_url...
Implement a function in Python 3 to parse a host string into a dictionary host
You are a Python code architect, reviewing and designing scalable and efficient code
def make_path(*sub_paths): """ Create a path from a list of sub paths. :param sub_paths: a list of sub paths :return: """ queued_params = [quote(c.encode('utf-8'), '') for c in sub_paths if c not in NULL_VALUES] queued_params.insert(0, '') return '/'.join(...
Can you write a function in Python 3 where it creates a path from a list of sub paths.
As a Python code analyst, you investigate and solve complex coding mysteries
Prepare Elasticsearch request url.
Explain what the following Python 3 code does def prepare_url(hostname, path, params=None): url = hostname + path if params: url = url + '?' + urlencode(params) if not url.startswith(('http:', 'https:')): url = "http://" + url return url.encode('utf-8')
You are a Python code generator, capable of creating scripts from specifications.
Plot a basic sine wave with oscillating amplitude
Can you tell what is the following Python 3 function doing def basic_animation(frames=100, interval=30): fig = plt.figure() ax = plt.axes(xlim=(0, 10), ylim=(-2, 2)) line, = ax.plot([], [], lw=2) x = np.linspace(0, 10, 1000) def init(): line.set_data([], []) return line, def a...
As a python code expert, you are capable of creating scripts from specifications.
def lorenz_animation(N_trajectories=20, rseed=1, frames=200, interval=30): """Plot a 3D visualization of the dynamics of the Lorenz system""" from scipy import integrate from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import cnames def lorentz_deriv(coords, t0, sigma=10., beta=8./3, ...
How would you code a function in Python 3 to plot a 3D visualization of the dynamics of the Lorentz system.
You are a Python code generator, capable of creating scripts from specifications.
def _included_frames(frame_list, frame_format): """frame_list should be a list of filenames""" return INCLUDED_FRAMES.format(Nframes=len(frame_list), frame_dir=os.path.dirname(frame_list[0]), frame_format=frame_format)
Write a Python 3 function for returning a string that represents the included frames in the given frame_list.
As a python code expert, you are capable of creating scripts from specifications.
def _embedded_frames(frame_list, frame_format): """frame_list should be a list of base64-encoded png files""" template = ' frames[{0}] = "data:image/{1};base64,{2}"\n' embedded = "\n" for i, frame_data in enumerate(frame_list): embedded += template.format(i, frame_format, ...
Write a Python 3 script to return the embedded frames in the current image.
As a python code expert, you are capable of creating scripts from specifications.
def remove_noise(time, magnitude, error, error_limit=3, std_limit=5): """Points within 'std_limit' standard deviations from the mean and with errors greater than 'error_limit' times the error mean are considered as noise and thus are eliminated. """ data, mjd = magnitude, time data_len = len(m...
Implement a Python 3 function for removing noise from the mean and standard deviations from the time and magnitude.
As a Python code translator, you convert algorithms and pseudocode into Python.
Synchronizes the light - curves in the two different bands.
Can you tell what is the following Python 3 function doing def align(time, time2, magnitude, magnitude2, error, error2): error = np.zeros(time.shape) if error is None else error error2 = np.zeros(time2.shape) if error2 is None else error2 # this asume that the first series is the short one sserie = pd...
As a Python code composer, you craft elegant and concise scripts.
Return the full list of variables stars of OGLE - 3 as a DataFrame
Can you generate a brief explanation for the following Python 3 code def load_OGLE3_catalog(): with bz2.BZ2File(CATALOG_PATH) as bz2fp, warnings.catch_warnings(): warnings.simplefilter("ignore") df = pd.read_table(bz2fp, skiprows=6) df.rename(columns={"# ID": "ID"}, inplace=True) return df
As a Python code analyst, you investigate and solve complex coding mysteries
Retrieve a lighte curve from OGLE - 3 database.
Given the following Python 3 function, write the documentation def fetch_OGLE3(ogle3_id, data_home=None, metadata=None, download_if_missing=True): """Retrieve a lighte curve from OGLE-3 database Parameters ---------- ogle3_id : str The id of the source (see: ``load_OGLE3_catalog...
As a Python code translator, you convert algorithms and pseudocode into Python.
Calculate the Feature Extractor Resolution Order.
Given the following Python 3 function, write the documentation def sort_by_dependencies(exts, retry=None): sorted_ext, features_from_sorted = [], set() pending = [(e, 0) for e in exts] retry = len(exts) * 100 if retry is None else retry while pending: ext, cnt = pending.pop(0) if not is...
You are a Python code generator, capable of creating scripts from specifications.
returns the probability of the false alarm probabilitywk1 wk2 nout of ac
Make a summary of the following Python 3 code def getSignificance(wk1, wk2, nout, ofac): expy = exp(-wk2) effm = 2.0*(nout)/ofac sig = effm*expy ind = (sig > 0.01).nonzero() sig[ind] = 1.0-(1.0-expy[ind])**effm return sig
As a Python code analyst, you investigate and solve complex coding mysteries
def fetch(url, dest, force=False): """Retrieve data from an url and store it into dest. Parameters ---------- url: str Link to the remote data dest: str Path where the file must be stored force: bool (default=False) Overwrite if the file exists Returns ------- ...
Write a Python 3 function for retrieving data from an url and store it into dest.
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_random(magf, magf_params, errf, errf_params, timef=np.linspace, timef_params=None, size=DEFAULT_SIZE, id=None, ds_name=DS_NAME, description=DESCRIPTION, bands=BANDS, metadata=METADATA): """Generate a data with any given random function. Parameter...
Write a Python 3 script to generate a random light curve with any given random function.
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_normal(mu=0., sigma=1., mu_err=0., sigma_err=1., seed=None, **kwargs): """Generate a data with magnitudes that follows a Gaussian distribution. Also their errors are gaussian. Parameters ---------- mu : float (default=0) Mean of the gaussian distribution of ma...
Create a Python 3 function for generating a random data with magnitudes that follows a Gaussian distribution. Also their errors are gaussian.
As a Python code composer, you craft elegant and concise scripts.
def create_uniform(low=0., high=1., mu_err=0., sigma_err=1., seed=None, **kwargs): """Generate a data with magnitudes that follows a uniform distribution; the error instead are gaussian. Parameters ---------- low : float, optional Lower boundary of the output interval. ...
How would you implement a function in Python 3 that generates a data object with magnitudes that follows a uniform distribution ; the error instead are gaussian.
You are a Python code generator, capable of creating scripts from specifications.
Generate a data object with magnitudes with periodic variability of variability error.
How would you explain what the following Python 3 function does def create_periodic(mu_err=0., sigma_err=1., seed=None, **kwargs): random = np.random.RandomState(seed) size = kwargs.get("size", DEFAULT_SIZE) times, mags, errors = [], [], [] for b in kwargs.get("bands", BANDS): time = 100 * ra...
As a Python code composer, you craft elegant and concise scripts.
def pdf_single(z, N, normalization, dH=1, dK=3): """Probability density function for Lomb-Scargle periodogram Compute the expected probability density function of the periodogram for the null hypothesis - i.e. data consisting of Gaussian noise. Parameters ---------- z : array-like the ...
Implement a function in Python 3 to compute the expected probability density function for a single periodogram.
You are a Python code architect, reviewing and designing scalable and efficient code
def cdf_single(z, N, normalization, dH=1, dK=3): """Cumulative distribution for the Lomb-Scargle periodogram Compute the expected cumulative distribution of the periodogram for the null hypothesis - i.e. data consisting of Gaussian noise. Parameters ---------- z : array-like the period...
Can you write a function in Python 3 where it computes the expected cumulative distribution for the Lomb - Scargle periodogram.
As a python code expert, you are capable of creating scripts from specifications.
False Alarm Probability based on estimated number of indep frequencies
Given the following Python 3 function, write the documentation def fap_simple(Z, fmax, t, y, dy, normalization='standard'): N = len(t) T = max(t) - min(t) N_eff = fmax * T p_s = cdf_single(Z, N, normalization=normalization) return 1 - p_s ** N_eff
You are a Python code architect, reviewing and designing scalable and efficient code
def fap_baluev(Z, fmax, t, y, dy, normalization='standard'): """Alias-free approximation to false alarm probability (Eqn 6 of Baluev 2008) """ cdf = cdf_single(Z, len(t), normalization) tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization) return 1 - cdf * np.exp(-tau)
Create a Python 3 function for aliasing - free approximation to false alarm probability
You are a Python code architect, reviewing and designing scalable and efficient code
Approximate the False Alarm Probability
Here you have a function in Python 3, explain what it does def false_alarm_probability(Z, fmax, t, y, dy, normalization, method='baluev', method_kwds=None): """Approximate the False Alarm Probability Parameters ---------- TODO Returns ------- TODO """ if...
You are a Python code analyst, evaluating scripts for potential improvements.
def load_MACHO(macho_id): """lightcurve of 2 bands (R, B) from the MACHO survey. Notes ----- The files are gathered from the original FATS project tutorial: https://github.com/isadoranun/tsfeat """ tarfname = "{}.tar.bz2".format(macho_id) tarpath = os.path.join(DATA_PATH, tarfname) ...
Can you implement a function in Python 3 that loads the MACHO lightcurve of 2 bands from the MACHO survey.
You are a Python code architect, reviewing and designing scalable and efficient code
Generate HTML representation of the animation
How would you explain what the following Python 3 function does def anim_to_html(anim, fps=None, embed_frames=True, default_mode='loop'): if fps is None and hasattr(anim, '_interval'): # Convert interval in ms to frames per second fps = 1000. / anim._interval plt.close(anim._fig) if hasattr...
As a Python code composer, you craft elegant and concise scripts.
Display the animation with an IPython HTML object
Make a summary of the following Python 3 code def display_animation(anim, **kwargs): from IPython.display import HTML return HTML(anim_to_html(anim, **kwargs))
You are a Python code architect, reviewing and designing scalable and efficient code
def indent(s, c=" ", n=4): """Indent the string 's' with the character 'c', 'n' times. Parameters ---------- s : str String to indent c : str, default space String to use as indentation n : int, default 4 Number of chars to indent """ indentation = c * n re...
Write a Python 3 script for indenting the string s with the character c n times.
You are a Python code analyst, evaluating scripts for potential improvements.
Generates a list of RangeQueries usable to boost the scores of recent documents.
Explain what the following Python 3 code does def generate_date_tail_boost_queries( field, timedeltas_and_boosts, relative_to=None): """ Generate a list of RangeQueries usable to boost the scores of more recent documents. Example: ``` queries = generate_date_tail_boost_queries("publish...
As a Python code analyst, you investigate and solve complex coding mysteries
Recursively remove None - valued items from dict.
How would you explain what the following Python 3 function does def _clean_dict(in_dict): out = {} for key, value in iteritems(in_dict): if isinstance(value, dict): value = _clean_dict(value) if value is None: continue out[key] = value return out
You are a Python code generator, capable of creating scripts from specifications.
def batch_iterable(iterable, count): """ Yield batches of `count` items from the given iterable. >>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3): >>> print(x) [1, 2, 3] [4, 5, 6] [7] :param iterable: An iterable :type iterable: Iterable :param count: Number of items per batch. I...
Can you create a Python 3 function that yields batches of count items from the given iterable.
As a Python code composer, you craft elegant and concise scripts.
def get_objects(self, queryset=None): """ Return an iterator of Django model objects in Elasticsearch order, optionally using the given Django queryset. If no queryset is given, a default queryset (Model.objects.all) is used. :param queryset: Optional queryset to filter in. ...
Can you write a function in Python 3 where it returns an iterator of Django model objects in Elasticsearch order optionally using the given Django queryset.
You are a Python code architect, reviewing and designing scalable and efficient code
def reset(self): """ Reset target collection (rebuild index). """ self.connection.rebuild_index( self.index, coll_name=self.target_coll_name)
Implement a Python 3 function for resetting the target collection.
You are a Python code generator, capable of creating scripts from specifications.
Update the wordgatherer collection.
Explain what the following Python 3 code does def update(self, index, fields, tokenizer=default_tokenizer, cutoff=1): counts_by_uid = defaultdict(Counter) for word, count in self._gather_words( index, fields, tokenizer=tokenizer).items(): uid = hashlib.sha1(unicodedata.normal...
You are a Python code generator, capable of creating scripts from specifications.
Search for a word within the wordgatherer collection.
Can you generate the documentation for the following Python 3 function def search(self, word, limit=30): search = Search(PrefixQuery("word", word), sort={"count": "desc"}) for doc in self.connection.search( search, indexes=[self.index], count=limit): yield (doc["word"], doc["...
You are a Python code analyst, evaluating scripts for potential improvements.
Validate that given notebook JSON is importable and that the notebook language is python
Can you generate a brief explanation for the following Python 3 code def validate_nb(nb): if nb['nbformat'] != 4: return False language_name = (nb.get('metadata', {}) .get('kernelspec', {}) .get('language', '').lower()) return language_name == 'python'
As a python code expert, you are capable of creating scripts from specifications.
Filter a given module ast removing non - whitelisted nodes
Can you generate the documentation for the following Python 3 function def filter_ast(module_ast): def node_predicate(node): """ Return true if given node is whitelisted """ for an in ALLOWED_NODES: if isinstance(node, an): return True # Recurse t...
As a python code expert, you are capable of creating scripts from specifications.
Get the code for a given notebook
Here you have a function in Python 3, explain what it does def code_from_ipynb(nb, markdown=False): code = PREAMBLE for cell in nb['cells']: if cell['cell_type'] == 'code': # transform the input to executable Python code += ''.join(cell['source']) if cell['cell_type'] == ...
As a Python code composer, you craft elegant and concise scripts.
Generate ordered list of paths we should look for fullname module in
Can you tell what is the following Python 3 function doing def _get_paths(self, fullname): real_path = os.path.join(*fullname[len(self.package_prefix):].split('.')) for base_path in sys.path: if base_path == '': # Empty string means process's cwd base_path = o...
As a Python code translator, you convert algorithms and pseudocode into Python.
def find_spec(self, fullname, path, target=None): """ Claims modules that are under ipynb.fs """ if fullname.startswith(self.package_prefix): for path in self._get_paths(fullname): if os.path.exists(path): return ModuleSpec( ...
How would you implement a function in Python 3 that finds a module spec by name and path.
You are a Python code analyst, evaluating scripts for potential improvements.
Decorator for priming generator - based coroutines.
Given the following Python 3 function, write the documentation def coroutine(func): @wraps(func) def start(*args, **kwargs): g = func(*args, **kwargs) next(g) return g return start
As a Python code analyst, you investigate and solve complex coding mysteries
Yields numbers from 0 to every delay seconds.
Here you have a function in Python 3, explain what it does async def ticker(delay, to): for i in range(to): yield i await asyncio.sleep(delay)
As a Python code translator, you convert algorithms and pseudocode into Python.
def iterable_source(iterable, target): """Convert an iterable into a stream of events. Args: iterable: A series of items which will be sent to the target one by one. target: The target coroutine or sink. Returns: An iterator over any remaining items. """ it = iter(iterable)...
Can you write a function in Python 3 where it converts an iterable into a stream of events.
You are a Python code generator, capable of creating scripts from specifications.
Send events at random times with uniform probability.
How would you explain what the following Python 3 function does def poisson_source(rate, iterable, target): if rate <= 0.0: raise ValueError("poisson_source rate {} is not positive".format(rate)) it = iter(iterable) for item in it: duration = random.expovariate(rate) sleep(duration)...
You are a Python code architect, reviewing and designing scalable and efficient code
Compose functions right to left.
Can you generate the documentation for the following Python 3 function def compose(f, *fs): rfs = list(chain([f], fs)) rfs.reverse() def composed(*args, **kwargs): return reduce( lambda result, fn: fn(result), rfs[1:], rfs[0](*args, **kwargs)) return compose...
You are a Python code analyst, evaluating scripts for potential improvements.
def scanning(reducer, init=UNSET): """Create a scanning reducer.""" reducer2 = reducer def scanning_transducer(reducer): return Scanning(reducer, reducer2, init) return scanning_transducer
Create a Python 3 function for creating a scanning reducer.
As a Python code composer, you craft elegant and concise scripts.
def taking(n): """Create a transducer which takes the first n items""" if n < 0: raise ValueError("Cannot take fewer than zero ({}) items".format(n)) def taking_transducer(reducer): return Taking(reducer, n) return taking_transducer
Write a Python 3 script to create a transducer which takes the first n items
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a transducer which drops the first n items
Here you have a function in Python 3, explain what it does def dropping(n): if n < 0: raise ValueError("Cannot drop fewer than zero ({}) items".format(n)) def dropping_transducer(reducer): return Dropping(reducer, n) return dropping_transducer
As a Python code analyst, you investigate and solve complex coding mysteries
Create a transducer which produces non - overlapping batches.
Can you generate the documentation for the following Python 3 function def batching(size): if size < 1: raise ValueError("batching() size must be at least 1") def batching_transducer(reducer): return Batching(reducer, size) return batching_transducer
As a Python code analyst, you investigate and solve complex coding mysteries
Create a transducer which produces a moving window over items.
Can you generate a brief explanation for the following Python 3 code def windowing(size, padding=UNSET, window_type=tuple): if size < 1: raise ValueError("windowing() size {} is not at least 1".format(size)) def windowing_transducer(reducer): return Windowing(reducer, size, padding, window_typ...
As a Python code analyst, you investigate and solve complex coding mysteries
Create a transducer which obtains the first item then terminates.
Can you tell what is the following Python 3 function doing def first(predicate=None): predicate = true if predicate is None else predicate def first_transducer(reducer): return First(reducer, predicate) return first_transducer
As a Python code translator, you convert algorithms and pseudocode into Python.
def last(predicate=None): """Create a transducer which obtains the last item.""" predicate = true if predicate is None else predicate def last_transducer(reducer): return Last(reducer, predicate) return last_transducer
How would you code a function in Python 3 to create a transducer which obtains the last item.
As a python code expert, you are capable of creating scripts from specifications.
Create a transducer which obtains the item at the specified index.
Given the following Python 3 function, write the documentation def element_at(index): if index < 0: raise IndexError("element_at used with illegal index {}".format(index)) def element_at_transducer(reducer): return ElementAt(reducer, index) return element_at_transducer
You are a Python code architect, reviewing and designing scalable and efficient code
Compile source code files to object files.
Can you tell what is the following Python 3 function doing def compile_sources(files, CompilerRunner_=None, destdir=None, cwd=None, keep_dir_struct=False, per_file_kwargs=None, **kwargs): """ Compile source code files to object file...
As a Python code analyst, you investigate and solve complex coding mysteries
Link objects in obj_files into out_file.
Here you have a function in Python 3, explain what it does def link(obj_files, out_file=None, shared=False, CompilerRunner_=None, cwd=None, cplus=False, fort=False, **kwargs): """ Link object files. Parameters ---------- obj_files: iterable of path strings out_file: path string (option...
As a Python code analyst, you investigate and solve complex coding mysteries
def link_py_so(obj_files, so_file=None, cwd=None, libraries=None, cplus=False, fort=False, **kwargs): """ Link python extension module (shared object) for importing Parameters ---------- obj_files: iterable of path strings object files to be linked so_file: path string ...
Create a Python 3 function for linking Python extension module to the shared object file.
As a python code expert, you are capable of creating scripts from specifications.
A simple cythonize function that takes a source file and returns a path to the destination file.
Can you generate a brief explanation for the following Python 3 code def simple_cythonize(src, destdir=None, cwd=None, logger=None, full_module_name=None, only_update=False, **cy_kwargs): """ Generates a C file from a Cython source file. Parameters ---------- ...
As a Python code composer, you craft elegant and concise scripts.
def src2obj(srcpath, CompilerRunner_=None, objpath=None, only_update=False, cwd=None, out_ext=None, inc_py=False, **kwargs): """ Compiles a source code file to an object file. Files ending with '.pyx' assumed to be cython files and are dispatched to pyx2obj. Parameters -...
Write a Python 3 function that can return a new object file that can be used to compile a source code file.
You are a Python code analyst, evaluating scripts for potential improvements.
This function generates a C object from a Python source file.
Can you tell what is the following Python 3 function doing def pyx2obj(pyxpath, objpath=None, interm_c_dir=None, cwd=None, logger=None, full_module_name=None, only_update=False, metadir=None, include_numpy=False, include_dirs=None, cy_kwargs=None, gdb=False, cplus=None, **kwargs): ...
You are a Python code generator, capable of creating scripts from specifications.
Compiles sources in srcs to a shared object and links them to a shared object.
Given the following Python 3 function, write the documentation def compile_link_import_py_ext( srcs, extname=None, build_dir=None, compile_kwargs=None, link_kwargs=None, **kwargs): """ Compiles sources in `srcs` to a shared object (python extension) which is imported. If shared object is new...
You are a Python code analyst, evaluating scripts for potential improvements.
Compiles a list of source strings into a temporary directory and dumps and links them into a temporary directory.
Make a summary of the following Python 3 code def compile_link_import_strings(codes, build_dir=None, **kwargs): build_dir = build_dir or tempfile.mkdtemp() if not os.path.isdir(build_dir): raise OSError("Non-existent directory: ", build_dir) source_files = [] if kwargs.get('logger', False) is T...
As a Python code translator, you convert algorithms and pseudocode into Python.
def switch_db(name): """ Hack to switch Flask-Pymongo db :param name: db name """ with app.app_context(): app.extensions['pymongo'][mongo.config_prefix] = mongo.cx, mongo.cx[name]
Create a Python 3 function to switch Flask - Pymongo db to a different database
As a Python code composer, you craft elegant and concise scripts.
Return a row generator for a reference
Explain what the following Python 3 code does def get_row_generator(self, ref, cache=None): """Return a row generator for a reference""" from inspect import isgenerator from rowgenerators import get_generator g = get_generator(ref) if not g: raise GenerateError("Ca...
As a Python code composer, you craft elegant and concise scripts.
def create_key_filter(properties: Dict[str, list]) -> List[Tuple]: """Generate combinations of key, value pairs for each key in properties. Examples -------- properties = {'ent': ['geo_rev', 'supply_chain'], 'own', 'fi'} >> create_key_filter(properties) --> [('ent', 'geo_rev'), ('ent', 'suppl...
How would you implement a function in Python 3 that generates combinations of key value pairs for each key in properties.
You are a Python code architect, reviewing and designing scalable and efficient code
Create indexer function to pluck values from list.
Can you generate the documentation for the following Python 3 function def create_indexer(indexes: list): if len(indexes) == 1: index = indexes[0] return lambda x: (x[index],) else: return itemgetter(*indexes)
As a Python code translator, you convert algorithms and pseudocode into Python.
Include the elements matching the filter set.
Here you have a function in Python 3, explain what it does def including(self, sequence) -> Generator: return (element for element in sequence if self.indexer(element) in self.predicates)
You are a Python code analyst, evaluating scripts for potential improvements.
def excluding(self, sequence) -> Generator: """Exclude the sequence elements matching the filter set.""" return (element for element in sequence if self.indexer(element) not in self.predicates)
Write a Python 3 script to exclude the elements matching the filter set.
You are a Python code generator, capable of creating scripts from specifications.