output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Flip the mesh across the given axis.
Can you generate the documentation for the following Python 3 function def flip(self, axis=0, preserve_centroid=False): ''' Flip the mesh across the given axis: 0 for x, 1 for y, 2 for z. When `preserve_centroid` is True, translate after flipping to preserve the location of the centroid...
As a Python code analyst, you investigate and solve complex coding mysteries
Return the geometric center of the mesh.
Explain what the following Python 3 code does def centroid(self): ''' Return the geometric center. ''' if self.v is None: raise ValueError('Mesh has no vertices; centroid is not defined') return np.mean(self.v, axis=0)
As a Python code translator, you convert algorithms and pseudocode into Python.
def floor_point(self): ''' Return the point on the floor that lies below the centroid. ''' floor_point = self.centroid # y to floor floor_point[1] = self.v[:, 1].min() return floor_point
Write a Python 3 script for returning the point on the floor that lies below the centroid.
You are a Python code generator, capable of creating scripts from specifications.
Return the most extreme vertex in the direction of the axis provided.
How would you explain what the following Python 3 function does def apex(self, axis): ''' Find the most extreme vertex in the direction of the axis provided. axis: A vector, which is an 3x1 np.array. ''' from blmath.geometry.apex import apex return apex(self.v, axis)
As a python code expert, you are capable of creating scripts from specifications.
def first_blip(self, squash_axis, origin, initial_direction): ''' Flatten the mesh to the plane, dropping the dimension identified by `squash_axis`: 0 for x, 1 for y, 2 for z. Cast a ray from `origin`, pointing along `initial_direction`. Sweep the ray, like a radar, until encount...
Can you implement a function in Python 3 that returns the first blip of a set of nodes in the mesh.
You are a Python code analyst, evaluating scripts for potential improvements.
Cut the mesh by a plane discarding vertices that lie behind that plane or discarding vertices that lie outside that plane.
Given the following Python 3 function, write the documentation def cut_across_axis(self, dim, minval=None, maxval=None): ''' Cut the mesh by a plane, discarding vertices that lie behind that plane. Or cut the mesh by two parallel planes, discarding vertices that lie outside them. ...
You are a Python code architect, reviewing and designing scalable and efficient code
def cut_across_axis_by_percentile(self, dim, minpct=0, maxpct=100): ''' Like cut_across_axis, except the subset of vertices is constrained by percentile of the data along a given axis instead of specific values. (See numpy.percentile.) For example, if the mesh has 50,000 vertice...
Write a Python 3 script for liking cut_across_axis except the subset of vertices isisolate by percentile of the data along a given axis.
You are a Python code analyst, evaluating scripts for potential improvements.
Like cut_across_axis but works with an arbitrary plane.
Here you have a function in Python 3, explain what it does def cut_by_plane(self, plane, inverted=False): ''' Like cut_across_axis, but works with an arbitrary plane. Keeps vertices that lie in front of the plane (i.e. in the direction of the plane normal). inverted: When `True`...
You are a Python code generator, capable of creating scripts from specifications.
def purge_items(app, env, docname): """ Clean, if existing, ``item`` entries in ``traceability_all_items`` environment variable, for all the source docs being purged. This function should be triggered upon ``env-purge-doc`` event. """ keys = list(env.traceability_all_items.keys()) for key ...
Write a Python 3 function that can purge items from the traceability_all_items environment variable.
As a Python code translator, you convert algorithms and pseudocode into Python.
Process all item nodes in the item_list nodes.
Given the following Python 3 function, write the documentation def process_item_nodes(app, doctree, fromdocname): env = app.builder.env all_items = sorted(env.traceability_all_items, key=naturalsortkey) # Item matrix: # Create table with related items, printing their target references. # Only sour...
As a Python code translator, you convert algorithms and pseudocode into Python.
Update the option_spec with custom relationships defined in the application configuration file.
Explain what the following Python 3 code does def update_available_item_relationships(app): env = app.builder.env env.relationships = {} for rel in list(app.config.traceability_relationships.keys()): env.relationships[rel] = app.config.traceability_relationships[rel] env.relationships[app.c...
As a python code expert, you are capable of creating scripts from specifications.
Initialize the environment variables needed before the build process starts.
How would you explain what the following Python 3 function does def initialize_environment(app): env = app.builder.env # Assure ``traceability_all_items`` will always be there. if not hasattr(env, 'traceability_all_items'): env.traceability_all_items = {} update_available_item_relationships(ap...
You are a Python code analyst, evaluating scripts for potential improvements.
def make_item_ref(app, env, fromdocname, item_info): """ Creates a reference node for an item, embedded in a paragraph. Reference text adds also a caption if it exists. """ id = item_info['target']['refid'] if item_info['caption'] != '': caption = ', ' + item_info['caption'] else: ...
Write a Python 3 script to create a reference node for an item.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns True if source and target items are related to the given list of relationships.
How would you explain what the following Python 3 function does def are_related(env, source, target, relationships): if not relationships: relationships = list(env.relationships.keys()) for rel in relationships: if (target in env.traceability_all_items[source][rel] or source in ...
As a python code expert, you are capable of creating scripts from specifications.
def MeshViewer( titlebar='Mesh Viewer', static_meshes=None, static_lines=None, uid=None, autorecenter=True, keepalive=False, window_width=1280, window_height=960, snapshot_camera=None ): """Allows visual inspection of geometric primitives. Write-only Attributes: titlebar: string...
Create a Python 3 function to allow visual inspection of geometric primitives.
As a python code expert, you are capable of creating scripts from specifications.
def MeshViewers( shape=(1, 1), titlebar="Mesh Viewers", keepalive=False, window_width=1280, window_height=960 ): """Allows subplot-style inspection of primitives in multiple subwindows. Args: shape: a tuple indicating the number of vertical and horizontal windows requested Returns:...
Implement a function in Python 3 to allow subplot - style inspection of primitives in multiple subwindows.
As a Python code composer, you craft elegant and concise scripts.
def on_drag(self, cursor_x, cursor_y): """ Mouse cursor is moving Glut calls this function (when mouse button is down) and pases the mouse cursor postion in window coords as the mouse moves. """ from blmath.geometry.transform.rodrigues import as_rotation_matrix if...
Write a Python 3 script to handle mouse drag events for the current object.
As a Python code composer, you craft elegant and concise scripts.
Called by the mouse button click event handler.
Here you have a function in Python 3, explain what it does def on_click(self, button, button_state, cursor_x, cursor_y): self.isdragging = False if button == glut.GLUT_LEFT_BUTTON and button_state == glut.GLUT_UP: # Left button released self.lastrot = copy.copy(self.thisrot) # S...
You are a Python code analyst, evaluating scripts for potential improvements.
def _compute_cell_circumcenters(self): """Computes the center of the circumsphere of each cell. """ # Just like for triangular cells, tetrahedron circumcenters are most easily # computed with the quadrilateral coordinates available. # Luckily, we have the circumcenter-face distan...
Create a Python 3 function to compute the center of the circumsphere of each cell.
You are a Python code architect, reviewing and designing scalable and efficient code
def control_volumes(self): """Compute the control volumes of all nodes in the mesh. """ if self._control_volumes is None: # 1/3. * (0.5 * edge_length) * covolume # = 1/6 * edge_length**2 * ce_ratio_edge_ratio v = self.ei_dot_ei * self.ce_ratios / 6.0 ...
Create a Python 3 function for computing the control volumes of all nodes in the mesh.
You are a Python code generator, capable of creating scripts from specifications.
def show_edge(self, edge_id): """Displays edge with ce_ratio. :param edge_id: Edge ID for which to show the ce_ratio. :type edge_id: int """ # pylint: disable=unused-variable,relative-import from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as...
How would you implement a function in Python 3 that displays the edge with ce_ratio.
You are a Python code analyst, evaluating scripts for potential improvements.
Try to extract an integer from a string return the fallback if that s not possible.
Make a summary of the following Python 3 code def parse_int(text, fallback=None): try: if isinstance(text, six.integer_types): return text elif isinstance(text, six.string_types): return int(text) else: return fallback except ValueError: return...
You are a Python code architect, reviewing and designing scalable and efficient code
def _load_table(self, name): """ Reflect a given table from the database. """ table = self._tables.get(name, None) if table is not None: return table if not self.engine.has_table(name): raise BindingException('Table does not exist: %r' % name, ...
Implement a function in Python 3 to reflect a given table from the database.
As a Python code translator, you convert algorithms and pseudocode into Python.
def fact_pk(self): """ Try to determine the primary key of the fact table for use in fact table counting. If more than one column exists, return the first column of the pk. """ keys = [c for c in self.fact_table.columns if c.primary_key] return keys[0]
Write a Python 3 function for returning the primary key of the fact table for use in fact table counting.
You are a Python code architect, reviewing and designing scalable and efficient code
List all the distinct members of the given reference filtered and paginated.
Can you generate the documentation for the following Python 3 function def members(self, ref, cuts=None, order=None, page=None, page_size=None): def prep(cuts, ref, order, columns=None): q = select(columns=columns) bindings = [] cuts, q, bindings = Cuts(self).apply(q, binding...
You are a Python code analyst, evaluating scripts for potential improvements.
List all facts in the cube returning only the specified references if these are specified.
Can you generate a brief explanation for the following Python 3 code def facts(self, fields=None, cuts=None, order=None, page=None, page_size=None, page_max=None): """ List all facts in the cube, returning only the specified references if these are specified. """ def prep(cuts, co...
As a Python code composer, you craft elegant and concise scripts.
This method will count the number of distinct values for each in and add that count to the model.
Can you tell what is the following Python 3 function doing def compute_cardinalities(self): for dimension in self.model.dimensions: result = self.members(dimension.ref, page_size=0) dimension.spec['cardinality'] = result.get('total_member_count')
As a Python code composer, you craft elegant and concise scripts.
def restrict_joins(self, q, bindings): """ Restrict the joins across all tables referenced in the database query to those specified in the model for the relevant dimensions. If a single table is used for the query, no unnecessary joins are performed. If more than one table are re...
Create a Python 3 function to restrict joins across all tables referenced in the database to those specified in the model.
As a Python code analyst, you investigate and solve complex coding mysteries
def order_manually(sub_commands): """Order sub-commands for display""" order = [ "start", "projects", ] ordered = [] commands = dict(zip([cmd for cmd in sub_commands], sub_commands)) for k in order: ordered.append(commands.get(k, "")) if k in commands: ...
Can you implement a function in Python 3 that orders sub - commands for display.
You are a Python code analyst, evaluating scripts for potential improvements.
Format the help string.
How would you explain what the following Python 3 function does def format_help(help): help = help.replace('Options:', str(crayons.black('Options:', bold=True))) help = help.replace('Usage: pinax', str('Usage: {0}'.format(crayons.black('pinax', bold=True)))) help = help.replace(' start', str(crayons.gree...
As a Python code analyst, you investigate and solve complex coding mysteries
Return all existing concepts i. e. dimensions measures and aggregate and their attributes within the model.
Given the following Python 3 function, write the documentation def concepts(self): for measure in self.measures: yield measure for aggregate in self.aggregates: yield aggregate for dimension in self.dimensions: yield dimension for attribute in dime...
As a Python code translator, you convert algorithms and pseudocode into Python.
def match(self, ref): """ Get all concepts matching this ref. For a dimension, that is all its attributes, but not the dimension itself. """ try: concept = self[ref] if not isinstance(concept, Dimension): return [concept] return [a for a in con...
Implement a Python 3 function for getting all concepts matching this ref. For a dimension that is all its attributes but not the dimension itself. For a dimension that is all its attributes but not the dimension itself. For a dimension that is all its attributes but not the dimension itself.
As a Python code translator, you convert algorithms and pseudocode into Python.
Serializes a dictionary of points to a 3 - dimensional array.
Given the following Python 3 function, write the documentation def dumps(obj, mesh_filename=None, *args, **kwargs): # pylint: disable=unused-argument ''' obj: A dictionary mapping names to a 3-dimension array. mesh_filename: If provided, this value is included in the <DataFileName> attribute, which Me...
You are a Python code generator, capable of creating scripts from specifications.
Sets the landmarks given a set of landmarks given any of the keys in val.
Explain what the following Python 3 code does def landm(self, val): ''' Sets landmarks given any of: - ppfile - ldmk file - dict of {name:inds} (i.e. mesh.landm) - dict of {name:xyz} (i.e. mesh.landm_xyz) - Nx1 array or list of ints (treated as landm, given s...
As a Python code composer, you craft elegant and concise scripts.
def add(self, lineitem): """ Add a line item record to this Costs object. """ # Check for a ProductName in the lineitem. # If its not there, it is a subtotal line and including it # will throw the total cost calculation off. So ignore it. if lineitem['ProductName...
How would you code a function in Python 3 to add a line item record to this Costs object.
You are a Python code architect, reviewing and designing scalable and efficient code
def filter(self, filters): """ Pass in a list of tuples where each tuple represents one filter. The first element of the tuple is the name of the column to filter on and the second value is a regular expression which each value in that column will be compared against. If the ...
Write a Python 3 function for returning a new Costs object with only the entries that match the given filters.
As a Python code composer, you craft elegant and concise scripts.
def query(self, query, args=None): """ Execute the passed in query against the database @param query: MySQL Query to execute. %s or %(key)s will be replaced by parameter args sequence @param args: Sequence of value to replace in your query. A mapping may also be used but your query must use %(key)s @author...
Implement a function in Python 3 to execute a MySQL query against the database and store the result in the object store.
As a Python code translator, you convert algorithms and pseudocode into Python.
def queryOne(self, query, args=None): """ Execute the passed in query against the database. Uses a Generator & fetchone to reduce your process memory size. @param query: MySQL Query to execute. %s or %(key)s will be replaced by parameter args sequence @param args: Sequence of value to replace in your quer...
Write a Python 3 script to execute a MySQL query against the database.
You are a Python code generator, capable of creating scripts from specifications.
def queryMany(self, query, args): """ Executes a series of the same Insert Statments Each tuple in the args list will be applied to the query and executed. This is the equivilant of MySQLDB.cursor.executemany() @author: Nick Verbeck @since: 9/7/2008 """ self.lastError = None self.affectedRows = ...
Write a Python 3 script to execute a series of the same Insert Statments Each tuple in the args list will be applied to the query and executed.
You are a Python code generator, capable of creating scripts from specifications.
def queryMulti(self, queries): """ Execute a series of Deletes,Inserts, & Updates in the Queires List @author: Nick Verbeck @since: 9/7/2008 """ self.lastError = None self.affectedRows = 0 self.rowcount = None self.record = None cursor = None try: try: self._GetConnection() #Execu...
Create a Python 3 function for executing a series of Delete Inserts & Updates in the Queires list.
As a Python code analyst, you investigate and solve complex coding mysteries
Get a prelocked connection from the Pool.
Explain what the following Python 3 code does def _GetConnection(self): #Attempt to get a connection. If all connections are in use and we have reached the max number of connections, #we wait 1 second and try again. #The Connection is returned locked to be thread safe while self.conn is None: self.conn = Poo...
You are a Python code analyst, evaluating scripts for potential improvements.
def _ReturnConnection(self): """ Returns a connection back to the pool @author: Nick Verbeck @since: 9/7/2008 """ if self.conn is not None: if self.connInfo.commitOnEnd is True or self.commitOnEnd is True: self.conn.Commit() Pool().returnConnection(self.conn) self.conn = None
Implement a function in Python 3 to return a connection back to the pool Pool.
You are a Python code analyst, evaluating scripts for potential improvements.
def bind(self, cube): """ When one column needs to match, use the key. """ if self.measure: table, column = self.measure.bind(cube) else: table, column = cube.fact_table, cube.fact_pk # apply the SQL aggregation function: column = getattr(func, self.functi...
Can you write a function in Python 3 where it binds the fact table and column to the key.
As a python code expert, you are capable of creating scripts from specifications.
Retrieve the public key from the Travis API.
Explain what the following Python 3 code does def retrieve_public_key(user_repo): url = 'https://api.travis-ci.org/repos/{}/key' .format(user_repo) response = requests.get(url) try: return response.json()['key'].replace(' RSA ', ' ') except KeyError: username, repository = user_repo.spl...
You are a Python code generator, capable of creating scripts from specifications.
Encrypt the password with the public key and return an ASCII representation.
Explain what the following Python 3 code does def encrypt_key(key, password): public_key = load_pem_public_key(key.encode(), default_backend()) encrypted_password = public_key.encrypt(password, PKCS1v15()) return base64.b64encode(encrypted_password).decode('ascii')
As a Python code analyst, you investigate and solve complex coding mysteries
Dump the configuration settings into the travis. yml file.
Given the following Python 3 function, write the documentation def dump_travis_configuration(config, path): with open(path, 'w') as config_file: ordered_dump(config, config_file, default_flow_style=False)
You are a Python code generator, capable of creating scripts from specifications.
Load the texture from the file.
Can you generate a brief explanation for the following Python 3 code def load_texture(self, texture_version): ''' Expect a texture version number as an integer, load the texture version from /is/ps/shared/data/body/template/texture_coordinates/. Currently there are versions [0, 1, 2, 3] availiab...
You are a Python code architect, reviewing and designing scalable and efficient code
Show latest distribution section.
Given the following Python 3 function, write the documentation def show_distribution_section(config, title, section_name): payload = requests.get(config.apps_url).json() distributions = sorted(payload.keys(), reverse=True) latest_distribution = payload[distributions[0]] click.echo("{} {}".format("Releas...
You are a Python code generator, capable of creating scripts from specifications.
Verify that Django 1. 11 is present and that Python 2. 7 is active.
Can you tell what is the following Python 3 function doing def validate_django_compatible_with_python(): python_version = sys.version[:5] django_version = django.get_version() if sys.version_info == (2, 7) and django_version >= "2": click.BadArgumentUsage("Please install Django v1.11 for Python {}, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def list_commands(self, ctx): """Override for showing commands in particular order""" commands = super(PinaxGroup, self).list_commands(ctx) return [cmd for cmd in order_manually(commands)]
Can you create a Python 3 function that overrides for showing commands in particular order
As a python code expert, you are capable of creating scripts from specifications.
def all_edges_with_verts(self, v_indices, as_boolean=False): ''' returns all of the faces that contain at least one of the vertices in v_indices ''' included_vertices = np.zeros(self.v.shape[0], dtype=bool) included_vertices[v_indices] = True edges_with_verts = included_v...
Write a Python 3 function that can return all of the faces that contain at least one of the vertices in v_indices.
As a python code expert, you are capable of creating scripts from specifications.
Keep the given vertices and discard the others and any edges to which they may belong.
Can you generate a brief explanation for the following Python 3 code def keep_vertices(self, indices_to_keep, ret_kept_edges=False): ''' Keep the given vertices and discard the others, and any edges to which they may belong. If `ret_kept_edges` is `True`, return the original indices of...
You are a Python code generator, capable of creating scripts from specifications.
Reads an unstructured mesh with added data.
Given the following Python 3 function, write the documentation def read(filename): mesh = meshio.read(filename) # make sure to include the used nodes only if "tetra" in mesh.cells: points, cells = _sanitize(mesh.points, mesh.cells["tetra"]) return ( MeshTetra(points, cells), ...
As a python code expert, you are capable of creating scripts from specifications.
Lock connection from being used else where
Explain what the following Python 3 code does def lock(self, block=True): self._locked = True return self._lock.acquire(block)
You are a Python code architect, reviewing and designing scalable and efficient code
def release(self): """ Release the connection lock """ if self._locked is True: self._locked = False self._lock.release()
Write a Python 3 script to release the connection lock.
You are a Python code architect, reviewing and designing scalable and efficient code
Get a Dictionary Cursor for executing queries
Can you generate a brief explanation for the following Python 3 code def getCursor(self): if self.connection is None: self.Connect() return self.connection.cursor(MySQLdb.cursors.DictCursor)
As a python code expert, you are capable of creating scripts from specifications.
def Connect(self): """ Creates a new physical connection to the database @author: Nick Verbeck @since: 5/12/2008 """ if self.connection is None: self.connection = MySQLdb.connect(*[], **self.connectionInfo.info) if self.connectionInfo.commitOnEnd is True: self.connection.autocommit() se...
Write a Python 3 function for creating a new physical connection to the database and updates the check time.
As a Python code composer, you craft elegant and concise scripts.
def being(self): """ Being a Transaction @author: Nick Verbeck @since: 5/14/2011 """ try: if self.connection is not None: self.lock() c = self.getCursor() c.execute('BEGIN;') c.close() except Exception, e: pass
Write a Python 3 function for being a Transaction @author: Nick Verbeck @since: 5/14/2011
As a python code expert, you are capable of creating scripts from specifications.
Commits the current transaction to the database.
Can you generate a brief explanation for the following Python 3 code def commit(self): try: if self.connection is not None: self.connection.commit() self._updateCheckTime() self.release() except Exception, e: pass
As a Python code composer, you craft elegant and concise scripts.
def rollback(self): """ Rollback MySQL Transaction to database. MySQLDB: If the database and tables support transactions, this rolls back (cancels) the current transaction; otherwise a NotSupportedError is raised. @author: Nick Verbeck @since: 5/12/2008 """ try: if self.connection is not None:...
Write a Python 3 function for rolling back the current transaction to the database.
As a Python code analyst, you investigate and solve complex coding mysteries
Closes the current connection.
Can you generate a brief explanation for the following Python 3 code def Close(self): if self.connection is not None: try: self.connection.commit() self.connection.close() self.connection = None except Exception, e: pass
As a Python code composer, you craft elegant and concise scripts.
Configure the current Flask app with an instance of cubemanager.
Here you have a function in Python 3, explain what it does def configure_api(app, manager): if not hasattr(app, 'extensions'): app.extensions = {} # pragma: nocover app.extensions['babbage'] = manager return blueprint
You are a Python code generator, capable of creating scripts from specifications.
Load the named cube from the current registered cube manager.
Given the following Python 3 function, write the documentation def get_cube(name): manager = get_manager() if not manager.has_cube(name): raise NotFound('No such cube: %r' % name) return manager.get_cube(name)
As a Python code composer, you craft elegant and concise scripts.
Get a listing of all publicly available cubes.
How would you explain what the following Python 3 function does def cubes(): cubes = [] for cube in get_manager().list_cubes(): cubes.append({ 'name': cube }) return jsonify({ 'status': 'ok', 'data': cubes })
As a Python code composer, you craft elegant and concise scripts.
def aggregate(name): """ Perform an aggregation request. """ cube = get_cube(name) result = cube.aggregate(aggregates=request.args.get('aggregates'), drilldowns=request.args.get('drilldown'), cuts=request.args.get('cut'), or...
Write a Python 3 function that can perform an aggregation request.
You are a Python code architect, reviewing and designing scalable and efficient code
List the fact table entries in the current cube. This is the full materialized dataset.
Can you generate the documentation for the following Python 3 function def facts(name): cube = get_cube(name) result = cube.facts(fields=request.args.get('fields'), cuts=request.args.get('cut'), order=request.args.get('order'), page=request...
As a python code expert, you are capable of creating scripts from specifications.
List the members of a specific dimension or the distinct values of a given attribute.
Can you generate the documentation for the following Python 3 function def members(name, ref): cube = get_cube(name) result = cube.members(ref, cuts=request.args.get('cut'), order=request.args.get('order'), page=request.args.get('page'), ...
As a Python code analyst, you investigate and solve complex coding mysteries
Apply a set of grouping criteria and project them.
Can you generate a brief explanation for the following Python 3 code def apply(self, q, bindings, drilldowns): info = [] for drilldown in self.parse(drilldowns): for attribute in self.cube.model.match(drilldown): info.append(attribute.ref) table, column = attr...
As a Python code translator, you convert algorithms and pseudocode into Python.
def check_attribute_exists(instance): """ Additional check for the dimension model, to ensure that attributes given as the key and label attribute on the dimension exist. """ attributes = instance.get('attributes', {}).keys() if instance.get('key_attribute') not in attributes: return False l...
How would you code a function in Python 3 to check if the attribute exists on the dimension.
As a Python code analyst, you investigate and solve complex coding mysteries
def check_valid_hierarchies(instance): """ Additional check for the hierarchies model, to ensure that levels given are pointing to actual dimensions """ hierarchies = instance.get('hierarchies', {}).values() dimensions = set(instance.get('dimensions', {}).keys()) all_levels = set() for hierarcy ...
Implement a Python 3 function for checking if the hierarchies model is valid.
As a Python code analyst, you investigate and solve complex coding mysteries
def load_validator(name): """ Load the JSON Schema Draft 4 validator with the given name from the local schema directory. """ with open(os.path.join(SCHEMA_PATH, name)) as fh: schema = json.load(fh) Draft4Validator.check_schema(schema) return Draft4Validator(schema, format_checker=checker)
Write a Python 3 script to load the JSON Schema Draft 4 validator with the given name from the local schema directory.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_cube(self, name): """ Given a cube name, construct that cube and return it. Do not overwrite this method unless you need to. """ return Cube(self.get_engine(), name, self.get_cube_model(name))
How would you code a function in Python 3 to give a name construct a cube and return it.
As a Python code translator, you convert algorithms and pseudocode into Python.
List all available JSON files.
Can you generate a brief explanation for the following Python 3 code def list_cubes(self): for file_name in os.listdir(self.directory): if '.' in file_name: name, ext = file_name.rsplit('.', 1) if ext.lower() == 'json': yield name
As a Python code composer, you craft elegant and concise scripts.
This method closes all open connections and commits all queries and closes all the connections.
Given the following Python 3 function, write the documentation def Terminate(self): self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.Close() except Exception: #We may throw exceptions due to already closed...
You are a Python code analyst, evaluating scripts for potential improvements.
Commits all currently open connections.
Can you generate the documentation for the following Python 3 function def Commit(self): self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.commit() conn.release() except Exception: conn.release() ex...
As a Python code composer, you craft elegant and concise scripts.
def GetConnection(self, ConnectionObj): """ Get a Open and active connection Returns a PySQLConnectionManager if one is open else it will create a new one if the max active connections hasn't been hit. If all possible connections are used. Then None is returned. @param PySQLConnectionObj: PySQLConnectio...
Implement a Python 3 function for getting a Open and active connection Returns a PySQLConnectionManager
You are a Python code architect, reviewing and designing scalable and efficient code
def main(): """ Generates code for name_to_rgb dict, assuming an rgb.txt file available (in X11 format).""" import re with open('rgb.txt') as fp: line = fp.readline() while line: reg = re.match(r'\s*(\d+)\s*(\d+)\s*(\d+)\s*(\w.*\w).*', line) if reg: r ...
Create a Python 3 function to generate code for name_to_rgb dict assuming an rgb. txt file available
As a python code expert, you are capable of creating scripts from specifications.
Get statistics for a certain date.
Can you generate the documentation for the following Python 3 function async def on_date(self, date: datetime.date) -> dict: return await self._request( 'get', 'dailystats/{0}'.format(date.strftime('%Y-%m-%d')))
You are a Python code analyst, evaluating scripts for potential improvements.
Return watering statistics for the next 6 days.
Can you generate the documentation for the following Python 3 function async def upcoming(self, details: bool = False) -> list: endpoint = 'dailystats' key = 'DailyStats' if details: endpoint += '/details' key = 'DailyStatsDetails' data = await self._request('get'...
You are a Python code generator, capable of creating scripts from specifications.
def _raise_for_remote_status(url: str, data: dict) -> None: """Raise an error from the remote API if necessary.""" if data.get('errorType') and data['errorType'] > 0: raise_remote_error(data['errorType']) if data.get('statusCode') and data['statusCode'] != 200: raise RequestError( ...
Implement a Python 3 function for raising an error from the remote API if necessary.
As a python code expert, you are capable of creating scripts from specifications.
async def login( host: str, password: str, websession: ClientSession, *, port: int = 8080, ssl: bool = True, request_timeout: int = DEFAULT_TIMEOUT) -> Controller: """Authenticate against a RainMachine device.""" print('regenmaschine.client.login() is depr...
Implement a function in Python 3 to authenticate against a RainMachine device.
As a python code expert, you are capable of creating scripts from specifications.
async def load_local( # pylint: disable=too-many-arguments self, host: str, password: str, port: int = DEFAULT_LOCAL_PORT, ssl: bool = True, skip_existing: bool = True) -> None: """Create a local client.""" controller = LocalContro...
How would you implement a function in Python 3 that creates a local client.
As a Python code analyst, you investigate and solve complex coding mysteries
async def load_remote( self, email: str, password: str, skip_existing: bool = True) -> None: """Create a local client.""" auth_resp = await self._request( 'post', 'https://my.rainmachine.com/login/auth', json={'user': { 'email':...
Write a Python 3 function that can load a remote client.
As a Python code analyst, you investigate and solve complex coding mysteries
async def _request( self, method: str, url: str, *, access_token: str = None, access_token_expiration: datetime = None, headers: dict = None, params: dict = None, json: dict = None, ssl: bool = True) ...
How would you implement a function in Python 3 that makes a request against the RainMachine device.
You are a Python code architect, reviewing and designing scalable and efficient code
Raise the appropriate error with a remote error code.
Given the following Python 3 function, write the documentation def raise_remote_error(error_code: int) -> None: try: error = next((v for k, v in ERROR_CODES.items() if k == error_code)) raise RequestError(error) except StopIteration: raise RequestError( 'Unknown remote error ...
As a python code expert, you are capable of creating scripts from specifications.
def quarter_boundaries(quarter): """Returns first and last day of a quarter Args: quarter (str) quarter, in format '2015Q1' Returns: (tuple) datetime.dates for the first and last days of the quarter """ year, quarter = quarter.split('Q') year = int(year) quarter = int(quarter) ...
Can you write a function in Python 3 where it returns first and last day of a quarter
As a Python code analyst, you investigate and solve complex coding mysteries
Returns metta metadata suitable for a quarter s SOC code classifier matrix
How would you explain what the following Python 3 function does def metta_config(quarter, num_dimensions): first_day, last_day = quarter_boundaries(quarter) return { 'start_time': first_day, 'end_time': last_day, 'prediction_window': 3, # ??? 'label_name': 'onet_soc_code', ...
You are a Python code architect, reviewing and designing scalable and efficient code
Uploads train and test matrices to Metta.
Here you have a function in Python 3, explain what it does def upload_to_metta(train_features_path, train_labels_path, test_features_path, test_labels_path, train_quarter, test_quarter, num_dimensions): train_config = metta_config(train_quarter, num_dimensions) test_config = metta_config(test_quarter, num_dimen...
You are a Python code analyst, evaluating scripts for potential improvements.
Search the dependencies of the specified packages.
Given the following Python 3 function, write the documentation def usedby_packages(self, deps_file_path=None, depslock_file_path=None, packages=None): if deps_file_path is None: deps_file_path = self._deps_path if depslock_file_path is None: depslock_file_path = self._depslock_pa...
As a python code expert, you are capable of creating scripts from specifications.
def upload(s3_conn, filepath, s3_path): """Uploads the given file to s3 Args: s3_conn: (boto.s3.connection) an s3 connection filepath (str) the local filename s3_path (str) the destination path on s3 """ bucket_name, prefix = split_s3_path(s3_path) bucket = s3_conn.get_bucke...
Create a Python 3 function to upload the given file to the s3 object
As a Python code analyst, you investigate and solve complex coding mysteries
Syncs a dictionary to an S3 bucket
Can you generate the documentation for the following Python 3 function def upload_dict(s3_conn, s3_prefix, data_to_sync): bucket_name, prefix = split_s3_path(s3_prefix) bucket = s3_conn.get_bucket(bucket_name) for key, value in data_to_sync.items(): full_name = '{}/{}.json'.format(prefix, key) ...
You are a Python code analyst, evaluating scripts for potential improvements.
Downloads the given s3_path into out_filename.
Can you generate a brief explanation for the following Python 3 code def download(s3_conn, out_filename, s3_path): bucket_name, prefix = split_s3_path(s3_path) bucket = s3_conn.get_bucket(bucket_name) key = boto.s3.key.Key( bucket=bucket, name=prefix ) logging.info('loading from %s i...
As a Python code analyst, you investigate and solve complex coding mysteries
Wrap the generic request method to add access token and expiration.
Can you generate the documentation for the following Python 3 function async def _request( self, method: str, endpoint: str, *, headers: dict = None, params: dict = None, json: dict = None, ssl: bool = True) -> dict: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Authenticate against the device locally.
Can you generate a brief explanation for the following Python 3 code async def login(self, password): auth_resp = await self._client_request( 'post', '{0}/auth/login'.format(self._host), json={ 'pwd': password, 'remember': 1 }) ...
As a Python code analyst, you investigate and solve complex coding mysteries
async def login( self, stage_1_access_token: str, sprinkler_id: str, password: str) -> None: """Authenticate against the device (remotely).""" auth_resp = await self._client_request( 'post', 'https://my.rainmachine.com/devices/login-sprinkler', ...
Create a Python 3 function for authenticating against the device.
As a python code expert, you are capable of creating scripts from specifications.
def set_duplicated_flag(self): """ For all package set flag duplicated, if it's not unique package :return: """ package_by_name = defaultdict(list) for package1 in self._root_package.all_packages: if package1 is None: continue pkg_...
Create a Python 3 function for setting the duplicated flag for all package set flag duplicated
You are a Python code architect, reviewing and designing scalable and efficient code
def get_object_from_string(object_path): """ Return python object from string :param object_path: e.g os.path.join :return: python object """ # split like crosspm.template.GUS => crosspm.template, GUS try: module_name, object_name = object_path.rsplit('.', maxsplit=1) module_...
Implement a function in Python 3 to return python object from string
As a python code expert, you are capable of creating scripts from specifications.
async def _post(self, zone_id: int = None, json: dict = None) -> dict: """Post data to a (non)existing zone.""" return await self._request( 'post', 'zone/{0}/properties'.format(zone_id), json=json)
Can you create a Python 3 function that posts data to a non - existing zone.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return all zones in the system.
Can you generate the documentation for the following Python 3 function async def all( self, *, details: bool = False, include_inactive: bool = False) -> list: """Return all zones (with optional advanced properties).""" endpoint = 'zone' if details: endpoint +=...
You are a Python code architect, reviewing and designing scalable and efficient code
async def get(self, zone_id: int, *, details: bool = False) -> dict: """Return a specific zone.""" endpoint = 'zone/{0}'.format(zone_id) if details: endpoint += '/properties' return await self._request('get', endpoint)
Write a Python 3 function for returning a specific zone.
You are a Python code analyst, evaluating scripts for potential improvements.