text:
<!DOCTYPE html >

    <link rel="stylesheet" href="demos.css" type="text/css" media="screen" />

    <title>A Pie chart using the CSV reader</title>

    <meta name="robots" content="noindex,nofollow" />
    <meta name="description" content="A Pie chart using the CSV reader" />

A Pie chart using the CSV reader

        Note:
        For browser security reasons the AJAX demos don't work offline. You can view the demos on the RGraph website here:
        http://www.rgraph.net/demos

    <canvas id="cvs" width="500" height="250">[No canvas support]</canvas>

    This goes in the documents header:

<script src="RGraph.common.core.js"></script>
<script src="RGraph.common.csv.js"></script>
<script src="RGraph.pie.js"></script>

    Put this where you want the chart to show up:

<canvas id="cvs" width="500" height="250">
    [No canvas support]
</canvas>

    This is the code that generates the chart:

<script>
    window.onload = function ()
    {
        RGraph.CSV('/sample.csv', function (csv)
        {
            // Fetch the labels from the CSV file (the first column)
            var labels = csv.getCol(0);

            // Fetch the second column of the CSV file
            var data = csv.getCol(1);

            var pie = new RGraph.Pie({
                id: 'cvs',
                data: data,
                options: {
                    labels: labels,
                    exploded: 5
                }
            }).draw();
        });
    };
</script>

        « Back


text:
title:  Yakub Si Pengganti
date:  21/05/2022
---

### Bacaan Untuk Pelajaran Minggu Ini
Kej. 25:21–34, Kej. 28:10–22, Kej. 11:1–9, Kej. 29:1–30, Kej. 30:25–32.

>
Ayat Hafalan

> "Kata Esau: 'Bukankah tepat namanya Yakub, kerana ia telah dua kali menipu aku. Hak kesulunganku telah dirampasnya, dan sekarang dirampasnya pula berkat yang untukku.' Lalu katanya: 'Apakah bapa tidak mempunyai berkat lain bagiku? ' " (Kejadian 27:36).

Sekarang kita lihat sejarah keluarga Ishak seterusnya, anak keajaiban dan leluhur awal benih yang dijanjikan. Walau bagaimanapun, cerita itu tidak bermula dengan baik. Kecacatan karakter anaknya Yakub akan kelihatan dalam persaingan antara dua beradik itu mengenai hak kesulungan (Kej. 25:27–34) dan sudah tentu mengenai hak untuk memperoleh berkat Ishak (Kejadian 27).

Oleh kerana Yakub menipu ayahnya dan mencuri berkat daripada abangnya, dia terpaksa melarikan diri untuk menyelamatkan nyawanya. Dalam buangan, Tuhan menemuinya di Betel (Kej. 28:10–22). Sejak itu Yakub, si penipu, akan mengalami sendiri penipuan. Bukan Rahel, yang dicintai Yakub (Kejadian 29),  akan diberikan kepadanya, sebaliknya Lea, anak perempuan Laban yang lebih tua, dan dia perlu bekerja selama 14 tahun untuk mendapatkan isteri-isterinya.

Namun, Yakub juga akan mengalami berkat Tuhan, kerana selama dalam pembuangan dia akan mempunyai 11 orang anak lelaki, dan Tuhan akan menambahkan kekayaannya.

Oleh itu, apapun yang  kita lihat dalam kisah ini, kita dapat melihat bagaimana Tuhan akan memenuhi janji perjanjianNya, dalam apa carapun, tidak kira berapa kerap umatNya gagal.

*Sila kaji Pelajaran minggu ini sebagai persediaan untuk Sabat, 28 Mei.

redpajama_set_name: RedPajamaGithub


text:
CM_ADMIN_USERNAME=admin
CM_ADMIN_PASSWORD=admin
CM_CLUSTER_NAME=Cluster1
CM_API_VERSION=12
CM_HOSTNAME="$(hostname -f)"
API_CLUSTER_BASE="http://$CM_HOSTNAME:7180/api/v$CM_API_VERSION/clusters/$CM_CLUSTER_NAME"
API_CM_BASE="http://$CM_HOSTNAME:7180/api/v$CM_API_VERSION/cm"
API_COMMANDS_BASE="http://$CM_HOSTNAME:7180/api/v$CM_API_VERSION/commands"

INITIAL_START_DONE_FLAG="/var/lib/.cloudera-manager"

function log()
{
    echo "[$(date +"%T")][DEPLOYER] ${1}"
}

function wait_for_command_done()
{
    local CMD_ID="$@"
    local CHECK_CMD="curl -sS -u "$CM_ADMIN_USERNAME:$CM_ADMIN_PASSWORD" "$API_COMMANDS_BASE/$CMD_ID" | jq '.success'"

    while [[ "$(eval $CHECK_CMD)" == "null" ]]
    do
        log "Waiting for done of command=$CMD_ID"
        sleep 10
    done

    if [[ "$(eval $CHECK_CMD)" == "true" ]]
    then
        log "command=$CMD_ID is done"
    else
        log "command=$CMD_ID failed"
        exit 1
    fi
}

function waitcm()
{
    # TODO - a short cut check only on port 7180 for service 'cloudera-scm-server'
    local isOpen=$(nmap -sT $CM_HOSTNAME -p 7180 | grep open)
    while [[ -z "$isOpen" ]]
    do
      log "Waiting for CM to be started on port 7180"
      sleep 5
      isOpen=$(nmap -sT $CM_HOSTNAME -p 7180 | grep open)
    done
    log "waitcm - DONE"
}

function startcm()
{
    # the cm core agents, this list is for the server, not for agent
    cloudera-scm-server-db start
    cloudera-scm-server start
    #cloudera-scm-agent start
}

function stopcm()
{
    # the cm core agents, this list is for the server, not for agent
    #cloudera-scm-agent stop
    cloudera-scm-server stop
    cloudera-scm-server-db stop
}

function restart_cm_services()
{
    # TODO - the management services may not exists
    # the cm core services
    log "restarting cm services..."
    local command="curl -sS -u $CM_ADMIN_USERNAME:$CM_ADMIN_PASSWORD -X POST $API_CM_BASE/service/commands/restart | jq '.id'"
    log "command=$command"
    local CMD_ID=$(command)
    wait_for_command_done $CMD_ID
    log "restarting cm services done"
}

function restart_cluster_services()
{
    # TODO - the cluster services may not exists
    # services of the cluster, this also redeploy client configs
    log "restarting cluster services for cluster $CM_CLUSTER ..."
    CMD_ID=$(curl -sS -u "$CM_ADMIN_USERNAME:$CM_ADMIN_PASSWORD" -X POST -H "Content-Type:application/json" -d '{ "redeployClientConfiguration": "true" }' "$API_CLUSTER_BASE/commands/restart" | jq '.id')
    wait_for_command_done $CMD_ID
    log "restarting cluster services for cluster $CM_CLUSTER done"
}

function main()
{
    if [[ ! -e $INITIAL_START_DONE_FLAG ]]; then
        log "initial start of cm..."
        startcm
        waitcm
        touch $INITIAL_START_DONE_FLAG
    else
        log "restart of cm..."
        stopcm
        startcm
        waitcm
        restart_cm_services
        restart_cluster_services
    fi
}

main "$@"


text:
import pymongo

class ZhihuPipeline(object):
    def process_item(self, item, spider):
        return item

class MongoPipeline(object):
    collection_name = 'users'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE')
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        self.db[self.collection_name].update({'url_token': item['url_token']}, dict(item), True)
        return item


