jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def sendEmail(sydent, templateName, mailTo, substitutions):
        mailFrom = sydent.cfg.get('email', 'email.from')
        mailTemplateFile = sydent.cfg.get('email', templateName)

        myHostname = sydent.cfg.get('email', 'email.hostname')
        if myHostname == '':
            myHostname = socket.getfqdn()
        midRandom = "".join([random.choice(string.ascii_letters) for _ in range(16)])
        messageid = "<%d%s@%s>" % (time_msec(), midRandom, myHostname)

        allSubstitutions = {}
        allSubstitutions.update(substitutions)
        allSubstitutions.update({
            'messageid': messageid,
            'date': email.utils.formatdate(localtime=False),
            'to': mailTo,
            'from': mailFrom,
        })

        for k,v in allSubstitutions.items():
            allSubstitutions[k] = v.decode('utf8')
            allSubstitutions[k+"_forhtml"] = cgi.escape(v.decode('utf8'))
            allSubstitutions[k+"_forurl"] = urllib.quote(v)

        mailString = open(mailTemplateFile).read() % allSubstitutions
        rawFrom = email.utils.parseaddr(mailFrom)[1]
        rawTo = email.utils.parseaddr(mailTo)[1]
        if rawFrom == '' or rawTo == '':
            logger.info("Couldn't parse from / to address %s / %s", mailFrom, mailTo)
            raise EmailAddressException()
        mailServer = sydent.cfg.get('email', 'email.smtphost')
        mailPort = sydent.cfg.get('email', 'email.smtpport')
        mailUsername = sydent.cfg.get('email', 'email.smtpusername')
        mailPassword = sydent.cfg.get('email', 'email.smtppassword')
        mailTLSMode = sydent.cfg.get('email', 'email.tlsmode')
        logger.info("Sending mail to %s with mail server: %s" % (mailTo, mailServer,))
        try:
            if mailTLSMode == 'SSL' or mailTLSMode == 'TLS':
                smtp = smtplib.SMTP_SSL(mailServer, mailPort, myHostname)
            elif mailTLSMode == 'STARTTLS':
                smtp = smtplib.SMTP(mailServer, mailPort, myHostname)
                smtp.starttls()
            else:
                smtp = smtplib.SMTP(mailServer, mailPort, myHostname)
            if mailUsername != '':
                smtp.login(mailUsername, mailPassword)
            smtp.sendmail(rawFrom, rawTo, mailString.encode('utf-8'))
            smtp.quit()
        except Exception as origException:
            twisted.python.log.err()
            ese = EmailSendException()
            ese.cause = origException
            raise ese
//  [python]
def _get_shared_models(self, args: "DictConfig") -> Dict[str, dict]:
    with open(args.blueprint.model_opt_path) as f:
        all_model_opts = yaml.safe_load(f.read())
    active_model_opts = {
        model: opt
        for model, opt in all_model_opts.items()
        if self.conversations_needed[model] > 0
    }
    return TurkLikeAgent.get_bot_agents(args=args, model_opts=active_model_opts)
//  [python]
def _get_shared_models(self, args: "DictConfig") -> Dict[str, dict]:
    with open(args.blueprint.model_opt_path) as f:
        all_model_opts = yaml.load(f.read())
    active_model_opts = {
        model: opt
        for model, opt in all_model_opts.items()
        if self.conversations_needed[model] > 0
    }
    return TurkLikeAgent.get_bot_agents(args=args, model_opts=active_model_opts)
//  [python]
def model_from_yaml(yaml_string, custom_objects=None):
  """Parses a yaml model configuration file and returns a model instance.

  Note: Since TF 2.6, this method is no longer supported and will raise a
  RuntimeError.

  Args:
      yaml_string: YAML string or open file encoding a model configuration.
      custom_objects: Optional dictionary mapping names
          (strings) to custom classes or functions to be
          considered during deserialization.

  Returns:
      A Keras model instance (uncompiled).

  Raises:
      RuntimeError: announces that the method poses a security risk
  """
  raise RuntimeError(
      'Method `model_from_yaml()` has been removed due to security risk of '
      'arbitrary code execution. Please use `Model.to_json()` and '
      '`model_from_json()` instead.'
  )
//  [python]
def model_from_yaml(yaml_string, custom_objects=None):
  """Parses a yaml model configuration file and returns a model instance.

  Usage:

  >>> model = tf.keras.Sequential([
  ...     tf.keras.layers.Dense(5, input_shape=(3,)),
  ...     tf.keras.layers.Softmax()])
  >>> try:
  ...   import yaml
  ...   config = model.to_yaml()
  ...   loaded_model = tf.keras.models.model_from_yaml(config)
  ... except ImportError:
  ...   pass

  Args:
      yaml_string: YAML string or open file encoding a model configuration.
      custom_objects: Optional dictionary mapping names
          (strings) to custom classes or functions to be
          considered during deserialization.

  Returns:
      A Keras model instance (uncompiled).

  Raises:
      ImportError: if yaml module is not found.
  """
  if yaml is None:
    raise ImportError('Requires yaml module installed (`pip install pyyaml`).')
  # The method unsafe_load only exists in PyYAML 5.x+, so which branch of the
  # try block is covered by tests depends on the installed version of PyYAML.
  try:
    # PyYAML 5.x+
    config = yaml.unsafe_load(yaml_string)
  except AttributeError:
    config = yaml.load(yaml_string)
  from tensorflow.python.keras.layers import deserialize  # pylint: disable=g-import-not-at-top
  return deserialize(config, custom_objects=custom_objects)
