output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Load the persisted cache and return a new instance of this class.
Can you generate the documentation for the following Python 3 function def load(cls, cache_key, deserializer, key_attr): items = unitdata.kv().get(cache_key) or [] return cls(cache_key, [deserializer(item) for item in items], key_attr)
You are a Python code generator, capable of creating scripts from specifications.
Returns the JSONUnitDataView of all received units in this list.
Can you tell what is the following Python 3 function doing def received(self): if not hasattr(self, '_data'): # NB: units are reversed so that lowest numbered unit takes precedence self._data = JSONUnitDataView({key: value for unit in reversed(s...
As a Python code composer, you craft elegant and concise scripts.
def AuthorizingClient(domain, auth, user_agent=None): """Creates a Podio client using an auth object.""" http_transport = transport.HttpTransport(domain, build_headers(auth, user_agent)) return client.Client(http_transport)
Write a Python 3 script to create a Podio client using an auth object.
As a Python code analyst, you investigate and solve complex coding mysteries
Create a PrintableImage from a PIL Image.
Make a summary of the following Python 3 code def from_image(cls, image): (w, h) = image.size # Thermal paper is 512 pixels wide if w > 512: ratio = 512. / w h = int(h * ratio) image = image.resize((512, h), Image.ANTIALIAS) if image.mode != '1': ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Append a Printable Image at the end of the current instance.
Can you tell what is the following Python 3 function doing def append(self, other): self.data.extend(other.data) self.height = self.height + other.height return self
As a python code expert, you are capable of creating scripts from specifications.
This method allows printing multiple images in one shot.
Given the following Python 3 function, write the documentation def print_images(self, *printable_images): printable_image = reduce(lambda x, y: x.append(y), list(printable_images)) self.print_image(printable_image)
You are a Python code generator, capable of creating scripts from specifications.
Encodes and quotes the given data.
Explain what the following Python 3 code does def encode_and_quote(data): if data is None: return None if isinstance(data, unicode): data = data.encode("utf-8") return urllib.quote_plus(data)
As a python code expert, you are capable of creating scripts from specifications.
def _strify(s): """If s is a unicode string, encode it to UTF-8 and return the results, otherwise return str(s), or None if s is None""" if s is None: return None if isinstance(s, unicode): return s.encode("utf-8") return str(s)
Write a Python 3 script for converting a unicode string to a string and return the results.
You are a Python code generator, capable of creating scripts from specifications.
def encode_file_header(boundary, paramname, filesize, filename=None, filetype=None): """Returns the leading data for a multipart/form-data field that contains file data. ``boundary`` is the boundary string used throughout a single request to separate variables. ``paramname``...
Write a Python 3 script for encoding a file header into a multipart - form - data field.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the number of bytes that the multipart - form - data encoding of params will be.
Can you generate the documentation for the following Python 3 function def get_body_size(params, boundary): size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params)) return size + len(boundary) + 6
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a dictionary with Content - Type and Content - Length headers for the multipart form - data encoding of params.
Explain what the following Python 3 code does def get_headers(params, boundary): headers = {} boundary = urllib.quote_plus(boundary) headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary headers['Content-Length'] = str(get_body_size(params, boundary)) return headers
As a Python code composer, you craft elegant and concise scripts.
def multipart_encode(params, boundary=None, cb=None): """Encode ``params`` as multipart/form-data. ``params`` should be a sequence of (name, value) pairs or MultipartParam objects, or a mapping of names to values. Values are either strings parameter values, or file-like objects to use as the parame...
Can you write a function in Python 3 where it encodes parameters as multipart / form - data.
You are a Python code architect, reviewing and designing scalable and efficient code
def from_file(cls, paramname, filename): """Returns a new MultipartParam object constructed from the local file at ``filename``. ``filesize`` is determined by os.path.getsize(``filename``) ``filetype`` is determined by mimetypes.guess_type(``filename``)[0] ``filename`` is set ...
Implement a Python 3 function for returning a new MultipartParam object constructed from the local file at filename.
As a Python code translator, you convert algorithms and pseudocode into Python.
def from_params(cls, params): """Returns a list of MultipartParam objects from a sequence of name, value pairs, MultipartParam instances, or from a mapping of names to values The values may be strings or file objects, or MultipartParam objects. MultipartParam object names must m...
Write a Python 3 function that can return a list of MultipartParam objects from a sequence of name value pairs or file objects.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the header of the encoding of this parameter
Can you generate the documentation for the following Python 3 function def encode_hdr(self, boundary): boundary = encode_and_quote(boundary) headers = ["--%s" % boundary] if self.filename: disposition = 'form-data; name="%s"; filename="%s"' % (self.name, ...
You are a Python code analyst, evaluating scripts for potential improvements.
def encode(self, boundary): """Returns the string encoding of this parameter""" if self.value is None: value = self.fileobj.read() else: value = self.value if re.search("^--%s$" % re.escape(boundary), value, re.M): raise ValueError("boundary found in ...
Create a Python 3 function to return the string encoding of this parameter
As a Python code composer, you craft elegant and concise scripts.
Yields the encoding of this parameter
Can you generate a brief explanation for the following Python 3 code def iter_encode(self, boundary, blocksize=4096): total = self.get_size(boundary) current = 0 if self.value is not None: block = self.encode(boundary) current += len(block) yield block ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_size(self, boundary): """Returns the size in bytes that this param will be when encoded with the given boundary.""" if self.filesize is not None: valuesize = self.filesize else: valuesize = len(self.value) return len(self.encode_hdr(boundary)) + 2...
Implement a function in Python 3 to return the size in bytes that this param will be encoded with the given boundary.
As a Python code translator, you convert algorithms and pseudocode into Python.
generator function to yield multipart / form - data representation of parameters
Can you generate the documentation for the following Python 3 function def next(self): if self.param_iter is not None: try: block = self.param_iter.next() self.current += len(block) if self.cb: self.cb(self.p, self.current, self.tot...
You are a Python code architect, reviewing and designing scalable and efficient code
Generates a query string with the appropriate options.
Can you generate the documentation for the following Python 3 function def get_options(silent=False, hook=True): options_ = {} if silent: options_['silent'] = silent if not hook: options_['hook'] = hook if options_: return '?' + urlencode(options_).low...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get item info by ID.
Can you generate a brief explanation for the following Python 3 code def find(self, item_id, basic=False, **kwargs): if basic: return self.transport.GET(url='/item/%d/basic' % item_id) return self.transport.GET(kwargs, url='/item/%d' % item_id)
As a Python code analyst, you investigate and solve complex coding mysteries
def update(self, item_id, attributes, silent=False, hook=True): """ Updates the item using the supplied attributes. If 'silent' is true, Podio will send no notifications to subscribed users and not post updates to the stream. Important: webhooks will still be called. """...
Write a Python 3 function for updating the item with the supplied attributes.
You are a Python code analyst, evaluating scripts for potential improvements.
def create(self, attributes, silent=False, hook=True): """ https://developers.podio.com/doc/tasks/create-task-22419 Creates the task using the supplied attributes. If 'silent' is true, Podio will send no notifications to subscribed users and not post updates to the stream. If 'ho...
Write a Python 3 function that can create a new task using the supplied attributes.
You are a Python code architect, reviewing and designing scalable and efficient code
Create a new task with the given attributes.
Can you generate a brief explanation for the following Python 3 code def create_for(self, ref_type, ref_id, attributes, silent=False, hook=True): # if not isinstance(attributes, dict): # raise TypeError('Must be of type dict') attributes = json.dumps(attributes) return self.transport....
You are a Python code analyst, evaluating scripts for potential improvements.
def find_by_url(self, space_url, id_only=True): """ Returns a space ID given the URL of the space. :param space_url: URL of the Space :param id_only: ? :return: space_id: Space url :rtype: str """ resp = self.transport.GET(url='/space/url?%s' % urlencode(...
Create a Python 3 function to return a space ID given the URL of the space.
As a Python code composer, you craft elegant and concise scripts.
Create a new space with the given attributes.
How would you explain what the following Python 3 function does def create(self, attributes): if not isinstance(attributes, dict): raise TypeError('Dictionary of values expected') attributes = json.dumps(attributes) return self.transport.POST(url='/space/', body=attributes, type='app...
As a Python code translator, you convert algorithms and pseudocode into Python.
def find_by_ref(self, ref_type, ref_id): """ Returns an object of type "item", "status" or "task" as a stream object. This is useful when a new status has been posted and should be rendered directly in the stream without reloading the entire stream. For details, see: htt...
Create a Python 3 function to return an object of type item status or task as a stream object.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns raw file as string. Pass to a file object
Can you generate the documentation for the following Python 3 function def find_raw(self, file_id): raw_handler = lambda resp, data: data return self.transport.GET(url='/file/%d/raw' % file_id, handler=raw_handler)
As a Python code analyst, you investigate and solve complex coding mysteries
def create(self, filename, filedata): """Create a file from raw data""" attributes = {'filename': filename, 'source': filedata} return self.transport.POST(url='/file/v2/', body=attributes, type='multipart/form-data')
Can you write a function in Python 3 where it creates a file from raw data
As a python code expert, you are capable of creating scripts from specifications.
def get(self, app_id, view_specifier): """ Retrieve the definition of a given view, provided the app_id and the view_id :param app_id: the app id :param view_specifier: Can be one of the following: 1. The view ID 2. The view's name 3. "las...
Write a Python 3 script to retrieve the definition of a given view.
As a Python code analyst, you investigate and solve complex coding mysteries
Get all of the views for the app with the specified app_id.
Explain what the following Python 3 code does def get_views(self, app_id, include_standard_views=False): include_standard = "true" if include_standard_views is True else "false" return self.transport.GET(url='/view/app/{}/?include_standard_views={}'.format(app_id, include_standard))
As a Python code translator, you convert algorithms and pseudocode into Python.
Updates the last view for the active user.
Given the following Python 3 function, write the documentation def update_last_view(self, app_id, attributes): if not isinstance(attributes, dict): raise TypeError('Must be of type dict') attribute_data = json.dumps(attributes) return self.transport.PUT(url='/view/app/{}/last'.format...
As a Python code translator, you convert algorithms and pseudocode into Python.
def update_view(self, view_id, attributes): """ Update an existing view using the details supplied via the attributes parameter :param view_id: the view's id :param attributes: a dictionary containing the modifications to be made to the view :return: """ if not i...
Write a Python 3 function that can update an existing view with the attributes supplied via the attributes parameter.
As a Python code analyst, you investigate and solve complex coding mysteries
def is_active(self, timeout=2): """ :param timeout: int :return: boolean """ try: result = Result(*self.perform_request('HEAD', '/', params={'request_timeout': timeout})) except ConnectionError: return False except TransportError: ...
Write a Python 3 function for checking if a user is active on the current system.
You are a Python code generator, capable of creating scripts from specifications.
Submit a query and return results.
Given the following Python 3 function, write the documentation def query(self, sql, timeout=10): if not sql: raise QueryError('No query passed to drill.') result = ResultQuery(*self.perform_request(**{ 'method': 'POST', 'url': '/query.json', 'body': { ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Execute an explain plan query.
Can you generate the documentation for the following Python 3 function def plan(self, sql, timeout=10): sql = 'explain plan for ' + sql return self.query(sql, timeout)
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the definition of the named storage plugin.
Make a summary of the following Python 3 code def storage_detail(self, name, timeout=10): result = Result(*self.perform_request(**{ 'method': 'GET', 'url': '/storage/{0}.json'.format(name), 'params': { 'request_timeout': timeout } })) ...
You are a Python code generator, capable of creating scripts from specifications.
Enable or disable the named storage plugin.
Make a summary of the following Python 3 code def storage_enable(self, name, value=True, timeout=10): value = 'true' if value else 'false' result = Result(*self.perform_request(**{ 'method': 'GET', 'url': '/storage/{0}/enable/{1}'.format(name, value), 'params': { ...
As a Python code composer, you craft elegant and concise scripts.
def storage_update(self, name, config, timeout=10): """ Create or update a storage plugin configuration. :param name: The name of the storage plugin configuration to create or update. :param config: Overwrites the existing configuration if there is any, and therefore, must include all ...
Implement a Python 3 function for creating or update a storage plugin configuration.
You are a Python code architect, reviewing and designing scalable and efficient code
Delete a storage plugin configuration.
Here you have a function in Python 3, explain what it does def storage_delete(self, name, timeout=10): result = Result(*self.perform_request(**{ 'method': 'DELETE', 'url': '/storage/{0}.json'.format(name), 'params': { 'request_timeout': timeout } ...
You are a Python code analyst, evaluating scripts for potential improvements.
Get the profile of the query that has the given queryid.
Can you generate the documentation for the following Python 3 function def profile(self, query_id, timeout=10): result = Result(*self.perform_request(**{ 'method': 'GET', 'url': '/profiles/{0}.json'.format(query_id), 'params': { 'request_timeout': timeout ...
You are a Python code analyst, evaluating scripts for potential improvements.
Cancel the query that has the given queryid.
Given the following Python 3 function, write the documentation def profile_cancel(self, query_id, timeout=10): result = Result(*self.perform_request(**{ 'method': 'GET', 'url': '/profiles/cancel/{0}'.format(query_id), 'params': { 'request_timeout': timeout ...
You are a Python code architect, reviewing and designing scalable and efficient code
def log_request_success(self, method, full_url, path, body, status_code, response, duration): """ Log a successful API call. """ if body and not isinstance(body, dict): body = body.decode('utf-8') logger.info( '%s %s [status:%s request:%.3fs]', method, full_url, ...
How would you implement a function in Python 3 that logs a successful API call.
You are a Python code generator, capable of creating scripts from specifications.
def log_request_fail(self, method, full_url, body, duration, status_code=None, exception=None): """ Log an unsuccessful API call. """ logger.warning( '%s %s [status:%s request:%.3fs]', method, full_url, status_code or 'N/A', duration, exc_info=exception is not Non...
How would you code a function in Python 3 to log an unsuccessful API call.
As a python code expert, you are capable of creating scripts from specifications.
def _raise_error(self, status_code, raw_data): """ Locate appropriate exception and raise it. """ error_message = raw_data additional_info = None try: additional_info = json.loads(raw_data) error_message = additional_info.get('error', error_message...
Implement a Python 3 function for raising an exception if it exists.
You are a Python code analyst, evaluating scripts for potential improvements.
Perform a request to the specified url and return the response.
Can you tell what is the following Python 3 function doing def perform_request(self, method, url, params=None, body=None): if body is not None: body = self.serializer.dumps(body) # some clients or environments don't support sending GET with body if method in ('HEAD', 'GET') ...
As a python code expert, you are capable of creating scripts from specifications.
def release(ctx, type_, repo, prebump=PREBUMP, config_file=None, commit=True, yes=False): """Make a new release. """ if prebump not in REL_TYPES: raise ValueError(f"{type_} not in {REL_TYPES}") prebump = REL_TYPES.index(prebump) version = _read_version() version = _bump_release(version,...
Write a Python 3 function for creating a new release.
You are a Python code generator, capable of creating scripts from specifications.
def init_menu(): """Initialize menu before first request.""" # Register breadcrumb root item = current_menu.submenu('breadcrumbs.settings') item.register('', _('Account')) item = current_menu.submenu('breadcrumbs.{0}'.format( current_app.config['SECURITY_BLUEPRINT_NAME'])) if current_ap...
Implement a function in Python 3 to initialize menu before first request.
As a Python code translator, you convert algorithms and pseudocode into Python.
def check_security_settings(): """Warn if session cookie is not secure in production.""" in_production = not (current_app.debug or current_app.testing) secure = current_app.config.get('SESSION_COOKIE_SECURE') if in_production and not secure: current_app.logger.warning( "SESSION_COOKI...
Can you implement a function in Python 3 that warns if session cookie is not secure in production.
You are a Python code generator, capable of creating scripts from specifications.
Context processor for jwt.
How would you explain what the following Python 3 function does def jwt_proccessor(): def jwt(): """Context processor function to generate jwt.""" token = current_accounts.jwt_creation_factory() return Markup( render_template( current_app.config['ACCOUNTS_JWT_DOM_...
You are a Python code analyst, evaluating scripts for potential improvements.
Format key for MySQL AES.
Here you have a function in Python 3, explain what it does def _mysql_aes_key(key): final_key = bytearray(16) for i, c in enumerate(key): final_key[i % 16] ^= key[i] if PY3 else ord(key[i]) return bytes(final_key)
You are a Python code analyst, evaluating scripts for potential improvements.
def _mysql_aes_pad(val): """Padding.""" val = _to_string(val) pad_value = 16 - (len(val) % 16) return _to_binary('{0}{1}'.format(val, chr(pad_value) * pad_value))
Write a Python 3 function that can pad a string to 16 bytes.
You are a Python code generator, capable of creating scripts from specifications.
Parse an instance from a string in Modular Crypt Format.
How would you explain what the following Python 3 function does def from_string(cls, hash, **context): salt, checksum = parse_mc2(hash, cls.ident, handler=cls) return cls(salt=salt, checksum=checksum)
As a Python code composer, you craft elegant and concise scripts.
def _calc_checksum(self, secret): """Calculate string. :param secret: The secret key. :returns: The checksum. """ return str_to_uascii( hashlib.sha256(mysql_aes_encrypt(self.salt, secret)).hexdigest() )
How would you implement a function in Python 3 that calculates string. :param secret: The secret key. :returns: The checksum.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _extract_info_from_useragent(user_agent): """Extract extra informations from user.""" parsed_string = user_agent_parser.Parse(user_agent) return { 'os': parsed_string.get('os', {}).get('family'), 'browser': parsed_string.get('user_agent', {}).get('family'), 'browser_version': par...
Write a Python 3 function that can extract extra informations from user agent.
As a python code expert, you are capable of creating scripts from specifications.
r Add a session to the SessionActivity table.
Can you tell what is the following Python 3 function doing def add_session(session=None): user_id, sid_s = session['user_id'], session.sid_s with db.session.begin_nested(): session_activity = SessionActivity( user_id=user_id, sid_s=sid_s, ip=request.remote_addr, ...
You are a Python code generator, capable of creating scripts from specifications.
Connect to the user_logged_in signal for table population.
Given the following Python 3 function, write the documentation def login_listener(app, user): @after_this_request def add_user_session(response): """Regenerate current session and add to the SessionActivity table. .. note:: `flask.session.regenerate()` actually calls Flask-KVSession's ...
As a Python code analyst, you investigate and solve complex coding mysteries
Connect to the user_logged_out signal.
Can you generate a brief explanation for the following Python 3 code def logout_listener(app, user): @after_this_request def _commit(response=None): if hasattr(session, 'sid_s'): delete_session(session.sid_s) # Regenerate the session to avoid session fixation vulnerabilities. ...
As a python code expert, you are capable of creating scripts from specifications.
Delete the session with the given sid_s.
Can you generate a brief explanation for the following Python 3 code def delete_session(sid_s): # Remove entries from sessionstore _sessionstore.delete(sid_s) # Find and remove the corresponding SessionActivity entry with db.session.begin_nested(): SessionActivity.query.filter_by(sid_s=sid_s).de...
You are a Python code generator, capable of creating scripts from specifications.
def delete_user_sessions(user): """Delete all active user sessions. :param user: User instance. :returns: If ``True`` then the session is successfully deleted. """ with db.session.begin_nested(): for s in user.active_sessions: _sessionstore.delete(s.sid_s) SessionActivi...
Implement a Python 3 function for deleting all active user sessions.
As a Python code translator, you convert algorithms and pseudocode into Python.
def confirm_register_form_factory(Form, app): """Return confirmation for extended registration form.""" if app.config.get('RECAPTCHA_PUBLIC_KEY') and \ app.config.get('RECAPTCHA_PRIVATE_KEY'): class ConfirmRegisterForm(Form): recaptcha = FormField(RegistrationFormRecaptcha, separ...
Can you implement a function in Python 3 that returns confirmation for extended registration form.
As a python code expert, you are capable of creating scripts from specifications.
Return extended registration form.
Explain what the following Python 3 code does def register_form_factory(Form, app): if app.config.get('RECAPTCHA_PUBLIC_KEY') and \ app.config.get('RECAPTCHA_PRIVATE_KEY'): class RegisterForm(Form): recaptcha = FormField(RegistrationFormRecaptcha, separator='.') return Regis...
You are a Python code architect, reviewing and designing scalable and efficient code
def login_form_factory(Form, app): """Return extended login form.""" class LoginForm(Form): def __init__(self, *args, **kwargs): """Init the login form. .. note:: The ``remember me`` option will be completely disabled. """ super(LoginFor...
Write a Python 3 function for returning extended login form.
You are a Python code analyst, evaluating scripts for potential improvements.
def on_model_change(self, form, User, is_created): """Hash password when saving.""" if form.password.data is not None: pwd_ctx = current_app.extensions['security'].pwd_context if pwd_ctx.identify(form.password.data) is None: User.password = hash_password(form.pass...
How would you implement a function in Python 3 that hashes password when saving.
As a Python code analyst, you investigate and solve complex coding mysteries
def after_model_change(self, form, User, is_created): """Send password instructions if desired.""" if is_created and form.notification.data is True: send_reset_password_instructions(User)
Can you implement a function in Python 3 that sends password instructions if desired.
As a python code expert, you are capable of creating scripts from specifications.
Delete a specific session.
How would you explain what the following Python 3 function does def delete_model(self, model): if SessionActivity.is_current(sid_s=model.sid_s): flash('You could not remove your current session', 'error') return delete_session(sid_s=model.sid_s) db.session.commit()
As a Python code translator, you convert algorithms and pseudocode into Python.
Celery task to send security email.
Can you generate the documentation for the following Python 3 function def send_security_email(data): msg = Message() msg.__dict__.update(data) current_app.extensions['mail'].send(msg)
As a python code expert, you are capable of creating scripts from specifications.
Automatically clean the session table.
Can you generate a brief explanation for the following Python 3 code def clean_session_table(): sessions = SessionActivity.query_by_expired().all() for session in sessions: delete_session(sid_s=session.sid_s) db.session.commit()
You are a Python code generator, capable of creating scripts from specifications.
Encode the JWT token.
Can you generate a brief explanation for the following Python 3 code def jwt_create_token(user_id=None, additional_data=None): # Create an ID uid = str(uuid.uuid4()) # The time in UTC now now = datetime.utcnow() # Build the token data token_data = { 'exp': now + current_app.config['ACCOU...
You are a Python code generator, capable of creating scripts from specifications.
Decode the JWT token.
Explain what the following Python 3 code does def jwt_decode_token(token): try: return decode( token, current_app.config['ACCOUNTS_JWT_SECRET_KEY'], algorithms=[ current_app.config['ACCOUNTS_JWT_ALOGORITHM'] ] ) except DecodeError a...
As a Python code translator, you convert algorithms and pseudocode into Python.
def set_session_info(app, response, **extra): """Add X-Session-ID and X-User-ID to http response.""" session_id = getattr(session, 'sid_s', None) if session_id: response.headers['X-Session-ID'] = session_id if current_user.is_authenticated: response.headers['X-User-ID'] = current_user.ge...
Write a Python 3 function for adding X - Session - ID and X - User - ID to http response.
As a python code expert, you are capable of creating scripts from specifications.
View for security page.
Can you generate the documentation for the following Python 3 function def security(): sessions = SessionActivity.query_by_user( user_id=current_user.get_id() ).all() master_session = None for index, session in enumerate(sessions): if SessionActivity.is_current(session.sid_s): ...
As a python code expert, you are capable of creating scripts from specifications.
def upgrade(): """Upgrade database.""" with op.batch_alter_table('accounts_user_session_activity') as batch_op: batch_op.add_column(sa.Column('browser', sa.String(80), nullable=True)) batch_op.add_column( sa.Column('browser_version', sa.String(30), nullable=True)) batch_op.ad...
Implement a function in Python 3 to upgrade database to version 80.
As a Python code composer, you craft elegant and concise scripts.
def query_by_expired(cls): """Query to select all expired sessions.""" lifetime = current_app.permanent_session_lifetime expired_moment = datetime.utcnow() - lifetime return cls.query.filter(cls.created < expired_moment)
Write a Python 3 function that can query to select all expired sessions.
As a python code expert, you are capable of creating scripts from specifications.
def monkey_patch_flask_security(): """Monkey-patch Flask-Security.""" if utils.get_hmac != get_hmac: utils.get_hmac = get_hmac if utils.hash_password != hash_password: utils.hash_password = hash_password changeable.hash_password = hash_password rec...
How would you implement a function in Python 3 that monkeys - patch Flask - Security.
You are a Python code generator, capable of creating scripts from specifications.
Flask application initialization. The following actions are executed: #. Initialize the configuration. #. Monkey-patch Flask-Security. #. Create the user datastore. #. Create the sessionstore. #. Initialize the extension, the forms to register users and c...
Given the following Python 3 function, write the documentation def init_app(self, app, sessionstore=None, register_blueprint=True): self.init_config(app) # Monkey-patch Flask-Security InvenioAccounts.monkey_patch_flask_security() # Create user datastore if not self.datastore: ...
As a Python code composer, you craft elegant and concise scripts.
def init_config(self, app): """Initialize configuration. :param app: The Flask application. """ try: pkg_resources.get_distribution('celery') app.config.setdefault( "ACCOUNTS_USE_CELERY", not (app.debug or app.testing)) except pkg_resource...
Write a Python 3 function that can initialize configuration. :param app: The Flask application.
You are a Python code architect, reviewing and designing scalable and efficient code
Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``) :param register_blueprint: If ``True``, the application registers the ...
Given the following Python 3 function, write the documentation def init_app(self, app, sessionstore=None, register_blueprint=False): return super(InvenioAccountsREST, self).init_app( app, sessionstore=sessionstore, register_blueprint=register_blueprint, )
You are a Python code analyst, evaluating scripts for potential improvements.
def init_app(self, app, sessionstore=None, register_blueprint=True): """Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``) ...
Can you implement a function in Python 3 that flasks application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``) :param register_blueprint: If ``True``, the application registers the blue...
As a Python code composer, you craft elegant and concise scripts.
Deactivate a user. :param user: A :class:`invenio_accounts.models.User` instance. :returns: The datastore instance.
Make a summary of the following Python 3 code def deactivate_user(self, user): res = super(SessionAwareSQLAlchemyUserDatastore, self).deactivate_user( user) if res: delete_user_sessions(user) return res
As a Python code composer, you craft elegant and concise scripts.
Initialize the attributes of the model class.
Here you have a function in Python 3, explain what it does def _initialize_attributes(model_class, name, bases, attrs): model_class._attributes = {} for k, v in attrs.iteritems(): if isinstance(v, Attribute): model_class._attributes[k] = v v.name = v.name or k
As a python code expert, you are capable of creating scripts from specifications.
Adds a property to the target of a reference field that returns the list of associated objects.
Explain what the following Python 3 code does def _initialize_referenced(model_class, attribute): # this should be a descriptor def _related_objects(self): return (model_class.objects .filter(**{attribute.attname: self.id})) klass = attribute._target_type if isinstance(klass, ba...
As a python code expert, you are capable of creating scripts from specifications.
def _initialize_lists(model_class, name, bases, attrs): """Stores the list fields descriptors of a model.""" model_class._lists = {} for k, v in attrs.iteritems(): if isinstance(v, ListField): model_class._lists[k] = v v.name = v.name or k
Write a Python 3 script to store the list fields descriptors of a model.
You are a Python code architect, reviewing and designing scalable and efficient code
def _initialize_references(model_class, name, bases, attrs): """Stores the list of reference field descriptors of a model.""" model_class._references = {} h = {} deferred = [] for k, v in attrs.iteritems(): if isinstance(v, ReferenceField): model_class._references[k] = v ...
Create a Python 3 function to store the list of reference field descriptors of a model.
You are a Python code generator, capable of creating scripts from specifications.
def _initialize_indices(model_class, name, bases, attrs): """Stores the list of indexed attributes.""" model_class._indices = [] for k, v in attrs.iteritems(): if isinstance(v, (Attribute, ListField)) and v.indexed: model_class._indices.append(k) if model_class._meta['indices']: ...
Write a Python 3 function that can store the list of indexed attributes.
As a python code expert, you are capable of creating scripts from specifications.
Stores the list of counter fields.
Can you generate a brief explanation for the following Python 3 code def _initialize_counters(model_class, name, bases, attrs): model_class._counters = [] for k, v in attrs.iteritems(): if isinstance(v, Counter): model_class._counters.append(k)
As a Python code composer, you craft elegant and concise scripts.
def get_model_from_key(key): """Gets the model from a given key.""" _known_models = {} model_name = key.split(':', 2)[0] # populate for klass in Model.__subclasses__(): _known_models[klass.__name__] = klass return _known_models.get(model_name, None)
Create a Python 3 function for getting the model from a given key.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the model instance based on the key.
Here you have a function in Python 3, explain what it does def from_key(key): model = get_model_from_key(key) if model is None: raise BadKeyError try: _, id = key.split(':', 2) id = int(id) except ValueError, TypeError: raise BadKeyError return model.objects.get_by_id...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns True if all the fields are valid.
Here you have a function in Python 3, explain what it does def is_valid(self): self._errors = [] for field in self.fields: try: field.validate(self) except FieldValidationError, e: self._errors.extend(e.errors) self.validate() retur...
You are a Python code architect, reviewing and designing scalable and efficient code
Updates the attributes of the model.
Can you tell what is the following Python 3 function doing def update_attributes(self, **kwargs): attrs = self.attributes.values() + self.lists.values() \ + self.references.values() for att in attrs: if att.name in kwargs: att.__set__(self, kwargs[att.name])
As a Python code translator, you convert algorithms and pseudocode into Python.
def save(self): """Saves the instance to the datastore.""" if not self.is_valid(): return self._errors _new = self.is_new() if _new: self._initialize_id() with Mutex(self): self._write(_new) return True
Write a Python 3 script to save the instance to the datastore.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the Redis key where the values are stored.
Can you generate a brief explanation for the following Python 3 code def key(self, att=None): if att is not None: return self._key[self.id][att] else: return self._key[self.id]
As a Python code composer, you craft elegant and concise scripts.
Deletes the object from the datastore.
How would you explain what the following Python 3 function does def delete(self): pipeline = self.db.pipeline() self._delete_from_indices(pipeline) self._delete_membership(pipeline) pipeline.delete(self.key()) pipeline.execute()
As a Python code composer, you craft elegant and concise scripts.
Returns the mapping of the model attributes and their values.
How would you explain what the following Python 3 function does def attributes_dict(self): h = {} for k in self.attributes.keys(): h[k] = getattr(self, k) for k in self.lists.keys(): h[k] = getattr(self, k) for k in self.references.keys(): h[k] = getat...
As a Python code composer, you craft elegant and concise scripts.
def fields(self): """Returns the list of field names of the model.""" return (self.attributes.values() + self.lists.values() + self.references.values())
Implement a function in Python 3 to return the list of field names of the model.
As a python code expert, you are capable of creating scripts from specifications.
def exists(cls, id): """Checks if the model with id exists.""" return bool(redisco.get_client().exists(cls._key[str(id)]) or redisco.get_client().sismember(cls._key['all'], str(id)))
How would you code a function in Python 3 to check if the model with id exists.
You are a Python code analyst, evaluating scripts for potential improvements.
def _initialize_id(self): """Initializes the id of the instance.""" self.id = str(self.db.incr(self._key['id']))
Can you write a function in Python 3 where it initializes the id of the instance.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _write(self, _new=False): """Writes the values of the attributes to the datastore. This method also creates the indices and saves the lists associated to the object. """ pipeline = self.db.pipeline() self._create_membership(pipeline) self._update_indices(pipe...
Implement a Python 3 function for writing the values of the attributes and the lists of the object to the datastore.
As a Python code translator, you convert algorithms and pseudocode into Python.
Adds the id of the object to the set of all objects of the same class.
Given the following Python 3 function, write the documentation def _create_membership(self, pipeline=None): Set(self._key['all'], pipeline=pipeline).add(self.id)
As a Python code translator, you convert algorithms and pseudocode into Python.
Removes the id of the object from the set of all objects of the same class.
Here you have a function in Python 3, explain what it does def _delete_membership(self, pipeline=None): Set(self._key['all'], pipeline=pipeline).remove(self.id)
You are a Python code architect, reviewing and designing scalable and efficient code