text:
package nl.talsmasoftware.context.servletrequest;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Servlet {@link Filter} that registers the current {@link ServletRequest} with the
 * {@link ServletRequestContextManager} to become the
 * {@link ServletRequestContextManager#getActiveContext() active context}
 * while the filter is active.
 *
 * @author Sjoerd Talsma
 */
public class ServletRequestContextFilter implements Filter {
    private static final Logger LOGGER = Logger.getLogger(ServletRequestContextFilter.class.getName());

    public void init(FilterConfig filterConfig) {
        // no-op
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {

            new ServletRequestContext(request); // Automatically becomes the new active context.
            if (request.isAsyncStarted()) try {
                request.getAsyncContext().addListener(new ServletRequestContextAsyncListener());
            } catch (IllegalStateException e) {
                LOGGER.log(Level.FINE, "Could not register servletrequest asynchronous listener: " + e.getMessage(), e);
            }

            chain.doFilter(request, response);

        } finally {
            ServletRequestContextManager.clear(); // Make sure there are no requests returned to the HTTP threadpool.
        }
    }

    public void destroy() {
        // no-op
    }

    @Override
    public String toString() {
        return getClass().getSimpleName();
    }

}


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/login/auth/auth_session_authenticator.h"

#include <map>
#include <memory>
#include <string>
#include <utility>

#include "ash/constants/ash_features.h"
#include "base/callback_helpers.h"
#include "base/check.h"
#include "base/memory/scoped_refptr.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/test/test_future.h"
#include "chromeos/ash/components/cryptohome/system_salt_getter.h"
#include "chromeos/ash/components/dbus/cryptohome/UserDataAuth.pb.h"
#include "chromeos/ash/components/dbus/cryptohome/key.pb.h"
#include "chromeos/ash/components/dbus/cryptohome/rpc.pb.h"
#include "chromeos/ash/components/dbus/userdataauth/cryptohome_misc_client.h"
#include "chromeos/ash/components/dbus/userdataauth/mock_userdataauth_client.h"
#include "chromeos/ash/components/dbus/userdataauth/userdataauth_client.h"
#include "chromeos/ash/components/login/auth/mock_auth_status_consumer.h"
#include "chromeos/ash/components/login/auth/mock_safe_mode_delegate.h"
#include "chromeos/ash/components/login/auth/public/auth_failure.h"
#include "chromeos/ash/components/login/auth/public/cryptohome_key_constants.h"
#include "chromeos/ash/components/login/auth/public/key.h"
#include "chromeos/ash/components/login/auth/public/user_context.h"
#include "components/account_id/account_id.h"
#include "components/prefs/pref_service_factory.h"
#include "components/prefs/testing_pref_service.h"
#include "components/prefs/testing_pref_store.h"
#include "components/user_manager/user_directory_integrity_manager.h"
#include "components/user_manager/user_type.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using cryptohome::KeyData;
using testing::_;
using testing::AllOf;
using testing::AtMost;
using testing::Return;
using user_data_auth::AddAuthFactorReply;
using user_data_auth::AddCredentialsReply;
using user_data_auth::AUTH_FACTOR_TYPE_KIOSK;
using user_data_auth::AUTH_FACTOR_TYPE_PASSWORD;
using user_data_auth::AUTH_INTENT_DECRYPT;
using user_data_auth::AUTH_INTENT_VERIFY_ONLY;
using user_data_auth::AUTH_SESSION_FLAGS_EPHEMERAL_USER;
using user_data_auth::AUTH_SESSION_FLAGS_NONE;
using user_data_auth::AuthenticateAuthFactorReply;
using user_data_auth::AuthenticateAuthSessionReply;
using user_data_auth::AuthFactor;
using user_data_auth::CreatePersistentUserReply;
using user_data_auth::ListAuthFactorsReply;
using user_data_auth::PrepareEphemeralVaultReply;
using user_data_auth::PrepareGuestVaultReply;
using user_data_auth::PreparePersistentVaultReply;
using user_data_auth::RemoveReply;
using user_data_auth::StartAuthSessionReply;

namespace ash {

namespace {

constexpr char kEmail[] = "fake-email@example.com";
constexpr char kPassword[] = "pass";
constexpr char kFirstAuthSessionId[] = "123";
constexpr char kSecondAuthSessionId[] = "456";

// Matchers that verify the given cryptohome ...Request protobuf has the
// expected auth_session_id.
MATCHER(WithFirstAuthSessionId, "") {
  return arg.auth_session_id() == kFirstAuthSessionId;
}

MATCHER(WithSecondAuthSessionId, "") {
  return arg.auth_session_id() == kSecondAuthSessionId;
}

// Matcher for `ListAuthFactors` that checks its account_id.
MATCHER(WithAccountId, "") {
  return arg.account_id().account_id() == kEmail;
}

// Matcher for `StartAuthSessionRequest` that checks its account_id, flags and
// intent.
MATCHER_P2(WithAccountIdAndFlags, flags, intent, "") {
  return arg.account_id().account_id() == kEmail &&
         arg.flags() == static_cast<unsigned>(flags) && arg.intent() == intent;
}

// Matchers for `AuthenticateAuthSessionRequest` and `AddCredentialsRequest`
// that verify the key properties.
MATCHER_P(WithPasswordKey, expected_label, "") {
  if (arg.authorization().key().data().type() != KeyData::KEY_TYPE_PASSWORD ||
      arg.authorization().key().data().label() != expected_label) {
    return false;
  }
  // Validate the password is already hashed here.
  EXPECT_NE(arg.authorization().key().secret(), "");
  EXPECT_NE(arg.authorization().key().secret(), kPassword);
  return true;
}

// Matcher for `AuthenticateAuthFactorRequest` that verify the key properties.
MATCHER_P(WithPasswordFactorAuth, expected_label, "") {
  if (!arg.auth_input().has_password_input())
    return false;
  if (arg.auth_factor_label() != expected_label)
    return false;

  // Validate the password is already hashed here.
  EXPECT_NE(arg.auth_input().password_input().secret(), "");
  EXPECT_NE(arg.auth_input().password_input().secret(), kPassword);
  return true;
}

// Matcher `AddAuthFactorRequest` that verify the key properties.
MATCHER_P(WithPasswordFactorAdd, expected_label, "") {
  if (!arg.auth_input().has_password_input())
    return false;
  if (arg.auth_factor().label() != expected_label)
    return false;
  if (arg.auth_factor().type() != user_data_auth::AUTH_FACTOR_TYPE_PASSWORD)
    return false;

  // Validate the password is already hashed here.
  EXPECT_NE(arg.auth_input().password_input().secret(), "");
  EXPECT_NE(arg.auth_input().password_input().secret(), kPassword);
  return true;
}

MATCHER(WithKioskKey, "") {
  return arg.authorization().key().data().type() == KeyData::KEY_TYPE_KIOSK &&
         arg.authorization().key().data().label() ==
             kCryptohomePublicMountLabel;
}

MATCHER(WithKioskFactorAdd, "") {
  if (!arg.auth_input().has_kiosk_input())
    return false;
  if (arg.auth_factor().label() != kCryptohomePublicMountLabel)
    return false;
  if (arg.auth_factor().type() != user_data_auth::AUTH_FACTOR_TYPE_KIOSK)
    return false;
  return true;
}

MATCHER(WithKioskFactorAuth, "") {
  if (!arg.auth_input().has_kiosk_input())
    return false;
  if (arg.auth_factor_label() != kCryptohomePublicMountLabel)
    return false;
  return true;
}

// GMock action that runs the callback (which is expected to be the second
// argument in the mocked function) with the given reply.
template <typename ReplyType>
auto ReplyWith(const ReplyType& reply) {
  return base::test::RunOnceCallback<1>(reply);
}

StartAuthSessionReply BuildStartReply(
    const std::string& auth_session_id,
    bool user_exists,
    const std::map<std::string, KeyData>& keys,
    const std::vector<AuthFactor>& factors) {
  StartAuthSessionReply reply;
  reply.set_auth_session_id(auth_session_id);
  reply.set_user_exists(user_exists);
  for (const auto& [key, data] : keys)
    (*reply.mutable_key_label_data())[key] = data;
  for (const auto& factor : factors)
    (*reply.add_auth_factors()) = factor;
  return reply;
}

AuthenticateAuthSessionReply BuildAuthenticateSuccessReply() {
  AuthenticateAuthSessionReply reply;
  reply.set_authenticated(true);
  return reply;
}

AuthenticateAuthFactorReply BuildAuthenticateFactorSuccessReply() {
  AuthenticateAuthFactorReply reply;
  reply.set_authenticated(true);
  reply.add_authorized_for(user_data_auth::AUTH_INTENT_DECRYPT);
  return reply;
}

AuthenticateAuthSessionReply BuildAuthenticateFailureReply() {
  AuthenticateAuthSessionReply reply;
  reply.set_authenticated(false);
  reply.set_error(user_data_auth::CRYPTOHOME_ERROR_AUTHORIZATION_KEY_FAILED);
  reply.mutable_error_info()->set_primary_action(
      user_data_auth::PRIMARY_INCORRECT_AUTH);
  return reply;
}

AuthenticateAuthFactorReply BuildAuthenticateFactorFailureReply() {
  AuthenticateAuthFactorReply reply;
  reply.set_authenticated(false);
  reply.set_error(user_data_auth::CRYPTOHOME_ERROR_AUTHORIZATION_KEY_FAILED);
  reply.mutable_error_info()->set_primary_action(
      user_data_auth::PRIMARY_INCORRECT_AUTH);
  return reply;
}

AuthFactor PasswordFactor(const std::string& label) {
  AuthFactor factor;
  factor.set_type(AUTH_FACTOR_TYPE_PASSWORD);
  factor.set_label(label);
  factor.mutable_common_metadata();
  factor.mutable_password_metadata();
  return factor;
}

AuthFactor KioskFactor() {
  AuthFactor factor;
  factor.set_type(AUTH_FACTOR_TYPE_KIOSK);
  factor.set_label(kCryptohomePublicMountLabel);
  factor.mutable_common_metadata();
  factor.mutable_kiosk_metadata();
  return factor;
}

}  // namespace

class AuthSessionAuthenticatorTest : public ::testing::Test,
                                     public testing::WithParamInterface<bool> {
 protected:
  const AccountId kAccountId = AccountId::FromUserEmail(kEmail);

  AuthSessionAuthenticatorTest() {
    if (GetParam()) {
      scoped_feature_list_.InitAndEnableFeature(features::kUseAuthFactors);
    } else {
      scoped_feature_list_.InitAndDisableFeature(features::kUseAuthFactors);
    }

    CryptohomeMiscClient::InitializeFake();
    chromeos::SystemSaltGetter::Initialize();
    UserDataAuthClient::OverrideGlobalInstanceForTesting(&userdataauth_);

    EXPECT_CALL(auth_status_consumer_, OnAuthSuccess(_))
        .Times(AtMost(1))
        .WillOnce([this](const UserContext& user_context) {
          on_auth_success_future_.SetValue(user_context);
        });
    EXPECT_CALL(auth_status_consumer_, OnAuthFailure(_))
        .Times(AtMost(1))
        .WillOnce([this](const AuthFailure& error) {
          on_auth_failure_future_.SetValue(error);
        });
    EXPECT_CALL(auth_status_consumer_, OnPasswordChangeDetected(_))
        .Times(AtMost(1))
        .WillOnce([this](const UserContext& user_context) {
          on_password_change_detected_future_.SetValue(user_context);
        });
    EXPECT_CALL(auth_status_consumer_, OnOffTheRecordAuthSuccess())
        .Times(AtMost(1))
        .WillOnce([this]() {
          on_off_the_record_auth_success_future_.SetValue(true);
        });
  }

  ~AuthSessionAuthenticatorTest() override {
    chromeos::SystemSaltGetter::Shutdown();
    CryptohomeMiscClient::Shutdown();
  }

  void RegisterPrefs() {
    user_manager::UserDirectoryIntegrityManager::RegisterLocalStatePrefs(
        local_state_.registry());
  }

  void CreateAuthenticator(bool is_ephemeral_mount_enforced) {
    auto owned_safe_mode_delegate = std::make_unique<MockSafeModeDelegate>();
    safe_mode_delegate_ = owned_safe_mode_delegate.get();
    ON_CALL(*safe_mode_delegate_, IsSafeMode).WillByDefault(Return(false));
    RegisterPrefs();
    authenticator_ = base::MakeRefCounted<AuthSessionAuthenticator>(
        &auth_status_consumer_, std::move(owned_safe_mode_delegate),
        /*user_recorder=*/base::DoNothing(), is_ephemeral_mount_enforced,
        &local_state_);
  }

  MockUserDataAuthClient& userdataauth() { return userdataauth_; }

  Authenticator& authenticator() {
    DCHECK(authenticator_);
    return *authenticator_;
  }

  base::test::TestFuture<UserContext>& on_auth_success_future() {
    return on_auth_success_future_;
  }
  base::test::TestFuture<AuthFailure>& on_auth_failure_future() {
    return on_auth_failure_future_;
  }
  base::test::TestFuture<UserContext>& on_password_change_detected_future() {
    return on_password_change_detected_future_;
  }
  base::test::TestFuture<bool>& on_off_the_record_auth_success_future() {
    return on_off_the_record_auth_success_future_;
  }

 private:
  base::test::SingleThreadTaskEnvironment task_environment_;
  base::test::ScopedFeatureList scoped_feature_list_;
  base::test::TestFuture<UserContext> on_auth_success_future_;
  base::test::TestFuture<AuthFailure> on_auth_failure_future_;
  base::test::TestFuture<UserContext> on_password_change_detected_future_;
  base::test::TestFuture<bool> on_off_the_record_auth_success_future_;
  MockUserDataAuthClient userdataauth_;
  MockAuthStatusConsumer auth_status_consumer_{
      /*quit_closure=*/base::DoNothing()};
  scoped_refptr<AuthSessionAuthenticator> authenticator_;
  // Unowned (points to the object owned by `authenticator_`).
  MockSafeModeDelegate* safe_mode_delegate_ = nullptr;
  TestingPrefServiceSimple local_state_;
};

// Test the `CompleteLogin()` method in the new regular user scenario.
TEST_P(AuthSessionAuthenticatorTest, CompleteLoginRegularNew) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/false);
  auto user_context = std::make_unique<UserContext>(
      user_manager::USER_TYPE_REGULAR, kAccountId);
  user_context->SetKey(Key(kPassword));
  EXPECT_CALL(userdataauth(),
              StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_NONE,
                                                     AUTH_INTENT_DECRYPT),
                               _))
      .WillOnce(ReplyWith(BuildStartReply(kFirstAuthSessionId,
                                          /*user_exists=*/false,
                                          /*keys=*/{},
                                          /*factors=*/{})));
  EXPECT_CALL(userdataauth(), CreatePersistentUser(WithFirstAuthSessionId(), _))
      .WillOnce(ReplyWith(CreatePersistentUserReply()));
  EXPECT_CALL(userdataauth(),
              PreparePersistentVault(WithFirstAuthSessionId(), _))
      .WillOnce(ReplyWith(PreparePersistentVaultReply()));
  if (features::IsUseAuthFactorsEnabled()) {
    EXPECT_CALL(
        userdataauth(),
        AddAuthFactor(AllOf(WithFirstAuthSessionId(),
                            WithPasswordFactorAdd(kCryptohomeGaiaKeyLabel)),
                      _))
        .WillOnce(ReplyWith(AddAuthFactorReply()));
    EXPECT_CALL(userdataauth(), ListAuthFactors(WithAccountId(), _))
        .WillOnce(ReplyWith(ListAuthFactorsReply()));
  } else {
    EXPECT_CALL(userdataauth(),
                AddCredentials(AllOf(WithFirstAuthSessionId(),
                                     WithPasswordKey(kCryptohomeGaiaKeyLabel)),
                               _))
        .WillOnce(ReplyWith(AddCredentialsReply()));
  }

  // Act.
  authenticator().CompleteLogin(std::move(user_context));
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kFirstAuthSessionId);
}