//  [python]
def test_unicorn_render_context_variable():
    token = Token(
        TokenType.TEXT,
        "unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs' test_kwarg=test_var.nested",
    )
    unicorn_node = unicorn(None, token)
    context = {"test_var": {"nested": "variable!"}}
    actual = unicorn_node.render(context)

    assert "<b>variable!</b>" in actual
//  [python]
def test_unicorn_render_context_variable():
    token = Token(
        TokenType.TEXT,
        "unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs' test_kwarg=test_var.nested",
    )
    unicorn_node = unicorn(None, token)
    context = {"test_var": {"nested": "variable!"}}
    actual = unicorn_node.render(context)

    assert "->variable!<-" in actual
//  [python]
def test_unicorn_render_kwarg():
    token = Token(
        TokenType.TEXT,
        "unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs' test_kwarg='tested!'",
    )
    unicorn_node = unicorn(None, token)
    context = {}
    actual = unicorn_node.render(context)

    assert "<b>tested!</b>" in actual
//  [python]
def test_unicorn_render_kwarg():
    token = Token(
        TokenType.TEXT,
        "unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs' test_kwarg='tested!'",
    )
    unicorn_node = unicorn(None, token)
    context = {}
    actual = unicorn_node.render(context)

    assert "->tested!<-" in actual
//  [python]
def handle_validate_token(self, req):
    """Handles the GET v2/.token/<token> call for validating a token, usually
    called by a service like Swift.

    On a successful validation, X-Auth-TTL will be set for how much longer
    this token is valid and X-Auth-Groups will contain a comma separated
    list of groups the user belongs to.

    The first group listed will be a unique identifier for the user the
    token represents.

    .reseller_admin is a special group that indicates the user should be
    allowed to do anything on any account.

    :param req: The swob.Request to process.
    :returns: swob.Response, 2xx on success with data set as explained
              above.
    """
    token = req.path_info_pop()
    if req.path_info or not token.startswith(self.reseller_prefix):
        return HTTPBadRequest(request=req)
    expires = groups = None
    memcache_client = cache_from_env(req.environ)
    if memcache_client:
        memcache_key = '%s/auth/%s' % (self.reseller_prefix, token)
        cached_auth_data = memcache_client.get(memcache_key)
        if cached_auth_data:
            expires, groups = cached_auth_data
            if expires < time():
                groups = None
    if not groups:
        object_name = self._get_concealed_token(token)
        path = quote('/v1/%s/.token_%s/%s' %
                     (self.auth_account, object_name[-1], object_name))
        resp = self.make_pre_authed_request(
            req.environ, 'GET', path).get_response(self.app)
        if resp.status_int // 100 != 2:
            return HTTPNotFound(request=req)
        detail = json.loads(resp.body)
        expires = detail['expires']
        if expires < time():
            self.make_pre_authed_request(
                req.environ, 'DELETE', path).get_response(self.app)
            return HTTPNotFound(request=req)
        groups = [g['name'] for g in detail['groups']]
        if '.admin' in groups:
            groups.remove('.admin')
            groups.append(detail['account_id'])
        groups = ','.join(groups)
    return HTTPNoContent(headers={'X-Auth-TTL': expires - time(),
                                  'X-Auth-Groups': groups})
//  [python]
def handle_validate_token(self, req):
    """Handles the GET v2/.token/<token> call for validating a token, usually
    called by a service like Swift.

    On a successful validation, X-Auth-TTL will be set for how much longer
    this token is valid and X-Auth-Groups will contain a comma separated
    list of groups the user belongs to.

    The first group listed will be a unique identifier for the user the
    token represents.

    .reseller_admin is a special group that indicates the user should be
    allowed to do anything on any account.

    :param req: The swob.Request to process.
    :returns: swob.Response, 2xx on success with data set as explained
              above.
    """
    token = req.path_info_pop()
    if req.path_info or not token.startswith(self.reseller_prefix):
        return HTTPBadRequest(request=req)
    expires = groups = None
    memcache_client = cache_from_env(req.environ)
    if memcache_client:
        memcache_key = '%s/auth/%s' % (self.reseller_prefix, token)
        cached_auth_data = memcache_client.get(memcache_key)
        if cached_auth_data:
            expires, groups = cached_auth_data
            if expires < time():
                groups = None
    if not groups:
        path = quote('/v1/%s/.token_%s/%s' %
                     (self.auth_account, token[-1], token))
        resp = self.make_pre_authed_request(
            req.environ, 'GET', path).get_response(self.app)
        if resp.status_int // 100 != 2:
            return HTTPNotFound(request=req)
        detail = json.loads(resp.body)
        expires = detail['expires']
        if expires < time():
            self.make_pre_authed_request(
                req.environ, 'DELETE', path).get_response(self.app)
            return HTTPNotFound(request=req)
        groups = [g['name'] for g in detail['groups']]
        if '.admin' in groups:
            groups.remove('.admin')
            groups.append(detail['account_id'])
        groups = ','.join(groups)
    return HTTPNoContent(headers={'X-Auth-TTL': expires - time(),
                                  'X-Auth-Groups': groups})
