output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Time a predicate and returns the time of the wait.
Can you generate a brief explanation for the following Python 3 code def time_wait( predicate, timeout_seconds=120, sleep_seconds=1, ignore_exceptions=True, inverse_predicate=False, noisy=True, required_consecutive_success_count=1): """ waits or spins for a predicate and returns the time...
You are a Python code generator, capable of creating scripts from specifications.
def wait_while_exceptions( predicate, timeout_seconds=120, sleep_seconds=1, noisy=False): """ waits for a predicate, ignoring exceptions, returning the result. Predicate is a function. Exceptions will trigger the sleep and retry; any non-exception result will ...
How would you code a function in Python 3 to wait for a predicate ignoring exceptions and returns the result.
As a Python code composer, you craft elegant and concise scripts.
def pretty_duration(seconds): """ Returns a user-friendly representation of the provided duration in seconds. For example: 62.8 => "1m2.8s", or 129837.8 => "2d12h4m57.8s" """ if seconds is None: return '' ret = '' if seconds >= 86400: ret += '{:.0f}d'.format(int(seconds / 86400))...
Can you implement a function in Python 3 that returns a user - friendly representation of the provided duration in seconds.
As a Python code analyst, you investigate and solve complex coding mysteries
Read configuration options from ~/.shakedown.
How would you explain what the following Python 3 function does def read_config(args): configfile = os.path.expanduser('~/.shakedown') if os.path.isfile(configfile): with open(configfile, 'r') as f: config = toml.loads(f.read()) for key in config: param = key.replace('...
You are a Python code architect, reviewing and designing scalable and efficient code
Set configuration defaults for the available language.
Here you have a function in Python 3, explain what it does def set_config_defaults(args): defaults = { 'fail': 'fast', 'stdout': 'fail' } for key in defaults: if not args[key]: args[key] = defaults[key] return args
As a Python code composer, you craft elegant and concise scripts.
def banner(): """ Display a product banner :return: a delightful Mesosphere logo rendered in unicode :rtype: str """ banner_dict = { 'a0': click.style(chr(9601), fg='magenta'), 'a1': click.style(chr(9601), fg='magenta', bold=True), 'b0': click.style(chr(9616), fg='m...
Write a Python 3 script to display a delightful Mesosphere logo
You are a Python code analyst, evaluating scripts for potential improvements.
Console decoration style definitions for the base class
Make a summary of the following Python 3 code def decorate(text, style): return { 'step-maj': click.style("\n" + '> ' + text, fg='yellow', bold=True), 'step-min': click.style(' - ' + text + ' ', bold=True), 'item-maj': click.style(' - ' + text + ' '), 'item-min': click.style(' ...
As a Python code analyst, you investigate and solve complex coding mysteries
def echo(text, **kwargs): """ Print results to the console :param text: the text string to print :type text: str :return: a string :rtype: str """ if shakedown.cli.quiet: return if not 'n' in kwargs: kwargs['n'] = True if 'd' in kwargs: te...
Can you create a Python 3 function that prints the results to the console
As a python code expert, you are capable of creating scripts from specifications.
Adds a user to the DCOS Enterprise.
Explain what the following Python 3 code does def add_user(uid, password, desc=None): try: desc = uid if desc is None else desc user_object = {"description": desc, "password": password} acl_url = urljoin(_acl_url(), 'users/{}'.format(uid)) r = http.put(acl_url, json=user_object) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a user from the DCOS Enterprise.
How would you explain what the following Python 3 function does def get_user(uid): try: acl_url = urljoin(_acl_url(), 'users/{}'.format(uid)) r = http.get(acl_url) return r.json() # assert r.status_code == 201 except DCOSHTTPException as e: if e.response.status_code == 40...
You are a Python code analyst, evaluating scripts for potential improvements.
Removes a user from the DCOS Enterprise.
Explain what the following Python 3 code does def remove_user(uid): try: acl_url = urljoin(_acl_url(), 'users/{}'.format(uid)) r = http.delete(acl_url) assert r.status_code == 204 except DCOSHTTPException as e: # doesn't exist if e.response.status_code != 400: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Ensures that a resource is added into the DCOS Enterprise System.
Can you tell what is the following Python 3 function doing def ensure_resource(rid): try: acl_url = urljoin(_acl_url(), 'acls/{}'.format(rid)) r = http.put(acl_url, json={'description': 'jope'}) assert r.status_code == 201 except DCOSHTTPException as e: if e.response.status_code ...
As a Python code composer, you craft elegant and concise scripts.
def set_user_permission(rid, uid, action='full'): """ Sets users permission on a given resource. The resource will be created if it doesn't exist. Actions are: read, write, update, delete, full. :param uid: user id :type uid: str :param rid: resource ID :type rid: str ...
Implement a function in Python 3 to set the user permission on a resource.
As a Python code composer, you craft elegant and concise scripts.
Removes a user permission on a resource.
Explain what the following Python 3 code does def remove_user_permission(rid, uid, action='full'): rid = rid.replace('/', '%252F') try: acl_url = urljoin(_acl_url(), 'acls/{}/users/{}/{}'.format(rid, uid, action)) r = http.delete(acl_url) assert r.status_code == 204 except DCOSHTTPE...
You are a Python code analyst, evaluating scripts for potential improvements.
def no_user(): """ Provides a context with no logged in user. """ o_token = dcos_acs_token() dcos.config.set_val('core.dcos_acs_token', '') yield dcos.config.set_val('core.dcos_acs_token', o_token)
Can you implement a function in Python 3 that provides a context with no logged in user.
You are a Python code architect, reviewing and designing scalable and efficient code
def new_dcos_user(user_id, password): """ Provides a context with a newly created user. """ o_token = dcos_acs_token() shakedown.add_user(user_id, password, user_id) token = shakedown.authenticate(user_id, password) dcos.config.set_val('core.dcos_acs_token', token) yield dcos.config.set...
Implement a function in Python 3 to provide a context with a newly created user.
As a python code expert, you are capable of creating scripts from specifications.
def dcos_user(user_id, password): """ Provides a context with user otherthan super """ o_token = dcos_acs_token() token = shakedown.authenticate(user_id, password) dcos.config.set_val('core.dcos_acs_token', token) yield dcos.config.set_val('core.dcos_acs_token', o_token)
Can you create a Python 3 function that provides a context with user other than super
As a Python code analyst, you investigate and solve complex coding mysteries
def add_group(id, description=None): """ Adds group to the DCOS Enterprise. If not description is provided the id will be used for the description. :param id: group id :type id: str :param desc: description of user :type desc: str """ if not description: de...
How would you code a function in Python 3 to add a group to the Enterprise.
As a python code expert, you are capable of creating scripts from specifications.
def get_group(id): """ Returns a group from the DCOS Enterprise. It returns None if none exists. :param id: group id :type id: str :return: Group :rtype: dict """ acl_url = urljoin(_acl_url(), 'groups/{}'.format(id)) try: r = http.get(acl_url) return r.j...
Implement a Python 3 function for returning a group from the DCOS Enterprise.
As a Python code translator, you convert algorithms and pseudocode into Python.
def remove_group(id): """ Removes a group from the DCOS Enterprise. The group is removed regardless of associated users. :param id: group id :type id: str """ acl_url = urljoin(_acl_url(), 'groups/{}'.format(id)) try: r = http.delete(acl_url) print(r.status_code...
Can you write a function in Python 3 where it removes a group from the DCOS Enterprise.
As a Python code composer, you craft elegant and concise scripts.
def add_user_to_group(uid, gid, exist_ok=True): """ Adds a user to a group within DCOS Enterprise. The group and user must exist. :param uid: user id :type uid: str :param gid: group id :type gid: str :param exist_ok: True if it is ok for the relationship to pre-exi...
Write a Python 3 function for adding a user to a group.
As a Python code analyst, you investigate and solve complex coding mysteries
Removes a user from a group within DCOS Enterprise.
Make a summary of the following Python 3 code def remove_user_from_group(uid, gid): acl_url = urljoin(_acl_url(), 'groups/{}/users/{}'.format(gid, uid)) try: r = http.delete(acl_url) assert r.status_code == 204 except dcos.errors.DCOSBadRequest: pass
You are a Python code architect, reviewing and designing scalable and efficient code
def easybake(css_in, html_in=sys.stdin, html_out=sys.stdout, last_step=None, coverage_file=None, use_repeatable_ids=False): """Process the given HTML file stream with the css stream.""" html_doc = etree.parse(html_in) oven = Oven(css_in, use_repeatable_ids) oven.bake(html_doc, last_step) ...
Write a Python 3 function for processing the given HTML file stream with the css stream.
As a Python code translator, you convert algorithms and pseudocode into Python.
Commandline script wrapping Baker.
Make a summary of the following Python 3 code def main(argv=None): parser = argparse.ArgumentParser(description="Process raw HTML to baked" " (embedded numbering and" " collation)") parser.add_argument('-v', '--ver...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the version of marathon on marathon.
Can you generate a brief explanation for the following Python 3 code def mom_version(name='marathon-user'): if service_available_predicate(name): with marathon_on_marathon(name): return marathon_version() else: # We can either skip the corresponding test by returning False ...
As a Python code composer, you craft elegant and concise scripts.
Returns True if the given MoM has a version less than the given version.
Given the following Python 3 function, write the documentation def mom_version_less_than(version, name='marathon-user'): if service_available_predicate(name): return mom_version() < LooseVersion(version) else: # We can either skip the corresponding test by returning False # or raise an e...
As a python code expert, you are capable of creating scripts from specifications.
def get_transport(host, username, key): """ Create a transport object :param host: the hostname to connect to :type host: str :param username: SSH username :type username: str :param key: key object used for authentication :type key: paramiko.RSAKey :return:...
Write a Python 3 script to create a transport object for the given host username and key.
As a Python code composer, you craft elegant and concise scripts.
Begin a transport client and authenticate it with the given username and key.
Make a summary of the following Python 3 code def start_transport(transport, username, key): transport.start_client() agent = paramiko.agent.Agent() keys = itertools.chain((key,) if key else (), agent.get_keys()) for test_key in keys: try: transport.auth_publickey(username, test_ke...
You are a Python code generator, capable of creating scripts from specifications.
def validate_key(key_path): """ Validate a key :param key_path: path to a key to use for authentication :type key_path: str :return: key object used for authentication :rtype: paramiko.RSAKey """ key_path = os.path.expanduser(key_path) if not os.path.isfile(key_path):...
Write a Python 3 function that can validate a key in a key_path and return a paramiko. RSAKey object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get a dictionary describing a service
How would you explain what the following Python 3 function does def get_service( service_name, inactive=False, completed=False ): """ Get a dictionary describing a service :param service_name: the service name :type service_name: str :param inactive: whether to includ...
As a python code expert, you are capable of creating scripts from specifications.
def get_service_framework_id( service_name, inactive=False, completed=False ): """ Get the framework ID for a service :param service_name: the service name :type service_name: str :param inactive: whether to include inactive services :type inactive: bool ...
Write a Python 3 script to get the framework ID for a service
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_service_tasks( service_name, inactive=False, completed=False ): """ Get a list of tasks associated with a service :param service_name: the service name :type service_name: str :param inactive: whether to include inactive services :type inactive: bool ...
Create a Python 3 function to get a list of tasks associated with a service
You are a Python code generator, capable of creating scripts from specifications.
Get a list of task IDs associated with a service.
Can you tell what is the following Python 3 function doing def get_service_task_ids( service_name, task_predicate=None, inactive=False, completed=False ): """ Get a list of task IDs associated with a service :param service_name: the service name :type service_name: st...
As a Python code composer, you craft elegant and concise scripts.
def get_service_task( service_name, task_name, inactive=False, completed=False ): """ Get a dictionary describing a service task, or None :param service_name: the service name :type service_name: str :param task_name: the task name :type task_name: str...
Create a Python 3 function for getting a dictionary describing a service task
You are a Python code generator, capable of creating scripts from specifications.
def get_marathon_task( task_name, inactive=False, completed=False ): """ Get a dictionary describing a named marathon task """ return get_service_task('marathon', task_name, inactive, completed)
Implement a function in Python 3 to get a dictionary describing a named marathon task
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_mesos_task(task_name): """ Get a mesos task with a specific task name """ tasks = get_mesos_tasks() if tasks is not None: for task in tasks: if task['name'] == task_name: return task return None
Can you implement a function in Python 3 that gets a mesos task with a specific task name
As a Python code analyst, you investigate and solve complex coding mysteries
Get a list of the IPs associated with a service and task.
Here you have a function in Python 3, explain what it does def get_service_ips( service_name, task_name=None, inactive=False, completed=False ): """ Get a set of the IPs associated with a service :param service_name: the service name :type service_name: str :p...
As a Python code composer, you craft elegant and concise scripts.
Check if a service is healthy.
Explain what the following Python 3 code does def service_healthy(service_name, app_id=None): marathon_client = marathon.create_client() apps = marathon_client.get_apps_for_framework(service_name) if apps: for app in apps: if (app_id is not None) and (app['id'] != "/{}".format(str(app_...
You are a Python code generator, capable of creating scripts from specifications.
def delete_persistent_data(role, zk_node): """ Deletes any persistent data associated with the specified role, and zk node. :param role: the mesos role to delete, or None to omit this :type role: str :param zk_node: the zookeeper node to be deleted, or None to skip this deletion :ty...
Write a Python 3 function that can delete any persistent data associated with the specified role and zk node.
As a Python code composer, you craft elegant and concise scripts.
def destroy_volumes(role): """ Destroys all volumes on all the slaves in the cluster for the role. """ state = dcos_agents_state() if not state or 'slaves' not in state.keys(): return False all_success = True for agent in state['slaves']: if not destroy_volume(agent, role): ...
Write a Python 3 script to destroy all volumes on all the slaves in the cluster for the given role.
You are a Python code generator, capable of creating scripts from specifications.
Delete the volumes on the specific agent for the specific role.
Can you tell what is the following Python 3 function doing def destroy_volume(agent, role): volumes = [] agent_id = agent['id'] reserved_resources_full = agent.get('reserved_resources_full', None) if not reserved_resources_full: # doesn't exist return True reserved_resources = rese...
As a Python code translator, you convert algorithms and pseudocode into Python.
Unreserves all the resources for all the slaves for the role.
How would you explain what the following Python 3 function does def unreserve_resources(role): state = dcos_agents_state() if not state or 'slaves' not in state.keys(): return False all_success = True for agent in state['slaves']: if not unreserve_resource(agent, role): all_s...
You are a Python code analyst, evaluating scripts for potential improvements.
Checks the service url if available it returns true on expiration it returns false on timeout_sec
Can you tell what is the following Python 3 function doing def wait_for_service_endpoint(service_name, timeout_sec=120): master_count = len(get_all_masters()) return time_wait(lambda: service_available_predicate(service_name), timeout_seconds=timeout_sec, required_cons...
You are a Python code generator, capable of creating scripts from specifications.
Returns True if the provided service_names s tasks have at least expected_task_count tasks which are in any of expected_task_states False otherwise.
Given the following Python 3 function, write the documentation def task_states_predicate(service_name, expected_task_count, expected_task_states): try: tasks = get_service_tasks(service_name) except (DCOSConnectionError, DCOSHTTPException): tasks = [] matching_tasks = [] other_tasks = []...
As a python code expert, you are capable of creating scripts from specifications.
def wait_for_service_tasks_state( service_name, expected_task_count, expected_task_states, timeout_sec=120 ): """ Returns once the service has at least N tasks in one of the specified state(s) :param service_name: the service name :type service_name: str :par...
Write a Python 3 function for waiting until the service has at least N tasks in one of the specified state
You are a Python code analyst, evaluating scripts for potential improvements.
def tasks_all_replaced_predicate( service_name, old_task_ids, task_predicate=None ): """ Returns whether ALL of old_task_ids have been replaced with new tasks :param service_name: the service name :type service_name: str :param old_task_ids: list of original task ids...
How would you code a function in Python 3 to return True if all of old_task_ids have been replaced with new tasks
You are a Python code analyst, evaluating scripts for potential improvements.
def tasks_missing_predicate( service_name, old_task_ids, task_predicate=None ): """ Returns whether any of old_task_ids are no longer present :param service_name: the service name :type service_name: str :param old_task_ids: list of original task ids as returned by g...
Write a Python 3 script to return whether any of old_task_ids are no longer present in the service_name.
You are a Python code analyst, evaluating scripts for potential improvements.
Waits until ALL of old_task_ids have been replaced with new tasks
Can you generate the documentation for the following Python 3 function def wait_for_service_tasks_all_changed( service_name, old_task_ids, task_predicate=None, timeout_sec=120 ): """ Returns once ALL of old_task_ids have been replaced with new tasks :param service_name: the ...
You are a Python code generator, capable of creating scripts from specifications.
def wait_for_service_tasks_all_unchanged( service_name, old_task_ids, task_predicate=None, timeout_sec=30 ): """ Returns after verifying that NONE of old_task_ids have been removed or replaced from the service :param service_name: the service name :type service_name:...
Implement a Python 3 function for waiting until all of the old_task_ids of the service has been removed or replaced from the service.
As a Python code composer, you craft elegant and concise scripts.
def docker_version(host=None, component='server'): """ Return the version of Docker [Server] :param host: host or IP of the machine Docker is running on :type host: str :param component: Docker component :type component: str :return: Docker version :rtype: str ""...
Can you implement a function in Python 3 that returns the version of Docker [ Server ]
You are a Python code analyst, evaluating scripts for potential improvements.
def create_docker_credentials_file( username, password, file_name='docker.tar.gz'): """ Create a docker credentials file. Docker username and password are used to create a `{file_name}` with `.docker/config.json` containing the credentials. :param username: docker us...
Write a Python 3 function for creating a docker credentials file.
You are a Python code architect, reviewing and designing scalable and efficient code
Create and distribute a docker credentials file to all private agents.
Can you generate a brief explanation for the following Python 3 code def distribute_docker_credentials_to_private_agents( username, password, file_name='docker.tar.gz'): """ Create and distributes a docker credentials file to all private agents :param username: docker username ...
You are a Python code architect, reviewing and designing scalable and efficient code
Given a docker image create a prefetch app on all private agents.
Can you generate the documentation for the following Python 3 function def prefetch_docker_image_on_private_agents( image, timeout=timedelta(minutes=5).total_seconds()): """ Given a docker image. An app with the image is scale across the private agents to ensure that the image is prefetched ...
You are a Python code generator, capable of creating scripts from specifications.
def _get_options(options_file=None): """ Read in options_file as JSON. :param options_file: filename to return :type options_file: str :return: options as dictionary :rtype: dict """ if options_file is not None: with open(options_file, 'r') as opt_file: ...
Implement a function in Python 3 to read in options_file as JSON.
As a Python code analyst, you investigate and solve complex coding mysteries
def install_package( package_name, package_version=None, service_name=None, options_file=None, options_json=None, wait_for_completion=False, timeout_sec=600, expected_running_tasks=0 ): """ Install a package via the DC/OS library :param packag...
Write a Python 3 script for installing a marathon package via the DC / OS library.
You are a Python code analyst, evaluating scripts for potential improvements.
def install_package_and_wait( package_name, package_version=None, service_name=None, options_file=None, options_json=None, wait_for_completion=True, timeout_sec=600, expected_running_tasks=0 ): """ Install a package via the DC/OS library and wait for c...
Can you create a Python 3 function that installs a package via DC / OS library and wait for completion.
As a Python code analyst, you investigate and solve complex coding mysteries
Check whether the given package is currently installed.
Here you have a function in Python 3, explain what it does def package_installed(package_name, service_name=None): package_manager = _get_package_manager() app_installed = len(package_manager.installed_apps(package_name, service_name)) > 0 subcommand_installed = False for subcmd in package.installed_...
You are a Python code analyst, evaluating scripts for potential improvements.
Uninstalls a package using the DC / OS library.
How would you explain what the following Python 3 function does def uninstall_package( package_name, service_name=None, all_instances=False, wait_for_completion=False, timeout_sec=600 ): """ Uninstall a package using the DC/OS library. :param package_name: name of th...
You are a Python code architect, reviewing and designing scalable and efficient code
Uninstall a package via DC / OS library and wait for completion.
Can you generate the documentation for the following Python 3 function def uninstall_package_and_wait( package_name, service_name=None, all_instances=False, wait_for_completion=True, timeout_sec=600 ): """ Uninstall a package via the DC/OS library and wait for completion ...
As a Python code composer, you craft elegant and concise scripts.
Adds a repository to the list of package sources that can be used to create a new version of the package.
Can you generate the documentation for the following Python 3 function def add_package_repo( repo_name, repo_url, index=None, wait_for_package=None, expect_prev_version=None): """ Add a repository to the list of package sources :param repo_name: name of the repositor...
As a Python code composer, you craft elegant and concise scripts.
def remove_package_repo(repo_name, wait_for_package=None): """ Remove a repository from the list of package sources :param repo_name: name of the repository to remove :type repo_name: str :param wait_for_package: the package whose version should change after the repo is removed :typ...
Can you implement a function in Python 3 that removes a repository from the list of package sources.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_package_versions(package_name): """ Returns the list of versions of a given package :param package_name: name of the package :type package_name: str """ package_manager = _get_package_manager() pkg = package_manager.get_package_version(package_name, None) return pkg.package_v...
Create a Python 3 function for returning the list of versions of a given package
As a Python code composer, you craft elegant and concise scripts.
This is the main CLI for the DCOS test - harness tool.
Can you generate the documentation for the following Python 3 function def cli(**args): import shakedown # Read configuration options from ~/.shakedown (if exists) args = read_config(args) # Set configuration defaults args = set_config_defaults(args) if args['quiet']: shakedown.cli.qu...
You are a Python code analyst, evaluating scripts for potential improvements.
def find_coverage(self, zoom): """ Returns the bounding box (minx, miny, maxx, maxy) of an adjacent group of tiles at this zoom level. """ # Find a group of adjacent available tiles at this zoom level rows = self._query('''SELECT tile_column, tile_row FROM tiles ...
Create a Python 3 function to find the bounding box of the tile that is available at a given zoom level.
You are a Python code architect, reviewing and designing scalable and efficient code
Download the specified tile from the specified URL.
Here you have a function in Python 3, explain what it does def tile(self, z, x, y): logger.debug(_("Download tile %s") % ((z, x, y),)) # Render each keyword in URL ({s}, {x}, {y}, {z}, {size} ... ) size = self.tilesize s = self.tiles_subdomains[(x + y) % len(self.tiles_subdomains)]; ...
As a python code expert, you are capable of creating scripts from specifications.
def tile(self, z, x, y): """ Render the specified tile with Mapnik """ logger.debug(_("Render tile %s") % ((z, x, y),)) proj = GoogleProjection(self.tilesize, [z]) return self.render(proj.tile_bbox((z, x, y)))
Create a Python 3 function for rendering the specified tile with Mapnik
As a Python code composer, you craft elegant and concise scripts.
Render the specified tile with Mapnik
Can you generate the documentation for the following Python 3 function def render(self, bbox, width=None, height=None): width = width or self.tilesize height = height or self.tilesize self._prepare_rendering(bbox, width=width, height=height) # Render image with default Agg renderer ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Render a grid with Mapnik s tile bounding box.
Given the following Python 3 function, write the documentation def grid(self, z, x, y, fields, layer): logger.debug(_("Render grid %s") % ((z, x, y),)) proj = GoogleProjection(self.tilesize, [z]) return self.render_grid(proj.tile_bbox((z, x, y)), fields, layer)
As a Python code translator, you convert algorithms and pseudocode into Python.
Render the specified grid with Mapnik
Make a summary of the following Python 3 code def render_grid(self, bbox, grid_fields, layer, width=None, height=None): width = width or self.tilesize height = height or self.tilesize self._prepare_rendering(bbox, width=width, height=height) grid = mapnik.Grid(width, height) map...
You are a Python code architect, reviewing and designing scalable and efficient code
def tile_at(self, zoom, position): """ Returns a tuple of (z, x, y) """ x, y = self.project_pixels(position, zoom) return (zoom, int(x/self.tilesize), int(y/self.tilesize))
Can you create a Python 3 function that returns a tuple of z x y coordinates for the tile at the given zoom level and position.
As a Python code translator, you convert algorithms and pseudocode into Python.
def project(self, lng_lat): """ Returns the coordinates in meters from WGS84 """ (lng, lat) = lng_lat x = lng * DEG_TO_RAD lat = max(min(MAX_LATITUDE, lat), -MAX_LATITUDE) y = lat * DEG_TO_RAD y = log(tan((pi / 4) + (y / 2))) return (x*EARTH_RADIUS...
Implement a Python 3 function for returning the coordinates in meters from WGS84
You are a Python code generator, capable of creating scripts from specifications.
def string2rgba(cls, colorstring): """ Convert #RRGGBBAA to an (R, G, B, A) tuple """ colorstring = colorstring.strip() if colorstring[0] == '#': colorstring = colorstring[1:] if len(colorstring) < 6: raise ValueError("input #%s is not in #RRGGBB format" % colorst...
Create a Python 3 function for converting a color string to a color tuple.
As a Python code analyst, you investigate and solve complex coding mysteries
Build the tiles list within the bottom - left or top - right bounding box at the specified zoom levels.
Explain what the following Python 3 code does def tileslist(self, bbox, zoomlevels): proj = GoogleProjection(self.tile_size, zoomlevels, self.tile_scheme) return proj.tileslist(bbox)
As a Python code analyst, you investigate and solve complex coding mysteries
Add a layer to be blended on top of the tile.
Can you generate a brief explanation for the following Python 3 code def add_layer(self, tilemanager, opacity=1.0): assert has_pil, _("Cannot blend layers without python PIL") assert self.tile_size == tilemanager.tile_size, _("Cannot blend layers whose tile size differs") assert 0 <= opacity <= ...
As a python code expert, you are capable of creating scripts from specifications.
def add_filter(self, filter_): """ Add an image filter for post-processing """ assert has_pil, _("Cannot add filters without python PIL") self.cache.basename += filter_.basename self._filters.append(filter_)
Write a Python 3 function for adding an image filter for post - processing.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the binary content of the tile and seed the cache.
Here you have a function in Python 3, explain what it does def tile(self, z_x_y): (z, x, y) = z_x_y logger.debug(_("tile method called with %s") % ([z, x, y])) output = self.cache.read((z, x, y)) if output is None: output = self.reader.tile(z, x, y) # Blend layer...
You are a Python code generator, capable of creating scripts from specifications.
Return the UTFGrid content for the given z - x - y.
Given the following Python 3 function, write the documentation def grid(self, z_x_y): # sources.py -> MapnikRenderer -> grid (z, x, y) = z_x_y content = self.reader.grid(z, x, y, self.grid_fields, self.grid_layer) return content
As a python code expert, you are capable of creating scripts from specifications.
Blends all layers into a single tile.
Can you generate the documentation for the following Python 3 function def _blend_layers(self, imagecontent, z_x_y): (z, x, y) = z_x_y result = self._tile_image(imagecontent) # Paste each layer for (layer, opacity) in self._layers: try: # Prepare tile of overl...
You are a Python code architect, reviewing and designing scalable and efficient code
def _tile_image(self, data): """ Tile binary content as PIL Image. """ image = Image.open(BytesIO(data)) return image.convert('RGBA')
Implement a function in Python 3 to tile binary content as PIL Image.
You are a Python code analyst, evaluating scripts for potential improvements.
Return the list of covered zoom levels in ascending order
Can you generate a brief explanation for the following Python 3 code def zoomlevels(self): zooms = set() for coverage in self._bboxes: for zoom in coverage[1]: zooms.add(zoom) return sorted(zooms)
As a Python code analyst, you investigate and solve complex coding mysteries
def run(self, force=False): """ Build a MBTile file. force -- overwrite if MBTiles file already exists. """ if os.path.exists(self.filepath): if force: logger.warn(_("%s already exists. Overwrite.") % self.filepath) os.remove(self.file...
Can you implement a function in Python 3 that builds a MBTile file and add coverage to the metadata.
You are a Python code generator, capable of creating scripts from specifications.
def grid_tiles(self, bbox, zoomlevel): """ Return a grid of (x, y) tuples representing the juxtaposition of tiles on the specified ``bbox`` at the specified ``zoomlevel``. """ tiles = self.tileslist(bbox, [zoomlevel]) grid = {} for (z, x, y) in tiles: ...
Create a Python 3 function to return a grid of x y tuples representing the juxtaposition of tiles on the specified bounding box at the specified zoomlevel.
As a Python code translator, you convert algorithms and pseudocode into Python.
Exports the image for the specified bounding box and zoomlevel.
Make a summary of the following Python 3 code def export_image(self, bbox, zoomlevel, imagepath): assert has_pil, _("Cannot export image without python PIL") grid = self.grid_tiles(bbox, zoomlevel) width = len(grid[0]) height = len(grid) widthpix = width * self.tile_size ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _makeScriptOrder(gpos): """ Run therough GPOS and make an alphabetically ordered list of scripts. If DFLT is in the list, move it to the front. """ scripts = [] for scriptRecord in gpos.ScriptList.ScriptRecord: scripts.append(scriptRecord.ScriptTag) if "DFLT" in scripts: ...
Write a Python 3 function that can run therough GPOS and make an alphabetically ordered list of scripts.
You are a Python code analyst, evaluating scripts for potential improvements.
def _gatherDataFromLookups(gpos, scriptOrder): """ Gather kerning and classes from the applicable lookups and return them in script order. """ lookupIndexes = _gatherLookupIndexes(gpos) seenLookups = set() kerningDictionaries = [] leftClassDictionaries = [] rightClassDictionaries = [...
Write a Python 3 function that can gather kerning and classes from the applicable lookups and return them in script order.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _gatherLookupIndexes(gpos): """ Gather a mapping of script to lookup indexes referenced by the kern feature for each script. Returns a dictionary of this structure: { "latn" : [0], "DFLT" : [0] } """ # gather the indexes of the kern features kernFe...
How would you implement a function in Python 3 that gathers a mapping of script to lookup indexes for each kern feature.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _gatherKerningForLookup(gpos, lookupIndex): """ Gather the kerning and class data for a particular lookup. Returns kerning, left clases, right classes. The kerning dictionary is of this structure: { ("a", "a") : 10, ((1, 1, 3), "a") : -20 } The class dicti...
Implement a Python 3 function for gathering the kerning and left clases and right classes for a particular lookup.
As a Python code analyst, you investigate and solve complex coding mysteries
def _handleLookupType2Format1(subtable): """ Extract a kerning dictionary from a Lookup Type 2 Format 1. """ kerning = {} coverage = subtable.Coverage.glyphs valueFormat1 = subtable.ValueFormat1 pairSets = subtable.PairSet for index, leftGlyphName in enumerate(coverage): pairSet ...
How would you implement a function in Python 3 that handles a Lookup Type 2 Format 1 subtable.
As a python code expert, you are capable of creating scripts from specifications.
def _handleLookupType2Format2(subtable, lookupIndex, subtableIndex): """ Extract kerning, left class and right class dictionaries from a Lookup Type 2 Format 2. """ # extract the classes leftClasses = _extractFeatureClasses(lookupIndex=lookupIndex, subtableIndex=subtableIndex, classDefs=subtable.Cla...
Write a Python 3 script to handle a Lookup Type 2 Format 2.
As a Python code analyst, you investigate and solve complex coding mysteries
Merge all of the kerning dictionaries found into one flat dictionary.
Here you have a function in Python 3, explain what it does def _mergeKerningDictionaries(kerningDictionaries): # work through the dictionaries backwards since # this uses an update to load the kerning. this # will ensure that the script order is honored. kerning = {} for dictionaryGroup in reversed(...
As a Python code analyst, you investigate and solve complex coding mysteries
Find all classes that have only one member.
Here you have a function in Python 3, explain what it does def _findSingleMemberGroups(classDictionaries): toRemove = {} for classDictionaryGroup in classDictionaries: for classDictionary in classDictionaryGroup: for name, members in list(classDictionary.items()): if len(memb...
As a python code expert, you are capable of creating scripts from specifications.
def _removeSingleMemberGroupReferences(kerning, leftGroups, rightGroups): """ Translate group names into glyph names in pairs if the group only contains one glyph. """ new = {} for (left, right), value in kerning.items(): left = leftGroups.get(left, left) right = rightGroups.get(...
Write a Python 3 script to translate group names into glyph names in pairs
As a Python code analyst, you investigate and solve complex coding mysteries
This function merges the classes that have the exact same list of members and flag them for removal.
Given the following Python 3 function, write the documentation def _mergeClasses(classDictionaries): # build a mapping of members to names memberTree = {} for classDictionaryGroup in classDictionaries: for classDictionary in classDictionaryGroup: for name, members in classDictionary.item...
As a python code expert, you are capable of creating scripts from specifications.
def _setGroupNames(classes, classRename): """ Set the final names into the groups. """ groups = {} for groupName, glyphList in classes.items(): groupName = classRename.get(groupName, groupName) # if the glyph list has only one member, # the glyph name will be used in the pair...
Can you write a function in Python 3 where it sets the final names into the groups.
As a Python code analyst, you investigate and solve complex coding mysteries
Validate that a glyph is part of more than one class.
Explain what the following Python 3 code does def _validateClasses(classes): glyphToClass = {} for className, glyphList in classes.items(): for glyphName in glyphList: if glyphName not in glyphToClass: glyphToClass[glyphName] = set() glyphToClass[glyphName].add(cl...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _replaceRenamedPairMembers(kerning, leftRename, rightRename): """ Populate the renamed pair members into the kerning. """ renamedKerning = {} for (left, right), value in kerning.items(): left = leftRename.get(left, left) right = rightRename.get(right, right) renamedKernin...
Implement a Python 3 function for replacing the renamed pair members in the kerning with the new ones.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a dictionary mapping class IDs to nice strings.
Can you tell what is the following Python 3 function doing def _renameClasses(classes, prefix): renameMap = {} for classID, glyphList in classes.items(): if len(glyphList) == 0: groupName = "%s_empty_lu.%d_st.%d_cl.%d" % (prefix, classID[0], classID[1], classID[2]) elif len(glyphList...
You are a Python code generator, capable of creating scripts from specifications.
Extract classes for a specific lookup in a specific subtable.
Can you tell what is the following Python 3 function doing def _extractFeatureClasses(lookupIndex, subtableIndex, classDefs, coverage=None): # gather the class members classDict = {} for glyphName, classIndex in classDefs.items(): if classIndex not in classDict: classDict[classIndex] = s...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _get_voters(cls, session, owner_id, poll_id, answer_id): """ https://vk.com/dev/polls.getVoters """ from .users import User return session.fetch_items("polls.getVoters", User._get_users, count=100, owner_id=owner_id, poll_id=poll_id, answer_ids=answer_id)
Can you write a function in Python 3 where it gets the voters from the server.
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_include(self, name, module_spec): """Adds a module as an included module. :param name: Name under which the included module should be exposed in the current module. :param module_spec: ModuleSpec of the included module. """ assert name...
Write a Python 3 function that can add a module as an included module.
You are a Python code architect, reviewing and designing scalable and efficient code