text:
#include "expression_editor/Operator.h"
#include "InteractionBaseException.h"

#include "expression_editor/OperatorDescriptor.h"
#include "expression_editor/ExpressionVisitor.h"

namespace Interaction {

Operator::Operator(OperatorDescriptor* descriptor, Operator* parent)
	: Expression(type(), parent), descriptor_(descriptor), do_not_delete_transient_descriptor_(false)
{
}

void Operator::accept(ExpressionVisitor* visitor)
{
	visitor->visit(this);
}

Operator::~Operator()
{
	clear();
	if (descriptor()->isTransient() && !do_not_delete_transient_descriptor_) delete descriptor();
}

Expression* Operator::possiblyRemove(Expression* e, bool remove)
{
	if (remove && e)
	{
		operands_.removeAll(e);
		e->setParent(nullptr);
	}

	return e;
}

Expression* Operator::first(bool remove_from_list)
{
	Expression* tmp = operands_.isEmpty()?nullptr:operands_.first();
	return possiblyRemove(tmp, remove_from_list);
}

Expression* Operator::last(bool remove_from_list)
{
	Expression* tmp = operands_.isEmpty()?nullptr:operands_.last();
	return possiblyRemove(tmp, remove_from_list);
}

Expression* Operator::at(int i, bool remove_from_list)
{
	Expression* tmp = operands_.size() <= i ?nullptr:operands_.at(i);
	return possiblyRemove(tmp, remove_from_list);
}

void Operator::clear()
{
	for (int i = 0; i<operands_.size(); ++i)
		delete operands_.at(i);
	operands_.clear();
}

void Operator::remove(Expression* e)
{
	operands_.removeAll(e);
	if (e) e->setParent(nullptr);
}

void Operator::insert(Expression* e, int pos)
{
	if (e)
	{
		e->setParent(this);
		operands_.insert(pos, e);
	}
}

Expression* Operator::replaceOperand(Expression* oldExpr, Expression* newExpr)
{
	int i = operands_.indexOf(oldExpr);
	if (i <0) throw InteractionBaseException("Invalid replacement operation. Could not find expression to replace.");

	newExpr->setParent(this);
	operands_.replace(i, newExpr);
	return oldExpr;
}

QString Operator::renderText()
{
	QStringList children;
	children.append(descriptor_->prefix().join(""));
	children.append(operands_.first()->renderText());

	for (int i=0; i < descriptor_->infixes().size(); ++i)
	{
		children.append(descriptor_->infix(i).join(""));
		children.append(operands_.at(i+1)->renderText());
	}

	children.append(descriptor_->postfix().join(""));
	return children.join("");
}

ExpressionContext Operator::findContext(int cursor_pos)
{
	// Find which child contains the cursor

	// If the cursor is at the beginning
	if (cursor_pos == 0)
	{
		if (descriptor_->prefix().isEmpty()) return first()->findContext(0);
		else
		{
			ExpressionContext c;
			c.setRight(this);
			c.setRightDelim(0);
			c.setRightText(descriptor_->prefix().join(""));
			c.setRightType(ExpressionContext::Expr);
			return c;
		}
	}

	QStringList delims = descriptor_->delimiters();

	// If the cursor is at the end
	if (cursor_pos == length())
	{
		if (descriptor_->postfix().isEmpty()) return last()->findContext(last()->length());
		else
		{
			ExpressionContext c;
			c.setLeft(this);
			c.setLeftDelim(delims.size()-1);
			c.setLeftText(descriptor_->postfix().join(""));
			c.setLeftType(ExpressionContext::Expr);
			return c;
		}
	}

	// The cursor must be somewhere in the middle
	int length_so_far = 0;
	for (int d = 0; d < delims.size(); ++d)
	{
		QString current_d = delims.at(d);
		length_so_far += current_d.size();

		// Inside a delimiter
		if (cursor_pos < length_so_far)
		{
			ExpressionContext c;
			c.setLeft(this);
			c.setRight(this);
			c.setLeftDelim(d);
			c.setRightDelim(d);
			c.setLeftType(ExpressionContext::InOpDelim);
			c.setRightType(ExpressionContext::InOpDelim);

			int cursor_inside = cursor_pos - (length_so_far - current_d.size());
			c.setLeftText(current_d.left(cursor_inside));
			c.setRightText(current_d.mid(cursor_inside));
			return c;
		}

		// Just after a delimiter. Note: this can not be the last delimiter, this is handled above.
		if (cursor_pos == length_so_far)
		{
			ExpressionContext c = operands_.at(d)->findContext(0);
			c.setLeft(this);
			c.setLeftDelim(d);
			c.setLeftText(delims.at(d));

			// If d is the last 'visible' delimiter this is an OP, otherwise it is a boundary
			c.setLeftType( (d == delims.size()-2) && delims.last().isEmpty() ? ExpressionContext::OpDelim
																								  : ExpressionContext::OpBoundary);
			return c;
		}

		// Inside a child operand
		int child_length = operands_.at(d)->length();
		length_so_far += child_length;
		if (cursor_pos < length_so_far)
		{
			int cursor_inside = cursor_pos - (length_so_far - child_length);
			return operands_.at(d)->findContext(cursor_inside);
		}

		// Just after a child operand
		if (cursor_pos == length_so_far)
		{
			ExpressionContext c = operands_.at(d)->findContext(child_length);
			c.setRight(this);
			c.setRightDelim(d+1);
			c.setRightText(delims.at(d+1));

			// If (d+1) is the first 'visible' delimiter this is an OP, otherwise it is a boundary
			c.setRightType( (d == 0) && delims.first().isEmpty() ? ExpressionContext::OpDelim : ExpressionContext::OpBoundary);
			return c;
		}
	}

	// This end should not be reached
	throw InteractionBaseException("No context found");
}

Expression* Operator::smallestRightmostSubExpr()
{
	if (descriptor_->postfix().isEmpty()) return last()->smallestRightmostSubExpr();
	else return this;
}

Expression* Operator::smallestLeftmostSubExpr()
{
	if (descriptor_->prefix().isEmpty()) return first()->smallestLeftmostSubExpr();
	else return this;
}

void Operator::globalExpressionBoundaries(Expression* e, int& begin, int& end)
{
	if (parent()) parent()->globalExpressionBoundaries(this, begin, end);
	else begin = 0;

	QStringList delims = descriptor_->delimiters();
	for (int i = 0; i<size(); ++i)
	{
		begin += delims.at(i).size();
		end = begin + operands_.at(i)->length();
		if (operands_.at(i) == e)
			return;
		begin = end;
	}
}

void Operator::globalDelimiterBoundaries(int delim, int& begin, int& end)
{
	if (parent()) parent()->globalExpressionBoundaries(this, begin, end);
	else begin = 0;

	end = begin + descriptor_->prefix().join("").size();

	QStringList delims = descriptor_->delimiters();
	for (int i = 1; i<=delim; ++i)
	{
		begin = end + operands_.at(i-1)->length();
		end = begin + delims.at(i).size();
	}
}

Expression* Operator::findCutExpression(bool leftside, QString cut_string)
{
	Expression* result = nullptr;

	// If there is no delimiter, try to cut the subexpression closer to the cutting side
	if ( leftside ? descriptor_->prefix().isEmpty() : descriptor_->postfix().isEmpty() )
		result = leftside ? first()->findCutExpression(leftside, cut_string)
								: last()->findCutExpression(leftside, cut_string);

	if (result == nullptr)
	{
		// Try to cut this operator directly.
		if (leftside)
			result = descriptor_->postfix().isEmpty() || descriptor_->postfix().join("") == cut_string ? last() : nullptr;
		else
			result = descriptor_->prefix().isEmpty() || descriptor_->prefix().join("") == cut_string  ? first() : nullptr;
	}

	return result;
}

} /* namespace InteractionBase */


text:
extern "C"
{
	void Java_com_chilliworks_chillisource_web_WebViewNativeInterface_OnWebviewDismissed(JNIEnv* inpEnv, jobject thiz, u32 inudwIndex);
}
//--------------------------------------------------------------------------------------
/// On Update Text
///
/// Interface function called from java. This is called when the keyboard text has been
/// updated.
///
/// @param The jni environment.
/// @param the java object calling the function
/// @param the updated keyboard text
/// @return whether or not the text was accepted.
//--------------------------------------------------------------------------------------
void Java_com_chilliworks_chillisource_web_WebViewNativeInterface_OnWebviewDismissed(JNIEnv* inpEnv, jobject thiz, u32 inudwIndex)
{
	CSBackend::Android::WebView::OnWebViewDismissed(inudwIndex);
}

namespace CSBackend
{
	namespace Android
	{
		void WebViewJavaInterface::SetupJavaInterface(JavaVM* inpJavaVM)
		{
			mspJavaVM = inpJavaVM;

			InitCallableStaticMethod("com/chilliworks/chillisource/web/WebViewNativeInterface","Present", "(ILjava/lang/String;IIF)V");
			InitCallableStaticMethod("com/chilliworks/chillisource/web/WebViewNativeInterface","PresentFromFile", "(ILjava/lang/String;IILjava/lang/String;Ljava/lang/String;F)V");
			InitCallableStaticMethod("com/chilliworks/chillisource/web/WebViewNativeInterface","PresentInExternalBrowser", "(Ljava/lang/String;)V");
			InitCallableStaticMethod("com/chilliworks/chillisource/web/WebViewNativeInterface","Dismiss", "(I)V");
		}
		void WebViewJavaInterface::Present(u32 inudwIndex, const std::string& instrURL, const CSCore::Vector2& invSize, f32 in_dismissButtonRelativeSize)
		{
			MethodReference sdMethodRef = GetStaticMethodReference("Present");

			if (sdMethodRef.mMethodID != 0 && sdMethodRef.mClassID != 0)
			{
				JNIEnv* env = GetJNIEnvironmentPtr();
				jstring jstrURL = CreateJStringFromSTDString(instrURL);
				u32 udwIndex = inudwIndex;
				u32 udwWidth = invSize.x;
				u32 udwHeight = invSize.y;
				env->CallStaticVoidMethod(sdMethodRef.mClassID, sdMethodRef.mMethodID,udwIndex,jstrURL,udwWidth,udwHeight, in_dismissButtonRelativeSize);

				//delete local reference
				env->DeleteLocalRef(jstrURL);
			}
		}
		void WebViewJavaInterface::PresentFromFile(u32 inudwIndex, const std::string& instrHTMLContent, const CSCore::Vector2& invSize, const std::string& instrBasePath, const std::string& instrAnchor, f32 in_dismissButtonRelativeSize)
		{
			MethodReference sdMethodRef = GetStaticMethodReference("PresentFromFile");

			if (sdMethodRef.mMethodID != 0 && sdMethodRef.mClassID != 0)
			{
				JNIEnv* env = GetJNIEnvironmentPtr();
				jstring jstrContent = CreateJStringFromSTDString(instrHTMLContent);
				jstring jstrBasePath = CreateJStringFromSTDString(instrBasePath);
				jstring jstrAnchor = CreateJStringFromSTDString(instrAnchor);
				u32 udwIndex = inudwIndex;
				u32 udwWidth = invSize.x;
				u32 udwHeight = invSize.y;
				env->CallStaticVoidMethod(sdMethodRef.mClassID, sdMethodRef.mMethodID, udwIndex, jstrContent, udwWidth, udwHeight, jstrBasePath, jstrAnchor, in_dismissButtonRelativeSize);

				//delete local reference
				env->DeleteLocalRef(jstrContent);
				env->DeleteLocalRef(jstrBasePath);
				env->DeleteLocalRef(jstrAnchor);
			}
		}
		void WebViewJavaInterface::PresentInExternalBrowser(const std::string& instrURL)
		{
			MethodReference sdMethodRef = GetStaticMethodReference("PresentInExternalBrowser");

			if (sdMethodRef.mMethodID != 0 && sdMethodRef.mClassID != 0)
			{
				JNIEnv* env = GetJNIEnvironmentPtr();
				jstring jstrContent = CreateJStringFromSTDString(instrURL);
				env->CallStaticVoidMethod(sdMethodRef.mClassID, sdMethodRef.mMethodID,jstrContent);

				//delete local reference
				env->DeleteLocalRef(jstrContent);
			}
		}
		void WebViewJavaInterface::Dismiss(u32 inudwIndex)
		{
			MethodReference sdMethodRef = GetStaticMethodReference("Dismiss");

			if (sdMethodRef.mMethodID != 0 && sdMethodRef.mClassID != 0)
			{
				JNIEnv* env = GetJNIEnvironmentPtr();
				u32 udwIndex = inudwIndex;
				env->CallStaticVoidMethod(sdMethodRef.mClassID, sdMethodRef.mMethodID, udwIndex);
			}
		}
	}
}