//  [python]
def _handle_carbon_received(self, msg):
    if msg['from'].bare == self.xmpp.boundjid.bare:
        self.xmpp.event('carbon_received', msg)
//  [python]
def _handle_carbon_received(self, msg):
    self.xmpp.event('carbon_received', msg)
//  [python]
async def get_resolved_ref(self):
    if hasattr(self, 'resolved_ref'):
        return self.resolved_ref

    try:
        # Check if the reference is a valid SHA hash
        self.sha1_validate(self.unresolved_ref)
    except ValueError:
        # The ref is a head/tag and we resolve it using `git ls-remote`
        command = ["git", "ls-remote", "--", self.repo, self.unresolved_ref]
        result = subprocess.run(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if result.returncode:
            raise RuntimeError("Unable to run git ls-remote to get the `resolved_ref`: {}".format(result.stderr))
        if not result.stdout:
            return None
        resolved_ref = result.stdout.split(None, 1)[0]
        self.sha1_validate(resolved_ref)
        self.resolved_ref = resolved_ref
    else:
        # The ref already was a valid SHA hash
        self.resolved_ref = self.unresolved_ref

    return self.resolved_ref
//  [python]
async def get_resolved_ref(self):
    if hasattr(self, 'resolved_ref'):
        return self.resolved_ref

    try:
        # Check if the reference is a valid SHA hash
        self.sha1_validate(self.unresolved_ref)
    except ValueError:
        # The ref is a head/tag and we resolve it using `git ls-remote`
        command = ["git", "ls-remote", self.repo, self.unresolved_ref]
        result = subprocess.run(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if result.returncode:
            raise RuntimeError("Unable to run git ls-remote to get the `resolved_ref`: {}".format(result.stderr))
        if not result.stdout:
            return None
        resolved_ref = result.stdout.split(None, 1)[0]
        self.sha1_validate(resolved_ref)
        self.resolved_ref = resolved_ref
    else:
        # The ref already was a valid SHA hash
        self.resolved_ref = self.unresolved_ref

    return self.resolved_ref
//  [python]
def should_deny_admin(self):
    return not self.has_2fa() and config.get(
        "enable_force_admin_2fa"
    )
//  [python]
def should_deny_admin(self):
    return self.totp_status != TOTPStatus.ENABLED and config.get(
        "enable_force_admin_2fa"
    )
//  [python]
def _handle_carbon_sent(self, msg):
    if msg['from'].bare == self.xmpp.boundjid.bare:
        self.xmpp.event('carbon_sent', msg)
//  [python]
def _handle_carbon_sent(self, msg):
    self.xmpp.event('carbon_sent', msg)
//  [python]
def add_security_headers(resp):
    csp = "default-src 'self'"
    csp += ''.join([' ' + host for host in config.config_trustedhosts.strip().split(',')])
    csp += " 'unsafe-inline' 'unsafe-eval'; font-src 'self' data:; img-src 'self' data:"
    resp.headers['Content-Security-Policy'] = csp
    if request.endpoint == "edit-book.edit_book" or config.config_use_google_drive:
        resp.headers['Content-Security-Policy'] += " *"
    elif request.endpoint == "web.read_book":
        resp.headers['Content-Security-Policy'] += " blob:;style-src-elem 'self' blob: 'unsafe-inline';"
    resp.headers['X-Content-Type-Options'] = 'nosniff'
    resp.headers['X-Frame-Options'] = 'SAMEORIGIN'
    resp.headers['X-XSS-Protection'] = '1; mode=block'
    resp.headers['Strict-Transport-Security'] = 'max-age=31536000;'
    return resp
//  [python]
def add_security_headers(resp):
    resp.headers['Content-Security-Policy'] = "default-src 'self'" + ''.join([' '+host for host in config.config_trustedhosts.strip().split(',')]) + " 'unsafe-inline' 'unsafe-eval'; font-src 'self' data:; img-src 'self' data:"
    if request.endpoint == "editbook.edit_book" or config.config_use_google_drive:
        resp.headers['Content-Security-Policy'] += " *"
    elif request.endpoint == "web.read_book":
        resp.headers['Content-Security-Policy'] += " blob:;style-src-elem 'self' blob: 'unsafe-inline';"
    resp.headers['X-Content-Type-Options'] = 'nosniff'
    resp.headers['X-Frame-Options'] = 'SAMEORIGIN'
    resp.headers['X-XSS-Protection'] = '1; mode=block'
    resp.headers['Strict-Transport-Security'] = 'max-age=31536000;'
    return resp
//  [python]
def adv_search_shelf(q, include_shelf_inputs, exclude_shelf_inputs):
    q = q.outerjoin(ub.BookShelf, db.Books.id == ub.BookShelf.book_id) \
        .filter(or_(ub.BookShelf.shelf == None, ub.BookShelf.shelf.notin_(exclude_shelf_inputs)))
    if len(include_shelf_inputs) > 0:
        q = q.filter(ub.BookShelf.shelf.in_(include_shelf_inputs))
    return q
//  [python]
def adv_search_shelf(q, include_shelf_inputs, exclude_shelf_inputs):
    q = q.outerjoin(ub.BookShelf, db.Books.id == ub.BookShelf.book_id)\
        .filter(or_(ub.BookShelf.shelf == None, ub.BookShelf.shelf.notin_(exclude_shelf_inputs)))
    if len(include_shelf_inputs) > 0:
        q = q.filter(ub.BookShelf.shelf.in_(include_shelf_inputs))
    return q
//  [python]
def category_list():
    if current_user.check_visibility(constants.SIDEBAR_CATEGORY):
        if current_user.get_view_property('category', 'dir') == 'desc':
            order = db.Tags.name.desc()
            order_no = 0
        else:
            order = db.Tags.name.asc()
            order_no = 1
        entries = calibre_db.session.query(db.Tags, func.count('books_tags_link.book').label('count')) \
            .join(db.books_tags_link).join(db.Books).order_by(order).filter(calibre_db.common_filters()) \
            .group_by(text('books_tags_link.tag')).all()
        char_list = generate_char_list(db.Tags.name, db.books_tags_link)
        return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=char_list,
                                     title=_(u"Categories"), page="catlist", data="category", order=order_no)
    else:
        abort(404)
//  [python]
def category_list():
    if current_user.check_visibility(constants.SIDEBAR_CATEGORY):
        if current_user.get_view_property('category', 'dir') == 'desc':
            order = db.Tags.name.desc()
            order_no = 0
        else:
            order = db.Tags.name.asc()
            order_no = 1
        entries = calibre_db.session.query(db.Tags, func.count('books_tags_link.book').label('count')) \
            .join(db.books_tags_link).join(db.Books).order_by(order).filter(calibre_db.common_filters()) \
            .group_by(text('books_tags_link.tag')).all()
        charlist = calibre_db.session.query(func.upper(func.substr(db.Tags.name, 1, 1)).label('char')) \
            .join(db.books_tags_link).join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(func.upper(func.substr(db.Tags.name, 1, 1))).all()
        return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist,
                                     title=_(u"Categories"), page="catlist", data="category", order=order_no)
    else:
        abort(404)