// Test the `CompleteLogin()` method in the existing regular user scenario.
TEST_P(AuthSessionAuthenticatorTest, CompleteLoginRegularExisting) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/false);
  auto user_context = std::make_unique<UserContext>(
      user_manager::USER_TYPE_REGULAR, kAccountId);
  user_context->SetKey(Key(kPassword));
  EXPECT_CALL(userdataauth(),
              StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_NONE,
                                                     AUTH_INTENT_DECRYPT),
                               _))
      .WillOnce(ReplyWith(BuildStartReply(
          kFirstAuthSessionId, /*user_exists=*/true,
          /*keys=*/{{kCryptohomeGaiaKeyLabel, KeyData()}},
          /*factors=*/{PasswordFactor(kCryptohomeGaiaKeyLabel)})));
  if (features::IsUseAuthFactorsEnabled()) {
    EXPECT_CALL(userdataauth(),
                AuthenticateAuthFactor(
                    AllOf(WithFirstAuthSessionId(),
                          WithPasswordFactorAuth(kCryptohomeGaiaKeyLabel)),
                    _))
        .WillOnce(ReplyWith(BuildAuthenticateFactorSuccessReply()));
  } else {
    EXPECT_CALL(
        userdataauth(),
        AuthenticateAuthSession(AllOf(WithFirstAuthSessionId(),
                                      WithPasswordKey(kCryptohomeGaiaKeyLabel)),
                                _))
        .WillOnce(ReplyWith(BuildAuthenticateSuccessReply()));
  }
  EXPECT_CALL(userdataauth(),
              PreparePersistentVault(WithFirstAuthSessionId(), _))
      .WillOnce(ReplyWith(PreparePersistentVaultReply()));

  // Act.
  authenticator().CompleteLogin(std::move(user_context));
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kFirstAuthSessionId);
}
// Test the `CompleteLogin()` method in the password change scenario for the
// existing regular user.
TEST_P(AuthSessionAuthenticatorTest,
       CompleteLoginRegularExistingPasswordChange) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/false);
  auto user_context = std::make_unique<UserContext>(
      user_manager::USER_TYPE_REGULAR, kAccountId);
  user_context->SetKey(Key(kPassword));
  EXPECT_CALL(userdataauth(),
              StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_NONE,
                                                     AUTH_INTENT_DECRYPT),
                               _))
      .WillOnce(ReplyWith(BuildStartReply(
          kFirstAuthSessionId,
          /*user_exists=*/true,
          /*keys=*/{{kCryptohomeGaiaKeyLabel, KeyData()}},
          /*factors=*/{PasswordFactor(kCryptohomeGaiaKeyLabel)})));
  // Set up the cryptohome authentication request to return a failure, since
  // we're simulating the case when it only knows about the old password.
  if (features::IsUseAuthFactorsEnabled()) {
    EXPECT_CALL(userdataauth(),
                AuthenticateAuthFactor(
                    AllOf(WithFirstAuthSessionId(),
                          WithPasswordFactorAuth(kCryptohomeGaiaKeyLabel)),
                    _))
        .WillOnce(ReplyWith(BuildAuthenticateFactorFailureReply()));
  } else {
    EXPECT_CALL(
        userdataauth(),
        AuthenticateAuthSession(AllOf(WithFirstAuthSessionId(),
                                      WithPasswordKey(kCryptohomeGaiaKeyLabel)),
                                _))
        .WillOnce(ReplyWith(BuildAuthenticateFailureReply()));
  }

  // Act.
  authenticator().CompleteLogin(std::move(user_context));
  const UserContext got_user_context =
      on_password_change_detected_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kFirstAuthSessionId);
}

// Test the `CompleteLogin()` method in the ephemeral user scenario.
TEST_P(AuthSessionAuthenticatorTest, CompleteLoginEphemeral) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/true);
  auto user_context = std::make_unique<UserContext>(
      user_manager::USER_TYPE_REGULAR, kAccountId);
  user_context->SetKey(Key(kPassword));
  EXPECT_CALL(
      userdataauth(),
      StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_EPHEMERAL_USER,
                                             AUTH_INTENT_DECRYPT),
                       _))
      .WillOnce(ReplyWith(BuildStartReply(kFirstAuthSessionId,
                                          /*user_exists=*/false, /*keys=*/{},
                                          /*factors=*/{})));
  EXPECT_CALL(userdataauth(),
              PrepareEphemeralVault(WithFirstAuthSessionId(), _))
      .WillOnce(ReplyWith(PrepareEphemeralVaultReply()));
  if (features::IsUseAuthFactorsEnabled()) {
    EXPECT_CALL(
        userdataauth(),
        AddAuthFactor(AllOf(WithFirstAuthSessionId(),
                            WithPasswordFactorAdd(kCryptohomeGaiaKeyLabel)),
                      _))
        .WillOnce(ReplyWith(AddAuthFactorReply()));
    EXPECT_CALL(userdataauth(), ListAuthFactors(WithAccountId(), _))
        .WillOnce(ReplyWith(ListAuthFactorsReply()));
  } else {
    EXPECT_CALL(userdataauth(),
                AddCredentials(AllOf(WithFirstAuthSessionId(),
                                     WithPasswordKey(kCryptohomeGaiaKeyLabel)),
                               _))
        .WillOnce(ReplyWith(AddCredentialsReply()));
  }

  // Act.
  authenticator().CompleteLogin(std::move(user_context));
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kFirstAuthSessionId);
}

