output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def update(self, item, **kwargs): """ Update the information in this instance. :param item: a dictionary or a Message instance """ if isinstance(item, dict): self._dict.update(item) elif isinstance(item, Message): for key, val in item.ite...
Can you create a Python 3 function that updates the information in this instance.
As a Python code analyst, you investigate and solve complex coding mysteries
This method will take the information in this instance and then encrypt it with the given keys.
Can you generate a brief explanation for the following Python 3 code def to_jwe(self, keys, enc, alg, lev=0): _jwe = JWE(self.to_json(lev), alg=alg, enc=enc) return _jwe.encrypt(keys)
You are a Python code generator, capable of creating scripts from specifications.
Decrypt an encrypted JWT and load the JSON object that was the body of the JWT into this object.
Can you generate the documentation for the following Python 3 function def from_jwe(self, msg, keys): jwe = JWE() _res = jwe.decrypt(msg, keys) return self.from_json(_res.decode())
You are a Python code analyst, evaluating scripts for potential improvements.
Remove all key value pairs that are not standard
Can you generate a brief explanation for the following Python 3 code def weed(self): _ext = [k for k in self._dict.keys() if k not in self.c_param] for k in _ext: del self._dict[k]
As a Python code composer, you craft elegant and concise scripts.
def rm_blanks(self): """ Get rid of parameters that has no value. """ _blanks = [k for k in self._dict.keys() if not self._dict[k]] for key in _blanks: del self._dict[key]
Write a Python 3 script for removing parameters that have no value.
As a Python code composer, you craft elegant and concise scripts.
def proper_path(path): """ Clean up the path specification so it looks like something I could use. "./" <path> "/" """ if path.startswith("./"): pass elif path.startswith("/"): path = ".%s" % path elif path.startswith("."): while path.startswith("."): path...
Can you create a Python 3 function that cleans up the path specification so it looks like something I could use.
You are a Python code architect, reviewing and designing scalable and efficient code
Wrap text in an ansi escape sequence
Can you generate the documentation for the following Python 3 function def ansi(color, text): code = COLOR_CODES[color] return '\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)
As a Python code analyst, you investigate and solve complex coding mysteries
Decorator for methods that need to query security. It ensures all security related operations are flushed to DB.
Explain what the following Python 3 code does def require_flush(fun): @wraps(fun) def ensure_flushed(service, *args, **kwargs): if service.app_state.needs_db_flush: session = db.session() if not session._flushing and any( isinstance(m, (RoleAssignment, SecurityAu...
As a python code expert, you are capable of creating scripts from specifications.
def query_pa_no_flush(session, permission, role, obj): """Query for a :class:`PermissionAssignment` using `session` without any `flush()`. It works by looking in session `new`, `dirty` and `deleted`, and issuing a query with no autoflush. .. note:: This function is used by `add_permission...
Write a Python 3 function that can query for a : class:`PermissionAssignment` using the given session and permission role and object.
You are a Python code analyst, evaluating scripts for potential improvements.
def _current_user_manager(self, session=None): """Return the current user, or SYSTEM user.""" if session is None: session = db.session() try: user = g.user except Exception: return session.query(User).get(0) if sa.orm.object_session(user) is ...
How would you code a function in Python 3 to return the current user or SYSTEM user.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_roles(self, principal, object=None, no_group_roles=False): """Get all the roles attached to given `principal`, on a given `object`. :param principal: a :class:`User` or :class:`Group` :param object: an :class:`Entity` :param no_group_roles: If `True`, return only direc...
Can you write a function in Python 3 where it gets all the roles attached to a given principal on a given object.
You are a Python code generator, capable of creating scripts from specifications.
Return all users which are assigned given role.
Can you generate the documentation for the following Python 3 function def get_principals( self, role, anonymous=True, users=True, groups=True, object=None, as_list=True ): """Return all users which are assigned given role.""" if not isinstance(role, Role): role = Role(role) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _fill_role_cache(self, principal, overwrite=False): """Fill role cache for `principal` (User or Group), in order to avoid too many queries when checking role access with 'has_role'. Return role_cache of `principal` """ if not self.app_state.use_cache: return None...
Write a Python 3 function that can fill role cache for the given principal.
You are a Python code generator, capable of creating scripts from specifications.
def _fill_role_cache_batch(self, principals, overwrite=False): """Fill role cache for `principals` (Users and/or Groups), in order to avoid too many queries when checking role access with 'has_role'.""" if not self.app_state.use_cache: return query = db.session.query(RoleAss...
How would you code a function in Python 3 to fill role cache for principals in order to avoid too many queries when checking role access with has_role.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns True if the user has the specified role.
Can you generate a brief explanation for the following Python 3 code def has_role(self, principal, role, object=None): if not principal: return False principal = unwrap(principal) if not self.running: return True if isinstance(role, (Role, (str,))): ...
As a python code expert, you are capable of creating scripts from specifications.
def grant_role(self, principal, role, obj=None): """Grant `role` to `user` (either globally, if `obj` is None, or on the specific `obj`).""" assert principal principal = unwrap(principal) session = object_session(obj) if obj is not None else db.session manager = self._cur...
How would you implement a function in Python 3 that grants role to user.
As a python code expert, you are capable of creating scripts from specifications.
Ungrant a role to a user.
Explain what the following Python 3 code does def ungrant_role(self, principal, role, object=None): assert principal principal = unwrap(principal) session = object_session(object) if object is not None else db.session manager = self._current_user_manager(session=session) args = ...
As a Python code analyst, you investigate and solve complex coding mysteries
def has_permission(self, user, permission, obj=None, inherit=False, roles=None): """ :param obj: target object to check permissions. :param inherit: check with permission inheritance. By default, check only local roles. :param roles: additional valid role or itera...
Can you implement a function in Python 3 that checks if user has permission.
As a Python code analyst, you investigate and solve complex coding mysteries
Filter a query on an Entity or a Model with a permission.
Can you tell what is the following Python 3 function doing def query_entity_with_permission(self, permission, user=None, Model=Entity): assert isinstance(permission, Permission) assert issubclass(Model, Entity) RA = sa.orm.aliased(RoleAssignment) PA = sa.orm.aliased(PermissionAssignment)...
As a Python code composer, you craft elegant and concise scripts.
def get_permissions_assignments(self, obj=None, permission=None): """ :param permission: return only roles having this permission :returns: an dict where keys are `permissions` and values `roles` iterable. """ session = None if obj is not None: assert isinsta...
Create a Python 3 function for returning only roles having this permission
As a Python code composer, you craft elegant and concise scripts.
Register webassets bundle to be served on all pages.
Can you generate the documentation for the following Python 3 function def register_asset(self, type_, *assets): supported = list(self._assets_bundles.keys()) if type_ not in supported: msg = "Invalid type: {}. Valid types: {}".format( repr(type_), ", ".join(sorted(supported)...
As a Python code composer, you craft elegant and concise scripts.
Register templates path translations files like select2_locale_lang. js.
Given the following Python 3 function, write the documentation def register_i18n_js(self, *paths): languages = self.config["BABEL_ACCEPT_LANGUAGES"] assets = self.extensions["webassets"] for path in paths: for lang in languages: filename = path.format(lang=lang) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def register_base_assets(self): """Register assets needed by Abilian. This is done in a separate method in order to allow applications to redefine it at will. """ from abilian.web import assets as bundles self.register_asset("css", bundles.LESS) self.register_as...
Can you implement a function in Python 3 that registers assets needed by Abilian.
As a python code expert, you are capable of creating scripts from specifications.
def user_photo_url(user, size): """Return url to use for this user.""" endpoint, kwargs = user_url_args(user, size) return url_for(endpoint, **kwargs)
How would you code a function in Python 3 to return url to use for this user.
As a Python code analyst, you investigate and solve complex coding mysteries
Brand new logins each day and total of users each day.
Can you generate the documentation for the following Python 3 function def newlogins(sessions): if not sessions: return [], [] users = {} dates = {} for session in sessions: user = session.user # time value is discarded to aggregate on days only date = session.started_at...
As a Python code composer, you craft elegant and concise scripts.
Unique logins per day weeks and months.
Can you generate a brief explanation for the following Python 3 code def uniquelogins(sessions): # sessions = LoginSession.query.order_by(LoginSession.started_at.asc()).all() if not sessions: return [], [], [] dates = {} for session in sessions: user = session.user # time value i...
You are a Python code architect, reviewing and designing scalable and efficient code
def allow_access_for_roles(roles): """Access control helper to check user's roles against a list of valid roles.""" if isinstance(roles, Role): roles = (roles,) valid_roles = frozenset(roles) if Anonymous in valid_roles: return allow_anonymous def check_role(user, roles, **kwar...
How would you code a function in Python 3 to access control helper to check user s roles against a list of valid roles.
As a Python code composer, you craft elegant and concise scripts.
Gets the primary key from an identity object.
Can you generate the documentation for the following Python 3 function def _get_pk_from_identity(obj): from sqlalchemy.orm.util import identity_key cls, key = identity_key(instance=obj)[0:2] return ":".join(text_type(x) for x in key)
As a Python code translator, you convert algorithms and pseudocode into Python.
def keys(self, prefix=None): """List all keys, with optional prefix filtering.""" query = Setting.query if prefix: query = query.filter(Setting.key.startswith(prefix)) # don't use iteritems: 'value' require little processing whereas we only # want 'key' retur...
How would you implement a function in Python 3 that lists all keys with optional prefix filtering.
You are a Python code generator, capable of creating scripts from specifications.
Register an entity as a commentable class.
How would you explain what the following Python 3 function does def register(cls): if not issubclass(cls, Entity): raise ValueError("Class must be a subclass of abilian.core.entities.Entity") Commentable.register(cls) return cls
You are a Python code architect, reviewing and designing scalable and efficient code
def is_commentable(obj_or_class): """ :param obj_or_class: a class or instance """ if isinstance(obj_or_class, type): return issubclass(obj_or_class, Commentable) if not isinstance(obj_or_class, Commentable): return False if obj_or_class.id is None: return False re...
How would you code a function in Python 3 to return True if the object is Commentable
You are a Python code architect, reviewing and designing scalable and efficient code
Return comments on an entity.
Can you generate a brief explanation for the following Python 3 code def for_entity(obj, check_commentable=False): if check_commentable and not is_commentable(obj): return [] return getattr(obj, ATTRIBUTE)
You are a Python code analyst, evaluating scripts for potential improvements.
def available(self, context): """Determine if this actions is available in this `context`. :param context: a dict whose content is left to application needs; if :attr:`.condition` is a callable it receives `context` in parameter. """ if no...
Can you create a Python 3 function that determines if this actions is available in this context.
You are a Python code generator, capable of creating scripts from specifications.
def installed(self, app=None): """Return `True` if the registry has been installed in current applications.""" if app is None: app = current_app return self.__EXTENSION_NAME in app.extensions
Write a Python 3 function that can return True if the registry has been installed in current applications.
As a python code expert, you are capable of creating scripts from specifications.
Register actions in the current application.
Explain what the following Python 3 code does def register(self, *actions): assert self.installed(), "Actions not enabled on this application" assert all(isinstance(a, Action) for a in actions) for action in actions: cat = action.category reg = self._state["categories"]....
You are a Python code analyst, evaluating scripts for potential improvements.
Return a mapping of category => actions list.
Can you generate a brief explanation for the following Python 3 code def actions(self, context=None): assert self.installed(), "Actions not enabled on this application" result = {} if context is None: context = self.context for cat, actions in self._state["categories"].items...
You are a Python code architect, reviewing and designing scalable and efficient code
def for_category(self, category, context=None): """Returns actions list for this category in current application. Actions are filtered according to :meth:`.Action.available`. if `context` is None, then current action context is used (:attr:`context`) """ assert self.ins...
Create a Python 3 function to return the list of actions for this category in current application.
You are a Python code analyst, evaluating scripts for potential improvements.
def babel2datetime(pattern): """Convert date format from babel (http://babel.pocoo.org/docs/dates/#date- fields)) to a format understood by datetime.strptime.""" if not isinstance(pattern, DateTimePattern): pattern = parse_pattern(pattern) map_fmt = { # days "d": "%d", "...
Create a Python 3 function for converting date format from babel to datetime. strptime.
As a Python code analyst, you investigate and solve complex coding mysteries
Return the last known session for given user.
How would you explain what the following Python 3 function does def get_active_for(self, user, user_agent=_MARK, ip_address=_MARK): conditions = [LoginSession.user == user] if user_agent is not _MARK: if user_agent is None: user_agent = request.environ.get("HTTP_USER_AGENT",...
As a Python code translator, you convert algorithms and pseudocode into Python.
def show(only_path=False): """Show the current config.""" logger.setLevel(logging.INFO) infos = ["\n", f'Instance path: "{current_app.instance_path}"'] logger.info("\n ".join(infos)) if not only_path: log_config(current_app.config)
Can you implement a function in Python 3 that shows the current config.
As a Python code composer, you craft elegant and concise scripts.
Check if an event should be handled.
Can you generate the documentation for the following Python 3 function def should_handle(self, event_type, filename): return (event_type in ("modified", "created") and filename.startswith(self.searchpath) and os.path.isfile(filename))
As a Python code translator, you convert algorithms and pseudocode into Python.
Protects a view agains CSRF attacks by checking the csrf_token value in submitted values.
Here you have a function in Python 3, explain what it does def protect(view): @wraps(view) def csrf_check(*args, **kwargs): # an empty form is used to validate current csrf token and only that! if not FlaskForm().validate(): raise Forbidden("CSRF validation failed.") return...
As a python code expert, you are capable of creating scripts from specifications.
def createuser(email, password, role=None, name=None, first_name=None): """Create new user.""" if User.query.filter(User.email == email).count() > 0: print(f"A user with email '{email}' already exists, aborting.") return # if password is None: # password = prompt_pass("Password") ...
Implement a Python 3 function for creating a new user.
As a python code expert, you are capable of creating scripts from specifications.
Generate a slug from Entity. auto_slug if it is not already set.
Explain what the following Python 3 code does def auto_slug_on_insert(mapper, connection, target): if target.slug is None and target.name: target.slug = target.auto_slug
As a Python code analyst, you investigate and solve complex coding mysteries
Generate a slug from entity_type and id unless slug is already set.
Can you tell what is the following Python 3 function doing def auto_slug_after_insert(mapper, connection, target): if target.slug is None: target.slug = "{name}{sep}{id}".format( name=target.entity_class.lower(), sep=target.SLUG_SEPARATOR, id=target.id )
As a Python code translator, you convert algorithms and pseudocode into Python.
Setup default permissions on newly created entities according to. .
Can you tell what is the following Python 3 function doing def setup_default_permissions(session, instance): if instance not in session.new or not isinstance(instance, Entity): return if not current_app: # working outside app_context. Raw object manipulation return _setup_default_p...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _setup_default_permissions(instance): """Separate method to conveniently call it from scripts for example.""" from abilian.services import get_service security = get_service("security") for permission, roles in instance.__default_permissions__: if permission == "create": # use s...
Write a Python 3 function for separating method to conveniently call it from scripts for example.
You are a Python code generator, capable of creating scripts from specifications.
Return the list of all concrete persistent classes that are subclasses of Entity.
Explain what the following Python 3 code does def all_entity_classes(): persistent_classes = Entity._decl_class_registry.values() # with sqlalchemy 0.8 _decl_class_registry holds object that are not # classes return [ cls for cls in persistent_classes if isclass(cls) and issubclass(cls, Entity) ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _indexable_roles_and_users(self): """Return a string made for indexing roles having :any:`READ` permission on this object.""" from abilian.services.indexing import indexable_role from abilian.services.security import READ, Admin, Anonymous, Creator, Owner from abilian.service...
Write a Python 3 script to return a string made for indexing roles having READ permission on this object.
You are a Python code generator, capable of creating scripts from specifications.
def _indexable_tags(self): """Index tag ids for tags defined in this Entity's default tags namespace.""" tags = current_app.extensions.get("tags") if not tags or not tags.supports_taggings(self): return "" default_ns = tags.entity_default_ns(self) return [t f...
How would you implement a function in Python 3 that indexes tag ids for tags defined in this Entity s default tags namespace.
You are a Python code architect, reviewing and designing scalable and efficient code
def country_choices(first=None, default_country_first=True): """Return a list of (code, countries), alphabetically sorted on localized country name. :param first: Country code to be placed at the top :param default_country_first: :type default_country_first: bool """ locale = _get_locale() ...
Write a Python 3 script to return a list of ( code countries ) alphabetically sorted on localized country name.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns an iterable of tuples containing locale codes and labels supported by current application.
How would you explain what the following Python 3 function does def supported_app_locales(): locale = _get_locale() codes = current_app.config["BABEL_ACCEPT_LANGUAGES"] return ((Locale.parse(code), locale.languages.get(code, code)) for code in codes)
As a Python code composer, you craft elegant and concise scripts.
def timezones_choices(): """Timezones values and their labels for current locale. :return: an iterable of `(code, label)`, code being a timezone code and label the timezone name in current locale. """ utcnow = pytz.utc.localize(datetime.utcnow()) locale = _get_locale() for tz in sorted(pytz...
How would you code a function in Python 3 to return an iterable of tuples with code and label for each timezone in current locale.
As a python code expert, you are capable of creating scripts from specifications.
def _get_translations_multi_paths(): """Return the correct gettext translations that should be used for this request. This will never fail and return a dummy translation object if used outside of the request or if a translation cannot be found. """ ctx = _request_ctx_stack.top if ctx is Non...
Can you implement a function in Python 3 that returns the correct gettext translations that should be used for this request.
As a Python code analyst, you investigate and solve complex coding mysteries
def localeselector(): """Default locale selector used in abilian applications.""" # if a user is logged in, use the locale from the user settings user = getattr(g, "user", None) if user is not None: locale = getattr(user, "locale", None) if locale: return locale # Otherw...
Write a Python 3 script to default locale selector used in abilian applications.
As a Python code analyst, you investigate and solve complex coding mysteries
Build a list of templates with preceding locale if found.
Given the following Python 3 function, write the documentation def get_template_i18n(template_name, locale): if locale is None: return [template_name] template_list = [] parts = template_name.rsplit(".", 1) root = parts[0] suffix = parts[1] if locale.territory is not None: loca...
You are a Python code analyst, evaluating scripts for potential improvements.
def render_template_i18n(template_name_or_list, **context): """Try to build an ordered list of template to satisfy the current locale.""" template_list = [] # Use locale if present in **context if "locale" in context: locale = Locale.parse(context["locale"]) else: # Use get_local...
Can you implement a function in Python 3 that tries to build an ordered list of template to satisfy the current locale.
As a Python code analyst, you investigate and solve complex coding mysteries
Add translations from external module.
Explain what the following Python 3 code does def add_translations( self, module_name, translations_dir="translations", domain="messages" ): """Add translations from external module. For example:: babel.add_translations('abilian.core') Will add translations files from ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a response object with the content - type and filename as the content - disposition header.
Given the following Python 3 function, write the documentation def get(self, attach, *args, **kwargs): response = self.make_response(*args, **kwargs) # type: Response response.content_type = self.get_content_type(*args, **kwargs) if attach: filename = self.get_filename(*args, **kwa...
As a Python code composer, you craft elegant and concise scripts.
def ping_connection(dbapi_connection, connection_record, connection_proxy): """Ensure connections are valid. From: `http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html` In case db has been restarted pool may return invalid connections. """ cursor = dbapi_connection.cursor() try: cu...
How would you implement a function in Python 3 that pings the connection to the database.
You are a Python code analyst, evaluating scripts for potential improvements.
def filter_cols(model, *filtered_columns): """Return columnsnames for a model except named ones. Useful for defer() for example to retain only columns of interest """ m = sa.orm.class_mapper(model) return list( {p.key for p in m.iterate_properties if hasattr(p, "columns")}.difference( ...
Create a Python 3 function for returning columnsnames for a model except named ones.
As a Python code translator, you convert algorithms and pseudocode into Python.
Stores a list as JSON on database with mutability support.
Given the following Python 3 function, write the documentation def JSONList(*args, **kwargs): type_ = JSON try: if kwargs.pop("unique_sorted"): type_ = JSONUniqueListType except KeyError: pass return MutationList.as_mutable(type_(*args, **kwargs))
As a Python code composer, you craft elegant and concise scripts.
def coerce(cls, key, value): """Convert plain dictionaries to MutationDict.""" if not isinstance(value, MutationDict): if isinstance(value, dict): return MutationDict(value) # this call will raise ValueError return Mutable.coerce(key, value) e...
Implement a Python 3 function for converting plain dictionaries to MutationDict.
As a python code expert, you are capable of creating scripts from specifications.
Convert list to MutationList.
Make a summary of the following Python 3 code def coerce(cls, key, value): if not isinstance(value, MutationList): if isinstance(value, list): return MutationList(value) # this call will raise ValueError return Mutable.coerce(key, value) else: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_file(self, user, file_obj, **metadata): """Add a new file. :returns: file handle """ user_dir = self.user_dir(user) if not user_dir.exists(): user_dir.mkdir(mode=0o775) handle = str(uuid1()) file_path = user_dir / handle with file_pa...
Write a Python 3 function that can add a new file.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_file(self, user, handle): """Retrieve a file for a user. :returns: a :class:`pathlib.Path` instance to this file, or None if no file can be found for this handle. """ user_dir = self.user_dir(user) if not user_dir.exists(): return None if...
Implement a function in Python 3 to retrieve a file for a user.
As a python code expert, you are capable of creating scripts from specifications.
Scan upload directory and delete stalled files.
Here you have a function in Python 3, explain what it does def clear_stalled_files(self): # FIXME: put lock in directory? CLEAR_AFTER = self.config["DELETE_STALLED_AFTER"] minimum_age = time.time() - CLEAR_AFTER for user_dir in self.UPLOAD_DIR.iterdir(): if not user_dir.is_d...
You are a Python code architect, reviewing and designing scalable and efficient code
Friendly name of fully qualified class name.
Here you have a function in Python 3, explain what it does def friendly_fqcn(cls_name): if isinstance(cls_name, type): cls_name = fqcn(cls_name) return cls_name.rsplit(".", 1)[-1]
As a python code expert, you are capable of creating scripts from specifications.
Return a naive or aware datetime in system timezone.
Make a summary of the following Python 3 code def local_dt(dt): if not dt.tzinfo: dt = pytz.utc.localize(dt) return LOCALTZ.normalize(dt.astimezone(LOCALTZ))
As a python code expert, you are capable of creating scripts from specifications.
def utc_dt(dt): """Set UTC timezone on a datetime object. A naive datetime is assumed to be in UTC TZ. """ if not dt.tzinfo: return pytz.utc.localize(dt) return dt.astimezone(pytz.utc)
Can you write a function in Python 3 where it sets UTC timezone on a datetime object.
As a python code expert, you are capable of creating scripts from specifications.
def get_params(names): """Return a dictionary with params from request. TODO: I think we don't use it anymore and it should be removed before someone gets hurt. """ params = {} for name in names: value = request.form.get(name) or request.files.get(name) if value is not None: ...
Can you implement a function in Python 3 that returns a dictionary with params from request.
As a Python code translator, you convert algorithms and pseudocode into Python.
Validate that a string made of numeric characters verify Luhn test. Used by siret validator.
Here you have a function in Python 3, explain what it does def luhn(n): r = [int(ch) for ch in str(n)][::-1] return (sum(r[0::2]) + sum(sum(divmod(d * 2, 10)) for d in r[1::2])) % 10 == 0
You are a Python code architect, reviewing and designing scalable and efficient code
Validate a SIRET field.
Can you tell what is the following Python 3 function doing def siret_validator(): def _validate_siret(form, field, siret=""): """SIRET validator. A WTForm validator wants a form and a field as parameters. We also want to give directly a siret, for a scripting use. """ if fi...
You are a Python code generator, capable of creating scripts from specifications.
def abs_path(self, uuid): # type: (UUID) -> Path """Return absolute :class:`Path` object for given uuid. :param:uuid: :class:`UUID` instance """ top = self.app_state.path rel_path = self.rel_path(uuid) dest = top / rel_path assert top in dest.parents ...
How would you implement a function in Python 3 that returns absolute path for given uuid.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get(self, uuid, default=None): # type: (UUID, Optional[Path]) -> Optional[Path] """Return absolute :class:`Path` object for given uuid, if this uuid exists in repository, or `default` if it doesn't. :param:uuid: :class:`UUID` instance """ path = self.abs_path(uuid) ...
Create a Python 3 function for returning absolute path object for given uuid if this uuid does not exist in repository or default if it doesn t exist.
As a python code expert, you are capable of creating scripts from specifications.
def set(self, uuid, content, encoding="utf-8"): # type: (UUID, Any, Optional[Text]) -> None """Store binary content with uuid as key. :param:uuid: :class:`UUID` instance :param:content: string, bytes, or any object with a `read()` method :param:encoding: encoding to use when con...
Create a Python 3 function to store binary content with uuid as key.
As a Python code translator, you convert algorithms and pseudocode into Python.
Delete file with given uuid.
Given the following Python 3 function, write the documentation def delete(self, uuid): # type: (UUID) -> None """Delete file with given uuid. :param:uuid: :class:`UUID` instance :raises:KeyError if file does not exists """ dest = self.abs_path(uuid) if not dest.e...
You are a Python code generator, capable of creating scripts from specifications.
def set_transaction(self, session, transaction): # type: (Session, RepositoryTransaction) -> None """ :param:session: :class:`sqlalchemy.orm.session.Session` instance :param:transaction: :class:`RepositoryTransaction` instance """ if isinstance(session, sa.orm.scoped_sess...
How would you implement a function in Python 3 that sets the given session as the current transaction.
As a Python code composer, you craft elegant and concise scripts.
def _session_for(self, model_or_session): """Return session instance for object parameter. If parameter is a session instance, it is return as is. If parameter is a registered model instance, its session will be used. If parameter is a detached model instance, or None, application scop...
Create a Python 3 function to return a session instance for the specified object parameter.
As a Python code translator, you convert algorithms and pseudocode into Python.
Commit all modified objects into parent transaction.
Explain what the following Python 3 code does def commit(self, session=None): if self.__cleared: return if self._parent: # nested transaction self._commit_parent() else: self._commit_repository() self._clear()
As a Python code analyst, you investigate and solve complex coding mysteries
Add item to dest set ensuring item is not present in other set.
Make a summary of the following Python 3 code def _add_to(self, uuid, dest, other): _assert_uuid(uuid) try: other.remove(uuid) except KeyError: pass dest.add(uuid)
As a Python code composer, you craft elegant and concise scripts.
Class decorator that sets default tags namespace to use with its instances.
Can you generate the documentation for the following Python 3 function def ns(ns): def setup_ns(cls): setattr(cls, ENTITY_DEFAULT_NS_ATTR, ns) return cls return setup_ns
You are a Python code generator, capable of creating scripts from specifications.
Returns an iterable of Tag instances from a hit.
Make a summary of the following Python 3 code def tags_from_hit(self, tag_ids): ids = [] for t in tag_ids.split(): t = t.strip() try: t = int(t) except ValueError: pass else: ids.append(t) if not ids...
You are a Python code architect, reviewing and designing scalable and efficient code
def entity_tags_form(self, entity, ns=None): """Construct a form class with a field for tags in namespace `ns`.""" if ns is None: ns = self.entity_default_ns(entity) field = TagsField(label=_l("Tags"), ns=ns) cls = type("EntityNSTagsForm", (_TagsForm,), {"tags": field}) ...
Can you write a function in Python 3 where it constructs a form class with a field for tags in namespace ns.
You are a Python code analyst, evaluating scripts for potential improvements.
def get(self, ns, label=None): """Return :class:`tags instances<~Tag>` for the namespace `ns`, ordered by label. If `label` is not None the only one instance may be returned, or `None` if no tags exists for this label. """ query = Tag.query.filter(Tag.ns == ns) ...
Can you create a Python 3 function that returns all tags for the namespace ns ordered by label.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a dict of form instance action button submit url...
Can you tell what is the following Python 3 function doing def get_form_context(self, obj, ns=None): return { "url": url_for("entity_tags.edit", object_id=obj.id), "form": self.entity_tags_form(obj)(obj=obj, ns=ns), "buttons": [EDIT_BUTTON], }
As a python code expert, you are capable of creating scripts from specifications.
Reindex all content ; optionally clear index before.
Can you generate the documentation for the following Python 3 function def reindex(clear: bool, progressive: bool, batch_size: int): reindexer = Reindexer(clear, progressive, batch_size) reindexer.reindex_all()
You are a Python code analyst, evaluating scripts for potential improvements.
Helper for building URLs from results.
Make a summary of the following Python 3 code def url_for_hit(hit, default="#"): try: object_type = hit["object_type"] object_id = int(hit["id"]) return current_app.default_view.url_for(hit, object_type, object_id) except KeyError: return default except Exception: log...
As a Python code translator, you convert algorithms and pseudocode into Python.
def index_update(index, items): """ :param:index: index name :param:items: list of (operation, full class name, primary key, data) tuples. """ index_name = index index = service.app_state.indexes[index_name] adapted = service.adapted session = safe_session() updated = set() writ...
Write a Python 3 function that can update the items in an index.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create indexes for schemas.
Can you tell what is the following Python 3 function doing def init_indexes(self): state = self.app_state for name, schema in self.schemas.items(): if current_app.testing: storage = TestingStorage() else: index_path = (Path(state.whoosh_base) / na...
As a Python code analyst, you investigate and solve complex coding mysteries
def clear(self): """Remove all content from indexes, and unregister all classes. After clear() the service is stopped. It must be started again to create new indexes and register classes. """ logger.info("Resetting indexes") state = self.app_state for _name, idx...
Write a Python 3 function for removing all content from indexes and unregister all classes.
You are a Python code architect, reviewing and designing scalable and efficient code
List of object types present in the index.
Make a summary of the following Python 3 code def searchable_object_types(self): try: idx = self.index() except KeyError: # index does not exists: service never started, may happens during # tests return [] with idx.reader() as r: inde...
You are a Python code architect, reviewing and designing scalable and efficient code
Search for a single entry in the index.
Can you tell what is the following Python 3 function doing def search( self, q, index="default", fields=None, Models=(), object_types=(), prefix=True, facet_by_type=None, **search_args, ): """Interface to search indexes. :param...
You are a Python code analyst, evaluating scripts for potential improvements.
Register a model class.
How would you explain what the following Python 3 function does def register_class(self, cls, app_state=None): state = app_state if app_state is not None else self.app_state for Adapter in self.adapters_cls: if Adapter.can_adapt(cls): break else: return ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Bulk index a list of objects.
Given the following Python 3 function, write the documentation def index_objects(self, objects, index="default"): if not objects: return index_name = index index = self.app_state.indexes[index_name] indexed = set() with index.writer() as writer: for obj ...
As a python code expert, you are capable of creating scripts from specifications.
Tranform an URL pulled from the database to a safe HTML fragment.
Make a summary of the following Python 3 code def linkify_url(value): value = value.strip() rjs = r"[\s]*(&#x.{1,7})?".join(list("javascript:")) rvb = r"[\s]*(&#x.{1,7})?".join(list("vbscript:")) re_scripts = re.compile(f"({rjs})|({rvb})", re.IGNORECASE) value = re_scripts.sub("", value) url...
As a Python code analyst, you investigate and solve complex coding mysteries
Return a string - > value dictionnary representing the given user s preferences.
Can you tell what is the following Python 3 function doing def get_preferences(self, user=None): if user is None: user = current_user return {pref.key: pref.value for pref in user.preferences}
As a Python code analyst, you investigate and solve complex coding mysteries
def set_preferences(self, user=None, **kwargs): """Set preferences from keyword arguments.""" if user is None: user = current_user d = {pref.key: pref for pref in user.preferences} for k, v in kwargs.items(): if k in d: d[k].value = v ...
Create a Python 3 function for setting preferences from keyword arguments.
As a Python code analyst, you investigate and solve complex coding mysteries
def manager(self, obj): """Returns the :class:`AttachmentsManager` instance for this object.""" manager = getattr(obj, _MANAGER_ATTR, None) if manager is None: manager = AttachmentsManager() setattr(obj.__class__, _MANAGER_ATTR, manager) return manager
Write a Python 3 script to return the AttachmentsManager instance for this object.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_form_context(self, obj): """Return a dict: form instance, action button, submit url... Used by macro m_attachment_form(entity) """ return { "url": url_for("attachments.create", entity_id=obj.id), "form": self.Form(), "buttons": [UPLOAD_BUTTON]...
Create a Python 3 function to return a dict of form instance action button submit url...
You are a Python code analyst, evaluating scripts for potential improvements.