//  [python]
def change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages):
    to_save = request.form.to_dict()
    current_user.random_books = 0
    if current_user.role_passwd() or current_user.role_admin():
        if to_save.get("password"):
            current_user.password = generate_password_hash(to_save["password"])
    try:
        if to_save.get("kindle_mail", current_user.kindle_mail) != current_user.kindle_mail:
            current_user.kindle_mail = valid_email(to_save["kindle_mail"])
        if to_save.get("email", current_user.email) != current_user.email:
            current_user.email = check_email(to_save["email"])
        if current_user.role_admin():
            if to_save.get("name", current_user.name) != current_user.name:
                # Query username, if not existing, change
                current_user.name = check_username(to_save["name"])
        current_user.random_books = 1 if to_save.get("show_random") == "on" else 0
        if to_save.get("default_language"):
            current_user.default_language = to_save["default_language"]
        if to_save.get("locale"):
            current_user.locale = to_save["locale"]
        old_state = current_user.kobo_only_shelves_sync
        # 1 -> 0: nothing has to be done
        # 0 -> 1: all synced books have to be added to archived books, + currently synced shelfs which
        # don't have to be synced have to be removed (added to Shelf archive)
        current_user.kobo_only_shelves_sync = int(to_save.get("kobo_only_shelves_sync") == "on") or 0
        if old_state == 0 and current_user.kobo_only_shelves_sync == 1:
            kobo_sync_status.update_on_sync_shelfs(current_user.id)

    except Exception as ex:
        flash(str(ex), category="error")
        return render_title_template("user_edit.html",
                                     content=current_user,
                                     translations=translations,
                                     profile=1,
                                     languages=languages,
                                     title=_(u"%(name)s's profile", name=current_user.name),
                                     page="me",
                                     kobo_support=kobo_support,
                                     registered_oauth=local_oauth_check,
                                     oauth_status=oauth_status)

    val = 0
    for key, __ in to_save.items():
        if key.startswith('show'):
            val += int(key[5:])
    current_user.sidebar_view = val
    if to_save.get("Show_detail_random"):
        current_user.sidebar_view += constants.DETAIL_RANDOM

    try:
        ub.session.commit()
        flash(_(u"Profile updated"), category="success")
        log.debug(u"Profile updated")
    except IntegrityError:
        ub.session.rollback()
        flash(_(u"Found an existing account for this e-mail address"), category="error")
        log.debug(u"Found an existing account for this e-mail address")
    except OperationalError as e:
        ub.session.rollback()
        log.error("Database error: %s", e)
        flash(_(u"Database error: %(error)s.", error=e), category="error")