// Test the `CompleteLogin()` method in the scenario when an ephemeral login is
// requested while having stale persistent data for the same user.
TEST_P(AuthSessionAuthenticatorTest, CompleteLoginEphemeralStaleData) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/true);
  auto user_context = std::make_unique<UserContext>(
      user_manager::USER_TYPE_REGULAR, kAccountId);
  user_context->SetKey(Key(kPassword));
  {
    testing::InSequence seq;
    EXPECT_CALL(userdataauth(),
                StartAuthSession(
                    WithAccountIdAndFlags(AUTH_SESSION_FLAGS_EPHEMERAL_USER,
                                          AUTH_INTENT_DECRYPT),
                    _))
        .WillOnce(
            ReplyWith(BuildStartReply(kFirstAuthSessionId, /*user_exists=*/true,
                                      /*keys=*/{}, /*factors=*/{})))
        .RetiresOnSaturation();
    EXPECT_CALL(userdataauth(), Remove(WithFirstAuthSessionId(), _))
        .WillOnce(ReplyWith(RemoveReply()));
    EXPECT_CALL(userdataauth(),
                StartAuthSession(
                    WithAccountIdAndFlags(AUTH_SESSION_FLAGS_EPHEMERAL_USER,
                                          AUTH_INTENT_DECRYPT),
                    _))
        .WillOnce(ReplyWith(BuildStartReply(kSecondAuthSessionId,
                                            /*user_exists=*/false, /*keys=*/{},
                                            /*factors=*/{})));
    EXPECT_CALL(userdataauth(),
                PrepareEphemeralVault(WithSecondAuthSessionId(), _))
        .WillOnce(ReplyWith(PrepareEphemeralVaultReply()));
    if (features::IsUseAuthFactorsEnabled()) {
      EXPECT_CALL(
          userdataauth(),
          AddAuthFactor(AllOf(WithSecondAuthSessionId(),
                              WithPasswordFactorAdd(kCryptohomeGaiaKeyLabel)),
                        _))
          .WillOnce(ReplyWith(AddAuthFactorReply()));
      EXPECT_CALL(userdataauth(), ListAuthFactors(WithAccountId(), _))
          .WillOnce(ReplyWith(ListAuthFactorsReply()));
    } else {
      EXPECT_CALL(
          userdataauth(),
          AddCredentials(AllOf(WithSecondAuthSessionId(),
                               WithPasswordKey(kCryptohomeGaiaKeyLabel)),
                         _))
          .WillOnce(ReplyWith(AddCredentialsReply()));
    }
  }

  // Act.
  authenticator().CompleteLogin(std::move(user_context));
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kSecondAuthSessionId);
}

// Test the `AuthenticateToLogin()` method in the successful scenario.
TEST_P(AuthSessionAuthenticatorTest, AuthenticateToLogin) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/false);
  auto user_context = std::make_unique<UserContext>(
      user_manager::USER_TYPE_REGULAR, kAccountId);
  user_context->SetKey(Key(kPassword));
  EXPECT_CALL(userdataauth(),
              StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_NONE,
                                                     AUTH_INTENT_DECRYPT),
                               _))
      .WillOnce(ReplyWith(BuildStartReply(
          kFirstAuthSessionId,
          /*user_exists=*/true,
          /*keys=*/{{kCryptohomeGaiaKeyLabel, KeyData()}},
          /*factors=*/{PasswordFactor(kCryptohomeGaiaKeyLabel)})));
  if (features::IsUseAuthFactorsEnabled()) {
    EXPECT_CALL(userdataauth(),
                AuthenticateAuthFactor(
                    AllOf(WithFirstAuthSessionId(),
                          WithPasswordFactorAuth(kCryptohomeGaiaKeyLabel)),
                    _))
        .WillOnce(ReplyWith(BuildAuthenticateFactorSuccessReply()));
  } else {
    EXPECT_CALL(
        userdataauth(),
        AuthenticateAuthSession(AllOf(WithFirstAuthSessionId(),
                                      WithPasswordKey(kCryptohomeGaiaKeyLabel)),
                                _))
        .WillOnce(ReplyWith(BuildAuthenticateSuccessReply()));
  }
  EXPECT_CALL(userdataauth(),
              PreparePersistentVault(WithFirstAuthSessionId(), _))
      .WillOnce(ReplyWith(PreparePersistentVaultReply()));

  // Act.
  authenticator().AuthenticateToLogin(std::move(user_context));
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kFirstAuthSessionId);
}

// Test the `AuthenticateToLogin()` method in the authentication failure
// scenario.
TEST_P(AuthSessionAuthenticatorTest, AuthenticateToLoginAuthFailure) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/false);
  auto user_context = std::make_unique<UserContext>(
      user_manager::USER_TYPE_REGULAR, kAccountId);
  user_context->SetKey(Key(kPassword));
  EXPECT_CALL(userdataauth(),
              StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_NONE,
                                                     AUTH_INTENT_DECRYPT),
                               _))
      .WillOnce(ReplyWith(BuildStartReply(
          kFirstAuthSessionId, /*user_exists=*/true,
          /*keys=*/{{kCryptohomeGaiaKeyLabel, KeyData()}},
          /*factors=*/{PasswordFactor(kCryptohomeGaiaKeyLabel)})));
  if (features::IsUseAuthFactorsEnabled()) {
    EXPECT_CALL(userdataauth(),
                AuthenticateAuthFactor(
                    AllOf(WithFirstAuthSessionId(),
                          WithPasswordFactorAuth(kCryptohomeGaiaKeyLabel)),
                    _))
        .WillOnce(ReplyWith(BuildAuthenticateFactorFailureReply()));
  } else {
    EXPECT_CALL(
        userdataauth(),
        AuthenticateAuthSession(AllOf(WithFirstAuthSessionId(),
                                      WithPasswordKey(kCryptohomeGaiaKeyLabel)),
                                _))
        .WillOnce(ReplyWith(BuildAuthenticateFailureReply()));
  }

  // Act.
  authenticator().AuthenticateToLogin(std::move(user_context));
  const AuthFailure auth_failure = on_auth_failure_future().Get();

  // Assert.
  EXPECT_EQ(auth_failure.reason(), AuthFailure::COULD_NOT_MOUNT_CRYPTOHOME);
}

// Test the `LoginOffTheRecord()` method in the successful scenario.
TEST_P(AuthSessionAuthenticatorTest, LoginOffTheRecord) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/false);
  EXPECT_CALL(userdataauth(), PrepareGuestVault(_, _))
      .WillOnce(ReplyWith(PrepareGuestVaultReply()));

  // Act.
  authenticator().LoginOffTheRecord();
  EXPECT_TRUE(on_off_the_record_auth_success_future().Wait());
}

// Test the `LoginAsPublicSession()` method in the successful scenario.
TEST_P(AuthSessionAuthenticatorTest, LoginAsPublicSession) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/false);
  UserContext user_context(user_manager::USER_TYPE_PUBLIC_ACCOUNT, kAccountId);
  EXPECT_CALL(
      userdataauth(),
      StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_EPHEMERAL_USER,
                                             AUTH_INTENT_DECRYPT),
                       _))
      .WillOnce(ReplyWith(BuildStartReply(kFirstAuthSessionId,
                                          /*user_exists=*/false, /*keys=*/{},
                                          /*factors=*/{})));
  EXPECT_CALL(userdataauth(),
              PrepareEphemeralVault(WithFirstAuthSessionId(), _))
      .WillOnce(ReplyWith(PrepareEphemeralVaultReply()));

  // Act.
  authenticator().LoginAsPublicSession(user_context);
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kFirstAuthSessionId);
}

// Test the `LoginAsKioskAccount()` method in the scenario when the kiosk
// homedir needs to be created.
TEST_P(AuthSessionAuthenticatorTest, LoginAsKioskAccountNew) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/false);
  EXPECT_CALL(userdataauth(),
              StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_NONE,
                                                     AUTH_INTENT_DECRYPT),
                               _))
      .WillOnce(
          ReplyWith(BuildStartReply(kFirstAuthSessionId, /*user_exists=*/false,
                                    /*keys=*/{},
                                    /*factors=*/{})));
  EXPECT_CALL(userdataauth(), CreatePersistentUser(WithFirstAuthSessionId(), _))
      .WillOnce(ReplyWith(CreatePersistentUserReply()));
  EXPECT_CALL(userdataauth(),
              PreparePersistentVault(WithFirstAuthSessionId(), _))
      .WillOnce(ReplyWith(PreparePersistentVaultReply()));
  if (features::IsUseAuthFactorsEnabled()) {
    EXPECT_CALL(
        userdataauth(),
        AddAuthFactor(AllOf(WithFirstAuthSessionId(), WithKioskFactorAdd()), _))
        .WillOnce(ReplyWith(AddAuthFactorReply()));
    // Note: kiosk flow, unlike other, does not request to list auth factors,
    // as no further editing is assumed.
  } else {
    EXPECT_CALL(
        userdataauth(),
        AddCredentials(AllOf(WithFirstAuthSessionId(), WithKioskKey()), _))
        .WillOnce(ReplyWith(AddCredentialsReply()));
  }

  // Act.
  authenticator().LoginAsKioskAccount(kAccountId);
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kFirstAuthSessionId);
}

// Test the `LoginAsKioskAccount()` method in the scenario when the kiosk
// homedir already exists.
TEST_P(AuthSessionAuthenticatorTest, LoginAsKioskAccountExisting) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/false);
  KeyData key_data;
  key_data.set_type(KeyData::KEY_TYPE_KIOSK);
  EXPECT_CALL(userdataauth(),
              StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_NONE,
                                                     AUTH_INTENT_DECRYPT),
                               _))
      .WillOnce(ReplyWith(
          BuildStartReply(kFirstAuthSessionId, /*user_exists=*/true,
                          /*keys=*/{{kCryptohomePublicMountLabel, key_data}},
                          /*factors=*/{KioskFactor()})));
  if (features::IsUseAuthFactorsEnabled()) {
    EXPECT_CALL(userdataauth(),
                AuthenticateAuthFactor(
                    AllOf(WithFirstAuthSessionId(), WithKioskFactorAuth()), _))
        .WillOnce(ReplyWith(BuildAuthenticateFactorSuccessReply()));
  } else {
    EXPECT_CALL(userdataauth(),
                AuthenticateAuthSession(
                    AllOf(WithFirstAuthSessionId(), WithKioskKey()), _))
        .WillOnce(ReplyWith(BuildAuthenticateSuccessReply()));
  };
  EXPECT_CALL(userdataauth(),
              PreparePersistentVault(WithFirstAuthSessionId(), _))
      .WillOnce(ReplyWith(PreparePersistentVaultReply()));

  // Act.
  authenticator().LoginAsKioskAccount(kAccountId);
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kFirstAuthSessionId);
}

