output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def table_exists(self, tablename: str) -> bool: """Does the table exist?""" # information_schema is ANSI standard sql = """ SELECT COUNT(*) FROM information_schema.tables WHERE table_name=? AND table_schema={} """.format(self.get_current_sc...
Write a Python 3 function for doing the table exist?
As a Python code analyst, you investigate and solve complex coding mysteries
def column_exists(self, tablename: str, column: str) -> bool: """Does the column exist?""" sql = """ SELECT COUNT(*) FROM information_schema.columns WHERE table_name=? AND column_name=? AND table_schema={} """.format(self.get_current_sc...
Write a Python 3 function that can do the column exist?
As a Python code translator, you convert algorithms and pseudocode into Python.
def drop_table(self, tablename: str) -> int: """Drops a table. Use caution!""" sql = "DROP TABLE IF EXISTS {}".format(tablename) log.info("Dropping table " + tablename + " (ignore any warning here)") return self.db_exec_literal(sql)
Create a Python 3 function for dropping a table. Use caution!
As a Python code analyst, you investigate and solve complex coding mysteries
def make_table(self, tablename: str, fieldspeclist: FIELDSPECLIST_TYPE, dynamic: bool = False, compressed: bool = False) -> Optional[int]: """Makes a table, if it doesn't already exist.""" if self.table_exists(tablename): ...
Write a Python 3 function for making a table if it doesn t already exist.
You are a Python code architect, reviewing and designing scalable and efficient code
def rename_table(self, from_table: str, to_table: str) -> Optional[int]: """Renames a table. MySQL-specific.""" if not self.table_exists(from_table): log.info("Skipping renaming of table " + from_table + " (doesn't exist)") return None if self.table_e...
Can you write a function in Python 3 where it renames a table. MySQL - specific.
As a Python code analyst, you investigate and solve complex coding mysteries
Adds a column to an existing table.
Can you generate a brief explanation for the following Python 3 code def add_column(self, tablename: str, fieldspec: FIELDSPEC_TYPE) -> int: sql = "ALTER TABLE {} ADD COLUMN {}".format( tablename, self.fielddefsql_from_fieldspec(fieldspec)) log.info(sql) return self.db_exec_literal(s...
You are a Python code analyst, evaluating scripts for potential improvements.
Drops a column from an existing table.
Given the following Python 3 function, write the documentation def drop_column(self, tablename: str, fieldname: str) -> int: sql = "ALTER TABLE {} DROP COLUMN {}".format(tablename, fieldname) log.info(sql) return self.db_exec_literal(sql)
You are a Python code generator, capable of creating scripts from specifications.
Alters a column s definition without renaming it.
Can you generate a brief explanation for the following Python 3 code def modify_column_if_table_exists(self, tablename: str, fieldname: str, newdef: str) -> Optional[int]: """Alters a column's defin...
You are a Python code generator, capable of creating scripts from specifications.
Renames a column and alters its definition.
Explain what the following Python 3 code does def change_column_if_table_exists(self, tablename: str, oldfieldname: str, newfieldname: str, newdef: str) -> Optional[int...
You are a Python code generator, capable of creating scripts from specifications.
Create or update a new table.
Make a summary of the following Python 3 code def create_or_update_table(self, tablename: str, fieldspeclist: FIELDSPECLIST_TYPE, drop_superfluous_columns: bool = False, dynamic: bool = False, ...
As a Python code composer, you craft elegant and concise scripts.
def describe_table(self, table: str) -> List[List[Any]]: """Returns details on a specific table.""" return self.flavour.describe_table(self, table)
Can you implement a function in Python 3 that returns details on a specific table.
You are a Python code analyst, evaluating scripts for potential improvements.
def fetch_column_names(self, table: str) -> List[str]: """Returns all column names for a table.""" return self.flavour.fetch_column_names(self, table)
Can you write a function in Python 3 where it returns all column names for a table.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns database SQL datatype for a column. e. g. VARCHAR.
Given the following Python 3 function, write the documentation def get_datatype(self, table: str, column: str) -> str: return self.flavour.get_datatype(self, table, column).upper()
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_column_type(self, table: str, column: str) -> str: """Returns database SQL datatype for a column, e.g. VARCHAR(50).""" return self.flavour.get_column_type(self, table, column).upper()
Implement a function in Python 3 to return database SQL datatype for a column e. g. VARCHAR ( 50 ).
You are a Python code analyst, evaluating scripts for potential improvements.
Returns database SQL comment for a column.
Can you generate a brief explanation for the following Python 3 code def get_comment(self, table: str, column: str) -> str: return self.flavour.get_comment(self, table, column)
As a Python code analyst, you investigate and solve complex coding mysteries
def debug_query(self, sql: str, *args) -> None: """Executes SQL and writes the result to the log.""" rows = self.fetchall(sql, *args) debug_query_result(rows)
Write a Python 3 function for executing SQL and writes the result to the log.
As a Python code analyst, you investigate and solve complex coding mysteries
def wipe_table(self, table: str) -> int: """Delete all records from a table. Use caution!""" sql = "DELETE FROM " + self.delimit(table) return self.db_exec(sql)
Can you create a Python 3 function that deletes all records from a table. Use caution!
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a primary key or replace it if it exists.
Given the following Python 3 function, write the documentation def create_or_replace_primary_key(self, table: str, fieldnames: Sequence[str]) -> int: """Make a primary key, or replace it if it exists.""" # *** create_or_replace_...
As a python code expert, you are capable of creating scripts from specifications.
def noise_covariance(fit, dof=2, **kw): """ Covariance taking into account the 'noise covariance' of the data. This is technically more realistic for continuously sampled data. From Faber, 1993 """ ev = fit.eigenvalues measurement_noise = ev[-1]/(fit.n-dof) return 4*ev*measurement_noise
Write a Python 3 function for returning the noise covariance of the data.
You are a Python code generator, capable of creating scripts from specifications.
Returns a tuple of minimum and maximum angular errors corresponding to 1st and 2nd axes of PCA distribution.
Given the following Python 3 function, write the documentation def angular_errors(hyp_axes): # Not quite sure why this is sqrt but it is empirically correct ax = N.sqrt(hyp_axes) return tuple(N.arctan2(ax[-1],ax[:-1]))
As a python code expert, you are capable of creating scripts from specifications.
Returns a Hyperbolic error using a statistical process.
Explain what the following Python 3 code does def statistical_axes(fit, **kw): method = kw.pop('method', 'noise') confidence_level = kw.pop('confidence_level', 0.95) dof = kw.pop('dof',2) nominal = fit.eigenvalues if method == 'sampling': cov = sampling_covariance(fit,**kw) elif method...
As a python code expert, you are capable of creating scripts from specifications.
Implements ``CREATE VIEW``. Args: operations: instance of ``alembic.operations.base.Operations`` operation: instance of :class:`.ReversibleOp` Returns: ``None``
Here you have a function in Python 3, explain what it does def create_view(operations, operation): operations.execute("CREATE VIEW %s AS %s" % ( operation.target.name, operation.target.sqltext ))
You are a Python code architect, reviewing and designing scalable and efficient code
def create_sp(operations, operation): """ Implements ``CREATE FUNCTION``. Args: operations: instance of ``alembic.operations.base.Operations`` operation: instance of :class:`.ReversibleOp` Returns: ``None`` """ operations.execute( "CREATE FUNCTION %s %s" % ( ...
Create a Python 3 function to implement ``CREATE FUNCTION``. Args: operations: instance of ``alembic.operations.base.Operations`` operation: instance of :class:`.ReversibleOp` Returns: ``None``
As a Python code composer, you craft elegant and concise scripts.
def _get_object_from_version(cls, operations, ident): """ Returns a Python object from an Alembic migration module (script). Args: operations: instance of ``alembic.operations.base.Operations`` ident: string of the format ``version.objname`` Returns: ...
Implement a function in Python 3 to return a Python object from an Alembic migration module.
You are a Python code analyst, evaluating scripts for potential improvements.
Takes an ISO - 8601 string and returns a datetime. datetime object.
Here you have a function in Python 3, explain what it does def iso_string_to_python_datetime( isostring: str) -> Optional[datetime.datetime]: """ Takes an ISO-8601 string and returns a ``datetime``. """ if not isostring: return None # if you parse() an empty string, you get today's date...
As a Python code composer, you craft elegant and concise scripts.
def python_utc_datetime_to_sqlite_strftime_string( value: datetime.datetime) -> str: """ Converts a Python datetime to a string literal compatible with SQLite, including the millisecond field. """ millisec_str = str(round(value.microsecond / 1000)).zfill(3) return value.strftime("%Y-%m-%...
Write a Python 3 function that can convert a Python datetime to a string literal compatible with SQLite
As a Python code composer, you craft elegant and concise scripts.
def python_localized_datetime_to_human_iso(value: datetime.datetime) -> str: """ Converts a Python ``datetime`` that has a timezone to an ISO-8601 string with ``:`` between the hours and minutes of the timezone. Example: >>> import datetime >>> import pytz >>> x = datetime.datet...
Implement a Python 3 function for converting a Python datetime object that has a timezone to an ISO - 8601 string.
You are a Python code generator, capable of creating scripts from specifications.
def isodt_lookup_mysql(lookup, compiler, connection, operator) -> Tuple[str, Any]: """ For a comparison "LHS *op* RHS", transforms the LHS from a column containing an ISO-8601 date/time into an SQL ``DATETIME``, for MySQL. """ lhs, lhs_params = compiler.compile(lookup.lhs)...
Can you implement a function in Python 3 that converts a MySQL lookup into a SQL string.
As a Python code composer, you craft elegant and concise scripts.
def deconstruct(self) -> Tuple[str, str, List[Any], Dict[str, Any]]: """ Takes an instance and calculates the arguments to pass to ``__init__`` to reconstruct it. """ name, path, args, kwargs = super().deconstruct() del kwargs['max_length'] return name, path, args...
How would you code a function in Python 3 to take an instance and calculates the arguments to pass to the constructor.
As a Python code translator, you convert algorithms and pseudocode into Python.
def from_db_value(self, value, expression, connection, context): """ Convert database value to Python value. Called when data is loaded from the database. """ # log.debug("from_db_value: {}, {}", value, type(value)) if value is None: return value if va...
Write a Python 3 function for converting database value to Python value.
You are a Python code generator, capable of creating scripts from specifications.
Converts value to a Python value.
Can you generate the documentation for the following Python 3 function def to_python(self, value: Optional[str]) -> Optional[Any]: # https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/ # log.debug("to_python: {}, {}", value, type(value)) if isinstance(value, datetime.datetime): ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_prep_value(self, value): """ Convert Python value to database value for QUERYING. We query with UTC, so this function converts datetime values to UTC. Calls to this function are followed by calls to ``get_db_prep_value()``, which is for backend-specific conversions. ...
Write a Python 3 script to convert Python value to database value for QUERYING.
As a Python code analyst, you investigate and solve complex coding mysteries
This method is used to convert the value to the database value for QUERYING.
Can you generate the documentation for the following Python 3 function def get_db_prep_value(self, value, connection, prepared=False): log.debug("get_db_prep_value: {}, {}", value, type(value)) value = super().get_db_prep_value(value, connection, prepared) if value is None: return va...
As a Python code composer, you craft elegant and concise scripts.
Convert Python value to database value for SAVING.
Make a summary of the following Python 3 code def get_db_prep_save(self, value, connection, prepared=False): log.debug("get_db_prep_save: {}, {}", value, type(value)) if not value: return '' # For underlying (database) string types, e.g. VARCHAR, this # function must ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a sorted list of every file extension found in a directory and its subdirectories.
Here you have a function in Python 3, explain what it does def list_file_extensions(path: str, reportevery: int = 1) -> List[str]: extensions = set() count = 0 for root, dirs, files in os.walk(path): count += 1 if count % reportevery == 0: log.debug("Walking directory {}: {!r}", ...
You are a Python code architect, reviewing and designing scalable and efficient code
Command - line processor.
Can you generate the documentation for the following Python 3 function def main() -> None: main_only_quicksetup_rootlogger(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument("directory", nargs="?", default=os.getcwd()) parser.add_argument("--reportevery", default=10000) args...
You are a Python code architect, reviewing and designing scalable and efficient code
Check which of a list of Debian packages are installed via dpkg - query.
Make a summary of the following Python 3 code def are_debian_packages_installed(packages: List[str]) -> Dict[str, bool]: assert len(packages) >= 1 require_executable(DPKG_QUERY) args = [ DPKG_QUERY, "-W", # --show # "-f='${Package} ${Status} ${Version}\n'", "-f=${Package} ${...
As a Python code composer, you craft elegant and concise scripts.
Ensures that specific packages are installed under Debian.
How would you explain what the following Python 3 function does def require_debian_packages(packages: List[str]) -> None: present = are_debian_packages_installed(packages) missing_packages = [k for k, v in present.items() if not v] if missing_packages: missing_packages.sort() msg = ( ...
You are a Python code analyst, evaluating scripts for potential improvements.
Validate that the object is a valid pair of objects.
Here you have a function in Python 3, explain what it does def validate_pair(ob: Any) -> bool: try: if len(ob) != 2: log.warning("Unexpected result: {!r}", ob) raise ValueError() except ValueError: return False return True
As a Python code analyst, you investigate and solve complex coding mysteries
def windows_get_environment_from_batch_command( env_cmd: Union[str, List[str]], initial_env: Dict[str, str] = None) -> Dict[str, str]: """ Take a command (either a single command or list of arguments) and return the environment created after running that command. Note that the command mu...
Can you implement a function in Python 3 that takes a command (either a single command or list of arguments) and return the environment created after running that command. Note that the command must be a batch (``.bat``) file or ``.cmd`` file, or the changes to the environment will not be captured. If ``initial_env`` i...
You are a Python code analyst, evaluating scripts for potential improvements.
def contains_unquoted_target(x: str, quote: str = '"', target: str = '&') -> bool: """ Checks if ``target`` exists in ``x`` outside quotes (as defined by ``quote``). Principal use: from :func:`contains_unquoted_ampersand_dangerous_to_windows`. """ in_quote = False ...
Write a Python 3 script for checking if target exists in x outside quotes.
You are a Python code generator, capable of creating scripts from specifications.
def gut_message(message: Message) -> Message: """ Remove body from a message, and wrap in a message/external-body. """ wrapper = Message() wrapper.add_header('Content-Type', 'message/external-body', access_type='x-spam-deleted', expiration=time.strftime(...
Implement a Python 3 function for returning a message that is wrapped in a message.
You are a Python code analyst, evaluating scripts for potential improvements.
def clean_message(message: Message, topmost: bool = False) -> Message: """ Clean a message of all its binary parts. This guts all binary attachments, and returns the message itself for convenience. """ if message.is_multipart(): # Don't recurse in already-deleted attachments if...
Write a Python 3 function for cleaning a message by all its binary parts and return the message itself for convenience.
As a Python code translator, you convert algorithms and pseudocode into Python.
def hash_password(plaintextpw: str, log_rounds: int = BCRYPT_DEFAULT_LOG_ROUNDS) -> str: """ Makes a hashed password (using a new salt) using ``bcrypt``. The hashed password includes the salt at its start, so no need to store a separate salt. """ salt = bcrypt.gensalt(log_roun...
Write a Python 3 script for hashing a plaintext password using bcrypt.
You are a Python code generator, capable of creating scripts from specifications.
Checks if a plaintext password matches a stored hash.
Here you have a function in Python 3, explain what it does def is_password_valid(plaintextpw: str, storedhash: str) -> bool: # Upon CamCOPS from MySQL 5.5.34 (Ubuntu) to 5.1.71 (CentOS 6.5), the # VARCHAR was retrieved as Unicode. We needed to convert that to a str. # For Python 3 compatibility, we just str...
You are a Python code analyst, evaluating scripts for potential improvements.
Create a system ODBC data source name.
Can you tell what is the following Python 3 function doing def create_sys_dsn(driver: str, **kw) -> bool: attributes = [] # type: List[str] for attr in kw.keys(): attributes.append("%s=%s" % (attr, kw[attr])) return bool( ctypes.windll.ODBCCP32.SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, ...
As a Python code composer, you craft elegant and concise scripts.
Create a user ODBC data source name.
Make a summary of the following Python 3 code def create_user_dsn(driver: str, **kw) -> bool: attributes = [] # type: List[str] for attr in kw.keys(): attributes.append("%s=%s" % (attr, kw[attr])) return bool( ctypes.windll.ODBCCP32.SQLConfigDataSource(0, ODBC_ADD_DSN, driver, ...
As a Python code composer, you craft elegant and concise scripts.
def register_access_db(fullfilename: str, dsn: str, description: str) -> bool: """ (Windows only.) Registers a Microsoft Access database with ODBC. Args: fullfilename: filename of the existing database dsn: ODBC data source name to create description: description of the database...
Write a Python 3 function that can register a Microsoft Access database with Microsoft SQL Server.
As a python code expert, you are capable of creating scripts from specifications.
Creates a Microsoft Access 97 database and registers it with ODBC.
Can you tell what is the following Python 3 function doing def create_and_register_access97_db(filename: str, dsn: str, description: str) -> bool: """ (Windows only.) Creates a Microsoft Access 97 database and registers it with ODBC. ...
You are a Python code generator, capable of creating scripts from specifications.
Creates a Microsoft Access 2000 database and registers it with ODBC.
Can you tell what is the following Python 3 function doing def create_and_register_access2000_db(filename: str, dsn: str, description: str) -> bool: """ (Windows only.) Creates a Microsoft Access 2000 database and registers it with ...
As a Python code analyst, you investigate and solve complex coding mysteries
def create_and_register_access_db(filename: str, dsn: str, description: str) -> bool: """ (Windows only.) Creates a Microsoft Access database and registers it with ODBC. Args: filename: filename of the database to create ...
How would you implement a function in Python 3 that creates a Microsoft Access database and registers it with ODBC.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return true if all dependencies have been finalized and that they ll have sent at least one batch of data.
Explain what the following Python 3 code does def _finalized(self): return \ len(self._finalized_dependencies) >= self.dependency_count \ and len(self._enqueued_dependencies) >= self.dependency_count
As a Python code analyst, you investigate and solve complex coding mysteries
Compute the version identifier for this functional node using the functional node s local names and closure fingerprint.
Can you generate a brief explanation for the following Python 3 code def version(self): try: f = self.func.__call__.__code__ except AttributeError: f = self.func.__code__ h = md5() h.update(f.co_code) h.update(str(f.co_names).encode()) try: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_table_from_orm_class(engine: Engine, ormclass: DeclarativeMeta, without_constraints: bool = False) -> None: """ From an SQLAlchemy ORM class, creates the database table via the specified engine, using a ``CREATE TABLE`` SQL (DDL) sta...
How would you code a function in Python 3 to create a table from an SQLAlchemy ORM class.
You are a Python code generator, capable of creating scripts from specifications.
Initialize the counties and extractor objects
Make a summary of the following Python 3 code def mapper_init(self): self.counties = CachedCountyLookup(precision=GEOHASH_PRECISION) self.extractor = WordExtractor()
You are a Python code analyst, evaluating scripts for potential improvements.
Load the state and county GeoJSON files into MongoDB DB
Can you generate the documentation for the following Python 3 function def run(self): logging.info("Starting GeoJSON MongoDB loading process.") mongo = dict(uri=self.mongo, db=self.db, collection=self.collection) self.load(self.source, **mongo) logging.info("Finished loading {0} into Mon...
You are a Python code generator, capable of creating scripts from specifications.
Load a geojson file into a mongodb instance
Can you generate a brief explanation for the following Python 3 code def load(self, geojson, uri=None, db=None, collection=None): logging.info("Mongo URI: {0}".format(uri)) logging.info("Mongo DB: {0}".format(db)) logging.info("Mongo Collection: {0}".format(collection)) logging.info("Geo...
You are a Python code generator, capable of creating scripts from specifications.
def get_version(): """ Return formatted version string. Returns: str: string with project version or empty string. """ if all([VERSION, UPDATED, any([isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]), ]): return FORMAT_STRING.format(**{"version": VERSION, "updated": UPD...
Create a Python 3 function for returning formatted version string.
As a Python code analyst, you investigate and solve complex coding mysteries
Processes an OpenXML file and returns a list of the ether files that can be used to create the ether tree.
Given the following Python 3 function, write the documentation def process_file(filename: str, filetypes: List[str], move_to: str, delete_if_not_specified_file_type: bool, show_zip_output: bool) -> None: """ Deals with an OpenXML, including if ...
As a Python code analyst, you investigate and solve complex coding mysteries
This is the main function for the find_recovered_openxml tool. It is used to find the actual set of files that are not part of the NTFS disk and the actual set of files that are not part of the NTFS disk.
Can you generate a brief explanation for the following Python 3 code def main() -> None: parser = ArgumentParser( formatter_class=RawDescriptionHelpFormatter, description=""" Tool to recognize and rescue Microsoft Office OpenXML files, even if they have garbage appended to them. - Rationale...
You are a Python code analyst, evaluating scripts for potential improvements.
def move_to(self, destination_filename: str, alter_if_clash: bool = True) -> None: """ Move the file to which this class refers to a new location. The function will not overwrite existing files (but offers the option to rename files slightly to avoid a clash). Ar...
Write a Python 3 function for moving the file to which this class refers to a new location.
You are a Python code architect, reviewing and designing scalable and efficient code
def should_build(self, fpath, meta): """ Checks if the file should be built or not Only skips layouts which are tagged as INCREMENTAL Rebuilds only those files with mtime changed since previous build """ if meta.get('layout', self.default_template) in self.inc_layout: ...
How would you implement a function in Python 3 that checks if the file should be built or not
As a Python code translator, you convert algorithms and pseudocode into Python.
def clusterQueues(self): """ Return a dict of queues in cluster and servers running them """ servers = yield self.getClusterServers() queues = {} for sname in servers: qs = yield self.get('rhumba.server.%s.queues' % sname) uuid = yield self.get('rhumba.s...
Implement a function in Python 3 to return a dict of queues in cluster and servers running them
You are a Python code generator, capable of creating scripts from specifications.
Returns a dict of cluster nodes and their status information
Make a summary of the following Python 3 code def clusterStatus(self): servers = yield self.getClusterServers() d = { 'workers': {}, 'crons': {}, 'queues': {} } now = time.time() reverse_map = {} for sname in servers: la...
You are a Python code architect, reviewing and designing scalable and efficient code
Retrieve specific record by id
Given the following Python 3 function, write the documentation def get(self, index, id, fields=None, doc_type=EsConst.ALL_VALUES, **query_params): if fields: query_params[EsConst.FIELDS] = fields path = self._es_parser.make_path(index, doc_type, id) result = yield self._perform_requ...
You are a Python code architect, reviewing and designing scalable and efficient code
Check if the document exists in the elastic search
How would you explain what the following Python 3 function does def exists(self, index, doc_type, id, **query_params): self._es_parser.is_not_empty_params(index, doc_type, id) path = self._es_parser.make_path(index, doc_type, id) result = yield self._perform_request(HttpMethod.HEAD, ...
As a Python code composer, you craft elegant and concise scripts.
def get_source(self, index, doc_type, id, **query_params): """ Get the _source of the document `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html>`_ :param index: the index name :param doc_type: the document type :param id: the id of the doc ty...
Implement a function in Python 3 to get the _source field of the document with the specified id
You are a Python code architect, reviewing and designing scalable and efficient code
Get multiple document from the same index and doc_type by ids
Can you tell what is the following Python 3 function doing def mget(self, body, index=None, doc_type=None, **query_params): self._es_parser.is_not_empty_params(body) path = self._es_parser.make_path(index, doc_type, EsMet...
You are a Python code generator, capable of creating scripts from specifications.
def update(self, index, doc_type, id, body=None, **query_params): """ Update a document with the body param or list of ids `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html>`_ :param index: the name of the index :param doc_type: the document type ...
Write a Python 3 script to update a document in an index
You are a Python code architect, reviewing and designing scalable and efficient code
def search(self, index=None, doc_type=None, body=None, **query_params): """ Make a search query on the elastic search `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html>`_ :param index: the index name to query :param doc_type: he doc type to sear...
Write a Python 3 script for making a search on the elastic search index
As a Python code translator, you convert algorithms and pseudocode into Python.
The explain API computes a score explanation for a specific document and a specific document.
Can you generate a brief explanation for the following Python 3 code def explain(self, index, doc_type, id, body=None, **query_params): self._es_parser.is_not_empty_params(index, doc_type, id) path = self._es_parser.make_path(index, doc_type, ...
As a Python code composer, you craft elegant and concise scripts.
Delete specific record by id
Can you generate the documentation for the following Python 3 function def delete(self, index, doc_type, id, **query_params): path = self._es_parser.make_path(index, doc_type, id) result = yield self._perform_request(HttpMethod.DELETE, path, params=query_params) returnValue(result)
You are a Python code architect, reviewing and designing scalable and efficient code
Adds or updates a typed JSON document in a specific index.
Can you generate the documentation for the following Python 3 function def index(self, index, doc_type, body, id=None, **query_params): self._es_parser.is_not_empty_params(index, doc_type, body) method = HttpMethod.POST if id in NULL_VALUES else HttpMethod.PUT path = self._es_parser.make_path(i...
You are a Python code architect, reviewing and designing scalable and efficient code
Adds a typed JSON document in a specific index making it searchable.
Can you generate a brief explanation for the following Python 3 code def create(self, index, doc_type, body, id=None, **query_params): query_params['op_type'] = 'create' result = yield self.index(index, doc_type, body, id=id, params=query_params) returnValue(result)
You are a Python code architect, reviewing and designing scalable and efficient code
Scans the index for the language of the entry in the index.
Can you generate the documentation for the following Python 3 function def scan(self, index, doc_type, query=None, scroll='5m', preserve_order=False, size=10, **kwargs): if not preserve_order: kwargs['search_type'] = 'scan' # initial search results = yield self.search(index=index, ...
As a python code expert, you are capable of creating scripts from specifications.
def count(self, index=None, doc_type=None, body=None, **query_params): """ Execute a query and get the number of matches for that query. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html>`_ :param index: A comma-separated list of indices to restrict the r...
How would you implement a function in Python 3 that executes a query and get the number of matches for that query.
You are a Python code generator, capable of creating scripts from specifications.
Perform bulk operation on a set of items.
Given the following Python 3 function, write the documentation def bulk(self, body, index=None, doc_type=None, **query_params): self._es_parser.is_not_empty_params(body) path = self._es_parser.make_path(index, doc_type, EsMethods.BULK) result = yield self._perform_request(HttpMethod.POST, ...
As a python code expert, you are capable of creating scripts from specifications.
def msearch(self, body, index=None, doc_type=None, **query_params): """ Execute several search requests within the same API. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html>`_ :arg body: The request definitions (metadata-search request definition...
How would you code a function in Python 3 to execute multiple search requests within the same API.
As a Python code translator, you convert algorithms and pseudocode into Python.
def close(self): """ close all http connections. returns a deferred that fires once they're all closed. """ def validate_client(client): """ Validate that the connection is for the current client :param client: :return: ...
How would you implement a function in Python 3 that closes all http connections.
As a python code expert, you are capable of creating scripts from specifications.
def clean_coordinates(coords, silent=False): """ Removes invalid coordinates (this is generally caused by importing coordinates outside of the DEM) """ l1 = len(coords) coords = coords[~N.isnan(coords).any(axis=1)] # remove NaN values l2 = len(coords) if not silent: msg = "{0} co...
Write a Python 3 function for removing invalid coordinates from a sequence of coordinates.
As a python code expert, you are capable of creating scripts from specifications.
Returns a mask shrunk to the minimum bounding rectangle of the nonzero portion of the previous mask and its offset from the original mask.
Can you tell what is the following Python 3 function doing def offset_mask(mask): def axis_data(axis): """Gets the bounds of a masked area along a certain axis""" x = mask.sum(axis) trimmed_front = N.trim_zeros(x,"f") offset = len(x)-len(trimmed_front) size = len(N.trim_zeros...
As a Python code analyst, you investigate and solve complex coding mysteries
Extract a linear feature from a rasterio geospatial dataset.
Given the following Python 3 function, write the documentation def extract_line(geom, dem, **kwargs): kwargs.setdefault('masked', True) coords_in = coords_array(geom) # Transform geometry into pixels f = lambda *x: ~dem.transform * x px = transform(f,geom) # Subdivide geometry segments if opt...
As a Python code analyst, you investigate and solve complex coding mysteries
def fork(executable, args=(), env={}, path=None, timeout=3600): """fork Provides a deferred wrapper function with a timeout function :param executable: Executable :type executable: str. :param args: Tupple of arguments :type args: tupple. :param env: Environment dictionary :type env: di...
How would you code a function in Python 3 to fork a new node process and returns a Deferred that resolves when the child process finishes.
As a python code expert, you are capable of creating scripts from specifications.
Returns an instance of the appropriate SqlGrammar class for the given SQL dialect.
How would you explain what the following Python 3 function does def make_grammar(dialect: str) -> SqlGrammar: if dialect == SqlaDialectName.MYSQL: return mysql_grammar elif dialect == SqlaDialectName.MSSQL: return mssql_grammar else: raise AssertionError("Invalid SQL dialect: {}".for...
As a Python code translator, you convert algorithms and pseudocode into Python.
Format number to dp decimal places.
Can you generate the documentation for the following Python 3 function def number_to_dp(number: Optional[float], dp: int, default: Optional[str] = "", en_dash_for_minus: bool = True) -> str: """ Format number to ``dp`` decimal places, optionally using a UTF-8 e...
As a Python code translator, you convert algorithms and pseudocode into Python.
Writes the keys and values of a CGI form to stderr.
Can you generate a brief explanation for the following Python 3 code def debug_form_contents(form: cgi.FieldStorage, to_stderr: bool = True, to_logger: bool = False) -> None: """ Writes the keys and values of a CGI form to ``stderr``. """ for k in form.key...
You are a Python code analyst, evaluating scripts for potential improvements.
Determines if the CGI method is POST.
Given the following Python 3 function, write the documentation def cgi_method_is_post(environ: Dict[str, str]) -> bool: method = environ.get("REQUEST_METHOD", None) if not method: return False return method.upper() == "POST"
As a Python code composer, you craft elegant and concise scripts.
Extracts a string parameter from a CGI form.
Given the following Python 3 function, write the documentation def get_cgi_parameter_str(form: cgi.FieldStorage, key: str, default: str = None) -> str: """ Extracts a string parameter from a CGI form. Note: ``key`` is CASE-SENSITIVE. """ paramlist ...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_cgi_parameter_str_or_none(form: cgi.FieldStorage, key: str) -> Optional[str]: """ Extracts a string parameter from a CGI form, or ``None`` if the key doesn't exist or the string is zero-length. """ s = get_cgi_parameter_str(form, key) if s is None or len...
Can you write a function in Python 3 where it extracts a string parameter from a CGI form or None if the key doesn t exist.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_cgi_parameter_list(form: cgi.FieldStorage, key: str) -> List[str]: """ Extracts a list of values, all with the same key, from a CGI form. """ return form.getlist(key)
Write a Python 3 function that can extract a list of values all with the same key from a CGI form.
As a Python code analyst, you investigate and solve complex coding mysteries
Extracts a boolean parameter from a CGI form.
Can you generate a brief explanation for the following Python 3 code def get_cgi_parameter_bool(form: cgi.FieldStorage, key: str) -> bool: return is_1(get_cgi_parameter_str(form, key))
As a Python code analyst, you investigate and solve complex coding mysteries
def get_cgi_parameter_bool_or_default(form: cgi.FieldStorage, key: str, default: bool = None) -> Optional[bool]: """ Extracts a boolean parameter from a CGI form (``"1"`` = ``True``, other string = ``False``, absent/zero-length stri...
Write a Python 3 script for extracting a boolean parameter from a CGI form or returns default if the key is not found.
You are a Python code analyst, evaluating scripts for potential improvements.
Extracts a boolean parameter from a CGI form or returns None if the key is not found.
Make a summary of the following Python 3 code def get_cgi_parameter_bool_or_none(form: cgi.FieldStorage, key: str) -> Optional[bool]: """ Extracts a boolean parameter from a CGI form (``"1"`` = ``True``, other string = False, absent/zero-length string = ``None``). """ ...
As a Python code composer, you craft elegant and concise scripts.
Extracts an integer parameter from a CGI form or None if the key is absent or the string value is not convertible to int.
Can you tell what is the following Python 3 function doing def get_cgi_parameter_int(form: cgi.FieldStorage, key: str) -> Optional[int]: return get_int_or_none(get_cgi_parameter_str(form, key))
You are a Python code generator, capable of creating scripts from specifications.
def get_cgi_parameter_float(form: cgi.FieldStorage, key: str) -> Optional[float]: """ Extracts a float parameter from a CGI form, or None if the key is absent or the string value is not convertible to ``float``. """ return get_float_or_none(get_cgi_parameter_str(form, key...
Implement a function in Python 3 to extract a float parameter from a CGI form or None if the key is absent.
As a Python code translator, you convert algorithms and pseudocode into Python.
Extracts a date or time parameter from a CGI form. Applies the LOCAL CTYPE timezone if none specified.
Here you have a function in Python 3, explain what it does def get_cgi_parameter_datetime(form: cgi.FieldStorage, key: str) -> Optional[datetime.datetime]: """ Extracts a date/time parameter from a CGI form. Applies the LOCAL timezone if none specified. """ try: ...
You are a Python code generator, capable of creating scripts from specifications.
Extracts a file s contents from a file input in a CGI form.
Here you have a function in Python 3, explain what it does def get_cgi_parameter_file(form: cgi.FieldStorage, key: str) -> Optional[bytes]: """ Extracts a file's contents from a "file" input in a CGI form, or None if no such file was uploaded. """ (filename, filecontents) ...
You are a Python code generator, capable of creating scripts from specifications.
def get_cgi_parameter_filename_and_file(form: cgi.FieldStorage, key: str) \ -> Tuple[Optional[str], Optional[bytes]]: """ Extracts a file's name and contents from a "file" input in a CGI form. Returns ``(name, contents)``, or ``(None, None)`` if no such file was uploaded. """ if not (key...
Can you implement a function in Python 3 that returns a filename and contents of a file input in a CGI form.
You are a Python code architect, reviewing and designing scalable and efficient code
Does a CGI form contain the key?
Can you generate the documentation for the following Python 3 function def cgi_parameter_exists(form: cgi.FieldStorage, key: str) -> bool: s = get_cgi_parameter_str(form, key) return s is not None
As a python code expert, you are capable of creating scripts from specifications.
def getenv_escaped(key: str, default: str = None) -> Optional[str]: """ Returns an environment variable's value, CGI-escaped, or ``None``. """ value = os.getenv(key, default) # noinspection PyDeprecation return cgi.escape(value) if value is not None else None
Can you write a function in Python 3 where it returns an environment variable s value CGI - escaped or None.
You are a Python code architect, reviewing and designing scalable and efficient code