//  [python]
def model_from_config(config, custom_objects=None):
  """Instantiates a Keras model from its config.

  Usage:
  ```
  # for a Functional API model
  tf.keras.Model().from_config(model.get_config())

  # for a Sequential model
  tf.keras.Sequential().from_config(model.get_config())
  ```

  Args:
      config: Configuration dictionary.
      custom_objects: Optional dictionary mapping names
          (strings) to custom classes or functions to be
          considered during deserialization.

  Returns:
      A Keras model instance (uncompiled).

  Raises:
      TypeError: if `config` is not a dictionary.
  """
  if isinstance(config, list):
    raise TypeError('`model_from_config` expects a dictionary, not a list. '
                    'Maybe you meant to use '
                    '`Sequential.from_config(config)`?')
  from tensorflow.python.keras.layers import deserialize  # pylint: disable=g-import-not-at-top
  return deserialize(config, custom_objects=custom_objects)
//  [python]
def model_from_config(config, custom_objects=None):
  """Instantiates a Keras model from its config.
 
  Usage:
  ```
  # for a Functional API model
  tf.keras.Model().from_config(model.get_config())

  # for a Sequential model
  tf.keras.Sequential().from_config(model.get_config())
  ```

  Args:
      config: Configuration dictionary.
      custom_objects: Optional dictionary mapping names
          (strings) to custom classes or functions to be
          considered during deserialization.

  Returns:
      A Keras model instance (uncompiled).

  Raises:
      TypeError: if `config` is not a dictionary.
  """
  if isinstance(config, list):
    raise TypeError('`model_from_config` expects a dictionary, not a list. '
                    'Maybe you meant to use '
                    '`Sequential.from_config(config)`?')
  from tensorflow.python.keras.layers import deserialize  # pylint: disable=g-import-not-at-top
  return deserialize(config, custom_objects=custom_objects)
//  [python]
def author_list():
    if current_user.check_visibility(constants.SIDEBAR_AUTHOR):
        if current_user.get_view_property('author', 'dir') == 'desc':
            order = db.Authors.sort.desc()
            order_no = 0
        else:
            order = db.Authors.sort.asc()
            order_no = 1
        entries = calibre_db.session.query(db.Authors, func.count('books_authors_link.book').label('count')) \
            .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(text('books_authors_link.author')).order_by(order).all()
        char_list = generate_char_list(db.Authors.sort, db.books_authors_link)
        # If not creating a copy, readonly databases can not display authornames with "|" in it as changing the name
        # starts a change session
        author_copy = copy.deepcopy(entries)
        for entry in author_copy:
            entry.Authors.name = entry.Authors.name.replace('|', ',')
        return render_title_template('list.html', entries=author_copy, folder='web.books_list', charlist=char_list,
                                     title=u"Authors", page="authorlist", data='author', order=order_no)
    else:
        abort(404)
//  [python]
def author_list():
    if current_user.check_visibility(constants.SIDEBAR_AUTHOR):
        if current_user.get_view_property('author', 'dir') == 'desc':
            order = db.Authors.sort.desc()
            order_no = 0
        else:
            order = db.Authors.sort.asc()
            order_no = 1
        entries = calibre_db.session.query(db.Authors, func.count('books_authors_link.book').label('count')) \
            .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(text('books_authors_link.author')).order_by(order).all()
        charlist = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('char')) \
            .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(func.upper(func.substr(db.Authors.sort, 1, 1))).all()
        # If not creating a copy, readonly databases can not display authornames with "|" in it as changing the name
        # starts a change session
        autor_copy = copy.deepcopy(entries)
        for entry in autor_copy:
            entry.Authors.name = entry.Authors.name.replace('|', ',')
        return render_title_template('list.html', entries=autor_copy, folder='web.books_list', charlist=charlist,
                                     title=u"Authors", page="authorlist", data='author', order=order_no)
    else:
        abort(404)
//  [python]
def handle_delete_user(self, req):
    """Handles the DELETE v2/<account>/<user> call for deleting a user from an
    account.

    Can only be called by an account .admin.

    :param req: The swob.Request to process.
    :returns: swob.Response, 2xx on success.
    """
    # Validate path info
    account = req.path_info_pop()
    user = req.path_info_pop()
    if req.path_info or not account or account[0] == '.' or not user or \
            user[0] == '.':
        return HTTPBadRequest(request=req)

    # if user to be deleted is reseller_admin, then requesting
    # user must be the super_admin
    is_reseller_admin = self.is_user_reseller_admin(req, account, user)
    if not is_reseller_admin and not req.credentials_valid:
        # if user to be deleted can't be found, return 404
        return HTTPNotFound(request=req)
    elif is_reseller_admin and not self.is_super_admin(req):
        return HTTPForbidden(request=req)

    if not self.is_account_admin(req, account):
        return self.denied_response(req)

    # Delete the user's existing token, if any.
    path = quote('/v1/%s/%s/%s' % (self.auth_account, account, user))
    resp = self.make_pre_authed_request(
        req.environ, 'HEAD', path).get_response(self.app)
    if resp.status_int == 404:
        return HTTPNotFound(request=req)
    elif resp.status_int // 100 != 2:
        raise Exception('Could not obtain user details: %s %s' %
                        (path, resp.status))
    candidate_token = resp.headers.get('x-object-meta-auth-token')
    if candidate_token:
        object_name = self._get_concealed_token(candidate_token)
        path = quote('/v1/%s/.token_%s/%s' %
            (self.auth_account, object_name[-1], object_name))
        resp = self.make_pre_authed_request(
            req.environ, 'DELETE', path).get_response(self.app)
        if resp.status_int // 100 != 2 and resp.status_int != 404:
            raise Exception('Could not delete possibly existing token: '
                            '%s %s' % (path, resp.status))
    # Delete the user entry itself.
    path = quote('/v1/%s/%s/%s' % (self.auth_account, account, user))
    resp = self.make_pre_authed_request(
        req.environ, 'DELETE', path).get_response(self.app)
    if resp.status_int // 100 != 2 and resp.status_int != 404:
        raise Exception('Could not delete the user object: %s %s' %
                        (path, resp.status))
    return HTTPNoContent(request=req)