// Test the `LoginAsKioskAccount()` method in the ephemeral kiosk scenario.
TEST_P(AuthSessionAuthenticatorTest, LoginAsKioskAccountEphemeral) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/true);
  EXPECT_CALL(
      userdataauth(),
      StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_EPHEMERAL_USER,
                                             AUTH_INTENT_DECRYPT),
                       _))
      .WillOnce(ReplyWith(BuildStartReply(kFirstAuthSessionId,
                                          /*user_exists=*/false, /*keys=*/{},
                                          /*factors=*/{})));
  EXPECT_CALL(userdataauth(),
              PrepareEphemeralVault(WithFirstAuthSessionId(), _))
      .WillOnce(ReplyWith(PrepareEphemeralVaultReply()));

  // Act.
  authenticator().LoginAsKioskAccount(kAccountId);
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kFirstAuthSessionId);
}

// Test the `LoginAsKioskAccount()` method in the scenario when an ephemeral
// kiosk is requested while having stale persistent data for the same user.
TEST_P(AuthSessionAuthenticatorTest, LoginAsKioskAccountEphemeralStaleData) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/true);
  {
    testing::InSequence seq;
    EXPECT_CALL(userdataauth(),
                StartAuthSession(
                    WithAccountIdAndFlags(AUTH_SESSION_FLAGS_EPHEMERAL_USER,
                                          AUTH_INTENT_DECRYPT),
                    _))
        .WillOnce(ReplyWith(BuildStartReply(kFirstAuthSessionId,
                                            /*user_exists=*/true, /*keys=*/{},
                                            /*factors=*/{})))
        .RetiresOnSaturation();
    EXPECT_CALL(userdataauth(), Remove(WithFirstAuthSessionId(), _))
        .WillOnce(ReplyWith(RemoveReply()));
    EXPECT_CALL(userdataauth(),
                StartAuthSession(
                    WithAccountIdAndFlags(AUTH_SESSION_FLAGS_EPHEMERAL_USER,
                                          AUTH_INTENT_DECRYPT),
                    _))
        .WillOnce(ReplyWith(BuildStartReply(kSecondAuthSessionId,
                                            /*user_exists=*/false, /*keys=*/{},
                                            /*factors=*/{})));
    EXPECT_CALL(userdataauth(),
                PrepareEphemeralVault(WithSecondAuthSessionId(), _))
        .WillOnce(ReplyWith(PrepareEphemeralVaultReply()));
  }

  // Act.
  authenticator().LoginAsKioskAccount(kAccountId);
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kSecondAuthSessionId);
}

// Test the `AuthenticateToUnlock()` method in the successful scenario.
TEST_P(AuthSessionAuthenticatorTest, AuthenticateToUnlock) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/false);
  auto user_context = std::make_unique<UserContext>(
      user_manager::USER_TYPE_REGULAR, kAccountId);
  user_context->SetKey(Key(kPassword));
  EXPECT_CALL(userdataauth(),
              StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_NONE,
                                                     AUTH_INTENT_VERIFY_ONLY),
                               _))
      .WillOnce(ReplyWith(BuildStartReply(
          kFirstAuthSessionId,
          /*user_exists=*/true,
          /*keys=*/{{kCryptohomeGaiaKeyLabel, KeyData()}},
          /*factors=*/{PasswordFactor(kCryptohomeGaiaKeyLabel)})));
  if (features::IsUseAuthFactorsEnabled()) {
    EXPECT_CALL(userdataauth(),
                AuthenticateAuthFactor(
                    AllOf(WithFirstAuthSessionId(),
                          WithPasswordFactorAuth(kCryptohomeGaiaKeyLabel)),
                    _))
        .WillOnce(ReplyWith(BuildAuthenticateFactorSuccessReply()));
  } else {
    EXPECT_CALL(
        userdataauth(),
        AuthenticateAuthSession(AllOf(WithFirstAuthSessionId(),
                                      WithPasswordKey(kCryptohomeGaiaKeyLabel)),
                                _))
        .WillOnce(ReplyWith(BuildAuthenticateSuccessReply()));
  }

  // Act.
  authenticator().AuthenticateToUnlock(std::move(user_context));
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kFirstAuthSessionId);
}

// Test the `AuthenticateToUnlock()` method in the successful scenario for
// ephemeral user with the configured password.
TEST_P(AuthSessionAuthenticatorTest, AuthenticateToUnlockEphemeral) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/true);
  auto user_context = std::make_unique<UserContext>(
      user_manager::USER_TYPE_REGULAR, kAccountId);
  user_context->SetKey(Key(kPassword));
  EXPECT_CALL(
      userdataauth(),
      StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_EPHEMERAL_USER,
                                             AUTH_INTENT_VERIFY_ONLY),
                       _))
      .WillOnce(ReplyWith(BuildStartReply(
          kFirstAuthSessionId,
          /*user_exists=*/true,
          /*keys=*/{{kCryptohomeGaiaKeyLabel, KeyData()}},
          /*factors=*/{PasswordFactor(kCryptohomeGaiaKeyLabel)})));
  if (features::IsUseAuthFactorsEnabled()) {
    EXPECT_CALL(userdataauth(),
                AuthenticateAuthFactor(
                    AllOf(WithFirstAuthSessionId(),
                          WithPasswordFactorAuth(kCryptohomeGaiaKeyLabel)),
                    _))
        .WillOnce(ReplyWith(BuildAuthenticateFactorSuccessReply()));
  } else {
    EXPECT_CALL(
        userdataauth(),
        AuthenticateAuthSession(AllOf(WithFirstAuthSessionId(),
                                      WithPasswordKey(kCryptohomeGaiaKeyLabel)),
                                _))
        .WillOnce(ReplyWith(BuildAuthenticateSuccessReply()));
  }

  // Act.
  authenticator().AuthenticateToUnlock(std::move(user_context));
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kFirstAuthSessionId);
}

// Test the `AuthenticateToUnlock()` method in the successful scenario for
// Managed Guest Session with the configured password (e.g., Imprivata).
TEST_P(AuthSessionAuthenticatorTest, AuthenticateToUnlockMgs) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/false);
  auto user_context = std::make_unique<UserContext>(
      user_manager::USER_TYPE_PUBLIC_ACCOUNT, kAccountId);
  EXPECT_CALL(
      userdataauth(),
      StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_EPHEMERAL_USER,
                                             AUTH_INTENT_VERIFY_ONLY),
                       _))
      .WillOnce(ReplyWith(BuildStartReply(
          kFirstAuthSessionId,
          /*user_exists=*/true,
          /*keys=*/{{kCryptohomeGaiaKeyLabel, KeyData()}},
          /*factors=*/{PasswordFactor(kCryptohomeGaiaKeyLabel)})));
  if (features::IsUseAuthFactorsEnabled()) {
    EXPECT_CALL(userdataauth(),
                AuthenticateAuthFactor(
                    AllOf(WithFirstAuthSessionId(),
                          WithPasswordFactorAuth(kCryptohomeGaiaKeyLabel)),
                    _))
        .WillOnce(ReplyWith(BuildAuthenticateFactorSuccessReply()));
  } else {
    EXPECT_CALL(
        userdataauth(),
        AuthenticateAuthSession(AllOf(WithFirstAuthSessionId(),
                                      WithPasswordKey(kCryptohomeGaiaKeyLabel)),
                                _))
        .WillOnce(ReplyWith(BuildAuthenticateSuccessReply()));
  }

  // Act.
  authenticator().AuthenticateToUnlock(std::move(user_context));
  const UserContext got_user_context = on_auth_success_future().Get();

  // Assert.
  EXPECT_EQ(got_user_context.GetAccountId(), kAccountId);
  EXPECT_EQ(got_user_context.GetAuthSessionId(), kFirstAuthSessionId);
}

// Test the `AuthenticateToUnlock()` method in the authentication failure
// scenario.
TEST_P(AuthSessionAuthenticatorTest, AuthenticateToUnlockinAuthFailure) {
  // Arrange.
  CreateAuthenticator(/*is_ephemeral_mount_enforced=*/false);
  auto user_context = std::make_unique<UserContext>(
      user_manager::USER_TYPE_REGULAR, kAccountId);
  user_context->SetKey(Key(kPassword));
  EXPECT_CALL(userdataauth(),
              StartAuthSession(WithAccountIdAndFlags(AUTH_SESSION_FLAGS_NONE,
                                                     AUTH_INTENT_VERIFY_ONLY),
                               _))
      .WillOnce(ReplyWith(BuildStartReply(
          kFirstAuthSessionId, /*user_exists=*/true,
          /*keys=*/{{kCryptohomeGaiaKeyLabel, KeyData()}},
          /*factors=*/{PasswordFactor(kCryptohomeGaiaKeyLabel)})));
  if (features::IsUseAuthFactorsEnabled()) {
    EXPECT_CALL(userdataauth(),
                AuthenticateAuthFactor(
                    AllOf(WithFirstAuthSessionId(),
                          WithPasswordFactorAuth(kCryptohomeGaiaKeyLabel)),
                    _))
        .WillOnce(ReplyWith(BuildAuthenticateFactorFailureReply()));
  } else {
    EXPECT_CALL(
        userdataauth(),
        AuthenticateAuthSession(AllOf(WithFirstAuthSessionId(),
                                      WithPasswordKey(kCryptohomeGaiaKeyLabel)),
                                _))
        .WillOnce(ReplyWith(BuildAuthenticateFailureReply()));
  }

  // Act.
  authenticator().AuthenticateToUnlock(std::move(user_context));
  const AuthFailure auth_failure = on_auth_failure_future().Get();

  // Assert.
  EXPECT_EQ(auth_failure.reason(), AuthFailure::UNLOCK_FAILED);
}

INSTANTIATE_TEST_SUITE_P(All, AuthSessionAuthenticatorTest, ::testing::Bool());

}  // namespace ash


