output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Load the configuration file and initialize the class with the default values.
How would you explain what the following Python 3 function does def _config_bootstrap(self): if not os.path.exists(CONFIG_PATH): os.makedirs(CONFIG_PATH) if not os.path.exists(CONFIG_FILE): json.dump(CONFIG_DEFAULTS, open(CONFIG_FILE, 'w'), indent=4, separat...
As a Python code analyst, you investigate and solve complex coding mysteries
def _session_check(self): """Attempt to authenticate the user through a session file. This process is done to avoid having to authenticate the user every single time. It uses a session file that is saved when a valid session is captured and then reused. Because sessions can expire, we n...
Can you implement a function in Python 3 that checks if the user is authenticated by checking the session file.
As a Python code composer, you craft elegant and concise scripts.
Create a logger to be used between processes.
Given the following Python 3 function, write the documentation def _logger(self): logger = logging.getLogger(self.NAME) logger.setLevel(self.LOG_LEVEL) shandler = logging.StreamHandler(sys.stdout) fmt = '\033[1;32m%(levelname)-5s %(module)s:%(funcName)s():' fmt += '%(lineno)d %(a...
As a Python code translator, you convert algorithms and pseudocode into Python.
def set_log_level(self, level): """Override the default log level of the class""" if level == 'info': level = logging.INFO if level == 'debug': level = logging.DEBUG if level == 'error': level = logging.ERROR self._log.setLevel(level)
Create a Python 3 function to override the default log level of the class
As a Python code analyst, you investigate and solve complex coding mysteries
Process the application state configuration.
Here you have a function in Python 3, explain what it does def _process_state(self): self._log.debug("Capturing state from the request") response = self._session.get(url=self.ALERTS_URL, headers=self.HEADERS) soup = BeautifulSoup(response.content, "html.parser") for i in soup.findAll('sc...
You are a Python code generator, capable of creating scripts from specifications.
Authenticate the user and setup our state.
Here you have a function in Python 3, explain what it does def authenticate(self): valid = self._session_check() if self._is_authenticated and valid: self._log.debug("[!] User has already authenticated") return init = self._session.get(url=self.LOGIN_URL, headers=self.HEA...
As a Python code analyst, you investigate and solve complex coding mysteries
List all the alerts configured for the account.
Can you generate a brief explanation for the following Python 3 code def list(self, term=None): if not self._state: raise InvalidState("State was not properly obtained from the app") self._process_state() if not self._state[1]: self._log.info("No monitors have been create...
You are a Python code analyst, evaluating scripts for potential improvements.
Create a monitor using passed configuration.
Can you generate the documentation for the following Python 3 function def create(self, term, options): if not self._state: raise InvalidState("State was not properly obtained from the app") options['action'] = 'CREATE' payload = self._build_payload(term, options) url = self....
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a new alert using passed configuration.
Here you have a function in Python 3, explain what it does def modify(self, monitor_id, options): if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors obj = None for monitor in monitors...
You are a Python code generator, capable of creating scripts from specifications.
def delete(self, monitor_id): """Delete a monitor by ID.""" if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors bit = None for monitor in monitors: if monitor_id !=...
Implement a Python 3 function for deleting an alert by ID.
As a Python code composer, you craft elegant and concise scripts.
Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory.
How would you explain what the following Python 3 function does def search_packages_info(query): installed = {} for p in pkg_resources.working_set: installed[canonicalize_name(p.project_name)] = p query_names = [canonicalize_name(name) for name in query] for dist in [installed[pkg] for pkg in ...
As a Python code analyst, you investigate and solve complex coding mysteries
def process_view(self, request, view_func, view_args, view_kwargs): """ Collect data on Class-Based Views """ # Purge data in view method cache # Python 3's keys() method returns an iterator, so force evaluation before iterating. view_keys = list(VIEW_METHOD_DATA.keys())...
Write a Python 3 script to process the view method.
As a Python code translator, you convert algorithms and pseudocode into Python.
def process_response(self, request, response): """Let's handle old-style response processing here, as usual.""" # For debug only. if not settings.DEBUG: return response # Check for responses where the data can't be inserted. content_encoding = response.get('Content-...
Create a Python 3 function to let s handle old - style response processing here as usual.
You are a Python code generator, capable of creating scripts from specifications.
Return the job class from the given string
Given the following Python 3 function, write the documentation def get_job_class(klass_str): mod_name, klass_name = klass_str.rsplit('.', 1) try: mod = importlib.import_module(mod_name) except ImportError as e: logger.error("Error importing job module %s: '%s'", mod_name, e) return ...
You are a Python code generator, capable of creating scripts from specifications.
def get(self, *raw_args, **raw_kwargs): """ Return the data for this function (using the cache if possible). This method is not intended to be overidden """ # We pass args and kwargs through a filter to allow them to be # converted into values that can be pickled. ...
Write a Python 3 script to return the data for this function (using the cache if possible). This method is not intended to be overidden
You are a Python code architect, reviewing and designing scalable and efficient code
Invalidate the cache item
Here you have a function in Python 3, explain what it does def invalidate(self, *raw_args, **raw_kwargs): args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwargs) item = self.cache.get(key) if item is not None: exp...
As a python code expert, you are capable of creating scripts from specifications.
Remove an item from the cache
Explain what the following Python 3 code does def delete(self, *raw_args, **raw_kwargs): args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwargs) item = self.cache.get(key) if item is not None: self.cache.delete(ke...
You are a Python code analyst, evaluating scripts for potential improvements.
def raw_get(self, *raw_args, **raw_kwargs): """ Retrieve the item (tuple of value and expiry) that is actually in the cache, without causing a refresh. """ args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwa...
Write a Python 3 script for retrieving the item that is actually in the cache without causing a refresh.
You are a Python code architect, reviewing and designing scalable and efficient code
Manually set the cache value with its appropriate expiry.
Can you generate a brief explanation for the following Python 3 code def set(self, *raw_args, **raw_kwargs): if self.set_data_kwarg in raw_kwargs: data = raw_kwargs.pop(self.set_data_kwarg) else: raw_args = list(raw_args) data = raw_args.pop() args = self.pre...
You are a Python code generator, capable of creating scripts from specifications.
Store a result in the cache.
Make a summary of the following Python 3 code def store(self, key, expiry, data): self.cache.set(key, (expiry, data), self.cache_ttl) if getattr(settings, 'CACHEBACK_VERIFY_CACHE_WRITE', True): # We verify that the item was cached correctly. This is to avoid a # Memcache proble...
You are a Python code generator, capable of creating scripts from specifications.
Fetch the result SYNCHRONOUSLY and populate the cache
Here you have a function in Python 3, explain what it does def refresh(self, *args, **kwargs): result = self.fetch(*args, **kwargs) self.store(self.key(*args, **kwargs), self.expiry(*args, **kwargs), result) return result
As a python code expert, you are capable of creating scripts from specifications.
def async_refresh(self, *args, **kwargs): """ Trigger an asynchronous job to refresh the cache """ # We trigger the task with the class path to import as well as the # (a) args and kwargs for instantiating the class # (b) args and kwargs for calling the 'refresh' method ...
Write a Python 3 script to trigger an asynchronous refresh of the cache with the specified arguments and kwargs.
As a python code expert, you are capable of creating scripts from specifications.
def should_stale_item_be_fetched_synchronously(self, delta, *args, **kwargs): """ Return whether to refresh an item synchronously when it is found in the cache but stale """ if self.fetch_on_stale_threshold is None: return False return delta > (self.fetch_on_s...
Implement a Python 3 function for returning whether to refresh an item synchronously when it is found in the cache but stale .
As a Python code translator, you convert algorithms and pseudocode into Python.
This method generates a cache key for the given arguments and keyword arguments.
Explain what the following Python 3 code does def key(self, *args, **kwargs): if not args and not kwargs: return self.class_path try: if args and not kwargs: return "%s:%s" % (self.class_path, self.hash(args)) # The line might break if your passed valu...
As a python code expert, you are capable of creating scripts from specifications.
Generate a hash of the given iterable.
Explain what the following Python 3 code does def hash(self, value): if is_iterable(value): value = tuple(to_bytestring(v) for v in value) return hashlib.md5(six.b(':').join(value)).hexdigest()
As a python code expert, you are capable of creating scripts from specifications.
Decorator for creating a new cache - related object.
Here you have a function in Python 3, explain what it does def cacheback(lifetime=None, fetch_on_miss=None, cache_alias=None, job_class=None, task_options=None, **job_class_kwargs): """ Decorate function to cache its return value. :lifetime: How long to cache items for :fetch_on_miss: Whe...
You are a Python code analyst, evaluating scripts for potential improvements.
def angle(v1, v2): """Return the angle in radians between vectors 'v1' and 'v2'.""" v1_u = unit_vector(v1) v2_u = unit_vector(v2) return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
Write a Python 3 script for returning the angle in radians between vectors v1 and v2.
You are a Python code architect, reviewing and designing scalable and efficient code
def keep_high_angle(vertices, min_angle_deg): """Keep vertices with angles higher then given minimum.""" accepted = [] v = vertices v1 = v[1] - v[0] accepted.append((v[0][0], v[0][1])) for i in range(1, len(v) - 2): v2 = v[i + 1] - v[i - 1] diff_angle = np.fabs(angle(v1, v2) * 18...
Can you write a function in Python 3 where it keeps vertices with angles higher then given minimum.
As a python code expert, you are capable of creating scripts from specifications.
Set property values for Polygon.
Can you generate the documentation for the following Python 3 function def set_contourf_properties(stroke_width, fcolor, fill_opacity, contour_levels, contourf_idx, unit): return { "stroke": fcolor, "stroke-width": stroke_width, "stroke-opacity": 1, "fill": fcolor, "fill-opac...
As a python code expert, you are capable of creating scripts from specifications.
Transform matplotlib. contour to geojson.
Explain what the following Python 3 code does def contour_to_geojson(contour, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, geojson_properties=None, strdump=False, serialize=True): """Transform matplotlib.contour to geojson.""" colle...
You are a Python code generator, capable of creating scripts from specifications.
def contourf_to_geojson_overlap(contourf, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, fill_opacity=.9, geojson_properties=None, strdump=False, serialize=True): """Transform matplotlib.contourf to geojson with overlapp...
Write a Python 3 script for transforming matplotlib. contourf to geojson with overlapping filled contours.
As a Python code composer, you craft elegant and concise scripts.
def contourf_to_geojson(contourf, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, fill_opacity=.9, geojson_properties=None, strdump=False, serialize=True): """Transform matplotlib.contourf to geojson with MultiPolygons.""" polygon_fe...
How would you implement a function in Python 3 that transforms matplotlib. contourf to geojson with MultiPolygons.
As a Python code composer, you craft elegant and concise scripts.
Get a qualified URL for the provider to return to upon authorization
Explain what the following Python 3 code does def get_authorize_callback(endpoint, provider_id): endpoint_prefix = config_value('BLUEPRINT_NAME') url = url_for(endpoint_prefix + '.' + endpoint, provider_id=provider_id) return request.url_root[:-1] + url
You are a Python code generator, capable of creating scripts from specifications.
def delete_connection(self, **kwargs): """Remove a single connection to a provider for the specified user.""" conn = self.find_connection(**kwargs) if not conn: return False self.delete(conn) return True
Implement a Python 3 function for removing a single connection to a provider for the specified user.
As a Python code analyst, you investigate and solve complex coding mysteries
Remove a single connection to a provider for the specified user.
Given the following Python 3 function, write the documentation def delete_connections(self, **kwargs): rv = False for c in self.find_connections(**kwargs): self.delete(c) rv = True return rv
As a python code expert, you are capable of creating scripts from specifications.
Starts the provider login OAuth flow
Can you tell what is the following Python 3 function doing def login(provider_id): provider = get_provider_or_404(provider_id) callback_url = get_authorize_callback('login', provider_id) post_login = request.form.get('next', get_post_login_redirect()) session[config_value('POST_OAUTH_LOGIN_SESSION_KEY')...
You are a Python code analyst, evaluating scripts for potential improvements.
def connect(provider_id): """Starts the provider connection OAuth flow""" provider = get_provider_or_404(provider_id) callback_url = get_authorize_callback('connect', provider_id) allow_view = get_url(config_value('CONNECT_ALLOW_VIEW')) pc = request.form.get('next', allow_view) session[config_va...
Can you create a Python 3 function that starts the provider connection OAuth flow
As a Python code translator, you convert algorithms and pseudocode into Python.
Remove all connections to the specified provider
How would you explain what the following Python 3 function does def remove_all_connections(provider_id): provider = get_provider_or_404(provider_id) ctx = dict(provider=provider.name, user=current_user) deleted = _datastore.delete_connections(user_id=current_user.get_id(), ...
You are a Python code analyst, evaluating scripts for potential improvements.
def remove_connection(provider_id, provider_user_id): """Remove a specific connection for the authenticated user to the specified provider """ provider = get_provider_or_404(provider_id) ctx = dict(provider=provider.name, user=current_user, provider_user_id=provider_user_id) del...
Write a Python 3 script for removing a specific connection to the specified provider
As a Python code composer, you craft elegant and concise scripts.
def connect_handler(cv, provider): """Shared method to handle the connection process :param connection_values: A dictionary containing the connection values :param provider_id: The provider ID the connection shoudl be made to """ cv.setdefault('user_id', current_user.get_id()) connection = _dat...
Can you implement a function in Python 3 that handles the connection process
As a python code expert, you are capable of creating scripts from specifications.
def login_handler(response, provider, query): """Shared method to handle the signin process""" connection = _datastore.find_connection(**query) if connection: after_this_request(_commit) token_pair = get_token_pair_from_oauth_response(provider, response) if (token_pair['access_toke...
Write a Python 3 script for handling the signin process
As a Python code translator, you convert algorithms and pseudocode into Python.
Initialize the application with the Social extension
Can you tell what is the following Python 3 function doing def init_app(self, app, datastore=None): datastore = datastore or self.datastore for key, value in default_config.items(): app.config.setdefault(key, value) providers = dict() for key, config in app.config.items()...
As a python code expert, you are capable of creating scripts from specifications.
def guess(filename, fallback='application/octet-stream'): """ Using the mimetypes library, guess the mimetype and encoding for a given *filename*. If the mimetype cannot be guessed, *fallback* is assumed instead. :param filename: Filename- can be absolute path. :param fallback: A fallback mimet...
Write a Python 3 function for guessing the mimetype and encoding for a given filename.
As a python code expert, you are capable of creating scripts from specifications.
Given an iterable of addresses or name - address tuples *addrs* return a header value that joins all of them together with a space and a comma.
Here you have a function in Python 3, explain what it does def format_addresses(addrs): return ', '.join( formataddr(item) if isinstance(item, tuple) else item for item in addrs )
You are a Python code analyst, evaluating scripts for potential improvements.
def stringify_address(addr, encoding='utf-8'): """ Given an email address *addr*, try to encode it with ASCII. If it's not possible, encode the *local-part* with the *encoding* and the *domain* with IDNA. The result is a unicode string with the domain encoded as idna. """ if isinsta...
Create a Python 3 function to give an email address addr try to encode it with ASCII and return a unicode string with the local - part and domain encoded as idna.
As a Python code composer, you craft elegant and concise scripts.
Creates a new Collection object with a HTML content and attachments.
Explain what the following Python 3 code does def email(sender=None, receivers=(), cc=(), bcc=(), subject=None, content=None, encoding='utf8', attachments=()): """ Creates a Collection object with a HTML *content*, and *attachments*. :param content: HTML content. :param encoding...
You are a Python code generator, capable of creating scripts from specifications.
def postman(host, port=587, auth=(None, None), force_tls=False, options=None): """ Creates a Postman object with TLS and Auth middleware. TLS is placed before authentication because usually authentication happens and is accepted only after TLS is enabled. :param auth: Tuple of (user...
Can you implement a function in Python 3 that returns a Postman object with TLS and Auth middleware.
As a python code expert, you are capable of creating scripts from specifications.
Returns the finalised mime object after applying the internal headers. Usually this assumes that the mime object is not overriden.
Explain what the following Python 3 code does def mime(self): mime = self.mime_object() self.headers.prepare(mime) return mime
You are a Python code generator, capable of creating scripts from specifications.
Send an envelope to the specified sender and return a SendmailResponse object.
Can you generate the documentation for the following Python 3 function def send(self, envelope): rejected = self.conn.sendmail( stringify_address(envelope.sender), [stringify_address(k) for k in envelope.receivers], envelope.string(), ) status_code, reason = s...
As a Python code composer, you craft elegant and concise scripts.
def sender(self): """ Returns the sender, respecting the Resent-* headers. In any case, prefer Sender over From, meaning that if Sender is present then From is ignored, as per the RFC. """ to_fetch = ( ['Resent-Sender', 'Resent-From'] if self.resent el...
Create a Python 3 function to return the sender of the current resource.
You are a Python code generator, capable of creating scripts from specifications.
def receivers(self): """ Returns a list of receivers, obtained from the To, Cc, and Bcc headers, respecting the Resent-* headers if the email was resent. """ attrs = ( ['Resent-To', 'Resent-Cc', 'Resent-Bcc'] if self.resent else ['To', 'Cc', 'Bcc']...
Write a Python 3 function that can return a list of addresses obtained from the To Cc and Bcc headers.
You are a Python code analyst, evaluating scripts for potential improvements.
Prepares a MIME object by applying the headers to the given MIME object.
Can you generate the documentation for the following Python 3 function def prepare(self, mime): for key in self: if key == 'Bcc' or key == 'Resent-Bcc': continue del mime[key] # Python 3.* email's compatibility layer will handle # unicode field val...
You are a Python code generator, capable of creating scripts from specifications.
Returns a middleware that uses TLS for SMTP connections.
How would you explain what the following Python 3 function does def tls(force=False): def middleware(conn): if force or conn.has_extn('STARTTLS'): conn.starttls() conn.ehlo() return middleware
As a Python code translator, you convert algorithms and pseudocode into Python.
def auth(username, password): """ Middleware implementing authentication via LOGIN. Most of the time this middleware needs to be placed *after* TLS. :param username: Username to login with. :param password: Password of the user. """ def middleware(conn): conn.login(username, pas...
How would you implement a function in Python 3 that returns a middleware that will login with the given username and password.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_existing_model(model_name): """ Try to find existing model class named `model_name`. :param model_name: String name of the model class. """ try: model_cls = engine.get_document_cls(model_name) log.debug('Model `{}` already exists. Using existing one'.format( model_na...
How would you implement a function in Python 3 that tries to find existing model class named model_name.
You are a Python code analyst, evaluating scripts for potential improvements.
def prepare_relationship(config, model_name, raml_resource): """ Create referenced model if it doesn't exist. When preparing a relationship, we check to see if the model that will be referenced already exists. If not, it is created so that it will be possible to use it in a relationship. Thus the first...
Implement a function in Python 3 to create referenced model if it doesn t exist.
As a Python code composer, you craft elegant and concise scripts.
Generate a new model class.
Explain what the following Python 3 code does def generate_model_cls(config, schema, model_name, raml_resource, es_based=True): """ Generate model class. Engine DB field types are determined using `type_fields` and only those types may be used. :param schema: Model schema dict p...
As a Python code translator, you convert algorithms and pseudocode into Python.
Generates model name and runs setup_data_model to get or generate actual model class.
Explain what the following Python 3 code does def handle_model_generation(config, raml_resource): model_name = generate_model_name(raml_resource) try: return setup_data_model(config, raml_resource, model_name) except ValueError as ex: raise ValueError('{}: {}'.format(model_name, str(ex)))
As a Python code composer, you craft elegant and concise scripts.
Setup model event subscribers.
Can you generate a brief explanation for the following Python 3 code def setup_model_event_subscribers(config, model_cls, schema): events_map = get_events_map() model_events = schema.get('_event_handlers', {}) event_kwargs = {'model': model_cls} for event_tag, subscribers in model_events.items(): ...
As a Python code analyst, you investigate and solve complex coding mysteries
Setup model fields processors.
Can you generate a brief explanation for the following Python 3 code def setup_fields_processors(config, model_cls, schema): properties = schema.get('properties', {}) for field_name, props in properties.items(): if not props: continue processors = props.get('_processors') ba...
As a Python code composer, you craft elegant and concise scripts.
Define and return AuthUser model using nefertari base classes
Given the following Python 3 function, write the documentation def get_authuser_model(): from nefertari.authentication.models import AuthUserMixin from nefertari import engine class AuthUser(AuthUserMixin, engine.BaseDocument): __tablename__ = 'ramses_authuser' return AuthUser
You are a Python code generator, capable of creating scripts from specifications.
Validate :perms: contains valid permissions. :param perms: List of permission names or ALL_PERMISSIONS.
Can you tell what is the following Python 3 function doing def validate_permissions(perms): if not isinstance(perms, (list, tuple)): perms = [perms] valid_perms = set(PERMISSIONS.values()) if ALL_PERMISSIONS in perms: return perms if set(perms) - valid_perms: raise ValueError( ...
You are a Python code generator, capable of creating scripts from specifications.
Parse permission names which are either exact permission names or the keyword all.
Can you tell what is the following Python 3 function doing def parse_permissions(perms): if isinstance(perms, six.string_types): perms = perms.split(',') perms = [perm.strip().lower() for perm in perms] if 'all' in perms: return ALL_PERMISSIONS return validate_permissions(perms)
As a Python code analyst, you investigate and solve complex coding mysteries
Parses a string containing a list of ACEs and returns a list of ACEs.
Explain what the following Python 3 code does def parse_acl(acl_string): if not acl_string: return [ALLOW_ALL] aces_list = acl_string.replace('\n', ';').split(';') aces_list = [ace.strip().split(' ', 2) for ace in aces_list if ace] aces_list = [(a, b, c.split(',')) for a, b, c in aces_list] ...
As a Python code composer, you craft elegant and concise scripts.
Generate an ACL. Generated ACL class has a `item_model` attribute set to :model_cls:. ACLs used for collection and item access control are generated from a first security scheme with type `x-ACL`. If :raml_resource: has no x-ACL security schemes defined then ALLOW_ALL ACL is used. If the `...
Here you have a function in Python 3, explain what it does def generate_acl(config, model_cls, raml_resource, es_based=True): schemes = raml_resource.security_schemes or [] schemes = [sch for sch in schemes if sch.type == 'x-ACL'] if not schemes: collection_acl = item_acl = [] log.debug('No...
As a Python code composer, you craft elegant and concise scripts.
def _apply_callables(self, acl, obj=None): """ Iterate over ACEs from :acl: and apply callable principals if any. Principals are passed 3 arguments on call: :ace: Single ACE object that looks like (action, callable, permission or [permission]) :request: C...
Can you write a function in Python 3 where it iterates over ACEs from acl and apply callable principals to the object instance.
As a Python code analyst, you investigate and solve complex coding mysteries
def item_acl(self, item): """ Objectify ACL if ES is used or call item.get_acl() if db is used. """ if self.es_based: from nefertari_guards.elasticsearch import get_es_item_acl return get_es_item_acl(item) return super(DatabaseACLMixin, self).item_acl(item...
Write a Python 3 script for returning the objectify ACL for the given item.
As a Python code translator, you convert algorithms and pseudocode into Python.
Override to support ACL filtering.
Here you have a function in Python 3, explain what it does def getitem_es(self, key): from nefertari_guards.elasticsearch import ACLFilterES es = ACLFilterES(self.item_model.__name__) params = { 'id': key, 'request': self.request, } obj = es.get_item(**par...
As a Python code composer, you craft elegant and concise scripts.
def convert_schema(raml_schema, mime_type): """ Restructure `raml_schema` to a dictionary that has 'properties' as well as other schema keys/values. The resulting dictionary looks like this:: { "properties": { "field1": { "required": boolean, "type":...
Write a Python 3 script for converting a RAML schema to a dictionary that has properties and other schema keys and values.
As a Python code composer, you craft elegant and concise scripts.
def generate_model_name(raml_resource): """ Generate model name. :param raml_resource: Instance of ramlfications.raml.ResourceNode. """ resource_uri = get_resource_uri(raml_resource).strip('/') resource_uri = re.sub('\W', ' ', resource_uri) model_name = inflection.titleize(resource_uri) ret...
Create a Python 3 function for generating model name. :param raml_resource: Instance of ramlfications.raml.ResourceNode.
As a Python code composer, you craft elegant and concise scripts.
Generate a dynamic part name for a resource.
How would you explain what the following Python 3 function does def dynamic_part_name(raml_resource, route_name, pk_field): subresources = get_resource_children(raml_resource) dynamic_uris = [res.path for res in subresources if is_dynamic_uri(res.path)] if dynamic_uris: dynamic_p...
You are a Python code analyst, evaluating scripts for potential improvements.
Extract dynamic url part from URI string.
Make a summary of the following Python 3 code def extract_dynamic_part(uri): for part in uri.split('/'): part = part.strip() if part.startswith('{') and part.endswith('}'): return clean_dynamic_uri(part)
As a Python code analyst, you investigate and solve complex coding mysteries
Generate view method names needed for a resource node.
How would you explain what the following Python 3 function does def resource_view_attrs(raml_resource, singular=False): from .views import collection_methods, item_methods # Singular resource doesn't have collection methods though # it looks like a collection if singular: collection_methods = it...
As a Python code analyst, you investigate and solve complex coding mysteries
def resource_schema(raml_resource): """ Get schema properties of RAML resource :raml_resource:. Must be called with RAML resource that defines body schema. First body that defines schema is used. Schema is converted on return using 'convert_schema'. :param raml_resource: Instance of ramlfications....
Write a Python 3 function for getting schema properties of a resource.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get static parent resource of the resource with HTTP method method.
Make a summary of the following Python 3 code def get_static_parent(raml_resource, method=None): parent = raml_resource.parent while is_dynamic_resource(parent): parent = parent.parent if parent is None: return parent match_method = method is not None if match_method: if pa...
You are a Python code generator, capable of creating scripts from specifications.
def attr_subresource(raml_resource, route_name): """ Determine if :raml_resource: is an attribute subresource. :param raml_resource: Instance of ramlfications.raml.ResourceNode. :param route_name: Name of the :raml_resource:. """ static_parent = get_static_parent(raml_resource, method='POST') i...
Write a Python 3 function for determining if the given resource is an attribute subresource.
You are a Python code analyst, evaluating scripts for potential improvements.
def singular_subresource(raml_resource, route_name): """ Determine if :raml_resource: is a singular subresource. :param raml_resource: Instance of ramlfications.raml.ResourceNode. :param route_name: Name of the :raml_resource:. """ static_parent = get_static_parent(raml_resource, method='POST') ...
Implement a function in Python 3 to determine if the resource is a singular subresource.
As a Python code composer, you craft elegant and concise scripts.
def is_callable_tag(tag): """ Determine whether :tag: is a valid callable string tag. String is assumed to be valid callable if it starts with '{{' and ends with '}}'. :param tag: String name of tag. """ return (isinstance(tag, six.string_types) and tag.strip().startswith('{{') and...
Write a Python 3 function that can determine whether a tag is a valid callable string.
As a python code expert, you are capable of creating scripts from specifications.
def resolve_to_callable(callable_name): """ Resolve string :callable_name: to a callable. :param callable_name: String representing callable name as registered in ramses registry or dotted import path of callable. Can be wrapped in double curly brackets, e.g. '{{my_callable}}'. """ from...
Write a Python 3 function for resolving string to a callable.
As a Python code composer, you craft elegant and concise scripts.
def get_resource_siblings(raml_resource): """ Get siblings of :raml_resource:. :param raml_resource: Instance of ramlfications.raml.ResourceNode. """ path = raml_resource.path return [res for res in raml_resource.root.resources if res.path == path]
Create a Python 3 function for getting siblings of a resource node.
As a Python code composer, you craft elegant and concise scripts.
Get children of a resource.
Here you have a function in Python 3, explain what it does def get_resource_children(raml_resource): path = raml_resource.path return [res for res in raml_resource.root.resources if res.parent and res.parent.path == path]
As a python code expert, you are capable of creating scripts from specifications.
def get_events_map(): """ Prepare map of event subscribers. * Extends copies of BEFORE_EVENTS and AFTER_EVENTS maps with 'set' action. * Returns map of {before/after: {action: event class(es)}} """ from nefertari import events set_keys = ('create', 'update', 'replace', 'update_many', 'r...
Write a Python 3 function that can prepare a map of event subscribers.
As a Python code composer, you craft elegant and concise scripts.
def patch_view_model(view_cls, model_cls): """ Patches view_cls.Model with model_cls. :param view_cls: View class "Model" param of which should be patched :param model_cls: Model class which should be used to patch view_cls.Model """ original_model = view_cls.Model view_cls.Mode...
How would you code a function in Python 3 to patch view_cls. Model with model_cls.
As a python code expert, you are capable of creating scripts from specifications.
def get_route_name(resource_uri): """ Get route name from RAML resource URI. :param resource_uri: String representing RAML resource URI. :returns string: String with route name, which is :resource_uri: stripped of non-word characters. """ resource_uri = resource_uri.strip('/') resource_...
Create a Python 3 function to get route name from RAML resource URI.
As a Python code translator, you convert algorithms and pseudocode into Python.
def generate_resource(config, raml_resource, parent_resource): """ Perform complete one resource configuration process This function generates: ACL, view, route, resource, database model for a given `raml_resource`. New nefertari resource is attached to `parent_resource` class which is an instance of ...
Can you implement a function in Python 3 that generates nefertari resource structure for a given resource.
As a python code expert, you are capable of creating scripts from specifications.
Generate server resources for a given RAML file.
Make a summary of the following Python 3 code def generate_server(raml_root, config): log.info('Server generation started') if not raml_root.resources: return root_resource = config.get_root_resource() generated_resources = {} for raml_resource in raml_root.resources: if raml_reso...
You are a Python code generator, capable of creating scripts from specifications.
Generate models for each resource in the list of resource nodes.
Given the following Python 3 function, write the documentation def generate_models(config, raml_resources): from .models import handle_model_generation if not raml_resources: return for raml_resource in raml_resources: # No need to generate models for dynamic resource if is_dynamic_u...
You are a Python code generator, capable of creating scripts from specifications.
Generate REST view for a given model class.
How would you explain what the following Python 3 function does def generate_rest_view(config, model_cls, attrs=None, es_based=True, attr_view=False, singular=False): """ Generate REST view for a model class. :param model_cls: Generated DB model class. :param attr: List of strings th...
As a Python code analyst, you investigate and solve complex coding mysteries
Set object ACL on creation if not already present.
Can you tell what is the following Python 3 function doing def set_object_acl(self, obj): if not obj._acl: from nefertari_guards import engine as guards_engine acl = self._factory(self.request).generate_item_acl(obj) obj._acl = guards_engine.ACLField.stringify_acl(acl)
As a Python code analyst, you investigate and solve complex coding mysteries
Resolve keyword arguments to the form of id 1.
Make a summary of the following Python 3 code def resolve_kw(self, kwargs): resolved = {} for key, value in kwargs.items(): split = key.split('_', 1) if len(split) > 1: key = split[1] resolved[key] = value return resolved
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the URL of the object in the resource.
Can you generate a brief explanation for the following Python 3 code def _location(self, obj): field_name = self.clean_id_name return self.request.route_url( self._resource.uid, **{self._resource.id_name: getattr(obj, field_name)})
As a Python code translator, you convert algorithms and pseudocode into Python.
Get queryset of parent view.
Can you generate the documentation for the following Python 3 function def _parent_queryset(self): parent = self._resource.parent if hasattr(parent, 'view'): req = self.request.blank(self.request.path) req.registry = self.request.registry req.matchdict = { ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_collection(self, **kwargs): """ Get objects collection taking into account generated queryset of parent view. This method allows working with nested resources properly. Thus a queryset returned by this method will be a subset of its parent view's queryset, thus filtering...
Write a Python 3 script for getting objects collection taking into account generated queryset of parent view.
As a python code expert, you are capable of creating scripts from specifications.
def get_item(self, **kwargs): """ Get collection item taking into account generated queryset of parent view. This method allows working with nested resources properly. Thus an item returned by this method will belong to its parent view's queryset, thus filtering out objects that...
Write a Python 3 function for getting the item from the parent view.
As a Python code composer, you craft elegant and concise scripts.
def reload_context(self, es_based, **kwargs): """ Reload `self.context` object into a DB or ES object. A reload is performed by getting the object ID from :kwargs: and then getting a context key item from the new instance of `self._factory` which is an ACL class used by the current view...
Can you create a Python 3 function that reloads the current context object into a DB or ES object.
As a python code expert, you are capable of creating scripts from specifications.
def _parent_queryset_es(self): """ Get queryset (list of object IDs) of parent view. The generated queryset is used to run queries in the current level's view. """ parent = self._resource.parent if hasattr(parent, 'view'): req = self.request.blank(self.reques...
Can you write a function in Python 3 where it gets queryset of objects of parent view.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_es_object_ids(self, objects): """ Return IDs of :objects: if they are not IDs already. """ id_field = self.clean_id_name ids = [getattr(obj, id_field, obj) for obj in objects] return list(set(str(id_) for id_ in ids))
Create a Python 3 function for returning the set of IDs of the objects in the ES database.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_collection_es(self): """ Get ES objects collection taking into account the generated queryset of parent view. This method allows working with nested resources properly. Thus a queryset returned by this method will be a subset of its parent view's queryset, thus filtering...
Can you create a Python 3 function that gets ES objects collection taking into account the generated queryset of parent view.
You are a Python code architect, reviewing and designing scalable and efficient code
Get an ES collection item taking into account generated queryset of parent view.
Can you tell what is the following Python 3 function doing def get_item_es(self, **kwargs): item_id = self._get_context_key(**kwargs) objects_ids = self._parent_queryset_es() if objects_ids is not None: objects_ids = self.get_es_object_ids(objects_ids) if six.callable(self.c...
As a Python code analyst, you investigate and solve complex coding mysteries
Get DB objects collection by first querying ES.
Given the following Python 3 function, write the documentation def get_dbcollection_with_es(self, **kwargs): es_objects = self.get_collection_es() db_objects = self.Model.filter_objects(es_objects) return db_objects
You are a Python code analyst, evaluating scripts for potential improvements.