//  [python]
def handle_delete_user(self, req):
    """Handles the DELETE v2/<account>/<user> call for deleting a user from an
    account.

    Can only be called by an account .admin.

    :param req: The swob.Request to process.
    :returns: swob.Response, 2xx on success.
    """
    # Validate path info
    account = req.path_info_pop()
    user = req.path_info_pop()
    if req.path_info or not account or account[0] == '.' or not user or \
            user[0] == '.':
        return HTTPBadRequest(request=req)

    # if user to be deleted is reseller_admin, then requesting
    # user must be the super_admin
    is_reseller_admin = self.is_user_reseller_admin(req, account, user)
    if not is_reseller_admin and not req.credentials_valid:
        # if user to be deleted can't be found, return 404
        return HTTPNotFound(request=req)
    elif is_reseller_admin and not self.is_super_admin(req):
        return HTTPForbidden(request=req)

    if not self.is_account_admin(req, account):
        return self.denied_response(req)

    # Delete the user's existing token, if any.
    path = quote('/v1/%s/%s/%s' % (self.auth_account, account, user))
    resp = self.make_pre_authed_request(
        req.environ, 'HEAD', path).get_response(self.app)
    if resp.status_int == 404:
        return HTTPNotFound(request=req)
    elif resp.status_int // 100 != 2:
        raise Exception('Could not obtain user details: %s %s' %
                        (path, resp.status))
    candidate_token = resp.headers.get('x-object-meta-auth-token')
    if candidate_token:
        path = quote('/v1/%s/.token_%s/%s' %
            (self.auth_account, candidate_token[-1], candidate_token))
        resp = self.make_pre_authed_request(
            req.environ, 'DELETE', path).get_response(self.app)
        if resp.status_int // 100 != 2 and resp.status_int != 404:
            raise Exception('Could not delete possibly existing token: '
                            '%s %s' % (path, resp.status))
    # Delete the user entry itself.
    path = quote('/v1/%s/%s/%s' % (self.auth_account, account, user))
    resp = self.make_pre_authed_request(
        req.environ, 'DELETE', path).get_response(self.app)
    if resp.status_int // 100 != 2 and resp.status_int != 404:
        raise Exception('Could not delete the user object: %s %s' %
                        (path, resp.status))
    return HTTPNoContent(request=req)
//  [python]
def language_overview():
    if current_user.check_visibility(constants.SIDEBAR_LANGUAGE) and current_user.filter_language() == u"all":
        order_no = 0 if current_user.get_view_property('language', 'dir') == 'desc' else 1
        char_list = list()
        languages = calibre_db.speaking_language(reverse_order=not order_no, with_count=True)
        for lang in languages:
            upper_lang = lang[0].name[0].upper()
            if upper_lang not in char_list:
                char_list.append(upper_lang)
        return render_title_template('languages.html', languages=languages,
                                     charlist=char_list, title=_(u"Languages"), page="langlist",
                                     data="language", order=order_no)
    else:
        abort(404)
//  [python]
def language_overview():
    if current_user.check_visibility(constants.SIDEBAR_LANGUAGE) and current_user.filter_language() == u"all":
        order_no = 0 if current_user.get_view_property('language', 'dir') == 'desc' else 1
        charlist = list()
        languages = calibre_db.speaking_language(reverse_order=not order_no, with_count=True)
        for lang in languages:
            upper_lang = lang[0].name[0].upper()
            if upper_lang not in charlist:
                charlist.append(upper_lang)
        return render_title_template('languages.html', languages=languages,
                                     charlist=charlist, title=_(u"Languages"), page="langlist",
                                     data="language", order=order_no)
    else:
        abort(404)