text:
// Copyright © 2017 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace chocolatey.infrastructure.app.configuration
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Reflection;
    using System.Security.Principal;
    using System.Text;
    using adapters;
    using logging;
    using nuget;
    using Environment = adapters.Environment;

    public static class EnvironmentSettings
    {
        private const string SET_ENVIRONMENT_METHOD = "SetEnvironment";
        private static Lazy<IEnvironment> _environmentInitializer = new Lazy<IEnvironment>(() => new Environment());

        [EditorBrowsable(EditorBrowsableState.Never)]
        public static void initialize_with(Lazy<IEnvironment> environment)
        {
            _environmentInitializer = environment;
        }

        private static IEnvironment Environment
        {
            get { return _environmentInitializer.Value; }
        }

        public static void reset_environment_variables(ChocolateyConfiguration config)
        {
            Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallLocation, null);
            Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallerType, null);
            Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageExitCode, null);

            Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyIgnoreChecksums, null);
            Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyAllowEmptyChecksums, null);
            Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyAllowEmptyChecksumsSecure, null);
            Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPowerShellHost, null);
            Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyForce, null);

            Environment.SetEnvironmentVariable("chocolateyProxyLocation", null);
            Environment.SetEnvironmentVariable("chocolateyProxyBypassList", null);
            Environment.SetEnvironmentVariable("chocolateyProxyBypassOnLocal", null);
        }

        public static void set_environment_variables(ChocolateyConfiguration config)
        {
            reset_environment_variables(config);

            Environment.SetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName, ApplicationParameters.InstallLocation);
            Environment.SetEnvironmentVariable("CHOCOLATEY_VERSION", config.Information.ChocolateyVersion);
            Environment.SetEnvironmentVariable("CHOCOLATEY_VERSION_PRODUCT", config.Information.ChocolateyProductVersion);
            Environment.SetEnvironmentVariable("OS_PLATFORM", config.Information.PlatformType.get_description_or_value());
            Environment.SetEnvironmentVariable("OS_VERSION", config.Information.PlatformVersion.to_string());
            Environment.SetEnvironmentVariable("OS_NAME", config.Information.PlatformName.to_string());
            // experimental until we know if this value returns correctly based on the OS and not the current process.
            Environment.SetEnvironmentVariable("OS_IS64BIT", config.Information.Is64BitOperatingSystem ? "true" : "false");
            Environment.SetEnvironmentVariable("PROCESS_IS64BIT", config.Information.Is64BitProcess ? "true" : "false");
            Environment.SetEnvironmentVariable("USER_NAME", config.Information.UserName);
            Environment.SetEnvironmentVariable("USER_DOMAIN", config.Information.UserDomainName);
            Environment.SetEnvironmentVariable("IS_ADMIN", config.Information.IsUserAdministrator ? "true" : "false");
            Environment.SetEnvironmentVariable("IS_SYSTEM", config.Information.IsUserSystemAccount ? "true" : "false");
            Environment.SetEnvironmentVariable("IS_REMOTEDESKTOP", config.Information.IsUserRemoteDesktop ? "true" : "false");
            Environment.SetEnvironmentVariable("IS_REMOTE", config.Information.IsUserRemote ? "true" : "false");
            Environment.SetEnvironmentVariable("IS_PROCESSELEVATED", config.Information.IsProcessElevated ? "true" : "false");
            Environment.SetEnvironmentVariable("TEMP", config.CacheLocation);
            Environment.SetEnvironmentVariable("TMP", config.CacheLocation);

            if (config.Debug) Environment.SetEnvironmentVariable("ChocolateyEnvironmentDebug", "true");
            if (config.Verbose) Environment.SetEnvironmentVariable("ChocolateyEnvironmentVerbose", "true");
            if (!config.Features.ChecksumFiles) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyIgnoreChecksums, "true");
            if (config.Features.AllowEmptyChecksums) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyAllowEmptyChecksums, "true");
            if (config.Features.AllowEmptyChecksumsSecure) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyAllowEmptyChecksumsSecure, "true");
            if (config.Features.ScriptsCheckLastExitCode) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyCheckLastExitCode, "true");
            Environment.SetEnvironmentVariable("chocolateyRequestTimeout", config.WebRequestTimeoutSeconds.to_string() + "000");

            if (config.CommandExecutionTimeoutSeconds != 0)
            {
                Environment.SetEnvironmentVariable("chocolateyResponseTimeout", config.CommandExecutionTimeoutSeconds.to_string() + "000");
            }

            if (!string.IsNullOrWhiteSpace(config.Proxy.Location))
            {
                var proxyCreds = string.Empty;
                if (!string.IsNullOrWhiteSpace(config.Proxy.User) &&
                    !string.IsNullOrWhiteSpace(config.Proxy.EncryptedPassword)
                    )
                {
                    proxyCreds = "{0}:{1}@".format_with(config.Proxy.User, NugetEncryptionUtility.DecryptString(config.Proxy.EncryptedPassword));

                    Environment.SetEnvironmentVariable("chocolateyProxyUser", config.Proxy.User);
                    Environment.SetEnvironmentVariable("chocolateyProxyPassword", NugetEncryptionUtility.DecryptString(config.Proxy.EncryptedPassword));
                }

                Environment.SetEnvironmentVariable("http_proxy", "{0}{1}".format_with(proxyCreds, config.Proxy.Location));
                Environment.SetEnvironmentVariable("https_proxy", "{0}{1}".format_with(proxyCreds, config.Proxy.Location));
                Environment.SetEnvironmentVariable("chocolateyProxyLocation", config.Proxy.Location);

                if (!string.IsNullOrWhiteSpace(config.Proxy.BypassList))
                {
                    Environment.SetEnvironmentVariable("chocolateyProxyBypassList", config.Proxy.BypassList);
                    Environment.SetEnvironmentVariable("no_proxy", config.Proxy.BypassList);

                }

                if (config.Proxy.BypassOnLocal) Environment.SetEnvironmentVariable("chocolateyProxyBypassOnLocal", "true");
            }

            if (config.Features.UsePowerShellHost) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPowerShellHost, "true");
            if (config.Force) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyForce, "true");
            set_licensed_environment(config);
        }

        private static void set_licensed_environment(ChocolateyConfiguration config)
        {
            if (!config.Information.IsLicensedVersion) return;

            Environment.SetEnvironmentVariable("ChocolateyLicenseType", config.Information.LicenseType);

            var licenseAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name.is_equal_to("chocolatey.licensed"));

            if (licenseAssembly != null)
            {
                Type licensedEnvironmentSettings = licenseAssembly.GetType(ApplicationParameters.LicensedEnvironmentSettings, throwOnError: false, ignoreCase: true);

                if (licensedEnvironmentSettings == null)
                {
                    if (config.RegularOutput) "chocolatey".Log().Warn(
                        ChocolateyLoggers.Important, @"Unable to set licensed environment settings. Please upgrade to a newer
 licensed version (choco upgrade chocolatey.extension).");
                    return;
                }
                try
                {
                    object componentClass = Activator.CreateInstance(licensedEnvironmentSettings);

                    licensedEnvironmentSettings.InvokeMember(
                        SET_ENVIRONMENT_METHOD,
                        BindingFlags.InvokeMethod,
                        null,
                        componentClass,
                        new Object[] { config }
                        );
                }
                catch (Exception ex)
                {
                    var isDebug = ApplicationParameters.is_debug_mode_cli_primitive();
                    if (config.Debug) isDebug = true;
                    var message = isDebug ? ex.ToString() : ex.Message;

                    if (isDebug && ex.InnerException != null)
                    {
                        message += "{0}{1}".format_with(Environment.NewLine, ex.InnerException.ToString());
                    }

                    "chocolatey".Log().Error(
                        ChocolateyLoggers.Important,
                        @"Error when setting environment for '{0}':{1} {2}".format_with(
                            licensedEnvironmentSettings.FullName,
                            Environment.NewLine,
                            message
                            ));
                }
            }
        }

        /// <summary>
        ///   Refreshes the current environment values with the updated values,
        ///   even if updated outside of the current process.
        /// </summary>
        /// <remarks>
        ///   This does not remove environment variables, but will ensure all updates are shown.
        ///   To see actual update with removed variables, one will need to restart a shell.
        /// </remarks>
        public static void update_environment_variables()
        {
            // grab original values
            var originalEnvironmentVariables = convert_to_case_insensitive_dictionary(Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process));
            var userName = originalEnvironmentVariables[ApplicationParameters.Environment.Username].to_string();
            var architecture = originalEnvironmentVariables[ApplicationParameters.Environment.ProcessorArchitecture].to_string();
            var originalPath = originalEnvironmentVariables[ApplicationParameters.Environment.Path]
                .to_string()
                .Split(new[] { ApplicationParameters.Environment.EnvironmentSeparator }, StringSplitOptions.RemoveEmptyEntries);
            var originalPathExt = originalEnvironmentVariables[ApplicationParameters.Environment.PathExtensions]
                .to_string()
                .Split(new[] { ApplicationParameters.Environment.EnvironmentSeparator }, StringSplitOptions.RemoveEmptyEntries);
            var originalPsModulePath = originalEnvironmentVariables[ApplicationParameters.Environment.PsModulePath]
                .to_string()
                .Split(new[] { ApplicationParameters.Environment.EnvironmentSeparator }, StringSplitOptions.RemoveEmptyEntries);

            // get updated values from the registry
            var machineVariables = convert_to_case_insensitive_dictionary(Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine));
            var userVariables = convert_to_case_insensitive_dictionary(Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User));

            // refresh current values with updated values, mathine first
            refresh_environment_variables(machineVariables);

            //if the user is SYSTEM, we should not even look at user Variables
            var setUserEnvironmentVariables = true;
            try
            {
                var userIdentity = WindowsIdentity.GetCurrent();
                if (userIdentity != null && userIdentity.User == ApplicationParameters.LocalSystemSid)
                {
                    setUserEnvironmentVariables = false;
                }
            }
            catch (Exception ex)
            {
                "chocolatey".Log().Debug("Unable to determine current user to determine if LocalSystem account (to skip user env vars).{0} Reported error: {1}".format_with(Environment.NewLine, ex.Message));
            }

            if (setUserEnvironmentVariables) refresh_environment_variables(userVariables);

            // restore process overridden variables
            if (originalEnvironmentVariables.Contains(ApplicationParameters.Environment.Username)) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.Username, userName);
            if (originalEnvironmentVariables.Contains(ApplicationParameters.Environment.ProcessorArchitecture)) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ProcessorArchitecture, architecture);

            // combine environment values that append together
            var updatedPath = "{0};{1};".format_with(
                machineVariables[ApplicationParameters.Environment.Path].to_string(),
                userVariables[ApplicationParameters.Environment.Path].to_string()
                ).Replace(";;", ";");
            var updatedPathExt = "{0};{1};".format_with(
                machineVariables[ApplicationParameters.Environment.PathExtensions].to_string(),
                userVariables[ApplicationParameters.Environment.PathExtensions].to_string()
                ).Replace(";;", ";");
            var updatedPsModulePath = "{0};{1};".format_with(
                userVariables[ApplicationParameters.Environment.PsModulePath].to_string(),
                machineVariables[ApplicationParameters.Environment.PsModulePath].to_string()
                ).Replace(";;", ";");

            // add back in process items
            updatedPath += gather_process_only_items(updatedPath, originalPath);
            updatedPathExt += gather_process_only_items(updatedPathExt, originalPathExt);
            updatedPsModulePath = "{0};{1}".format_with(gather_process_only_items(updatedPsModulePath, originalPsModulePath),updatedPsModulePath);

            if (!updatedPsModulePath.contains(ApplicationParameters.PowerShellModulePathProcessProgramFiles))
            {
                updatedPsModulePath = "{0};{1}".format_with(ApplicationParameters.PowerShellModulePathProcessProgramFiles, updatedPsModulePath).Replace(";;", ";");
            }

            if (!updatedPsModulePath.contains(ApplicationParameters.PowerShellModulePathProcessDocuments))
            {
                updatedPsModulePath = "{0};{1}".format_with(ApplicationParameters.PowerShellModulePathProcessDocuments, updatedPsModulePath).Replace(";;", ";");
            }

            if (updatedPsModulePath.StartsWith(";"))
            {
                updatedPsModulePath = updatedPsModulePath.Remove(0, 1);
            }

            Environment.SetEnvironmentVariable(ApplicationParameters.Environment.Path, updatedPath);
            Environment.SetEnvironmentVariable(ApplicationParameters.Environment.PathExtensions, updatedPathExt);
            Environment.SetEnvironmentVariable(ApplicationParameters.Environment.PsModulePath, updatedPsModulePath);
        }

        private static IDictionary convert_to_case_insensitive_dictionary(IDictionary originalDictionary)
        {
            if (originalDictionary == null) return new Hashtable(new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase);

            return new Hashtable(originalDictionary, StringComparer.OrdinalIgnoreCase);
        }

        private static void refresh_environment_variables(IDictionary environmentVariables)
        {
            foreach (DictionaryEntry variable in environmentVariables.or_empty_list_if_null())
            {
                Environment.SetEnvironmentVariable(variable.Key.to_string(), variable.Value.to_string());
            }
        }

        private static string gather_process_only_items(string currentValues, IEnumerable<string> originalValues)
        {
            var additionalItems = new StringBuilder();
            var items = currentValues.Split(
                new[] { ApplicationParameters.Environment.EnvironmentSeparator },
                StringSplitOptions.RemoveEmptyEntries
                );

            foreach (string originalValue in originalValues.or_empty_list_if_null())
            {
                if (!items.Contains(originalValue, StringComparer.InvariantCultureIgnoreCase))
                {
                    additionalItems.AppendFormat("{0};", originalValue);
                }
            }

            return additionalItems.to_string();
        }
    }
}