#endif

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import migrations, models
import model_utils.fields
import autoslug.fields
import django.utils.timezone
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Reservation',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('start', models.DateTimeField(null=True, blank=True, verbose_name='start')),
                ('end', models.DateTimeField(null=True, blank=True, verbose_name='end')),
                ('title', models.TextField()),
                ('is_public', models.BooleanField(default=False)),
                ('reserver', models.ForeignKey(related_name='reservations', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Room',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
                ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
                ('slug', autoslug.fields.AutoSlugField(populate_from='name', editable=False)),
                ('name', models.CharField(max_length=50, unique=True)),
                ('description', models.TextField(blank=True)),
                ('creator', models.ForeignKey(related_name='created_rooms', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.AddField(
            model_name='reservation',
            name='room',
            field=models.ForeignKey(to='arrr.Room'),
        ),
    ]


text:
package prj;

import org.capcaval.lafabrique.project.ProjectInfo;

public class Default extends ProjectInfo{
	public Default(){
		this.name = "laFabrique";
		this.author = "CapCaval.org";
		this.version = "0.0.4";
	}
}


text:
        <button data-field="newRepo" type="button" class="btn btn-success pull-right">
            New Repository
        </button>


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

#include "chrome/browser/ui/webui/signin/user_manager_screen_handler.h"

#include <stddef.h>
#include <utility>
#include <vector>

#include "base/bind.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/profiler/scoped_tracker.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/value_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/api/screenlock_private/screenlock_private_api.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/profiles/profile_avatar_icon_util.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profile_metrics.h"
#include "chrome/browser/profiles/profile_statistics.h"
#include "chrome/browser/profiles/profile_statistics_factory.h"
#include "chrome/browser/profiles/profile_window.h"
#include "chrome/browser/profiles/profiles_state.h"
#include "chrome/browser/signin/local_auth.h"
#include "chrome/browser/ui/app_list/app_list_service.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/singleton_tabs.h"
#include "chrome/browser/ui/user_manager.h"
#include "chrome/browser/ui/webui/profile_helper.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "components/prefs/pref_service.h"
#include "components/proximity_auth/screenlock_bridge.h"
#include "components/signin/core/account_id/account_id.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "google_apis/gaia/gaia_auth_fetcher.h"
#include "google_apis/gaia/gaia_constants.h"
#include "grit/components_strings.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_util.h"

#if defined(USE_ASH)
#include "ash/shell.h"
#endif

namespace {
// User dictionary keys.
const char kKeyUsername[] = "username";
const char kKeyDisplayName[]= "displayName";
const char kKeyEmailAddress[] = "emailAddress";
const char kKeyProfilePath[] = "profilePath";
const char kKeyPublicAccount[] = "publicAccount";
const char kKeyLegacySupervisedUser[] = "legacySupervisedUser";
const char kKeyChildUser[] = "childUser";
const char kKeyCanRemove[] = "canRemove";
const char kKeyIsOwner[] = "isOwner";
const char kKeyIsDesktop[] = "isDesktopUser";
const char kKeyAvatarUrl[] = "userImage";
const char kKeyNeedsSignin[] = "needsSignin";
const char kKeyHasLocalCreds[] = "hasLocalCreds";
const char kKeyStatistics[] = "statistics";
const char kKeyIsProfileLoaded[] = "isProfileLoaded";

// JS API callback names.
const char kJsApiUserManagerInitialize[] = "userManagerInitialize";
const char kJsApiUserManagerAddUser[] = "addUser";
const char kJsApiUserManagerAuthLaunchUser[] = "authenticatedLaunchUser";
const char kJsApiUserManagerLaunchGuest[] = "launchGuest";
const char kJsApiUserManagerLaunchUser[] = "launchUser";
const char kJsApiUserManagerRemoveUser[] = "removeUser";
const char kJsApiUserManagerAttemptUnlock[] = "attemptUnlock";
const char kJsApiUserManagerLogRemoveUserWarningShown[] =
    "logRemoveUserWarningShown";
const char kJsApiUserManagerRemoveUserWarningLoadStats[] =
    "removeUserWarningLoadStats";
const char kJsApiUserManagerGetRemoveWarningDialogMessage[] =
    "getRemoveWarningDialogMessage";
const size_t kAvatarIconSize = 180;
const int kMaxOAuthRetries = 3;

void HandleAndDoNothing(const base::ListValue* args) {
}

std::string GetAvatarImage(const ProfileAttributesEntry* entry) {
  bool is_gaia_picture = entry->IsUsingGAIAPicture() &&
                         entry->GetGAIAPicture() != nullptr;

  // If the avatar is too small (i.e. the old-style low resolution avatar),
  // it will be pixelated when displayed in the User Manager, so we should
  // return the placeholder avatar instead.
  gfx::Image avatar_image = entry->GetAvatarIcon();
  if (avatar_image.Width() <= profiles::kAvatarIconWidth ||
      avatar_image.Height() <= profiles::kAvatarIconHeight ) {
    avatar_image = ui::ResourceBundle::GetSharedInstance().GetImageNamed(
        profiles::GetPlaceholderAvatarIconResourceID());
  }
  gfx::Image resized_image = profiles::GetSizedAvatarIcon(
      avatar_image, is_gaia_picture, kAvatarIconSize, kAvatarIconSize);
  return webui::GetBitmapDataUrl(resized_image.AsBitmap());
}

extensions::ScreenlockPrivateEventRouter* GetScreenlockRouter(
    const std::string& email) {
  base::FilePath path =
      profiles::GetPathOfProfileWithEmail(g_browser_process->profile_manager(),
                                          email);
  Profile* profile = g_browser_process->profile_manager()
      ->GetProfileByPath(path);
  return extensions::ScreenlockPrivateEventRouter::GetFactoryInstance()->Get(
      profile);
}

bool IsGuestModeEnabled() {
  PrefService* service = g_browser_process->local_state();
  DCHECK(service);
  return service->GetBoolean(prefs::kBrowserGuestModeEnabled);
}

bool IsAddPersonEnabled() {
  PrefService* service = g_browser_process->local_state();
  DCHECK(service);
  return service->GetBoolean(prefs::kBrowserAddPersonEnabled);
}

// Executes the action specified by the URL's Hash parameter, if any. Deletes
// itself after the action would be performed.
class UrlHashHelper : public chrome::BrowserListObserver {
 public:
  UrlHashHelper(Browser* browser, const std::string& hash);
  ~UrlHashHelper() override;

  void ExecuteUrlHash();

  // chrome::BrowserListObserver overrides:
  void OnBrowserRemoved(Browser* browser) override;

 private:
  Browser* browser_;
  Profile* profile_;
  std::string hash_;

  DISALLOW_COPY_AND_ASSIGN(UrlHashHelper);
};

UrlHashHelper::UrlHashHelper(Browser* browser, const std::string& hash)
    : browser_(browser),
      profile_(browser->profile()),
      hash_(hash) {
  BrowserList::AddObserver(this);
}

UrlHashHelper::~UrlHashHelper() {
  BrowserList::RemoveObserver(this);
}

void UrlHashHelper::OnBrowserRemoved(Browser* browser) {
  if (browser == browser_)
    browser_ = nullptr;
}

void UrlHashHelper::ExecuteUrlHash() {
  if (hash_ == profiles::kUserManagerSelectProfileAppLauncher) {
    AppListService* app_list_service = AppListService::Get();
    app_list_service->ShowForProfile(profile_);
    return;
  }

  Browser* target_browser = browser_;
  if (!target_browser) {
    target_browser = chrome::FindLastActiveWithProfile(profile_);
    if (!target_browser)
      return;
  }

  if (hash_ == profiles::kUserManagerSelectProfileTaskManager)
    chrome::OpenTaskManager(target_browser);
  else if (hash_ == profiles::kUserManagerSelectProfileAboutChrome)
    chrome::ShowAboutChrome(target_browser);
  else if (hash_ == profiles::kUserManagerSelectProfileChromeSettings)
    chrome::ShowSettings(target_browser);
}

void HandleLogRemoveUserWarningShown(const base::ListValue* args) {
  ProfileMetrics::LogProfileDeleteUser(
      ProfileMetrics::DELETE_PROFILE_USER_MANAGER_SHOW_WARNING);
}

}  // namespace

// ProfileUpdateObserver ------------------------------------------------------

class UserManagerScreenHandler::ProfileUpdateObserver
    : public ProfileAttributesStorage::Observer {
 public:
  ProfileUpdateObserver(
      ProfileManager* profile_manager, UserManagerScreenHandler* handler)
      : profile_manager_(profile_manager),
        user_manager_handler_(handler) {
    DCHECK(profile_manager_);
    DCHECK(user_manager_handler_);
    profile_manager_->GetProfileAttributesStorage().AddObserver(this);
  }

  ~ProfileUpdateObserver() override {
    DCHECK(profile_manager_);
    profile_manager_->GetProfileAttributesStorage().RemoveObserver(this);
  }

 private:
  // ProfileAttributesStorage::Observer implementation:
  // If any change has been made to a profile, propagate it to all the
  // visible user manager screens.
  void OnProfileAdded(const base::FilePath& profile_path) override {
    user_manager_handler_->SendUserList();
  }

  void OnProfileWasRemoved(const base::FilePath& profile_path,
                           const base::string16& profile_name) override {
    // TODO(noms): Change 'SendUserList' to 'removeUser' JS-call when
    // UserManager is able to find pod belonging to removed user.
    user_manager_handler_->SendUserList();
  }

  void OnProfileNameChanged(const base::FilePath& profile_path,
                            const base::string16& old_profile_name) override {
    user_manager_handler_->SendUserList();
  }

  void OnProfileAvatarChanged(const base::FilePath& profile_path) override {
    user_manager_handler_->SendUserList();
  }

  void OnProfileHighResAvatarLoaded(
      const base::FilePath& profile_path) override {
    // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/461175
    // is fixed.
    tracked_objects::ScopedTracker tracking_profile(
        FROM_HERE_WITH_EXPLICIT_FUNCTION(
            "461175 UserManagerScreenHandler::OnProfileHighResAvatarLoaded"));
    user_manager_handler_->SendUserList();
  }

  void OnProfileSigninRequiredChanged(
      const base::FilePath& profile_path) override {
    user_manager_handler_->SendUserList();
  }

  void OnProfileIsOmittedChanged(
      const base::FilePath& profile_path) override {
    user_manager_handler_->SendUserList();
  }

  ProfileManager* profile_manager_;

  UserManagerScreenHandler* user_manager_handler_;  // Weak; owns us.

  DISALLOW_COPY_AND_ASSIGN(ProfileUpdateObserver);
};

// UserManagerScreenHandler ---------------------------------------------------

UserManagerScreenHandler::UserManagerScreenHandler() : weak_ptr_factory_(this) {
  profile_attributes_storage_observer_.reset(
      new UserManagerScreenHandler::ProfileUpdateObserver(
          g_browser_process->profile_manager(), this));
}

UserManagerScreenHandler::~UserManagerScreenHandler() {
  proximity_auth::ScreenlockBridge::Get()->SetLockHandler(NULL);
}

void UserManagerScreenHandler::ShowBannerMessage(
    const base::string16& message) {
  web_ui()->CallJavascriptFunction(
      "login.AccountPickerScreen.showBannerMessage",
      base::StringValue(message));
}

void UserManagerScreenHandler::ShowUserPodCustomIcon(
    const AccountId& account_id,
    const proximity_auth::ScreenlockBridge::UserPodCustomIconOptions&
        icon_options) {
  std::unique_ptr<base::DictionaryValue> icon =
      icon_options.ToDictionaryValue();
  if (!icon || icon->empty())
    return;
  web_ui()->CallJavascriptFunction(
      "login.AccountPickerScreen.showUserPodCustomIcon",
      base::StringValue(account_id.GetUserEmail()), *icon);
}

void UserManagerScreenHandler::HideUserPodCustomIcon(
    const AccountId& account_id) {
  web_ui()->CallJavascriptFunction(
      "login.AccountPickerScreen.hideUserPodCustomIcon",
      base::StringValue(account_id.GetUserEmail()));
}

void UserManagerScreenHandler::EnableInput() {
  // Nothing here because UI is not disabled when starting to authenticate.
}

void UserManagerScreenHandler::SetAuthType(
    const AccountId& account_id,
    proximity_auth::ScreenlockBridge::LockHandler::AuthType auth_type,
    const base::string16& auth_value) {
  if (GetAuthType(account_id) ==
      proximity_auth::ScreenlockBridge::LockHandler::FORCE_OFFLINE_PASSWORD)
    return;

  user_auth_type_map_[account_id.GetUserEmail()] = auth_type;
  web_ui()->CallJavascriptFunction("login.AccountPickerScreen.setAuthType",
                                   base::StringValue(account_id.GetUserEmail()),
                                   base::FundamentalValue(auth_type),
                                   base::StringValue(auth_value));
}

proximity_auth::ScreenlockBridge::LockHandler::AuthType
UserManagerScreenHandler::GetAuthType(const AccountId& account_id) const {
  const auto it = user_auth_type_map_.find(account_id.GetUserEmail());
  if (it == user_auth_type_map_.end())
    return proximity_auth::ScreenlockBridge::LockHandler::OFFLINE_PASSWORD;
  return it->second;
}

proximity_auth::ScreenlockBridge::LockHandler::ScreenType
UserManagerScreenHandler::GetScreenType() const {
  return proximity_auth::ScreenlockBridge::LockHandler::LOCK_SCREEN;
}

void UserManagerScreenHandler::Unlock(const AccountId& account_id) {
  const base::FilePath path = profiles::GetPathOfProfileWithEmail(
      g_browser_process->profile_manager(), account_id.GetUserEmail());
  if (!path.empty()) {
    authenticating_profile_path_ = path;
    ReportAuthenticationResult(true, ProfileMetrics::AUTH_LOCAL);
  }
}

void UserManagerScreenHandler::AttemptEasySignin(const AccountId& account_id,
                                                 const std::string& secret,
                                                 const std::string& key_label) {
  NOTREACHED();
}

void UserManagerScreenHandler::HandleInitialize(const base::ListValue* args) {
  // If the URL has a hash parameter, store it for later.
  args->GetString(0, &url_hash_);

  SendUserList();
  web_ui()->CallJavascriptFunction("cr.ui.UserManager.showUserManagerScreen",
      base::FundamentalValue(IsGuestModeEnabled()),
      base::FundamentalValue(IsAddPersonEnabled()));

  proximity_auth::ScreenlockBridge::Get()->SetLockHandler(this);
}

void UserManagerScreenHandler::HandleAddUser(const base::ListValue* args) {
  if (!IsAddPersonEnabled()) {
    // The 'Add User' UI should not be showing.
    NOTREACHED();
    return;
  }
  profiles::CreateAndSwitchToNewProfile(
      base::Bind(&UserManagerScreenHandler::OnSwitchToProfileComplete,
                 weak_ptr_factory_.GetWeakPtr()),
      ProfileMetrics::ADD_NEW_USER_MANAGER);
}

void UserManagerScreenHandler::HandleAuthenticatedLaunchUser(
    const base::ListValue* args) {
  const base::Value* profile_path_value;
  if (!args->Get(0, &profile_path_value))
    return;

  base::FilePath profile_path;
  if (!base::GetValueAsFilePath(*profile_path_value, &profile_path))
    return;

  ProfileAttributesEntry* entry;
  if (!g_browser_process->profile_manager()->GetProfileAttributesStorage().
          GetProfileAttributesWithPath(profile_path, &entry)) {
    return;
  }

  base::string16 email_address;
  if (!args->GetString(1, &email_address))
    return;

  std::string password;
  if (!args->GetString(2, &password))
    return;

  authenticating_profile_path_ = profile_path;
  email_address_ = base::UTF16ToUTF8(email_address);

  // Only try to validate locally or check the password change detection
  // if we actually have a local credential saved.
  if (!entry->GetLocalAuthCredentials().empty()) {
    if (LocalAuth::ValidateLocalAuthCredentials(entry, password)) {
      ReportAuthenticationResult(true, ProfileMetrics::AUTH_LOCAL);
      return;
    }

    // This could be a mis-typed password or typing a new password while we
    // still have a hash of the old one.  The new way of checking a password
    // change makes use of a token so we do that... if it's available.
    if (!oauth_client_) {
      oauth_client_.reset(new gaia::GaiaOAuthClient(
          content::BrowserContext::GetDefaultStoragePartition(
              web_ui()->GetWebContents()->GetBrowserContext())->
                  GetURLRequestContext()));
    }

    const std::string token = entry->GetPasswordChangeDetectionToken();
    if (!token.empty()) {
      oauth_client_->GetTokenHandleInfo(token, kMaxOAuthRetries, this);
      return;
    }
  }

  // In order to support the upgrade case where we have a local hash but no
  // password token, the user perform a full online reauth.
  UserManager::ShowReauthDialog(web_ui()->GetWebContents()->GetBrowserContext(),
                                email_address_);
}

void UserManagerScreenHandler::HandleRemoveUser(const base::ListValue* args) {
  DCHECK(args);
  const base::Value* profile_path_value;
  if (!args->Get(0, &profile_path_value)) {
    NOTREACHED();
    return;
  }

  base::FilePath profile_path;
  if (!base::GetValueAsFilePath(*profile_path_value, &profile_path)) {
    NOTREACHED();
    return;
  }

  DCHECK(profiles::IsMultipleProfilesEnabled());

  // The callback is run if the only profile has been deleted, and a new
  // profile has been created to replace it.
  webui::DeleteProfileAtPath(profile_path,
                             web_ui(),
                             ProfileMetrics::DELETE_PROFILE_USER_MANAGER);
}

void UserManagerScreenHandler::HandleLaunchGuest(const base::ListValue* args) {
  if (IsGuestModeEnabled()) {
    profiles::SwitchToGuestProfile(
        base::Bind(&UserManagerScreenHandler::OnSwitchToProfileComplete,
                   weak_ptr_factory_.GetWeakPtr()));
  } else {
    // The UI should have prevented the user from allowing the selection of
    // guest mode.
    NOTREACHED();
  }
}

void UserManagerScreenHandler::HandleLaunchUser(const base::ListValue* args) {
  const base::Value* profile_path_value = NULL;
  if (!args->Get(0, &profile_path_value))
    return;

  base::FilePath profile_path;
  if (!base::GetValueAsFilePath(*profile_path_value, &profile_path))
    return;

  ProfileAttributesEntry* entry;
  if (!g_browser_process->profile_manager()->GetProfileAttributesStorage().
          GetProfileAttributesWithPath(profile_path, &entry)) {
    NOTREACHED();
    return;
  }

  // It's possible that a user breaks into the user-manager page using the
  // JavaScript Inspector and causes a "locked" profile to call this
  // unauthenticated version of "launch" instead of the proper one.  Thus,
  // we have to validate in (secure) C++ code that it really is a profile
  // not needing authentication.  If it is, just ignore the "launch" request.
  if (entry->IsSigninRequired())
    return;
  ProfileMetrics::LogProfileAuthResult(ProfileMetrics::AUTH_UNNECESSARY);

  profiles::SwitchToProfile(
      profile_path, false, /* reuse any existing windows */
      base::Bind(&UserManagerScreenHandler::OnSwitchToProfileComplete,
                 weak_ptr_factory_.GetWeakPtr()),
      ProfileMetrics::SWITCH_PROFILE_MANAGER);
}

void UserManagerScreenHandler::HandleAttemptUnlock(
    const base::ListValue* args) {
  std::string email;
  CHECK(args->GetString(0, &email));
  GetScreenlockRouter(email)
      ->OnAuthAttempted(GetAuthType(AccountId::FromUserEmail(email)), "");
}

void UserManagerScreenHandler::HandleHardlockUserPod(
    const base::ListValue* args) {
  std::string email;
  CHECK(args->GetString(0, &email));
  const AccountId account_id = AccountId::FromUserEmail(email);
  SetAuthType(
      account_id,
      proximity_auth::ScreenlockBridge::LockHandler::FORCE_OFFLINE_PASSWORD,
      base::string16());
  HideUserPodCustomIcon(account_id);
}

void UserManagerScreenHandler::HandleRemoveUserWarningLoadStats(
    const base::ListValue* args) {
  const base::Value* profile_path_value;

  if (!args->Get(0, &profile_path_value))
    return;

  base::FilePath profile_path;

  if (!base::GetValueAsFilePath(*profile_path_value, &profile_path))
    return;

  base::StringValue return_profile_path(profile_path.value());
  Profile* profile = g_browser_process->profile_manager()->
      GetProfileByPath(profile_path);

  if (!profile)
    return;

  if (!chrome::FindAnyBrowser(profile, true)) {
    // If no windows are open for that profile, the statistics in
    // ProfileAttributesStorage are up to date. The statistics in
    // ProfileAttributesStorage are returned because the copy in user_pod_row.js
    // may be outdated. However, if some statistics are missing in
    // ProfileAttributesStorage (i.e. |item.success| is false), then the actual
    // statistics are queried instead.
    base::DictionaryValue return_value;
    profiles::ProfileCategoryStats stats =
        ProfileStatistics::GetProfileStatisticsFromAttributesStorage(
            profile_path);
    bool stats_success = true;
    for (const auto& item : stats) {
      std::unique_ptr<base::DictionaryValue> stat(new base::DictionaryValue);
      stat->SetIntegerWithoutPathExpansion("count", item.count);
      stat->SetBooleanWithoutPathExpansion("success", item.success);
      return_value.SetWithoutPathExpansion(item.category, std::move(stat));
      stats_success &= item.success;
    }
    if (stats_success) {
      web_ui()->CallJavascriptFunction("updateRemoveWarningDialog",
                                       base::StringValue(profile_path.value()),
                                       return_value);
      return;
    }
  }

  ProfileStatisticsFactory::GetForProfile(profile)->GatherStatistics(
      base::Bind(
          &UserManagerScreenHandler::RemoveUserDialogLoadStatsCallback,
          weak_ptr_factory_.GetWeakPtr(), profile_path));
}

void UserManagerScreenHandler::RemoveUserDialogLoadStatsCallback(
    base::FilePath profile_path,
    profiles::ProfileCategoryStats result) {
  // Copy result into return_value.
  base::DictionaryValue return_value;
  for (const auto& item : result) {
    std::unique_ptr<base::DictionaryValue> stat(new base::DictionaryValue);
    stat->SetIntegerWithoutPathExpansion("count", item.count);
    stat->SetBooleanWithoutPathExpansion("success", item.success);
    return_value.SetWithoutPathExpansion(item.category, std::move(stat));
  }
  web_ui()->CallJavascriptFunction("updateRemoveWarningDialog",
                                   base::StringValue(profile_path.value()),
                                   return_value);
}

void UserManagerScreenHandler::HandleGetRemoveWarningDialogMessage(
    const base::ListValue* args) {
  const base::DictionaryValue* arg;
  if (!args->GetDictionary(0, &arg))
    return;

  std::string profile_path("");
  bool is_synced_user = false;
  bool has_errors = false;

  if (!arg->GetString("profilePath", &profile_path) ||
      !arg->GetBoolean("isSyncedUser", &is_synced_user) ||
      !arg->GetBoolean("hasErrors", &has_errors))
    return;

  int total_count = 0;
  if (!arg->GetInteger("totalCount", &total_count))
    return;

  int message_id = is_synced_user ?
      (has_errors ? IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC_WITH_ERRORS :
                    IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC) :
      (has_errors ? IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC_WITH_ERRORS :
                    IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC);

  base::StringValue message = base::StringValue(
      l10n_util::GetPluralStringFUTF16(message_id, total_count));

  web_ui()->CallJavascriptFunction("updateRemoveWarningDialogSetMessage",
                                   base::StringValue(profile_path),
                                   message,
                                   base::FundamentalValue(total_count));
}

void UserManagerScreenHandler::OnGetTokenInfoResponse(
    std::unique_ptr<base::DictionaryValue> token_info) {
  // Password is unchanged so user just mistyped it.  Ask again.
  ReportAuthenticationResult(false, ProfileMetrics::AUTH_FAILED);
}

void UserManagerScreenHandler::OnOAuthError() {
  // Password has changed.  Go through online signin flow.
  DCHECK(!email_address_.empty());
  oauth_client_.reset();
  UserManager::ShowReauthDialog(web_ui()->GetWebContents()->GetBrowserContext(),
                                email_address_);
}

void UserManagerScreenHandler::OnNetworkError(int response_code) {
  // Inconclusive but can't do real signin without being online anyway.
    oauth_client_.reset();
    ReportAuthenticationResult(false, ProfileMetrics::AUTH_FAILED_OFFLINE);
}

void UserManagerScreenHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback(kJsApiUserManagerInitialize,
      base::Bind(&UserManagerScreenHandler::HandleInitialize,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(kJsApiUserManagerAddUser,
      base::Bind(&UserManagerScreenHandler::HandleAddUser,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(kJsApiUserManagerAuthLaunchUser,
      base::Bind(&UserManagerScreenHandler::HandleAuthenticatedLaunchUser,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(kJsApiUserManagerLaunchGuest,
      base::Bind(&UserManagerScreenHandler::HandleLaunchGuest,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(kJsApiUserManagerLaunchUser,
      base::Bind(&UserManagerScreenHandler::HandleLaunchUser,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(kJsApiUserManagerRemoveUser,
      base::Bind(&UserManagerScreenHandler::HandleRemoveUser,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(kJsApiUserManagerAttemptUnlock,
      base::Bind(&UserManagerScreenHandler::HandleAttemptUnlock,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(kJsApiUserManagerLogRemoveUserWarningShown,
      base::Bind(&HandleLogRemoveUserWarningShown));
  web_ui()->RegisterMessageCallback(kJsApiUserManagerRemoveUserWarningLoadStats,
      base::Bind(&UserManagerScreenHandler::HandleRemoveUserWarningLoadStats,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      kJsApiUserManagerGetRemoveWarningDialogMessage,
      base::Bind(&UserManagerScreenHandler::HandleGetRemoveWarningDialogMessage,
                 base::Unretained(this)));

  const content::WebUI::MessageCallback& kDoNothingCallback =
      base::Bind(&HandleAndDoNothing);

  // Unused callbacks from screen_account_picker.js
  web_ui()->RegisterMessageCallback("accountPickerReady", kDoNothingCallback);
  web_ui()->RegisterMessageCallback("loginUIStateChanged", kDoNothingCallback);
  web_ui()->RegisterMessageCallback("hideCaptivePortal", kDoNothingCallback);
  web_ui()->RegisterMessageCallback("getTouchViewState", kDoNothingCallback);
  // Unused callbacks from display_manager.js
  web_ui()->RegisterMessageCallback("showAddUser", kDoNothingCallback);
  web_ui()->RegisterMessageCallback("loadWallpaper", kDoNothingCallback);
  web_ui()->RegisterMessageCallback("updateCurrentScreen", kDoNothingCallback);
  web_ui()->RegisterMessageCallback("loginVisible", kDoNothingCallback);
  // Unused callbacks from user_pod_row.js
  web_ui()->RegisterMessageCallback("focusPod", kDoNothingCallback);
}

void UserManagerScreenHandler::GetLocalizedValues(
    base::DictionaryValue* localized_strings) {
  // For Control Bar.
  localized_strings->SetString("signedIn",
      l10n_util::GetStringUTF16(IDS_SCREEN_LOCK_ACTIVE_USER));
  localized_strings->SetString("addUser",
      l10n_util::GetStringUTF16(IDS_ADD_USER_BUTTON));
  localized_strings->SetString("cancel", l10n_util::GetStringUTF16(IDS_CANCEL));
  localized_strings->SetString("browseAsGuest",
      l10n_util::GetStringUTF16(IDS_GO_INCOGNITO_BUTTON));
  localized_strings->SetString("signOutUser",
      l10n_util::GetStringUTF16(IDS_SCREEN_LOCK_SIGN_OUT));
  localized_strings->SetString("addSupervisedUser",
      l10n_util::GetStringUTF16(IDS_CREATE_LEGACY_SUPERVISED_USER_MENU_LABEL));

  // For AccountPickerScreen.
  localized_strings->SetString("screenType", "login-add-user");
  localized_strings->SetString("highlightStrength", "normal");
  localized_strings->SetString("title",
      l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
  localized_strings->SetString("passwordHint",
      l10n_util::GetStringUTF16(IDS_LOGIN_POD_EMPTY_PASSWORD_TEXT));
  localized_strings->SetString("signingIn",
      l10n_util::GetStringUTF16(IDS_LOGIN_POD_SIGNING_IN));
  localized_strings->SetString("podMenuButtonAccessibleName",
      l10n_util::GetStringUTF16(IDS_LOGIN_POD_MENU_BUTTON_ACCESSIBLE_NAME));
  localized_strings->SetString("podMenuRemoveItemAccessibleName",
      l10n_util::GetStringUTF16(
          IDS_LOGIN_POD_MENU_REMOVE_ITEM_ACCESSIBLE_NAME));
  localized_strings->SetString("removeUser",
      l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_BUTTON));
  localized_strings->SetString("passwordFieldAccessibleName",
      l10n_util::GetStringUTF16(IDS_LOGIN_POD_PASSWORD_FIELD_ACCESSIBLE_NAME));
  localized_strings->SetString("bootIntoWallpaper", "off");

  // For AccountPickerScreen, the remove user warning overlay.
  localized_strings->SetString("removeUserWarningButtonTitle",
      l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_BUTTON));
  localized_strings->SetString("removeUserWarningTextNonSyncNoStats",
      l10n_util::GetStringUTF16(
          IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC_NOSTATS));
  localized_strings->SetString("removeUserWarningTextNonSyncCalculating",
      l10n_util::GetStringUTF16(
          IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC_CALCULATING));
  localized_strings->SetString("removeUserWarningTextHistory",
      l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_HISTORY));
  localized_strings->SetString("removeUserWarningTextPasswords",
      l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_PASSWORDS));
  localized_strings->SetString("removeUserWarningTextBookmarks",
      l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_BOOKMARKS));
  localized_strings->SetString("removeUserWarningTextSettings",
      l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_SETTINGS));
  localized_strings->SetString("removeUserWarningTextCalculating",
      l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_CALCULATING));
  localized_strings->SetString("removeUserWarningTextSyncNoStats",
      l10n_util::GetStringUTF16(
          IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC_NOSTATS));
  localized_strings->SetString("removeUserWarningTextSyncCalculating",
      l10n_util::GetStringUTF16(
          IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC_CALCULATING));
  localized_strings->SetString("removeLegacySupervisedUserWarningText",
      l10n_util::GetStringFUTF16(
          IDS_LOGIN_POD_LEGACY_SUPERVISED_USER_REMOVE_WARNING,
          base::UTF8ToUTF16(
              chrome::kLegacySupervisedUserManagementDisplayURL)));

  // Strings needed for the User Manager tutorial slides.
  localized_strings->SetString("tutorialNext",
      l10n_util::GetStringUTF16(IDS_USER_MANAGER_TUTORIAL_NEXT));
  localized_strings->SetString("tutorialDone",
      l10n_util::GetStringUTF16(IDS_USER_MANAGER_TUTORIAL_DONE));
  localized_strings->SetString("slideWelcomeTitle",
      l10n_util::GetStringUTF16(IDS_USER_MANAGER_TUTORIAL_SLIDE_INTRO_TITLE));
  localized_strings->SetString("slideWelcomeText",
      l10n_util::GetStringUTF16(IDS_USER_MANAGER_TUTORIAL_SLIDE_INTRO_TEXT));
  localized_strings->SetString("slideYourChromeTitle",
      l10n_util::GetStringUTF16(
          IDS_USER_MANAGER_TUTORIAL_SLIDE_YOUR_CHROME_TITLE));
  localized_strings->SetString("slideYourChromeText", l10n_util::GetStringUTF16(
      IDS_USER_MANAGER_TUTORIAL_SLIDE_YOUR_CHROME_TEXT));
  localized_strings->SetString("slideGuestsTitle",
      l10n_util::GetStringUTF16(IDS_USER_MANAGER_TUTORIAL_SLIDE_GUEST_TITLE));
  localized_strings->SetString("slideGuestsText",
      l10n_util::GetStringUTF16(IDS_USER_MANAGER_TUTORIAL_SLIDE_GUEST_TEXT));
  localized_strings->SetString("slideFriendsTitle",
      l10n_util::GetStringUTF16(IDS_USER_MANAGER_TUTORIAL_SLIDE_FRIENDS_TITLE));
  localized_strings->SetString("slideFriendsText",
      l10n_util::GetStringUTF16(IDS_USER_MANAGER_TUTORIAL_SLIDE_FRIENDS_TEXT));
  localized_strings->SetString("slideCompleteTitle",
      l10n_util::GetStringUTF16(IDS_USER_MANAGER_TUTORIAL_SLIDE_OUTRO_TITLE));
  localized_strings->SetString("slideCompleteText",
      l10n_util::GetStringUTF16(IDS_USER_MANAGER_TUTORIAL_SLIDE_OUTRO_TEXT));
  localized_strings->SetString("slideCompleteUserNotFound",
      l10n_util::GetStringUTF16(
          IDS_USER_MANAGER_TUTORIAL_SLIDE_OUTRO_USER_NOT_FOUND));
  localized_strings->SetString("slideCompleteAddUser",
      l10n_util::GetStringUTF16(
          IDS_USER_MANAGER_TUTORIAL_SLIDE_OUTRO_ADD_USER));

  // Strings needed for the user_pod_template public account div, but not ever
  // actually displayed for desktop users.
  localized_strings->SetString("publicAccountReminder", base::string16());
  localized_strings->SetString("publicSessionLanguageAndInput",
                               base::string16());
  localized_strings->SetString("publicAccountEnter", base::string16());
  localized_strings->SetString("publicAccountEnterAccessibleName",
                               base::string16());
  localized_strings->SetString("publicSessionSelectLanguage", base::string16());
  localized_strings->SetString("publicSessionSelectKeyboard", base::string16());
  localized_strings->SetString("signinBannerText", base::string16());
  localized_strings->SetString("launchAppButton", base::string16());
  localized_strings->SetString("multiProfilesRestrictedPolicyTitle",
                               base::string16());
  localized_strings->SetString("multiProfilesNotAllowedPolicyMsg",
                                base::string16());
  localized_strings->SetString("multiProfilesPrimaryOnlyPolicyMsg",
                                base::string16());
  localized_strings->SetString("multiProfilesOwnerPrimaryOnlyMsg",
                                base::string16());
}

void UserManagerScreenHandler::SendUserList() {
  base::ListValue users_list;
  std::vector<ProfileAttributesEntry*> entries =
      g_browser_process->profile_manager()->GetProfileAttributesStorage().
          GetAllProfilesAttributesSortedByName();
  user_auth_type_map_.clear();

  // Profile deletion is not allowed in Metro mode.
  bool can_remove = true;
#if defined(USE_ASH)
  can_remove = !ash::Shell::HasInstance();
#endif

  for (const ProfileAttributesEntry* entry : entries) {
    // Don't show profiles still in the middle of being set up as new legacy
    // supervised users.
    if (entry->IsOmitted())
      continue;

    base::DictionaryValue* profile_value = new base::DictionaryValue();
    base::FilePath profile_path = entry->GetPath();

    profile_value->SetString(kKeyUsername, entry->GetUserName());
    profile_value->SetString(kKeyEmailAddress, entry->GetUserName());
    profile_value->SetString(kKeyDisplayName,
                             profiles::GetAvatarNameForProfile(profile_path));
    profile_value->Set(kKeyProfilePath,
                       base::CreateFilePathValue(profile_path));
    profile_value->SetBoolean(kKeyPublicAccount, false);
    profile_value->SetBoolean(kKeyLegacySupervisedUser,
                              entry->IsLegacySupervised());
    profile_value->SetBoolean(kKeyChildUser, entry->IsChild());
    profile_value->SetBoolean(kKeyNeedsSignin, entry->IsSigninRequired());
    profile_value->SetBoolean(kKeyHasLocalCreds,
                              !entry->GetLocalAuthCredentials().empty());
    profile_value->SetBoolean(kKeyIsOwner, false);
    profile_value->SetBoolean(kKeyCanRemove, can_remove);
    profile_value->SetBoolean(kKeyIsDesktop, true);
    profile_value->SetString(kKeyAvatarUrl, GetAvatarImage(entry));

    profiles::ProfileCategoryStats stats =
        ProfileStatistics::GetProfileStatisticsFromAttributesStorage(
            profile_path);
    std::unique_ptr<base::DictionaryValue> stats_dict(
        new base::DictionaryValue);
    for (const auto& item : stats) {
      std::unique_ptr<base::DictionaryValue> stat(new base::DictionaryValue);
      stat->SetIntegerWithoutPathExpansion("count", item.count);
      stat->SetBooleanWithoutPathExpansion("success", item.success);
      stats_dict->SetWithoutPathExpansion(item.category, std::move(stat));
    }
    profile_value->SetWithoutPathExpansion(kKeyStatistics,
                                           std::move(stats_dict));

    // GetProfileByPath returns a pointer if the profile is fully loaded, NULL
    // otherwise.
    Profile* profile =
        g_browser_process->profile_manager()->GetProfileByPath(profile_path);
    profile_value->SetBoolean(kKeyIsProfileLoaded, profile != nullptr);

    users_list.Append(profile_value);
  }

  web_ui()->CallJavascriptFunction("login.AccountPickerScreen.loadUsers",
      users_list, base::FundamentalValue(IsGuestModeEnabled()));

  // This is the latest C++ code we have in the flow to show the UserManager.
  // This may be invoked more than once per UserManager lifetime; the
  // UserManager will ensure all relevant logging only happens once.
  UserManager::OnUserManagerShown();
}

void UserManagerScreenHandler::ReportAuthenticationResult(
    bool success,
    ProfileMetrics::ProfileAuth auth) {
  ProfileMetrics::LogProfileAuthResult(auth);
  email_address_.clear();

  if (success) {
    profiles::SwitchToProfile(
        authenticating_profile_path_, true,
        base::Bind(&UserManagerScreenHandler::OnSwitchToProfileComplete,
                   weak_ptr_factory_.GetWeakPtr()),
        ProfileMetrics::SWITCH_PROFILE_UNLOCK);
  } else {
    web_ui()->CallJavascriptFunction(
        "cr.ui.UserManager.showSignInError",
        base::FundamentalValue(0),
        base::StringValue(l10n_util::GetStringUTF8(
            auth == ProfileMetrics::AUTH_FAILED_OFFLINE ?
                IDS_LOGIN_ERROR_AUTHENTICATING_OFFLINE :
                IDS_LOGIN_ERROR_AUTHENTICATING)),
        base::StringValue(""),
        base::FundamentalValue(0));
  }
}

void UserManagerScreenHandler::OnBrowserWindowReady(Browser* browser) {
  DCHECK(browser);
  DCHECK(browser->window());

  // Unlock the profile after browser opens so startup can read the lock bit.
  // Any necessary authentication must have been successful to reach this point.
  if (!browser->profile()->IsGuestSession()) {
    ProfileAttributesEntry* entry = nullptr;
    bool has_entry = g_browser_process->profile_manager()->
        GetProfileAttributesStorage().
        GetProfileAttributesWithPath(browser->profile()->GetPath(), &entry);
    DCHECK(has_entry);
    entry->SetIsSigninRequired(false);
  }

  if (!url_hash_.empty()) {
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE,
        base::Bind(&UrlHashHelper::ExecuteUrlHash,
                   base::Owned(new UrlHashHelper(browser, url_hash_))));
  }

  // This call is last as it deletes this object.
  UserManager::Hide();
}

void UserManagerScreenHandler::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  switch (type) {
    case chrome::NOTIFICATION_BROWSER_WINDOW_READY:
      // Only respond to one Browser Window Ready event.
      registrar_.Remove(this,
                        chrome::NOTIFICATION_BROWSER_WINDOW_READY,
                        content::NotificationService::AllSources());
      OnBrowserWindowReady(content::Source<Browser>(source).ptr());
    break;
    default:
      NOTREACHED();
  }
}

// This callback is run after switching to a new profile has finished. This
// means either a new browser has been created (but not the window), or an
// existing one has been found. The HideUserManager task needs to be posted
// since closing the User Manager before the window is created can flakily
// cause Chrome to close.
void UserManagerScreenHandler::OnSwitchToProfileComplete(
    Profile* profile, Profile::CreateStatus profile_create_status) {
  Browser* browser = chrome::FindAnyBrowser(profile, false);
  if (browser && browser->window()) {
    OnBrowserWindowReady(browser);
  } else {
    registrar_.Add(this,
                   chrome::NOTIFICATION_BROWSER_WINDOW_READY,
                   content::NotificationService::AllSources());
  }
}


text:
var express = require("express");
var session = require('express-session');
var app = express();
var http = require("http").createServer(app);
var bodyParser = require("body-parser");

var io = require("socket.io").listen(http);
var passport = require('passport');
var _ = require("underscore");
var MongoStore = require('connect-mongo')({ session: session });
var mongoose = require('mongoose');

/**
 * API keys and Passport configuration.
 */

var secrets = require('./config/secrets');
var passportConf = require('./config/passport');

/**
 * Connect to MongoDB.
 */

mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
  console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});
var User = require('./models/User');

/*
  The list of participants in our chatroom.
  The format of each participant will be:
  {
    id: "sessionId",
    name: "participantName"
  }
*/
var participants = [];

app.set("ipaddr", "127.0.0.1");
app.set("port", 8080);

app.set("views", __dirname + "/views");
app.set("view engine", "jade");
//Specify where the static content is
app.use(express.static("public", __dirname + "/public"));

app.use(bodyParser.json());

app.use(session({secret: secrets.sessionSecret, resave: true, saveUninitialized: true}));
// Initialize Passport!  Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());

//route homepage
app.get("/", function(req, res) {
  res.render("index");
});

// GET /auth/windowslive
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in Windows Live authentication will involve
//   redirecting the user to live.com.  After authorization, Windows Live
//   will redirect the user back to this application at
//   /auth/windowslive/callback
app.get('/auth/windowslive',
  passport.authenticate('windowslive', { scope: ['wl.signin', 'wl.basic'] }),
  function(req, res){
    // The request will be redirected to Windows Live for authentication, so
    // this function will not be called.
  });

// GET /auth/windowslive/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which will redirect the user to the hub page.
app.get('/auth/windowslive/callback',
  passport.authenticate('windowslive', { failureRedirect: '/' }),
  function(req, res) {
    res.redirect('/hub');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

//route boards
app.get("/board", function(req, res) {
  res.render("board", { user: req.user });
});

app.get("/hub", function(req, res) {
  if (!req.user) {
    res.redirect('/');
  }
  req.user._id = req.user._id.toHexString();
  console.log(req.user)
  res.render("hub", { user: req.user });
});

app.post("/message", function(req, res) {

  //The request body expects a param named "message"
  var message = req.body.message;

  //If the message is empty or wasn't sent it's a bad request
  if(_.isUndefined(message) || _.isEmpty(message.trim())) {
    return res.json(400, {error: "Message is invalid"});
  }

  //We also expect the sender's name with the message
  var name = req.body.name;

  //Let our chatroom know there was a new message
  io.sockets.emit("incomingMessage", {message: message, name: name});

  //Looks good, let the client know
  res.json(200, {message: "Message received"});

});

/* Socket.IO events */
io.on("connection", function(socket){

  /*
    When a new user connects to our server, we expect an event called "newUser"
    and then we'll emit an event called "newConnection" with a list of all
    participants to all connected clients
  */
  socket.on("newUser", function(data) {
    participants.push({id: data.id, name: data.name});
    io.sockets.emit("newConnection", {participants: participants});
  });

  /*
    When a user changes his name, we are expecting an event called "nameChange"
    and then we'll emit an event called "nameChanged" to all participants with
    the id and new name of the user who emitted the original message
  */
  socket.on("nameChange", function(data) {
    _.findWhere(participants, {id: socket.id}).name = data.name;
    io.sockets.emit("nameChanged", {id: data.id, name: data.name});
  });

  /*
    When a client disconnects from the server, the event "disconnect" is automatically
    captured by the server. It will then emit an event called "userDisconnected" to
    all participants with the id of the client that disconnected
  */
  socket.on("disconnect", function() {
    participants = _.without(participants,_.findWhere(participants, {id: socket.id}));
    io.sockets.emit("userDisconnected", {id: socket.id, sender:"system"});
  });

});

http.listen(app.get("port"), app.get("ipaddr"), function() {
  console.log("Server up and running. Go to http://" + app.get("ipaddr") + ":" + app.get("port"));
});


text:
package manual

import (
	"github.com/ohsu-comp-bio/funnel/compute/scheduler"
	schedmock "github.com/ohsu-comp-bio/funnel/compute/scheduler/mocks"
	"github.com/ohsu-comp-bio/funnel/config"
	pbs "github.com/ohsu-comp-bio/funnel/proto/scheduler"
	"github.com/ohsu-comp-bio/funnel/proto/tes"
	. "github.com/stretchr/testify/mock"
	"testing"
)

func simpleNode() *pbs.Node {
	return &pbs.Node{
		// This ID MUST match the ID set in setup()
		// because the local scheduler is built to have only a single node
		Id: "test-node-id",
		Resources: &pbs.Resources{
			Cpus:   1.0,
			RamGb:  1.0,
			DiskGb: 1.0,
		},
		Available: &pbs.Resources{
			Cpus:   1.0,
			RamGb:  1.0,
			DiskGb: 1.0,
		},
		State: pbs.NodeState_ALIVE,
		Zone:  "ok-zone",
	}
}

func setup(nodes []*pbs.Node) (*schedmock.Client, *Backend) {
	conf := config.Config{}
	mc := new(schedmock.Client)

	// Mock in test nodes
	mc.On("ListNodes", Anything, Anything, Anything).Return(&pbs.ListNodesResponse{
		Nodes: nodes,
	}, nil)

	s := &Backend{
		conf,
		mc,
	}
	return mc, s
}

func TestNoNodes(t *testing.T) {
	_, s := setup([]*pbs.Node{})
	j := &tes.Task{}
	o := s.GetOffer(j)
	if o != nil {
		t.Error("Task scheduled on empty nodes")
	}
}

func TestSingleNode(t *testing.T) {
	_, s := setup([]*pbs.Node{
		simpleNode(),
	})

	j := &tes.Task{}
	o := s.GetOffer(j)
	if o == nil {
		t.Error("Failed to schedule task on single node")
		return
	}
	if o.Node.Id != "test-node-id" {
		t.Error("Scheduled task on unexpected node")
	}
}

// Test that scheduler ignores nodes without the "ALIVE" state
func TestIgnoreNonAliveNodes(t *testing.T) {
	j := &tes.Task{}

	for name, val := range pbs.NodeState_value {
		w := simpleNode()
		w.State = pbs.NodeState(val)
		_, s := setup([]*pbs.Node{w})
		o := s.GetOffer(j)

		if name == "ALIVE" {
			// Testing ALIVE just so I know this test is node as expected
			if o == nil {
				t.Error("Didn't schedule task to alive node")
			}
		} else {
			if o != nil {
				t.Errorf("Scheduled task to non-alive node: %s", name)
				return
			}
		}

	}
}

// Test whether the scheduler correctly filters nodes based on
// cpu, ram, disk, etc.
func TestMatch(t *testing.T) {
	_, s := setup([]*pbs.Node{
		simpleNode(),
	})

	var o *scheduler.Offer
	var j *tes.Task

	// Helper which sets up Task.Resources struct to non-nil
	blankTask := func() *tes.Task {
		return &tes.Task{Resources: &tes.Resources{}}
	}

	// test CPUs too big
	j = blankTask()
	j.Resources.CpuCores = 2
	o = s.GetOffer(j)
	if o != nil {
		t.Error("Scheduled task to node without enough CPU resources")
	}

	// test RAM too big
	j = blankTask()
	j.Resources.RamGb = 2.0
	o = s.GetOffer(j)
	if o != nil {
		t.Error("Scheduled task to node without enough RAM resources")
	}

	// test disk too big
	j = blankTask()
	j.Resources.DiskGb = 2.0
	o = s.GetOffer(j)
	if o != nil {
		t.Error("Scheduled task to node without enough DiskGb resources")
	}

	// test zones don't match
	j = blankTask()
	j.Resources.Zones = []string{"test-zone"}
	o = s.GetOffer(j)
	if o != nil {
		t.Error("Scheduled task to node out of zone")
	}

	// Now test a task that fits
	j = blankTask()
	j.Resources.CpuCores = 1
	j.Resources.RamGb = 1.0
	j.Resources.DiskGb = 1.0
	j.Resources.Zones = []string{"ok-zone", "not-ok-zone"}
	o = s.GetOffer(j)
	if o == nil {
		t.Error("Didn't schedule task when resources fit")
	}
}


text:
layout: guide
title: How can I convert WAV to MP3 on Mac?
keywords: wav to mp3 converter, wav to mp3 mac, wav to mp3 audio converter mac, convert a wav to mp3, change a wav to mp3, wav to mp3 batch, wav to mp3 conversion, wav to mp3 batch converter mac
description: Trying to convert WAV files to MP3 on a Mac? This article explains how to encode audio files from WAV format to MP3 format on Mac.
---
Trying to convert WAV files to MP3 on a Mac? Then you may wish to read this article. It explains how to encode audio files from WAV format to MP3 format on Mac.
![](../img/wav.jpg)

## What is WAV?
WAV is short for Waveform Audio File Format (WAVE), it is a Microsoft and IBM audio file format standard for storing an audio bitstream on PCs.

WAV files are audio files playable via multimedia playback software such as Windows Media Player and other software available for your operating system. These files contain any sounds such as sound effects, music or spoken words. WAV files are large in size and with the advent of MP3 and MP4 WAV files are becoming less popular and less common. They were created and developed by IBM and Microsoft but unlike MP3 and MP4 the WAV file format does not use a form of lossy compression so file sizes are therefore much bigger and now less popular.

The highest quality of WAV being th 16-bit at 44,100 HZ, this highest level is the sampling rate of an audio CD and uses 88KB of storage per second. All general sounds in Windows, such as when you log in, are in the .WAV format. The default content of a WAV file is uncompressed (although they can be used to store compressed formats such as MP3), pulse code modulated (PCM) digital samples derived from the analog source.

## How to convert WAV to MP3?
If you need to convert WAV to MP3 format, you will need a powerful audio converter to help you. Thankfully, there is  TryToMP3  for you.

1. Download a free trial of Gmagon TryToMP3

Note that this app requires Mac OS X 10.11 or later. It provides 30-day free trial.

2. Install and run Gmagon TryToMP3 on your Mac. Click "Continue" to try it out or click "Buy" to purchase it directly.
![](../img/continue.png)

3. After clicking "Continue", switch to "Convert", and the following interface will show up.
![](../img/convert.png)

4. Click "Import files" or "Import directory" to add WAV files that you want to convert to MP3. More than converting audio files to MP3, this app can also extrati audio tracks from various video files and save them as MP3.

After files loaded, click "Output directory" to set output path. When ready, click "Convert" to start. When the conversion is complete, click "Reveal in Folder" to find the generated MP3 files.

![](../img/steps.png)

>As you can see above, with Gmagon TryToMP3 installed, you can easily convert WAV files to MP3 on a Mac Machine.

Also read
Gmagon TryToMP3 4.1.0 has been released
How to extract an audio from a video to MP3 on Mac?
How can I convert FLAC to MP3?
How can I convert AAC to MP3?


text:
package random

import (
	"bytes"
	crand "crypto/rand"
	"encoding/binary"
	"math/rand"
	"reflect"
	"sort"
	"time"
)

var (
	digits         = []byte("0123456789")
	lowercaseChars = []byte("abcdefghijklmnopqrstuvwxyz")
	uppercaseChars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
	specialChars   = []byte("~!@#$%^&*")
)

const (
	O_DIGIT = 1 << iota
	O_LOWER_CHAR
	O_UPPER_CHAR
	O_SPECIAL_CHAR
)

type Source interface {
	Int63() int64
}

// defaultSource represents a unsafe random source
type defaultSource struct{}

func (source defaultSource) Int63() int64 { return rand.Int63() }

func newDefaultSource(seed int64) defaultSource {
	rand.Seed(seed)
	return defaultSource{}
}

// defaultSource represents a safe random source
type cryptoSource struct{}

func (source cryptoSource) Int63() int64 {
	var b [8]byte
	_, err := crand.Read(b[:])
	if err != nil {
		return DefaultSource.Int63()
	}
	b[0] &= 0x7F
	return int64(binary.BigEndian.Uint64(b[:]))
}

var (
	DefaultSource Source = newDefaultSource(time.Now().UnixNano())
	CryptoSource  Source = cryptoSource{}
)

func Int63(source Source) int64 {
	if source == nil {
		source = DefaultSource
	}
	return source.Int63()
}

func Intn(n int, source Source) int {
	return int(Int63(source) % int64(n))
}

func Bool(source Source) bool {
	return Intn(2, source) == 1
}

func String(length int, source Source, modes ...int) string {
	if length <= 0 {
		return ""
	}
	var mode int
	for _, m := range modes {
		mode |= m
	}
	if mode&(O_DIGIT|O_LOWER_CHAR|O_UPPER_CHAR|O_SPECIAL_CHAR) == 0 {
		mode = O_LOWER_CHAR | O_UPPER_CHAR
	}
	size := 0
	if mode&O_DIGIT != 0 {
		size += len(digits)
	}
	if mode&O_LOWER_CHAR != 0 {
		size += len(lowercaseChars)
	}
	if mode&O_UPPER_CHAR != 0 {
		size += len(uppercaseChars)
	}
	if mode&O_SPECIAL_CHAR != 0 {
		size += len(specialChars)
	}
	var buf bytes.Buffer
	for i := 0; i < length; i++ {
		index := Intn(size, source)
		tmpSize := 0
		if mode&O_DIGIT != 0 {
			tmpSize = len(digits)
			if index < tmpSize {
				buf.WriteByte(digits[index])
				continue
			}
			index -= tmpSize
		}
		if mode&O_LOWER_CHAR != 0 {
			tmpSize = len(lowercaseChars)
			if index < tmpSize {
				buf.WriteByte(lowercaseChars[index])
				continue
			}
			index -= tmpSize
		}
		if mode&O_UPPER_CHAR != 0 {
			tmpSize = len(uppercaseChars)
			if index < tmpSize {
				buf.WriteByte(uppercaseChars[index])
				continue
			}
			index -= tmpSize
		}
		if mode&O_SPECIAL_CHAR != 0 {
			tmpSize = len(specialChars)
			if index < tmpSize {
				buf.WriteByte(specialChars[index])
				continue
			}
		}
		buf.WriteByte('-')
	}
	return buf.String()
}

func Perm(n int, source Source) []int {
	s := make([]int, n)
	for i := 0; i < n; i++ {
		j := Intn(i+1, source)
		s[i] = s[j]
		s[j] = i
	}
	return s
}

type SwapableSlice interface {
	Len() int
	Swap(i, j int)
}

func Shuffle(orders SwapableSlice, source Source) {
	for i := orders.Len() - 1; i >= 0; i-- {
		if source == nil {
			orders.Swap(i, rand.Intn(i+1))
		} else {
			orders.Swap(i, int(source.Int63())%(i+1))
		}
	}
}

func ShuffleInts(orders []int, source Source)       { Shuffle(sort.IntSlice(orders), source) }
func ShuffleFloats(orders []float64, source Source) { Shuffle(sort.Float64Slice(orders), source) }
func ShuffleStrings(orders []string, source Source) { Shuffle(sort.StringSlice(orders), source) }

type swapableSlice struct {
	swapper func(int, int)
	length  int
}

func (s swapableSlice) Len() int      { return s.length }
func (s swapableSlice) Swap(i, j int) { s.swapper(i, j) }

func ShuffleSlice(slice interface{}, source Source) {
	Shuffle(swapableSlice{
		swapper: reflect.Swapper(slice),
		length:  reflect.ValueOf(slice).Len(),
	}, source)
}

// FiniteDistribution represents probability distribution
type FiniteDistribution interface {
	Len() int
	Probability(i int) int
}

type SummedFiniteDistribution interface {
	FiniteDistribution
	SumProbability() int
}

type IntsFiniteDistribution []int

func (d IntsFiniteDistribution) Len() int              { return len(d) }
func (d IntsFiniteDistribution) Probability(i int) int { return d[i] }

func sumFiniteDistribution(d FiniteDistribution) int {
	if summed, ok := d.(SummedFiniteDistribution); ok {
		return summed.SumProbability()
	}
	sum := 0
	for i, n := 0, d.Len(); i < n; i++ {
		sum += d.Probability(i)
	}
	return sum
}

func Index(d FiniteDistribution, source Source) int {
	sum := sumFiniteDistribution(d)
	if sum <= 0 {
		panic("sum < 0")
	}
	var (
		value = Intn(sum, source)
		acc   = 0
		end   = d.Len() - 1
	)
	for i := 0; i < end; i++ {
		acc += d.Probability(i)
		if acc > value {
			return i
		}
	}
	return end
}

func IndexInts(d []int, source Source) int {
	return Index(IntsFiniteDistribution(d), source)
}

type probabilityDistribution struct {
	probability func(int) int
	length      int
}

func (d probabilityDistribution) Len() int              { return d.length }
func (d probabilityDistribution) Probability(i int) int { return d.probability(i) }

func IndexSlice(d interface{}, probability func(int) int, source Source) int {
	return Index(probabilityDistribution{probability, reflect.ValueOf(d).Len()}, source)
}


text:
package openfoodfacts.github.scrachx.openfood.views.product.environment;

import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import openfoodfacts.github.scrachx.openfood.R;
import openfoodfacts.github.scrachx.openfood.databinding.FragmentEnvironmentProductBinding;
import openfoodfacts.github.scrachx.openfood.fragments.BaseFragment;
import openfoodfacts.github.scrachx.openfood.models.Nutriments;
import openfoodfacts.github.scrachx.openfood.models.Product;
import openfoodfacts.github.scrachx.openfood.models.ProductState;
import openfoodfacts.github.scrachx.openfood.utils.FragmentUtils;

import static openfoodfacts.github.scrachx.openfood.utils.Utils.bold;

public class EnvironmentProductFragment extends BaseFragment {
    private FragmentEnvironmentProductBinding binding;
    private ProductState activityProductState;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentEnvironmentProductBinding.inflate(inflater);
        return binding.getRoot();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding = null;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        activityProductState = FragmentUtils.requireStateFromArguments(this);

        final Product product = activityProductState.getProduct();
        Nutriments nutriments = product.getNutriments();

        if (nutriments != null && nutriments.contains(Nutriments.CARBON_FOOTPRINT)) {
            Nutriments.Nutriment carbonFootprintNutriment = nutriments.get(Nutriments.CARBON_FOOTPRINT);
            binding.textCarbonFootprint.setText(bold(getString(R.string.textCarbonFootprint)));
            binding.textCarbonFootprint.append(carbonFootprintNutriment.getFor100gInUnits());
            binding.textCarbonFootprint.append(carbonFootprintNutriment.getUnit());
        } else {
            binding.carbonFootprintCv.setVisibility(View.GONE);
        }

        if (product.getEnvironmentInfocard() != null && !product.getEnvironmentInfocard().isEmpty()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                binding.environmentInfoText.append(Html.fromHtml(product.getEnvironmentInfocard(), Html.FROM_HTML_MODE_COMPACT));
            } else {
                binding.environmentInfoText.append(Html.fromHtml(product.getEnvironmentInfocard()));
            }
        }

        if (product.getRecyclingInstructionsToDiscard() != null && !product.getRecyclingInstructionsToDiscard().isEmpty()) {
            binding.recyclingInstructionToDiscard.setText(bold("Recycling instructions - To discard: "));
            binding.recyclingInstructionToDiscard.append(product.getRecyclingInstructionsToDiscard());
        } else {
            binding.recyclingInstructionsDiscardCv.setVisibility(View.GONE);
        }

        if (product.getRecyclingInstructionsToRecycle() != null && !product.getRecyclingInstructionsToRecycle().isEmpty()) {
            binding.recyclingInstructionToRecycle.setText(bold("Recycling instructions - To recycle:"));
            binding.recyclingInstructionToRecycle.append(product.getRecyclingInstructionsToRecycle());
        } else {
            binding.recyclingInstructionsRecycleCv.setVisibility(View.GONE);
        }

        refreshView(activityProductState);
    }

    @Override
    public void refreshView(ProductState productState) {
        super.refreshView(productState);
        activityProductState = productState;
    }
}


text:
namespace org.apache.http.auth.@params
{
}


text:
package caperutxa.dimoni.parser.report.steps;

import caperutxa.dimoni.parser.report.ReportStep;

public class StepConsole extends ReportStep {

	public StepConsole(String content) {
		super(content);
		iconClass = "glyphicon glyphicon-console";
		cssClass = "col-xs-11 col-xs-offset-1";
	}

	@Override
	public void parseContent() {
		// Nothing to do
	}

}


text:
<?php

namespace VCard\Entry;

use VCard\Entry;

/**
 *

 * The interface called by {@link \VCard\Entry\Constructor}
 *

 *

 * This class is useful when you don't want to know vCard data in detail. If you want to know
 * it, it would be better to consider using {@link \VCard\Interpreter}.
 *

 */
interface Handler
{

    /**
     * Called when the parsing started.
     */
    public function onStart();

    /**
     * The method called when one vCard entry is created. Children come before their parent in
     * nested vCard files.
     *
     * e.g.
     * In the following vCard, the entry for "entry2" comes before one for "entry1".
     *
     * BEGIN:VCARD
     * N:entry1
     * BEGIN:VCARD
     * N:entry2
     * END:VCARD
     * END:VCARD
     *
     *
     * @param  \VCard\Entry $entry
     * @return void
     */
    public function onEntryCreated(Entry $entry);

    /**
     * Called when the parsing ended.
     * Able to be use this method for showing performance log, etc.
     *
     * @return void
     */
    public function onEnd();

}


text:
import os
import shutil
import glob
from .file import remove

def cleanup_experiment(experiment):
    '''
    Cleans up intermediate Dakota files after running an experiment.
    '''
    targets = ['dakota.rst', 'run.log', 'HYDRO_OUTPUT', 'S4']
    for fname in targets:
        remove(os.path.join(experiment, fname))
    for fname in glob.glob(os.path.join(experiment, 'LHS_*')):
        remove(fname)
    for dname in glob.glob(os.path.join(experiment, 'step.*')):
        shutil.rmtree(dname)
    for dname in glob.glob(os.path.join(experiment, 'run.*')):
        shutil.rmtree(dname)

def main():
    import argparse
    from dakota_utils import __version__, cleanup_script

    parser = argparse.ArgumentParser(
        description="Cleans up the results of a Dakota experiment.")
    parser.add_argument("experiment",
                        help="path to directory with Dakota experiment files")
    parser.add_argument('--version', action='version',
                        version=cleanup_script + ' ' + __version__)
    args = parser.parse_args()

    if os.path.isdir(args.experiment) is False:
        print('Error: Experiment path does not exist.')
        return
    else:
        cleanup_experiment(args.experiment)

if __name__ == '__main__':
    main()


text:
<?php
/**
 * Create new webhook
 *
 * http://api.jotform.com/docs/#post-form-id-webhooks
 */

require '../../vendor/autoload.php';

$key = 'your-api-key-from-jotform';

$client = new JotForm\JotFormClient();
$client->setAPIKey($key);

$form = new JotForm\Resource\Form($client);

try {
    $formId = 'form-ID-here';
    $webhook = [
            'webhookURL' => 'http://www.mywebsite.com/jotform/webhook'
    ];
    $response = $form->createFormWebhook($formId, $webhook);
    print_r($response);
} catch (\JotForm\Exception\ClientException $e) {
    echo $e->getMessage() . "\n";
}


text:
const decache = require('decache');
const isSubset = require('is-subset');

/**
 * Finds the matching endpoint among the provided endpoints, returns false if there are no matches
 * @param  {Object} req       An Express.js request object
 * @param  {Array} endpoints  An array of fejk endpoints
 * @return {Object}           A single fejk endpoint, or undefined if no matches can be found
 */
const findMatchingEndpoint = (req, endpoints) => {
  const matches = endpoints.filter(endpoint => {
    const { request } = endpoint;

    if (typeof request === 'function') {
      return request(req);
    }

    const valid = request && Object.keys(request).length;
    if (!valid) {
      return false;
    }

    let match = true;

    Object.keys(request).forEach(key => {
      if (typeof (request[key]) === 'object') {
        const set = Object.assign({}, request[key]);
        const subset = Object.assign({}, req[key]);
        match = match && isSubset(subset, set);
      } else if (key === 'path') {
        const regexp = RegExp(request[key]);
        match = match && regexp.test(req[key]);
      } else {
        match = match && req[key] === request[key];
      }
    });

    return match;
  });

  return matches.length ? matches[0] : undefined;
};

/**
 * Fetches the response object for the fejk object matching the incoming request, or undefined
 * if there is no response matching the incoming request.
 * @param  {Object} req     An Express request object
 * @param  {Object} options An options object
 * @return {Object}         A fejk response object
 */
const loadScenario = (req, options) => {
  const { logger, path, scenario: defaultScenario } = options;
  let response;

  try {
    const scenarioModule = req.query.scenario || defaultScenario;
    const fullScenarioPath = `${path}/${scenarioModule}`;

    // See https://github.com/dwyl/decache/pull/37
    if (typeof jest !== 'undefined') {
      jest.resetModules(); // eslint-disable-line
    } else {
      // clear module from require cache
      decache(fullScenarioPath);
    }

    const scenario = require(fullScenarioPath); // eslint-disable-line
    const { endpoints } = scenario;

    response = findMatchingEndpoint(req, endpoints);
  } catch (err) {
    logger.error('Scenario server error:', err);
  }

  return response;
};

/**
 * Parse response data from endpoint
 * @param  {Object} req       An Express.js request object
 * @param  {Object} endpoint  A fejk response object
 * @return {Object}           Response data for the matching request
 */
const responseData = (req, endpoint) => {
  if (typeof (endpoint.response.data) === 'function') {
    return endpoint.response.data(req);
  }
  return endpoint.response.data || 'OK';
};

module.exports = {
  findMatchingEndpoint,
  loadScenario,
  responseData,
};


text:
net use Z: /DELETE
vagrant halt


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.templates.commands;

/**
 *
 * @author Developer
 */
public class LauncherIncrementUp extends CommandBase {

    public LauncherIncrementUp() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(launcher);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
        launcher.upSpeed();
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return true;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
//
//  showView.m
//  DeliciousMenu
//
//  Created by scjy on 16/3/5.
//  Copyright © 2016年 刘海艳. All rights reserved.
//

#import "showView.h"

@interface showView ()

@end

@implementation showView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
import React from 'react';
import { StyleSheet, ScrollView } from 'react-native';
import Row from '../components/Row';

class Actions extends React.Component {

  constructor(props) {
    super(props);

    this._fab = false;
    this._rightButton = null;
    this._contextualMenu = false;
    this._toggleTabs = 'shown';
    this._toggleNavBar = 'shown';
    this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
  }

  onNavigatorEvent(event) {
    if (event.id === 'contextualMenuDismissed') {
      this._contextualMenu = false;
    }
  }

  setTitle = () => {
    this.props.navigator.setTitle({
      title: 'New Title!',
    });
  };

  toggleTabs = () => {
    const to = this._toggleTabs === 'shown' ? 'hidden' : 'shown';

    this.props.navigator.toggleTabs({
      to,
      animated: true,
    });
    this._toggleTabs = to;
  };

  setTabBadge = () => {
    this.props.navigator.setTabBadge({
      tabIndex: 1,
      badge: Math.floor(Math.random() * 20) + 1,
    });
  };

  switchToTab = () => {
    this.props.navigator.switchToTab({
      tabIndex: 0,
    });
  };

  toggleNavBar = () => {
    const to = this._toggleNavBar === 'shown' ? 'hidden' : 'shown';

    this.props.navigator.toggleNavBar({
      to,
      animated: true,
    });
    this._toggleNavBar = to;
  };

  showSnackbar = () => {
    this.props.navigator.showSnackbar({
      title: 'Woo Snacks!',
    });
  };

  toggleContextualMenu = () => {
    if (!this._contextualMenu) {
      this.props.navigator.showContextualMenu({
        rightButtons: [{
          title: 'Edit',
          icon: require('../../img/edit.png'),
        }, {
          title: 'Delete',
          icon: require('../../img/delete.png'),
        }],
        onButtonPressed: (index) => console.log(`Button ${index} tapped`)
      });
      this._contextualMenu = true;
    } else {
      this.props.navigator.dismissContextualMenu();
      this._contextualMenu = false;
    }

  };

  setButtons = () => {
    let title = '';

    if (!this._rightButton) {
      title = 'Hello';
    } else if (this._rightButton === 'Hello') {
      title = 'Its Me';
    }

    this.props.navigator.setButtons({
      rightButtons: [{
        title,
        id: 'topRight',
      }],
      animated: true,
    });
    this._rightButton = title;
  };

  toggleFAB = () => {
    if (this._fab) {
      this.props.navigator.setButtons({
        fab: {},
      });
      this._fab = false;
    } else {
      this.props.navigator.setButtons({
        fab: {
          collapsedId: 'share',
          collapsedIcon: require('../../img/edit@1x.png'),
          expendedId: 'clear',
          expendedIcon: require('../../img/edit@1x.png'),
          backgroundColor: '#ff505c',
          actions: [
            {
              id: 'mail',
              icon: require('../../img/edit@1x.png'),
              backgroundColor: '#03A9F4'
            },
            {
              id: 'delete',
              icon: require('../../img/delete@1x.png'),
              backgroundColor: '#4CAF50'
            }
          ]
        },
        animated: true,
      });
      this._fab = true;
    }
  };

  render() {
    return (
      <ScrollView style={styles.container}>
        <Row title={'Set Title'} onPress={this.setTitle} />
        <Row title={'Toggle Tabs'} onPress={this.toggleTabs} />
        <Row title={'Set Tab Badge'} onPress={this.setTabBadge} />
        <Row title={'Switch To Tab 0'} onPress={this.switchToTab} />
        <Row title={'Toggle Nav Bar'} onPress={this.toggleNavBar} />
        <Row title={'Show Snackbar'} onPress={this.showSnackbar} platform={'android'} />
        <Row title={'Toggle Contextual Menu'} onPress={this.toggleContextualMenu} platform={'android'} />
        <Row title={'Set Right Buttons'} onPress={this.setButtons} />
        <Row title={'Toggle FAB'} onPress={this.toggleFAB} platform={'android'} />
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {},
});

export default Actions;


text:
/***************************************
*  Compiler Options
***************************************/
/* Disable some Visual warning messages */
#define _CRT_SECURE_NO_WARNINGS                  /* fopen */

// Unix Large Files support (>4GB)
#define _FILE_OFFSET_BITS 64
#if (defined(__sun__) && (!defined(__LP64__)))   // Sun Solaris 32-bits requires specific definitions
#  define _LARGEFILE_SOURCE
#elif ! defined(__LP64__)                        // No point defining Large file for 64 bit
#  define _LARGEFILE64_SOURCE
#endif

// S_ISREG & gettimeofday() are not supported by MSVC
#if defined(_MSC_VER) || defined(_WIN32)
#  define BMK_LEGACY_TIMER 1
#endif

/**************************************
*  Includes
**************************************/
#include <stdlib.h>      /* malloc, free */
#include <string.h>      /* memset */
#include <stdio.h>       // fprintf, fopen, ftello64
#include <sys/types.h>   // stat64
#include <sys/stat.h>    // stat64

// Use ftime() if gettimeofday() is not available on your target
#if defined(BMK_LEGACY_TIMER)
#  include <sys/timeb.h>   // timeb, ftime
#else
#  include <sys/time.h>    // gettimeofday
#endif

#include "zstd.h"
#include "xxhash.h"

/**************************************
*  Compiler specifics
**************************************/
#if !defined(S_ISREG)
#  define S_ISREG(x) (((x) & S_IFMT) == S_IFREG)
#endif

/**************************************
*  Basic Types
**************************************/
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
# include <stdint.h>
  typedef uint8_t  BYTE;
  typedef uint16_t U16;
  typedef uint32_t U32;
  typedef  int32_t S32;
  typedef uint64_t U64;
#else
  typedef unsigned char       BYTE;
  typedef unsigned short      U16;
  typedef unsigned int        U32;
  typedef   signed int        S32;
  typedef unsigned long long  U64;
#endif

/**************************************
*  Constants
**************************************/
#define NBLOOPS    3
#define TIMELOOP   2500

#define KB *(1 <<10)
#define MB *(1 <<20)
#define GB *(1U<<30)

#define MAX_MEM             (2 GB - 64 MB)
#define DEFAULT_CHUNKSIZE   (4 MB)

static U32 g_compressibilityDefault = 50;
static U32 prime1 = 2654435761U;
static U32 prime2 = 2246822519U;

/**************************************
*  Macros
**************************************/
#define DISPLAY(...) fprintf(stderr, __VA_ARGS__)

/**************************************
*  Benchmark Parameters
**************************************/
static int nbIterations = NBLOOPS;

void BMK_SetNbIterations(int nbLoops)
{
    nbIterations = nbLoops;
    DISPLAY("- %i iterations -\n", nbIterations);
}

/*********************************************************
*  Private functions
*********************************************************/

#if defined(BMK_LEGACY_TIMER)

static int BMK_GetMilliStart(void)
{
  /* Based on Legacy ftime()
  *  Rolls over every ~ 12.1 days (0x100000/24/60/60)
  *  Use GetMilliSpan to correct for rollover */
  struct timeb tb;
  int nCount;
  ftime( &tb );
  nCount = (int) (tb.millitm + (tb.time & 0xfffff) * 1000);
  return nCount;
}

#else

static int BMK_GetMilliStart(void)
{
  /* Based on newer gettimeofday()
  *  Use GetMilliSpan to correct for rollover */
  struct timeval tv;
  int nCount;
  gettimeofday(&tv, NULL);
  nCount = (int) (tv.tv_usec/1000 + (tv.tv_sec & 0xfffff) * 1000);
  return nCount;
}

#endif

static int BMK_GetMilliSpan( int nTimeStart )
{
  int nSpan = BMK_GetMilliStart() - nTimeStart;
  if ( nSpan < 0 )
    nSpan += 0x100000 * 1000;
  return nSpan;
}

/*********************************************************
*  Data generator
*********************************************************/
/* will hopefully be converted into ROL instruction by compiler */
static U32 BMK_rotl32(unsigned val32, unsigned nbBits) { return((val32 << nbBits) | (val32 >> (32 - nbBits))); }

static U32 BMK_rand(U32* src)
{
    U32 rand32 = *src;
    rand32 *= prime1;
    rand32 += prime2;
    rand32 = BMK_rotl32(rand32, 13);
    *src = rand32;
    return rand32 >> 9;
}

#define BMK_RAND15BITS  ( BMK_rand(&seed) & 0x7FFF)
#define BMK_RANDLENGTH  ((BMK_rand(&seed) & 3) ? (BMK_rand(&seed) % 15) : (BMK_rand(&seed) % 510) + 15)
#define BMK_RANDCHAR    (BYTE)((BMK_rand(&seed) & 63) + '0')
static void BMK_datagen(void* buffer, size_t bufferSize, double proba, U32 seed)
{
    BYTE* BBuffer = (BYTE*)buffer;
    unsigned pos = 0;
    U32 P32 = (U32)(32768 * proba);

    /* First Byte */
    BBuffer[pos++] = BMK_RANDCHAR;

    while (pos < bufferSize)
    {
        /* Select : Literal (noise) or copy (within 64K) */
        if (BMK_RAND15BITS < P32)
        {
            /* Match */
            size_t match, end;
            unsigned length = BMK_RANDLENGTH + 4;
            unsigned offset = BMK_RAND15BITS + 1;
            if (offset > pos) offset = pos;
            match = pos - offset;
            end = pos + length;
            if (end > bufferSize) end = bufferSize;
            while (pos < end) BBuffer[pos++] = BBuffer[match++];
        }
        else
        {
            /* Literal */
            size_t end;
            unsigned length = BMK_RANDLENGTH;
            end = pos + length;
            if (end > bufferSize) end = bufferSize;
            while (pos < end) BBuffer[pos++] = BMK_RANDCHAR;
        }
    }
}

/*********************************************************
*  Bench functions
*********************************************************/

static int BMK_benchMem(void* srcBuffer, size_t srcSize, char* fileName, int cLevel)
{
    size_t maxCompressedSize = ZSTD_compressBound(srcSize);
    void* compressedBuffer = malloc(maxCompressedSize);
    void* resultBuffer = malloc(srcSize);
    U64 crcOrig;

    /* Init */
    (void)cLevel;

    /* Memory allocation & restrictions */
    if (!compressedBuffer || !resultBuffer)
    {
        DISPLAY("\nError: not enough memory!\n");
        free(compressedBuffer);
        free(resultBuffer);
        return 12;
    }

    /* Calculating input Checksum */
    crcOrig = XXH64(srcBuffer, srcSize, 0);

    /* warmimg up memory */
    BMK_datagen(compressedBuffer, maxCompressedSize, 0.10, 1);   /* warmimg up memory */

    /* Bench */
    {
        int loopNb;
        size_t cSize = 0;
        double fastestC = 100000000., fastestD = 100000000.;
        double ratio = 0.;
        U64 crcCheck = 0;

        DISPLAY("\r%79s\r", "");
        for (loopNb = 1; loopNb <= nbIterations; loopNb++)
        {
            int nbLoops;
            int milliTime;

            /* Compression */
            DISPLAY("%1i-%-14.14s : %9u ->\r", loopNb, fileName, (U32)srcSize);
            memset(compressedBuffer, 0xE5, maxCompressedSize);

            nbLoops = 0;
            milliTime = BMK_GetMilliStart();
            while (BMK_GetMilliStart() == milliTime);
            milliTime = BMK_GetMilliStart();
            while (BMK_GetMilliSpan(milliTime) < TIMELOOP)
            {
                cSize = ZSTD_compress(compressedBuffer, maxCompressedSize, srcBuffer, srcSize);
                nbLoops++;
            }
            milliTime = BMK_GetMilliSpan(milliTime);

            if ((double)milliTime < fastestC*nbLoops) fastestC = (double)milliTime / nbLoops;
            ratio = (double)cSize / (double)srcSize*100.;
            DISPLAY("%1i-%-14.14s : %9i -> %9i (%5.2f%%),%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000.);

#if 1
            /* Decompression */
            memset(resultBuffer, 0xD6, srcSize);

            nbLoops = 0;
            milliTime = BMK_GetMilliStart();
            while (BMK_GetMilliStart() == milliTime);
            milliTime = BMK_GetMilliStart();
            for ( ; BMK_GetMilliSpan(milliTime) < TIMELOOP; nbLoops++)
            {
                size_t result = ZSTD_decompress(resultBuffer, srcSize, compressedBuffer, cSize);
                if (ZSTD_isError(result))
                {
                    DISPLAY("\n!!! Decompression error !!! %s  !\n", ZSTD_getErrorName(result));
                    break;
                }
            }
            milliTime = BMK_GetMilliSpan(milliTime);

            if ((double)milliTime < fastestD*nbLoops) fastestD = (double)milliTime / nbLoops;
            DISPLAY("%1i-%-14.14s : %9i -> %9i (%5.2f%%),%7.1f MB/s ,%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.);

            /* CRC Checking */
            crcCheck = XXH64(resultBuffer, srcSize, 0);
            if (crcOrig!=crcCheck)
            {
                unsigned i;
                DISPLAY("\n!!! WARNING !!! %14s : Invalid Checksum : %x != %x\n", fileName, (unsigned)crcOrig, (unsigned)crcCheck);
                for (i=0; i<srcSize; i++)
                {
                    if (((BYTE*)srcBuffer)[i] != ((BYTE*)resultBuffer)[i])
                    {
                        printf("\nDecoding error at pos %u   \n", i);
                        break;
                    }
                }
                break;
            }
#endif
        }

        if (crcOrig == crcCheck)
        {
            if (ratio<100.)
                DISPLAY("%-16.16s : %9i -> %9i (%5.2f%%),%7.1f MB/s ,%7.1f MB/s\n", fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.);
            else
                DISPLAY("%-16.16s : %9i -> %9i (%5.1f%%),%7.1f MB/s ,%7.1f MB/s \n", fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.);
        }
    }

    /* End cleaning */
    free(compressedBuffer);
    free(resultBuffer);
    return 0;
}

static U64 BMK_GetFileSize(char* infilename)
{
    int r;
#if defined(_MSC_VER)
    struct _stat64 statbuf;
    r = _stat64(infilename, &statbuf);
#else
    struct stat statbuf;
    r = stat(infilename, &statbuf);
#endif
    if (r || !S_ISREG(statbuf.st_mode)) return 0;   /* No good... */
    return (U64)statbuf.st_size;
}

static size_t BMK_findMaxMem(U64 requiredMem)
{
    size_t step = 64 MB;
    BYTE* testmem = NULL;

    requiredMem = (((requiredMem >> 26) + 1) << 26);
    requiredMem += 2 * step;
    if (requiredMem > MAX_MEM) requiredMem = MAX_MEM;

    while (!testmem)
    {
        requiredMem -= step;
        testmem = (BYTE*)malloc((size_t)requiredMem);
    }

    free(testmem);
    return (size_t)(requiredMem - step);
}

static int BMK_benchOneFile(char* inFileName, int cLevel)
{
    FILE*  inFile;
    U64    inFileSize;
    size_t benchedSize, readSize;
    void* srcBuffer;
    int result;

    /* Init */
    (void)cLevel;

    // Check file existence
    inFile = fopen(inFileName, "rb");
    if (inFile == NULL)
    {
        DISPLAY("Pb opening %s\n", inFileName);
        return 11;
    }

    // Memory allocation & restrictions
    inFileSize = BMK_GetFileSize(inFileName);
    benchedSize = BMK_findMaxMem(inFileSize * 3) / 3;
    if ((U64)benchedSize > inFileSize) benchedSize = (size_t)inFileSize;
    if (benchedSize < inFileSize)
        DISPLAY("Not enough memory for '%s' full size; testing %i MB only...\n", inFileName, (int)(benchedSize >> 20));

    // Alloc
    srcBuffer = malloc(benchedSize);

    if (!srcBuffer)
    {
        DISPLAY("\nError: not enough memory!\n");
        free(srcBuffer);
        fclose(inFile);
        return 12;
    }

    // Fill input buffer
    DISPLAY("Loading %s...       \r", inFileName);
    readSize = fread(srcBuffer, 1, benchedSize, inFile);
    fclose(inFile);

    if (readSize != benchedSize)
    {
        DISPLAY("\nError: problem reading file '%s' !!    \n", inFileName);
        free(srcBuffer);
        return 13;
    }

    // Bench
    result = BMK_benchMem(srcBuffer, benchedSize, inFileName, cLevel);

    // End
    free(srcBuffer);
    DISPLAY("\n");
    return result;
}

static int BMK_syntheticTest(int cLevel, double compressibility)
{
    size_t benchedSize = 10000000;
    void* srcBuffer = malloc(benchedSize);
    int result;
    char name[20] = {0};

    /* Init */
    (void)cLevel;

    /* Memory allocation */
    if (!srcBuffer)
    {
        DISPLAY("\nError: not enough memory!\n");
        free(srcBuffer);
        return 12;
    }

    /* Fill input buffer */
    BMK_datagen(srcBuffer, benchedSize, compressibility, 0);

    /* Bench */
#ifdef _MSC_VER
    sprintf_s(name, 20, "Synthetic %2u%%", (unsigned)(compressibility*100));
#else
    snprintf (name, 20, "Synthetic %2u%%", (unsigned)(compressibility*100));
#endif
    result = BMK_benchMem(srcBuffer, benchedSize, name, cLevel);

    /* End */
    free(srcBuffer);
    DISPLAY("\n");
    return result;
}

int BMK_benchFiles(char** fileNamesTable, unsigned nbFiles, unsigned cLevel)
{
    double compressibility = (double)g_compressibilityDefault / 100;

    if (nbFiles == 0)
    {
        BMK_syntheticTest(cLevel, compressibility);
    }
    else
    {
        /* Loop for each file */
        unsigned fileIdx = 0;
        while (fileIdx<nbFiles)
        {
            BMK_benchOneFile(fileNamesTable[fileIdx], cLevel);
            fileIdx++;
        }
    }
    return 0;
}