//  [python]
def logout():
    if current_user is not None and current_user.is_authenticated:
        ub.delete_user_session(current_user.id, flask_session.get('_id', ""))
        logout_user()
        if feature_support['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3):
            logout_oauth_user()
    log.debug(u"User logged out")
    return redirect(url_for('web.login'))
//  [python]
def logout():
    if current_user is not None and current_user.is_authenticated:
        ub.delete_user_session(current_user.id, flask_session.get('_id',""))
        logout_user()
        if feature_support['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3):
            logout_oauth_user()
    log.debug(u"User logged out")
    return redirect(url_for('web.login'))
//  [python]
def publisher_list():
    if current_user.get_view_property('publisher', 'dir') == 'desc':
        order = db.Publishers.name.desc()
        order_no = 0
    else:
        order = db.Publishers.name.asc()
        order_no = 1
    if current_user.check_visibility(constants.SIDEBAR_PUBLISHER):
        entries = calibre_db.session.query(db.Publishers, func.count('books_publishers_link.book').label('count')) \
            .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(text('books_publishers_link.publisher')).order_by(order).all()
        char_list = generate_char_list(db.Publishers.name, db.books_publishers_link)
        return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=char_list,
                                     title=_(u"Publishers"), page="publisherlist", data="publisher", order=order_no)
    else:
        abort(404)
//  [python]
def publisher_list():
    if current_user.get_view_property('publisher', 'dir') == 'desc':
        order = db.Publishers.name.desc()
        order_no = 0
    else:
        order = db.Publishers.name.asc()
        order_no = 1
    if current_user.check_visibility(constants.SIDEBAR_PUBLISHER):
        entries = calibre_db.session.query(db.Publishers, func.count('books_publishers_link.book').label('count')) \
            .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(text('books_publishers_link.publisher')).order_by(order).all()
        charlist = calibre_db.session.query(func.upper(func.substr(db.Publishers.name, 1, 1)).label('char')) \
            .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(func.upper(func.substr(db.Publishers.name, 1, 1))).all()
        return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist,
                                     title=_(u"Publishers"), page="publisherlist", data="publisher", order=order_no)
    else:
        abort(404)
//  [python]
def ratings_list():
    if current_user.check_visibility(constants.SIDEBAR_RATING):
        if current_user.get_view_property('ratings', 'dir') == 'desc':
            order = db.Ratings.rating.desc()
            order_no = 0
        else:
            order = db.Ratings.rating.asc()
            order_no = 1
        entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'),
                                           (db.Ratings.rating / 2).label('name')) \
            .join(db.books_ratings_link).join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(text('books_ratings_link.rating')).order_by(order).all()
        return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=list(),
                                     title=_(u"Ratings list"), page="ratingslist", data="ratings", order=order_no)
    else:
        abort(404)
//  [python]
def ratings_list():
    if current_user.check_visibility(constants.SIDEBAR_RATING):
        if current_user.get_view_property('ratings', 'dir') == 'desc':
            order = db.Ratings.rating.desc()
            order_no = 0
        else:
            order = db.Ratings.rating.asc()
            order_no = 1
        entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'),
                                   (db.Ratings.rating / 2).label('name')) \
            .join(db.books_ratings_link).join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(text('books_ratings_link.rating')).order_by(order).all()
        return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=list(),
                                     title=_(u"Ratings list"), page="ratingslist", data="ratings", order=order_no)
    else:
        abort(404)
//  [python]
def profile():
    languages = calibre_db.speaking_language()
    translations = babel.list_translations() + [Locale('en')]
    kobo_support = feature_support['kobo'] and config.config_kobo_sync
    if feature_support['oauth'] and config.config_login_type == 2:
        oauth_status = get_oauth_status()
        local_oauth_check = oauth_check
    else:
        oauth_status = None
        local_oauth_check = {}

    if request.method == "POST":
        change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages)
    return render_title_template("user_edit.html",
                                 translations=translations,
                                 profile=1,
                                 languages=languages,
                                 content=current_user,
                                 kobo_support=kobo_support,
                                 title=_(u"%(name)s's profile", name=current_user.name),
                                 page="me",
                                 registered_oauth=local_oauth_check,
                                 oauth_status=oauth_status)
//  [python]
def profile():
    languages = calibre_db.speaking_language()
    translations = babel.list_translations() + [LC('en')]
    kobo_support = feature_support['kobo'] and config.config_kobo_sync
    if feature_support['oauth'] and config.config_login_type == 2:
        oauth_status = get_oauth_status()
        local_oauth_check = oauth_check
    else:
        oauth_status = None
        local_oauth_check = {}

    if request.method == "POST":
        change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages)
    return render_title_template("user_edit.html",
                                 translations=translations,
                                 profile=1,
                                 languages=languages,
                                 content=current_user,
                                 kobo_support=kobo_support,
                                 title=_(u"%(name)s's profile", name=current_user.name),
                                 page="me",
                                 registered_oauth=local_oauth_check,
                                 oauth_status=oauth_status)
//  [python]
def render_archived_books(page, sort_param):
    order = sort_param[0] or []
    archived_books = (ub.session.query(ub.ArchivedBook)
                      .filter(ub.ArchivedBook.user_id == int(current_user.id))
                      .filter(ub.ArchivedBook.is_archived == True)
                      .all())
    archived_book_ids = [archived_book.book_id for archived_book in archived_books]

    archived_filter = db.Books.id.in_(archived_book_ids)

    entries, random, pagination = calibre_db.fill_indexpage_with_archived_books(page, db.Books,
                                                                                0,
                                                                                archived_filter,
                                                                                order,
                                                                                True,
                                                                                False, 0)

    name = _(u'Archived Books') + ' (' + str(len(archived_book_ids)) + ')'
    page_name = "archived"
    return render_title_template('index.html', random=random, entries=entries, pagination=pagination,
                                 title=name, page=page_name, order=sort_param[1])