text:
<!DOCTYPE html>
<title>Prefetching SignedHTTPExchange with payload integrity error should fail</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/get-host-info.sub.js"></script>
<script src="./resources/sxg-util.js"></script>
<body>
<script>
promise_test(async (t) => {
  const sxgUrl = get_host_info().HTTPS_ORIGIN + '/signed-exchange/resources/sxg/sxg-merkle-integrity-error.sxg';
  await new Promise(resolve => {
    const link = document.createElement('link');
    link.rel = 'prefetch';
    link.href = sxgUrl;
    link.addEventListener('error', t.step_func(() => {
        resolve();
    }));
    link.addEventListener('load', t.step_func(() => {
        assert_unreached('Prefetch should fail');
    }));
    document.body.appendChild(link);
  });
}, "Prefetching SignedHTTPExchange with payload integrity error should fail");

</script>
</body>


text:
<?php

namespace OneOfZero\Json\Mappers;

use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use Reflector;

interface MapperInterface
{
	/**
	 * Should return the mapping source.
	 *
	 * @return SourceInterface
	 */
	public function getSource();

	/**
	 * Should return the reflection target of the mapper.
	 *
	 * @return Reflector|ReflectionClass|ReflectionMethod|ReflectionProperty
	 */
	public function getTarget();

	/**
	 * Should set the provided target as the reflection target of the mapper.
	 *
	 * @param Reflector|ReflectionClass|ReflectionMethod|ReflectionProperty $reflector
	 */
	public function setTarget(Reflector $reflector);

	/**
	 * Should return the mapper chain.
	 *
	 * @return MapperChainInterface|ObjectMapperChain|MemberMapperChain
	 */
	public function getChain();

	/**
	 * Should set the mapper chain to the provided chain.
	 *
	 * @param MapperChainInterface|ObjectMapperChain|MemberMapperChain $chain
	 */
	public function setChain(MapperChainInterface $chain);

	/**
	 * Should return the type of the first serializing custom converter for the field.
	 *
	 * @return string|null
	 */
	public function getSerializingConverterType();

	/**
	 * Should return the type of the first deserializing custom converter for the field.
	 *
	 * @return string|null
	 */
	public function getDeserializingConverterType();

	/**
	 * Should return a boolean value indicating whether or not the field has a serializing custom converter configured.
	 *
	 * @return bool
	 */
	public function hasSerializingConverter();

	/**
	 * Should return a boolean value indicating whether or not the field has a deserializing custom converter
	 * configured.
	 *
	 * @return bool
	 */
	public function hasDeserializingConverter();
}


text:
from __future__ import unicode_literals

from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse, reverse_lazy
from django.utils.decorators import method_decorator
from django.views import generic

from .test_forms import AuthorForm, ContactForm
from .models import Artist, Author, Book, Page, BookSigning

class CustomTemplateView(generic.TemplateView):
    template_name = 'generic_views/about.html'

    def get_context_data(self, **kwargs):
        context = super(CustomTemplateView, self).get_context_data(**kwargs)
        context.update({'key': 'value'})
        return context

class ObjectDetail(generic.DetailView):
    template_name = 'generic_views/detail.html'

    def get_object(self):
        return {'foo': 'bar'}

class ArtistDetail(generic.DetailView):
    queryset = Artist.objects.all()

class AuthorDetail(generic.DetailView):
    queryset = Author.objects.all()

class PageDetail(generic.DetailView):
    queryset = Page.objects.all()
    template_name_field = 'template'

class DictList(generic.ListView):
    """A ListView that doesn't use a model."""
    queryset = [
        {'first': 'John', 'last': 'Lennon'},
        {'first': 'Yoko',  'last': 'Ono'}
    ]
    template_name = 'generic_views/list.html'

class ArtistList(generic.ListView):
    template_name = 'generic_views/list.html'
    queryset = Artist.objects.all()

class AuthorList(generic.ListView):
    queryset = Author.objects.all()

class CustomPaginator(Paginator):
    def __init__(self, queryset, page_size, orphans=0, allow_empty_first_page=True):
        super(CustomPaginator, self).__init__(
            queryset,
            page_size,
            orphans=2,
            allow_empty_first_page=allow_empty_first_page)

class AuthorListCustomPaginator(AuthorList):
    paginate_by = 5

    def get_paginator(self, queryset, page_size, orphans=0, allow_empty_first_page=True):
        return super(AuthorListCustomPaginator, self).get_paginator(
            queryset,
            page_size,
            orphans=2,
            allow_empty_first_page=allow_empty_first_page)

class ContactView(generic.FormView):
    form_class = ContactForm
    success_url = reverse_lazy('authors_list')
    template_name = 'generic_views/form.html'

class ArtistCreate(generic.CreateView):
    model = Artist
    fields = '__all__'

class NaiveAuthorCreate(generic.CreateView):
    queryset = Author.objects.all()
    fields = '__all__'

class TemplateResponseWithoutTemplate(generic.detail.SingleObjectTemplateResponseMixin, generic.View):
    # we don't define the usual template_name here

    def __init__(self):
        # Dummy object, but attr is required by get_template_name()
        self.object = None

class AuthorCreate(generic.CreateView):
    model = Author
    success_url = '/list/authors/'
    fields = '__all__'

class SpecializedAuthorCreate(generic.CreateView):
    model = Author
    form_class = AuthorForm
    template_name = 'generic_views/form.html'
    context_object_name = 'thingy'

    def get_success_url(self):
        return reverse('author_detail', args=[self.object.id,])

class AuthorCreateRestricted(AuthorCreate):
    post = method_decorator(login_required)(AuthorCreate.post)

class ArtistUpdate(generic.UpdateView):
    model = Artist
    fields = '__all__'

class NaiveAuthorUpdate(generic.UpdateView):
    queryset = Author.objects.all()
    fields = '__all__'

class AuthorUpdate(generic.UpdateView):
    model = Author
    success_url = '/list/authors/'
    fields = '__all__'

class OneAuthorUpdate(generic.UpdateView):
    success_url = '/list/authors/'
    fields = '__all__'

    def get_object(self):
        return Author.objects.get(pk=1)

class SpecializedAuthorUpdate(generic.UpdateView):
    model = Author
    form_class = AuthorForm
    template_name = 'generic_views/form.html'
    context_object_name = 'thingy'

    def get_success_url(self):
        return reverse('author_detail', args=[self.object.id,])

class NaiveAuthorDelete(generic.DeleteView):
    queryset = Author.objects.all()

class AuthorDelete(generic.DeleteView):
    model = Author
    success_url = '/list/authors/'

