output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Resolves and imports all modules specified in parser_modules. | How would you explain what the following Python 3 function does
def import_parsers(parser_modules: t.Iterable[str]) -> t.Generator[t.Type[BaseParser], None, None]:
for import_path in parser_modules:
path_parts = import_path.rsplit('.', 1)
if len(path_parts) == 2:
mod_path... | As a Python code composer, you craft elegant and concise scripts. |
Loads options from environment variables and returns them as a dictionary. | Given the following Python 3 function, write the documentation
def load_parser_options_from_env(
parser_class: t.Type[BaseParser],
env: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, t.Any]:
"""
Extracts arguments from ``parser_class.__init__`` and populates them from enviro... | You are a Python code generator, capable of creating scripts from specifications. |
def from_env(parser_modules: t.Optional[t.Union[t.List[str], t.Tuple[str]]] = DEFAULT_PARSER_MODULES,
env: t.Optional[t.Dict[str, str]] = None,
silent: bool = False,
suppress_logs: bool = False,
extra: t.Optional[dict] = None) -> 'ConfigLoader':
... | Write a Python 3 function that can
create a ConfigLoader instance from a dict with parsers initialized from environment variables. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Prints all read queue options. | Can you tell what is the following Python 3 function doing
def print_config_read_queue(
self,
use_color: bool = False,
max_col_width: int = 50):
"""
Prints all read (in call order) options.
:param max_col_width: limit column width, ``50`` by default
:... | You are a Python code architect, reviewing and designing scalable and efficient code |
def format_config_read_queue(self,
use_color: bool = False,
max_col_width: int = 50) -> str:
"""
Prepares a string with pretty printed config read queue.
:param use_color: use terminal colors
:param max_col_width: limit c... | Create a Python 3 function for
formatting the config read queue as a pretty printed string. | As a Python code composer, you craft elegant and concise scripts. |
def get_graph(cls, response):
""" Given a Flask response, find the rdflib Graph """
if cls.is_graph(response): # single graph object
return response
if hasattr(response, '__getitem__'): # indexable tuple
if len(response) > 0 and \
cls.is_graph(response[0]): # graph object
return response[0] | Can you write a function in Python 3 where it
gives a Flask response find the rdflib Graph | As a python code expert, you are capable of creating scripts from specifications. |
def replace_graph(cls, response, serialized):
""" Replace the rdflib Graph in a Flask response """
if cls.is_graph(response): # single graph object
return serialized
if hasattr(response, '__getitem__'): # indexable tuple
if len(response) > 0 and \
cls.is_graph(response[0]): # graph object
return ... | Can you write a function in Python 3 where it
replaces the rdflib Graph in a Flask response | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _from_hex_digest(digest):
"""Convert hex digest to sequence of bytes."""
return "".join(
[chr(int(digest[x : x + 2], 16)) for x in range(0, len(digest), 2)]
) | Can you write a function in Python 3 where it
converts hex digest to sequence of bytes. | You are a Python code analyst, evaluating scripts for potential improvements. |
Perform encryption of provided data. | Can you generate the documentation for the following Python 3 function
def encrypt(data, digest=True):
alg = get_best_algorithm()
enc = implementations["encryption"][alg](
data, implementations["get_key"]()
)
return "%s$%s" % (alg, (_to_hex_digest(enc) if digest else enc)) | You are a Python code architect, reviewing and designing scalable and efficient code |
Reconstructs a directed acyclic graph according to prior information of edge significance levels. | Make a summary of the following Python 3 code
def one_greedy(self,dp,namax=None,nimax=None,nomax=None):
try: from exceptions import ValueError
except ImportError: pass
if self.lib is None:
raise ValueError("Not initialized.")
import numpy as np
from .auto import ftype_np
from .types import isint
if dp.dtype.ch... | As a python code expert, you are capable of creating scripts from specifications. |
def gen_vocab(cli, args):
''' Generate vocabulary list from a tokenized file '''
if args.topk and args.topk <= 0:
topk = None
cli.logger.warning("Invalid k will be ignored (k should be greater than or equal to 1)")
else:
topk = args.topk
if args.stopwords:
with open(args.... | Can you write a function in Python 3 where it
generates vocabulary list from a tokenized file | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_attachment(message, attachment, rfc2231=True):
'''Attach an attachment to a message as a side effect.
Arguments:
message: MIMEMultipart instance.
attachment: Attachment instance.
'''
data = attachment.read()
part = MIMEBase('application', 'octet-stream')
part.set_payloa... | Can you implement a function in Python 3 that
attaches an attachment to a message as a side effect. | You are a Python code generator, capable of creating scripts from specifications. |
def _login(self):
'''Login to the SMTP server specified at instantiation
Returns an authenticated SMTP instance.
'''
server, port, mode, debug = self.connection_details
if mode == 'SSL':
smtp_class = smtplib.SMTP_SSL
else:
smtp_class = smtplib.SM... | Implement a Python 3 function for
logging-in to the SMTP server specified at instantiation Returns an authenticated SMTP instance. | As a Python code analyst, you investigate and solve complex coding mysteries |
def send(self, email, attachments=()):
'''Send an email. Connect/Disconnect if not already connected
Arguments:
email: Email instance to send.
attachments: iterable containing Attachment instances
'''
msg = email.as_mime(attachments)
if 'From' not in ms... | Write a Python 3 script for
sending an email. Connect or Disconnect if not already connected. | As a python code expert, you are capable of creating scripts from specifications. |
Return a dict mapping column name to type for all columns in table
| Can you tell what is the following Python 3 function doing
def column_types(self):
column_types = {}
for c in self.sqla_columns:
column_types[c.name] = c.type
return column_types | As a Python code composer, you craft elegant and concise scripts. |
def _valid_table_name(self, table_name):
"""Check if the table name is obviously invalid.
"""
if table_name is None or not len(table_name.strip()):
raise ValueError("Invalid table name: %r" % table_name)
return table_name.strip() | Write a Python 3 script to
check if the table name is obviously invalid. | As a Python code analyst, you investigate and solve complex coding mysteries |
Add primary key constraint to specified column
| Given the following Python 3 function, write the documentation
def add_primary_key(self, column="id"):
if not self.primary_key:
sql = """ALTER TABLE {s}.{t}
ADD PRIMARY KEY ({c})
""".format(
s=self.schema, t=self.name, c=column
)
... | You are a Python code generator, capable of creating scripts from specifications. |
def drop(self):
"""Drop the table from the database
"""
if self._is_dropped is False:
self.table.drop(self.engine)
self._is_dropped = True | Implement a Python 3 function for
dropping the table from the database. | As a Python code analyst, you investigate and solve complex coding mysteries |
Drop the column with the given name. | Explain what the following Python 3 code does
def drop_column(self, name):
self._check_dropped()
if name in list(self.table.columns.keys()):
self.op.drop_column(self.table.name, name, schema=self.schema)
self.table = self._update_table(self.table.name) | As a Python code composer, you craft elegant and concise scripts. |
Create an index for a specific entry in the database. | Make a summary of the following Python 3 code
def create_index(self, columns, name=None, index_type="btree"):
self._check_dropped()
if not name:
sig = "||".join(columns + [index_type])
# This is a work-around for a bug in <=0.6.1 which would create
# indexes based on ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def distinct(self, *columns, **_filter):
"""
Returns all rows of a table, but removes rows in with duplicate values in ``columns``.
Interally this creates a `DISTINCT statement <http://www.w3schools.com/sql/sql_distinct.asp>`_.
::
# returns only one row per year, ignoring th... | How would you code a function in Python 3 to
return all rows of a table but removes rows with duplicate values in columns. | As a Python code composer, you craft elegant and concise scripts. |
Adds a row to the table. Returns the new row s primary key. | Can you generate a brief explanation for the following Python 3 code
def insert(self, row):
self._check_dropped()
res = self.engine.execute(self.table.insert(row))
if len(res.inserted_primary_key) > 0:
return res.inserted_primary_key[0] | You are a Python code generator, capable of creating scripts from specifications. |
def insert_many(self, rows, chunk_size=1000):
"""
Add many rows at a time, which is significantly faster than adding
them one by one. Per default the rows are processed in chunks of
1000 per commit, unless you specify a different ``chunk_size``.
See :py:meth:`insert() <dataset.Ta... | Create a Python 3 function for
adding many rows at a time. | As a python code expert, you are capable of creating scripts from specifications. |
def find_one(self, **kwargs):
"""
Works just like :py:meth:`find() <dataset.Table.find>` but returns one result, or None.
::
row = table.find_one(country='United States')
"""
kwargs["_limit"] = 1
iterator = self.find(**kwargs)
try:
return n... | Can you write a function in Python 3 where it
returns one result or None. | You are a Python code analyst, evaluating scripts for potential improvements. |
def find(
self,
_limit=None,
_offset=0,
_step=5000,
order_by="id",
return_count=False,
**_filter
):
"""
Performs a simple search on the table. Simply pass keyword arguments as ``filter``.
::
results = table.find(country='Fra... | Write a Python 3 function for
performing a simple search on the table. Simply pass keyword arguments as ``filter``. :: results = table.find(country='France') results = table.find(country='France', year=1980) Using ``_limit``:: # just return the first 10 rows results = table.find(country='France', _limit=10) You can sor... | As a Python code analyst, you investigate and solve complex coding mysteries |
Open a new connection to the postgres database. | Explain what the following Python 3 code does
def connect(url=None, schema=None, sql_path=None, multiprocessing=False):
if url is None:
url = os.environ.get("DATABASE_URL")
return Database(url, schema, sql_path=sql_path, multiprocessing=multiprocessing) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a new database
| Make a summary of the following Python 3 code
def create_db(url=None):
if url is None:
url = os.environ.get("DATABASE_URL")
parsed_url = urlparse(url)
db_name = parsed_url.path
db_name = db_name.strip("/")
db = connect("postgresql://" + parsed_url.netloc)
# check that db does not exist
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a value that can be used to hide a secret in a key_name. | Can you generate a brief explanation for the following Python 3 code
def shred(key_name: str,
value: t.Any,
field_names: t.Iterable[str] = SHRED_DATA_FIELD_NAMES) -> t.Union[t.Any, str]:
"""
Replaces sensitive data in ``value`` with ``*`` if ``key_name`` contains something that looks like a ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def dot_path(obj: t.Union[t.Dict, object],
path: str,
default: t.Any = None,
separator: str = '.'):
"""
Provides an access to elements of a mixed dict/object type by a delimiter-separated path.
::
class O1:
my_dict = {'a': {'b': 1}}
class ... | Implement a function in Python 3 to
return the value of the object at the specified path. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the value of a key in nested dict by dot - separated paths. | Can you generate the documentation for the following Python 3 function
def dotkey(obj: dict, path: str, default=None, separator='.'):
try:
return get(obj, path, separator=separator)
except KeyError:
return default | You are a Python code architect, reviewing and designing scalable and efficient code |
def _materialize_dict(bundle: dict, separator: str = '.') -> t.Generator[t.Tuple[str, t.Any], None, None]:
"""
Traverses and transforms a given dict ``bundle`` into tuples of ``(key_path, value)``.
:param bundle: a dict to traverse
:param separator: build paths with a given separator
:return: a gen... | Implement a Python 3 function for
traversing and transforms a given dict ``bundle`` into tuples of ``(key_path, value)``. :param bundle: a dict to traverse :param separator: build paths with a given separator :return: a generator of tuples ``(materialized_path, value)`` Example: >>> list(_materialize_dict({'test': {'pa... | You are a Python code analyst, evaluating scripts for potential improvements. |
def materialize_dict(bundle: dict, separator: str = '.') -> t.List[t.Tuple[str, t.Any]]:
"""
Transforms a given ``bundle`` into a *sorted* list of tuples with materialized value paths and values:
``('path.to.value', <value>)``. Output is ordered by depth: the deepest element first.
:param bundle: a dic... | How would you implement a function in Python 3 that
takes a dict of keys and returns a list of tuples with materialized value paths and values. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def mp_serialize_dict(
bundle: dict,
separator: str = '.',
serialize: t.Optional[t.Callable] = dump_yaml,
value_prefix: str = '::YAML::\n') -> t.List[t.Tuple[str, bytes]]:
"""
Transforms a given ``bundle`` into a *sorted* list of tuples with materialized value paths and values:
... | How would you implement a function in Python 3 that
serializes a given dictionary into a list of tuples with materialized value paths and values. | You are a Python code analyst, evaluating scripts for potential improvements. |
Writes a given string into a stream. | Explain what the following Python 3 code does
def wf(raw_str: str,
flush: bool = True,
prevent_completion_polluting: bool = True,
stream: t.TextIO = sys.stdout):
"""
Writes a given ``raw_str`` into a ``stream``. Ignores output if ``prevent_completion_polluting`` is set and there's
no ex... | You are a Python code analyst, evaluating scripts for potential improvements. |
Converts a given string representation of boolean into a boolean. | Can you tell what is the following Python 3 function doing
def coerce_str_to_bool(val: t.Union[str, int, bool, None], strict: bool = False) -> bool:
if isinstance(val, str):
val = val.lower()
flag = ENV_STR_BOOL_COERCE_MAP.get(val, None)
if flag is not None:
return flag
if strict:
... | As a Python code composer, you craft elegant and concise scripts. |
Converts an environment variable name into a boolean. | Given the following Python 3 function, write the documentation
def env_bool_flag(flag_name: str, strict: bool = False, env: t.Optional[t.Dict[str, str]] = None) -> bool:
env = env or os.environ
sentinel = object()
val = env.get(flag_name, sentinel)
if val is sentinel:
return False
return c... | As a python code expert, you are capable of creating scripts from specifications. |
Reads env DOCKERIZED env variable as a boolean. | Given the following Python 3 function, write the documentation
def is_dockerized(flag_name: str = 'DOCKERIZED', strict: bool = False):
return env_bool_flag(flag_name, strict=strict) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Reads environment variable PRODUCTION as a boolean. | Given the following Python 3 function, write the documentation
def is_production(flag_name: str = 'PRODUCTION', strict: bool = False):
return env_bool_flag(flag_name, strict=strict) | You are a Python code architect, reviewing and designing scalable and efficient code |
def runcode(code):
"""Run the given code line by line with printing, as list of lines, and return variable 'ans'."""
for line in code:
print('# '+line)
exec(line,globals())
print('# return ans')
return ans | Can you implement a function in Python 3 that
runs the given code line by line with printing as list of lines and return variable ans. | You are a Python code analyst, evaluating scripts for potential improvements. |
Execute each passed endpoint and collect the results. | How would you explain what the following Python 3 function does
def exec_all_endpoints(self, *args, **kwargs):
results = []
for handler in self.endpoints:
if isinstance(handler, weakref.ref):
handler = handler()
if self.adapt_params:
bind = self._a... | You are a Python code analyst, evaluating scripts for potential improvements. |
Execute all the handlers and return the result of the exec_wrapper method. | How would you explain what the following Python 3 function does
def run(self, *args, **kwargs):
if self.fvalidation is not None:
try:
if self.fvalidation(*args, **kwargs) is False:
raise ExecutionError("Validation returned ``False``")
except Exception ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def login_defs():
"""Discover the minimum and maximum UID number."""
uid_min = None
uid_max = None
login_defs_path = '/etc/login.defs'
if os.path.exists(login_defs_path):
with io.open(text_type(login_defs_path), encoding=text_type('utf-8')) as log_defs_file:
login_data = log_defs... | Write a Python 3 function for
discovering the minimum and maximum UID number. | You are a Python code architect, reviewing and designing scalable and efficient code |
Runs Django collectstatic command in silent mode. | Can you generate the documentation for the following Python 3 function
def collect_static() -> bool:
from django.core.management import execute_from_command_line
# from django.conf import settings
# if not os.listdir(settings.STATIC_ROOT):
wf('Collecting static files... ', False)
execute_from_comman... | You are a Python code analyst, evaluating scripts for potential improvements. |
def inner_parser(self) -> BaseParser:
"""
Prepares inner config parser for config stored at ``endpoint``.
:return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser`
:raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain ... | Can you create a Python 3 function that
returns an instance of the inner config parser for the specified endpoint. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate command to add a user. | Given the following Python 3 function, write the documentation
def generate_add_user_command(proposed_user=None, manage_home=None):
command = None
if get_platform() in ('Linux', 'OpenBSD'):
command = '{0} {1}'.format(sudo_check(), LINUX_CMD_USERADD)
if proposed_user.uid:
command = '{... | As a Python code analyst, you investigate and solve complex coding mysteries |
def generate_modify_user_command(task=None, manage_home=None):
"""Generate command to modify existing user to become the proposed user.
args:
task (dict): A proposed user and the differences between it and the existing user
returns:
list: The command string split into shell-like syntax
... | Write a Python 3 function that can
generate command to modify existing user. | You are a Python code generator, capable of creating scripts from specifications. |
Generate command to delete a user. | Can you generate the documentation for the following Python 3 function
def generate_delete_user_command(username=None, manage_home=None):
command = None
remove_home = '-r' if manage_home else ''
if get_platform() in ('Linux', 'OpenBSD'):
command = '{0} {1} {2} {3}'.format(sudo_check(), LINUX_CMD_US... | As a Python code composer, you craft elegant and concise scripts. |
Compare a User instance with the supplied Users list and return the differences. | Can you generate the documentation for the following Python 3 function
def compare_user(passed_user=None, user_list=None):
# Check if user exists
returned = user_list.describe_users(users_filter=dict(name=passed_user.name))
replace_keys = False
# User exists, so compare attributes
comparison_result ... | As a python code expert, you are capable of creating scripts from specifications. |
Force double quoted gecos. | Can you tell what is the following Python 3 function doing
def gecos(self):
if not self._gecos:
return None
if self._gecos.startswith(text_type('\'')) and self._gecos.endswith(text_type('\'')):
self._gecos = '\"{0}\"'.format(self._gecos[1:-1])
return self._gecos
... | As a python code expert, you are capable of creating scripts from specifications. |
def to_dict(self):
""" Return the user as a dict. """
public_keys = [public_key.b64encoded for public_key in self.public_keys]
return dict(name=self.name, passwd=self.passwd, uid=self.uid, gid=self.gid, gecos=self.gecos,
home_dir=self.home_dir, shell=self.shell, public_keys=p... | How would you code a function in Python 3 to
return the user as a dict. | As a Python code analyst, you investigate and solve complex coding mysteries |
def insert(self, index, value):
"""Insert an instance of User into the collection."""
self.check(value)
self._user_list.insert(index, value) | Create a Python 3 function to
insert an instance of User into the collection. | As a python code expert, you are capable of creating scripts from specifications. |
def remove(self, username=None):
"""Remove User instance based on supplied user name."""
self._user_list = [user for user in self._user_list if user.name != username] | Write a Python 3 script for
removing User instance based on supplied user name. | You are a Python code generator, capable of creating scripts from specifications. |
def describe_users(self, users_filter=None):
"""Return a list of users matching a filter (if provided)."""
user_list = Users(oktypes=User)
for user in self._user_list:
if users_filter and (users_filter.get('name') == user.name or users_filter.get('uid') == user.uid):
... | Implement a function in Python 3 to
return a list of users matching a filter ( if provided ). | You are a Python code generator, capable of creating scripts from specifications. |
def from_yaml(cls, file_path=None):
"""Create collection from a YAML file."""
try:
import yaml
except ImportError: # pragma: no cover
yaml = None
if not yaml:
import sys
sys.exit('PyYAML is not installed, but is required in order to parse ... | Can you implement a function in Python 3 that
creates a collection from a YAML file. | You are a Python code generator, capable of creating scripts from specifications. |
Create a collection from a JSON file. | Make a summary of the following Python 3 code
def from_json(cls, file_path=None):
with io.open(file_path, encoding=text_type('utf-8')) as stream:
try:
users_json = json.load(stream)
except ValueError:
raise ValueError('No JSON object could be decoded')
... | You are a Python code generator, capable of creating scripts from specifications. |
def from_passwd(uid_min=None, uid_max=None):
"""Create collection from locally discovered data, e.g. /etc/passwd."""
import pwd
users = Users(oktypes=User)
passwd_list = pwd.getpwall()
if not uid_min:
uid_min = UID_MIN
if not uid_max:
uid_max = UID... | Write a Python 3 script for
creating collection from locally discovered data e. g. / etc. passwd. | You are a Python code generator, capable of creating scripts from specifications. |
def construct_user_list(raw_users=None):
"""Construct a list of User objects from a list of dicts."""
users = Users(oktypes=User)
for user_dict in raw_users:
public_keys = None
if user_dict.get('public_keys'):
public_keys = [PublicKey(b64encoded=x, raw=Non... | How would you code a function in Python 3 to
construct a list of User objects from a list of dicts. | As a Python code composer, you craft elegant and concise scripts. |
Return a dict of the users. | Can you generate the documentation for the following Python 3 function
def to_dict(self):
users = dict(users=list())
for user in self:
users['users'].append(user.to_dict())
return users | You are a Python code generator, capable of creating scripts from specifications. |
def export(self, file_path=None, export_format=None):
""" Write the users to a file. """
with io.open(file_path, mode='w', encoding="utf-8") as export_file:
if export_format == 'yaml':
import yaml
yaml.safe_dump(self.to_dict(), export_file, default_flow_style=... | Implement a Python 3 function for
writing the users to a file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Helper function to read a TTL - TXT file | How would you explain what the following Python 3 function does
def read(path, mode='tsv'):
''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. read('~/data/myfile') is the same as Document('myfile', '~/data/').read()
'''
if mode == 'tsv':
return TxtReader.from_pa... | You are a Python code analyst, evaluating scripts for potential improvements. |
def tcmap(self):
''' Create a tokens-concepts map '''
tcmap = dd(list)
for concept in self.__concept_map.values():
for w in concept.tokens:
tcmap[w].append(concept)
return tcmap | Implement a function in Python 3 to
create a tokens - concepts map | You are a Python code analyst, evaluating scripts for potential improvements. |
def msw(self):
''' Return a generator of tokens with more than one sense. '''
return (t for t, c in self.tcmap().items() if len(c) > 1) | Implement a Python 3 function for
returning a generator of tokens with more than one sense. | As a Python code composer, you craft elegant and concise scripts. |
def surface(self, tag):
''' Get surface string that is associated with a tag object '''
if tag.cfrom is not None and tag.cto is not None and tag.cfrom >= 0 and tag.cto >= 0:
return self.text[tag.cfrom:tag.cto]
else:
return '' | Write a Python 3 function for
getting the surface string that is associated with a tag object | As a python code expert, you are capable of creating scripts from specifications. |
def new_tag(self, label, cfrom=-1, cto=-1, tagtype='', **kwargs):
''' Create a sentence-level tag '''
tag_obj = Tag(label, cfrom, cto, tagtype=tagtype, **kwargs)
return self.add_tag(tag_obj) | Write a Python 3 script to
create a sentence - level tag. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the first tag of a particular type | Make a summary of the following Python 3 code
def get_tag(self, tagtype):
''' Get the first tag of a particular type'''
for tag in self.__tags:
if tag.tagtype == tagtype:
return tag
return None | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_tags(self, tagtype):
''' Get all tags of a type '''
return [t for t in self.__tags if t.tagtype == tagtype] | Can you implement a function in Python 3 that
gets all tags of a type | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_token_object(self, token):
''' Add a token object into this sentence '''
token.sent = self # take ownership of given token
self.__tokens.append(token)
return token | Write a Python 3 function that can
add a token object into this sentence | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a new concept object and add it to concept list | Make a summary of the following Python 3 code
def new_concept(self, tag, clemma="", tokens=None, cidx=None, **kwargs):
''' Create a new concept object and add it to concept list
tokens can be a list of Token objects or token indices
'''
if cidx is None:
cidx = self.new_concep... | As a python code expert, you are capable of creating scripts from specifications. |
Add a concept to current concept list | How would you explain what the following Python 3 function does
def add_concept(self, concept_obj):
''' Add a concept to current concept list '''
if concept_obj is None:
raise Exception("Concept object cannot be None")
elif concept_obj in self.__concepts:
raise Exception(... | As a Python code composer, you craft elegant and concise scripts. |
def concept(self, cid, **kwargs):
''' Get concept by concept ID '''
if cid not in self.__concept_map:
if 'default' in kwargs:
return kwargs['default']
else:
raise KeyError("Invalid cid")
else:
return self.__concept_map[cid] | Implement a function in Python 3 to
get concept by concept ID | As a Python code composer, you craft elegant and concise scripts. |
def import_tokens(self, tokens, import_hook=None, ignorecase=True):
''' Import a list of string as tokens '''
text = self.text.lower() if ignorecase else self.text
has_hooker = import_hook and callable(import_hook)
cfrom = 0
if self.__tokens:
for tk in self.__tokens:
... | Can you write a function in Python 3 where it
imports a list of string as tokens | As a Python code composer, you craft elegant and concise scripts. |
def tag_map(self):
''' Build a map from tagtype to list of tags '''
tm = dd(list)
for tag in self.__tags:
tm[tag.tagtype].append(tag)
return tm | Write a Python 3 function for
building a map from tagtype to list of tags | As a python code expert, you are capable of creating scripts from specifications. |
Find the first tag with a type in this token | Make a summary of the following Python 3 code
def find(self, tagtype, **kwargs):
'''Get the first tag with a type in this token '''
for t in self.__tags:
if t.tagtype == tagtype:
return t
if 'default' in kwargs:
return kwargs['default']
else:
... | You are a Python code generator, capable of creating scripts from specifications. |
def find_all(self, tagtype):
''' Find all token-level tags with the specified tagtype '''
return [t for t in self.__tags if t.tagtype == tagtype] | Write a Python 3 function that can
find all token - level tags with the specified tagtype | As a Python code composer, you craft elegant and concise scripts. |
def new_tag(self, label, cfrom=None, cto=None, tagtype=None, **kwargs):
''' Create a new tag on this token '''
if cfrom is None:
cfrom = self.cfrom
if cto is None:
cto = self.cto
tag = Tag(label=label, cfrom=cfrom, cto=cto, tagtype=tagtype, **kwargs)
retur... | Implement a Python 3 function for
creating a new tag on this token | As a python code expert, you are capable of creating scripts from specifications. |
def get(self, sent_id, **kwargs):
''' If sent_id exists, remove and return the associated sentence object else return default.
If no default is provided, KeyError will be raised.'''
if sent_id is not None and not isinstance(sent_id, int):
sent_id = int(sent_id)
if sent_id is ... | Write a Python 3 script for
returning the associated sentence object. | You are a Python code analyst, evaluating scripts for potential improvements. |
def add_sent(self, sent_obj):
''' Add a ttl.Sentence object to this document '''
if sent_obj is None:
raise Exception("Sentence object cannot be None")
elif sent_obj.ID is None:
# if sentID is None, create a new ID
sent_obj.ID = next(self.__idgen)
elif... | How would you code a function in Python 3 to
add a ttl. Sentence object to this document. | As a Python code composer, you craft elegant and concise scripts. |
def new_sent(self, text, ID=None, **kwargs):
''' Create a new sentence and add it to this Document '''
if ID is None:
ID = next(self.__idgen)
return self.add_sent(Sentence(text, ID=ID, **kwargs)) | Write a Python 3 function that can
create a new sentence and add it to this Document | You are a Python code generator, capable of creating scripts from specifications. |
Removes and returns the associated sentence object. | Can you tell what is the following Python 3 function doing
def pop(self, sent_id, **kwargs):
''' If sent_id exists, remove and return the associated sentence object else return default.
If no default is provided, KeyError will be raised.'''
if sent_id is not None and not isinstance(sent_id, int)... | You are a Python code generator, capable of creating scripts from specifications. |
def read(self):
''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) '''
warnings.warn("Document.read() is deprecated and will be removed in near future.", DeprecationWarning)
with TxtReader.from_doc(self) as reader:
reader.read(self)
return self | Implement a Python 3 function for
reading tagged doc from mutliple files. | As a Python code composer, you craft elegant and concise scripts. |
def read(self, doc=None):
''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) '''
if not self.sent_stream:
raise Exception("There is no sentence data stream available")
if doc is None:
doc = Document(name=self.doc_name, path=self.doc_path)
... | Write a Python 3 function that can
read tagged doc from mutliple files. | As a Python code analyst, you investigate and solve complex coding mysteries |
Format the text for output adding ASCII frame around the text. | Can you generate a brief explanation for the following Python 3 code
def format_page(text):
width = max(map(len, text.splitlines()))
page = "+-" + "-" * width + "-+\n"
for line in text.splitlines():
page += "| " + line.ljust(width) + " |\n"
page += "+-" + "-" * width + "-+\n"
return pa... | As a Python code analyst, you investigate and solve complex coding mysteries |
Format the text as a table. | Make a summary of the following Python 3 code
def table(text):
def table_bar(col_lengths):
return "+-%s-+%s" % (
"-+-".join(["-" * length for length in col_lengths]),
os.linesep,
)
rows = []
for line in text.splitlines():
rows.append([part.strip() ... | You are a Python code generator, capable of creating scripts from specifications. |
def print_page(text):
"""Format the text and prints it on stdout.
Text is formatted by adding a ASCII frame around it and coloring the text.
Colors can be added to text using color tags, for example:
My [FG_BLUE]blue[NORMAL] text.
My [BG_BLUE]blue background[NORMAL] text.
"""
... | Can you create a Python 3 function that
formats the text and prints it on stdout. | As a python code expert, you are capable of creating scripts from specifications. |
def wrap_text(text, width=80):
"""Wrap text lines to maximum *width* characters.
Wrapped text is aligned against the left text border.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Wrapped text.
"""
text =... | Write a Python 3 function that can
wrap text to maximum width characters per line. | As a Python code composer, you craft elegant and concise scripts. |
Wrap text and adjust it to right border. | Can you tell what is the following Python 3 function doing
def rjust_text(text, width=80, indent=0, subsequent=None):
text = re.sub(r"\s+", " ", text).strip()
if subsequent is None:
subsequent = indent
wrapper = TextWrapper(
width=width,
break_long_words=False,
replace... | As a Python code analyst, you investigate and solve complex coding mysteries |
Center all lines of the text. | Given the following Python 3 function, write the documentation
def center_text(text, width=80):
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) | You are a Python code generator, capable of creating scripts from specifications. |
def check(qpi_or_h5file, checks=["attributes", "background"]):
"""Checks various properties of a :class:`qpimage.core.QPImage` instance
Parameters
----------
qpi_or_h5file: qpimage.core.QPImage or str
A QPImage object or a path to an hdf5 file
checks: list of str
Which checks to per... | Write a Python 3 script to
check various properties of a QPImage or a path to an hdf5 file. | You are a Python code architect, reviewing and designing scalable and efficient code |
def check_attributes(qpi):
"""Check QPimage attributes
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails
"""
missing_attrs = []
for key in DATA_KEYS:
if key not in qpi.meta:
missing_attrs.append(key)... | Write a Python 3 script for
checking that the attributes of the sequence of items in the sequence are present in the meta data. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check if background correction is correct for all images in the sequence. | Can you tell what is the following Python 3 function doing
def check_background(qpi):
for imdat in [qpi._amp, qpi._pha]:
try:
fit, attrs = imdat.get_bg(key="fit", ret_attrs=True)
except KeyError:
# No bg correction performed
pass
else:
kwargs =... | You are a Python code generator, capable of creating scripts from specifications. |
def write_image_dataset(group, key, data, h5dtype=None):
"""Write an image to an hdf5 group as a dataset
This convenience function sets all attributes such that the image
can be visualized with HDFView, sets the compression and fletcher32
filters, and sets the chunk size to the image shape.
Parame... | Can you implement a function in Python 3 that
writes an image to an HDF5 group as a dataset | You are a Python code architect, reviewing and designing scalable and efficient code |
def info(self):
"""list of background correction parameters"""
info = []
name = self.__class__.__name__.lower()
# get bg information
for key in VALID_BG_KEYS:
if key in self.h5["bg_data"]:
attrs = self.h5["bg_data"][key].attrs
for akey ... | Implement a function in Python 3 to
list of background correction parameters | As a Python code composer, you craft elegant and concise scripts. |
Removes the background image data for the specified key from the H5 file. | Make a summary of the following Python 3 code
def del_bg(self, key):
if key not in VALID_BG_KEYS:
raise ValueError("Invalid bg key: {}".format(key))
if key in self.h5["bg_data"]:
del self.h5["bg_data"][key]
else:
msg = "No bg data to clear for '{}' in {}.".for... | As a python code expert, you are capable of creating scripts from specifications. |
Estimate image background of a single object. | How would you explain what the following Python 3 function does
def estimate_bg(self, fit_offset="mean", fit_profile="tilt",
border_px=0, from_mask=None, ret_mask=False):
"""Estimate image background
Parameters
----------
fit_profile: str
The type of back... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the background image data for the specified key. | Given the following Python 3 function, write the documentation
def get_bg(self, key=None, ret_attrs=False):
if key is None:
if ret_attrs:
raise ValueError("No attributes for combined background!")
return self.bg
else:
if key not in VALID_BG_KEYS:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def set_bg(self, bg, key="data", attrs={}):
"""Set the background data
Parameters
----------
bg: numbers.Real, 2d ndarray, ImageData, or h5py.Dataset
The background data. If `bg` is an `h5py.Dataset` object,
it must exist in the same hdf5 file (a hard link is cre... | Write a Python 3 function that can
set the background data for the current object. | As a Python code composer, you craft elegant and concise scripts. |
def _bg_combine(self, bgs):
"""Combine several background amplitude images"""
out = np.ones(self.h5["raw"].shape, dtype=float)
# bg is an h5py.DataSet
for bg in bgs:
out *= bg[:]
return out | Write a Python 3 script for
combining several background amplitude images | You are a Python code generator, capable of creating scripts from specifications. |
Returns the Git tags of the current node. | Make a summary of the following Python 3 code
def git_tags() -> str:
try:
subprocess.check_call(['git', 'fetch', '--tags'])
except CalledProcessError:
pass
cmd = ['git', 'tag', '--list', '--sort=-v:refname']
rv = subprocess.check_output(cmd).decode('utf-8')
if rv == '':
rai... | As a Python code composer, you craft elegant and concise scripts. |
Converts a Git tag to a SemVer object. | Can you generate a brief explanation for the following Python 3 code
def git_tag_to_semver(git_tag: str) -> SemVer:
pattern = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$')
match = pattern.search(git_tag)
if match:
version = match.group(0)
else:
raise InvalidTagFormatException('Tag passed contai... | As a python code expert, you are capable of creating scripts from specifications. |
Returns the last Git release tag in a list. | Given the following Python 3 function, write the documentation
def last_git_release_tag(git_tags: str) -> str:
semver_re = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$')
str_ver = []
for i in git_tags.split():
if semver_re.search(i):
str_ver.append(i)
try:
return str_ver[0]
exce... | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.