//  [python]
def render_archived_books(page, sort_param):
    order = sort_param[0] or []
    archived_books = (
        ub.session.query(ub.ArchivedBook)
        .filter(ub.ArchivedBook.user_id == int(current_user.id))
        .filter(ub.ArchivedBook.is_archived == True)
        .all()
    )
    archived_book_ids = [archived_book.book_id for archived_book in archived_books]

    archived_filter = db.Books.id.in_(archived_book_ids)

    entries, random, pagination = calibre_db.fill_indexpage_with_archived_books(page, db.Books,
                                                                                0,
                                                                                archived_filter,
                                                                                order,
                                                                                True,
                                                                                False, 0)

    name = _(u'Archived Books') + ' (' + str(len(archived_book_ids)) + ')'
    pagename = "archived"
    return render_title_template('index.html', random=random, entries=entries, pagination=pagination,
                                 title=name, page=pagename, order=sort_param[1])
//  [python]
def download_list():
    if current_user.get_view_property('download', 'dir') == 'desc':
        order = ub.User.name.desc()
        order_no = 0
    else:
        order = ub.User.name.asc()
        order_no = 1
    if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD) and current_user.role_admin():
        entries = ub.session.query(ub.User, func.count(ub.Downloads.book_id).label('count')) \
            .join(ub.Downloads).group_by(ub.Downloads.user_id).order_by(order).all()
        char_list = ub.session.query(func.upper(func.substr(ub.User.name, 1, 1)).label('char')) \
            .filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) \
            .group_by(func.upper(func.substr(ub.User.name, 1, 1))).all()
        return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=char_list,
                                     title=_(u"Downloads"), page="downloadlist", data="download", order=order_no)
    else:
        abort(404)
//  [python]
def download_list():
    if current_user.get_view_property('download', 'dir') == 'desc':
        order = ub.User.name.desc()
        order_no = 0
    else:
        order = ub.User.name.asc()
        order_no = 1
    if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD) and current_user.role_admin():
        entries = ub.session.query(ub.User, func.count(ub.Downloads.book_id).label('count'))\
            .join(ub.Downloads).group_by(ub.Downloads.user_id).order_by(order).all()
        charlist = ub.session.query(func.upper(func.substr(ub.User.name, 1, 1)).label('char')) \
            .filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) \
            .group_by(func.upper(func.substr(ub.User.name, 1, 1))).all()
        return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist,
                                     title=_(u"Downloads"), page="downloadlist", data="download", order=order_no)
    else:
        abort(404)
//  [python]
def read_book(book_id, book_format):
    book = calibre_db.get_filtered_book(book_id)
    book.ordered_authors = calibre_db.order_authors([book], False)

    if not book:
        flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"),
              category="error")
        log.debug(u"Oops! Selected book title is unavailable. File does not exist or is not accessible")
        return redirect(url_for("web.index"))

    # check if book has a bookmark
    bookmark = None
    if current_user.is_authenticated:
        bookmark = ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(current_user.id),
                                                             ub.Bookmark.book_id == book_id,
                                                             ub.Bookmark.format == book_format.upper())).first()
    if book_format.lower() == "epub":
        log.debug(u"Start epub reader for %d", book_id)
        return render_title_template('read.html', bookid=book_id, title=book.title, bookmark=bookmark)
    elif book_format.lower() == "pdf":
        log.debug(u"Start pdf reader for %d", book_id)
        return render_title_template('readpdf.html', pdffile=book_id, title=book.title)
    elif book_format.lower() == "txt":
        log.debug(u"Start txt reader for %d", book_id)
        return render_title_template('readtxt.html', txtfile=book_id, title=book.title)
    elif book_format.lower() == "djvu":
        log.debug(u"Start djvu reader for %d", book_id)
        return render_title_template('readdjvu.html', djvufile=book_id, title=book.title)
    else:
        for fileExt in constants.EXTENSIONS_AUDIO:
            if book_format.lower() == fileExt:
                entries = calibre_db.get_filtered_book(book_id)
                log.debug(u"Start mp3 listening for %d", book_id)
                return render_title_template('listenmp3.html', mp3file=book_id, audioformat=book_format.lower(),
                                             entry=entries, bookmark=bookmark)
        for fileExt in ["cbr", "cbt", "cbz"]:
            if book_format.lower() == fileExt:
                all_name = str(book_id)
                title = book.title
                if len(book.series):
                    title = title + " - " + book.series[0].name
                    if book.series_index:
                        title = title + " #" + '{0:.2f}'.format(book.series_index).rstrip('0').rstrip('.')
                log.debug(u"Start comic reader for %d", book_id)
                return render_title_template('readcbr.html', comicfile=all_name, title=title,
                                             extension=fileExt)
        log.debug(u"Oops! Selected book title is unavailable. File does not exist or is not accessible")
        flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"),
              category="error")
        return redirect(url_for("web.index"))