class SpecializedAuthorDelete(generic.DeleteView):
    queryset = Author.objects.all()
    template_name = 'generic_views/confirm_delete.html'
    context_object_name = 'thingy'

    def get_success_url(self):
        return reverse('authors_list')

class BookConfig(object):
    queryset = Book.objects.all()
    date_field = 'pubdate'

class BookArchive(BookConfig, generic.ArchiveIndexView):
    pass

class BookYearArchive(BookConfig, generic.YearArchiveView):
    pass

class BookMonthArchive(BookConfig, generic.MonthArchiveView):
    pass

class BookWeekArchive(BookConfig, generic.WeekArchiveView):
    pass

class BookDayArchive(BookConfig, generic.DayArchiveView):
    pass

class BookTodayArchive(BookConfig, generic.TodayArchiveView):
    pass

class BookDetail(BookConfig, generic.DateDetailView):
    pass

class AuthorGetQuerySetFormView(generic.edit.ModelFormMixin):
    fields = '__all__'

    def get_queryset(self):
        return Author.objects.all()

class BookDetailGetObjectCustomQueryset(BookDetail):
    def get_object(self, queryset=None):
        return super(BookDetailGetObjectCustomQueryset,self).get_object(
            queryset=Book.objects.filter(pk=2))

class CustomMultipleObjectMixinView(generic.list.MultipleObjectMixin, generic.View):
    queryset = [
        {'name': 'John'},
        {'name': 'Yoko'},
    ]

    def get(self, request):
        self.object_list = self.get_queryset()

class CustomContextView(generic.detail.SingleObjectMixin, generic.View):
    model = Book
    object = Book(name='dummy')

    def get_object(self):
        return Book(name="dummy")

    def get_context_data(self, **kwargs):
        context = {'custom_key': 'custom_value'}
        context.update(kwargs)
        return super(CustomContextView, self).get_context_data(**context)

    def get_context_object_name(self, obj):
        return "test_name"

class CustomSingleObjectView(generic.detail.SingleObjectMixin, generic.View):
    model = Book
    object = Book(name="dummy")

class BookSigningConfig(object):
    model = BookSigning
    date_field = 'event_date'
    # use the same templates as for books
    def get_template_names(self):
        return ['generic_views/book%s.html' % self.template_name_suffix]

class BookSigningArchive(BookSigningConfig, generic.ArchiveIndexView):
    pass

class BookSigningYearArchive(BookSigningConfig, generic.YearArchiveView):
    pass

class BookSigningMonthArchive(BookSigningConfig, generic.MonthArchiveView):
    pass

class BookSigningWeekArchive(BookSigningConfig, generic.WeekArchiveView):
    pass

class BookSigningDayArchive(BookSigningConfig, generic.DayArchiveView):
    pass

class BookSigningTodayArchive(BookSigningConfig, generic.TodayArchiveView):
    pass

class BookSigningDetail(BookSigningConfig, generic.DateDetailView):
    context_object_name = 'book'

class NonModel(object):
    id = "non_model_1"

    _meta = None

class NonModelDetail(generic.DetailView):

    template_name = 'generic_views/detail.html'
    model = NonModel

    def get_object(self, queryset=None):
        return NonModel()


text:
<?php
use Concrete\Core\Device\Device;

?>

        <?= t('Devices') ?>

        <?php
        $preview_url = \URL::to('/ccm/system/panels/page/devices/preview');
        $preview_url = $preview_url->setQuery(array('cID' => \Page::getCurrentPage()->getCollectionID()));

        $manager = \Core::make('device/manager');

        $organized = array();

        $devices = $manager->getList();

        foreach ($devices as $device) {
            $type = $device->getType();

            if ($type == Device::UNKNOWN) {
                $organized[Device::UNKNOWN][] = $device;
            } elseif ($type & Device::MOBILE) {
                $organized[Device::MOBILE][] = $device;
            } elseif ($type & Device::TABLET) {
                $organized[Device::TABLET][] = $device;
            } elseif ($type & Device::DESKTOP) {
                $organized[Device::DESKTOP][] = $device;
            }
        }

        $categories = array(
            Device::UNKNOWN => t('General'),
            Device::MOBILE => t('Phone'),
            Device::TABLET => t('Tablet'),
            Device::DESKTOP => t('Desktop'), );

        /**
         * @var int
         * @var Device[] $device_list
         */
        foreach ($organized as $type => $device_list) {
            ?>

<?= $categories[$type] ?>

                    <?php
                    $page = \Page::getCurrentPage();
            foreach ($device_list as $device) {
                $device_preview_url = $preview_url->setQuery(array(
                            'cID' => $page->getCollectionID(),
                            'cvID' => $page->getVersionID(),
                            'device' => $device->getHandle(), ));
                ?>
                        <li class="ccm-panel-devicelist-device"
                            data-device-brand="<?= h($device->getBrand()) ?>"
                            data-device-name="<?= h($device->getName()) ?>"
                            data-device-handle="<?= h($device->getHandle()) ?>"
                            data-device-width="<?= h($device->getWidth()) ?>"
                            data-device-height="<?= h($device->getHeight()) ?>"
                            data-device-agent="<?= h($device->getUserAgent()) ?>"
                            data-device-ratio="<?= h($device->getPixelRatio()) ?>"
                            data-device-type="<?= $type ?>"
                            data-device-preview-url="<?= $device_preview_url ?>"
                            data-device-orientation="<?= h($device->getDefaultOrientation()) ?>">

                                        <i class="<?= $device->getIconClass() ?>">

                                        <?= h($device->getName()) ?>

                                    <?php
                                    $deviceWidth = h($device->getWidth());
                $deviceHeight = h($device->getHeight());
                $pixelRatio = h($device->getPixelRatio());
                $displayedWidth = floor($device->getWidth() / $device->getPixelRatio());
                $displayedHeight = floor($device->getHeight() / $device->getPixelRatio());

                echo "$deviceWidth x  $deviceHeight @{$pixelRatio}x ($displayedWidth x $displayedHeight)";
                ?>

                    <?php

            }
            ?>

        <?php

        }
        ?>


text:
package breeze.signal

import breeze.generic.UFunc
import breeze.linalg._
import breeze.numerics._
import breeze.macros.expand
import breeze.math.Complex
import breeze.stats.mean

/**Root mean square of a vector.
 * @author ktakagaki
 * @date 2/17/14.
 */
object rootMeanSquare extends UFunc {

  //ToDo: Expand to Int and Long once mean() is generified

  @expand
  @expand.valify
  implicit def rms1D[@expand.args(Float, Double) T] : rootMeanSquare.Impl[DenseVector[T], T] = {
    new rootMeanSquare.Impl[DenseVector[T], T] {
      def apply(v: DenseVector[T]): T = {
        val temp: T = mean( v.map( (elem: T) => elem * elem )  )
        sqrt( temp )
      }
    }
  }

  //temporary placeholder implementation until mean is fully generified
  implicit def rms1DInt : rootMeanSquare.Impl[DenseVector[Int], Double] = {
    new rootMeanSquare.Impl[DenseVector[Int], Double] {
      def apply(v: DenseVector[Int]): Double = sqrt(sum( convert(v, Double).map( elem => elem * elem ) ) / v.length.toDouble)
    }
  }
  implicit def rms1DLong : rootMeanSquare.Impl[DenseVector[Long], Double] = {
    new rootMeanSquare.Impl[DenseVector[Long], Double] {
      def apply(v: DenseVector[Long]): Double = sqrt(sum( convert(v, Double).map( elem => elem * elem ) ) / v.length.toDouble)
    }
  }

}


text:
package mx.com.adolfogarcia.popularmovies.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

import org.parceler.Parcels;

import de.greenrobot.event.EventBus;
import mx.com.adolfogarcia.popularmovies.R;
import mx.com.adolfogarcia.popularmovies.model.event.MovieSelectionEvent;
import mx.com.adolfogarcia.popularmovies.view.fragment.MovieDetailFragment;

/**
 * Presents a collection of movies to select from and shows the details of the
 * selected movie.
 *
 * @author Jesús Adolfo García Pasquel
 */
public class MainActivity extends AppCompatActivity {

    /**
     * Identifies the messages written to the log by this class.
     */
    private static final String LOG_TAG = MainActivity.class.getSimpleName();

    /**
     * Identifies the {@code Fragment} used to present the details of a movie.
     */
    private static final String MOVIE_DETAIL_FRAGMENT_TAG =
            MovieDetailFragment.class.getCanonicalName();

    /**
     * Indicates if the activity contains two panes (master-detail) or just
     * one.
     */
    private boolean mTwoPane;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (findViewById(R.id.movie_detail_container) != null) {
            mTwoPane = true;
            if (savedInstanceState == null) {
                // TODO: Put a placeholder fragment in the detail area.
            }
        } else {
            mTwoPane = false;
        }
    }

    @Override
    protected void onResume() {
        EventBus.getDefault().register(this);
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    /**
     * Displays the detail view of the selected movie.
     *
     * @param event the movie selection event.
     */
    public void onEvent(MovieSelectionEvent event) {
        if (mTwoPane) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            MovieDetailFragment movieDetailFragment =
                    MovieDetailFragment.newInstance(event.getSelectedMovie());
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.movie_detail_container, movieDetailFragment);
            transaction.commit();
        } else {
            Intent intent = new Intent(this, MovieDetailActivity.class);
            intent.putExtra(MovieDetailActivity.EXTRA_MOVIE
                    , Parcels.wrap(event.getSelectedMovie()));
            startActivity(intent);
        }
    }
}


text:
Let's Go play some TicTacToe!

 You are {{ player }}

 Turn: {{ turn }}

        <board></board>

= 0" class="uk-text-muted">Currently online: {{ xPlayers }} X vs {{ oPlayers }} O

        <p ng-if="xPlayers + oPlayers < 0"> Waiting for number of players...

Log

{{ m.datetime | date:'yyyy-MM-dd HH:mm:ss' }} {{ m.msg }}