text:
#region Using Directives
using System;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Xml.Serialization;
using Microsoft.Practices.EnterpriseLibrary.Data;
using PetShop.Business;
#endregion

namespace PetShop.Data.SqlClient
{
	/// <summary>
	/// Summary description for Procedures.
	/// </summary>
	[Serializable()]
	[XmlRoot("root")]
	public sealed class StoredProcedureProvider
	{
		private ArrayList procedures;
		private Hashtable shortNameProcedures;
		private Hashtable longNameProcedures;
		private static StoredProcedureProvider current = null;
		private static object syncRoot = new object();

		/// <summary>
		/// Creates a new <see cref="StoredProcedureProvider"/> instance.
		/// </summary>
		public StoredProcedureProvider()
		{
			procedures = new ArrayList();
		}

		/// <summary>
		/// Gets the current <see cref="StoredProcedureProvider"/> singleton instance.
		/// </summary>
		/// <value><see cref="StoredProcedureProvider"/></value>
		public static StoredProcedureProvider Current
		{
			get
			{
				if (current == null)
				{
					lock(syncRoot)
					{
						if (current == null)
						{
							current = (StoredProcedureProvider) StoredProcedureProvider.Deserialize();
						}
					}
				}
				return current;
			}
		}

		/// <summary>
		/// Gets or sets the procedures.
		/// </summary>
		/// <value>An <see cref="ArrayList"/> of <see cref="Procedure"/> objects.</value>
		[XmlArray("procedures")]
		[XmlArrayItem("procedure",typeof(Procedure))]
		public ArrayList Procedures
		{
			get
			{
				return procedures;
			}
			set
			{
				procedures = value;
				InitializeProcedureLookupTables();
			}
		}

		#region Public

		/// <summary>
		/// Gets or sets the <see cref="Procedure"/> instance with the specified name.
		/// </summary>
		public Procedure this[string name]
		{
			get
			{
				lock(syncRoot)
				{
					if (longNameProcedures == null)
						InitializeProcedureLookupTables();
				}

				Procedure result = null;

				result = longNameProcedures[name] as Procedure;
				if (result == null)
				{
					result = shortNameProcedures[name] as Procedure;
				}
				return result;
			}
		}

		/// <summary>
		/// Gets or sets the <see cref="Procedure"/> instance at the specified index.
		/// </summary>
		public Procedure this[int index]
		{
			get
			{
				return (Procedure) procedures[index];
			}
		}

		#endregion

		#region Serialization

		/// <summary>
		/// Serializes the specified filename.
		/// </summary>
		/// <param name="filename">Filename.</param>
		public void Serialize(string filename)
		{
			if (System.IO.File.Exists(filename))
			{
				System.IO.File.Delete(filename);
			}
			System.IO.FileStream fileStream = new System.IO.FileStream(filename,System.IO.FileMode.CreateNew,System.IO.FileAccess.ReadWrite,System.IO.FileShare.ReadWrite);
			XmlSerializer serializer = new XmlSerializer(this.GetType());
			serializer.Serialize(fileStream,this);
			fileStream.Close();
		}

		#endregion

		#region Deserialization

		/// <summary>
		/// Deserializes this instance.
		/// </summary>
		/// <returns></returns>
		private static object Deserialize ()
		{
			string nameSpace = "PetShop.Data.SqlClient"; //System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
			string resourceName = string.Format("{0}.Procedures.xml",nameSpace);
			System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
			XmlSerializer serializer = new XmlSerializer(typeof(StoredProcedureProvider));
			return serializer.Deserialize(stream);
		}

		#endregion

		#region Embedded XML Queries

		/// <summary>
	    /// Get the query text from the embedded xml file.
	    /// </summary>
	    /// <param name="name">The name of the query.</param>
	    /// <returns>the text of the query</returns>
	    private static string GetProcedureBodyFromEmbeddedResource(string name)
		{
			Procedure procedure = StoredProcedureProvider.Current[name];

			if ( procedure == null)
				throw new ApplicationException("cannot find the query '" + name + "' in the embedded xml file.");
			else
				return StoredProcedureProvider.Current[name].Body;
		}

		/// <summary>
		/// Get the command wrapper, either from the stored procedures or from the embedded queries.
		/// </summary>
		/// <param name="database">The database instance.</param>
		/// <param name="commandName">the name of the sp.</param>
		/// <param name="useStoredProcedure">Indicates if we want stored procedure.</param>
		/// <returns></returns>
		public static DbCommand GetCommandWrapper(Database database, string commandName, bool useStoredProcedure)
		{
			if (useStoredProcedure)
			{
				DbCommand command = database.GetStoredProcCommand(commandName);
                command.CommandTimeout = DataRepository.Provider.DefaultCommandTimeout;
                return command;
			}
			else
			{
                DbCommand command =
                    database.GetSqlStringCommand(StoredProcedureProvider.GetProcedureBodyFromEmbeddedResource(commandName));
                command.CommandTimeout = DataRepository.Provider.DefaultCommandTimeout;
                return command;
            }
		}

		/// <summary>
		/// Gets the command wrapper for a dynamically generated query and
		/// optionally includes server-side paging.
		/// </summary>
		/// <param name="database"></param>
		/// <param name="commandName"></param>
		/// <param name="columnEnum"></param>
		/// <param name="parameters"></param>
		/// <param name="orderBy"></param>
		/// <param name="start"></param>
		/// <param name="pageLength"></param>
		/// <returns></returns>
		public static DbCommand GetCommandWrapper(Database database, String commandName, Type columnEnum, SqlFilterParameterCollection parameters, String orderBy, int start, int pageLength)
		{
			String query = StoredProcedureProvider.GetProcedureBodyFromEmbeddedResource(commandName);
			//query = query.Replace(SqlUtil.PAGE_INDEX, string.Concat(SqlUtil.PAGE_INDEX, Guid.NewGuid().ToString("N").Substring(0,8)));
			String sortExpression = Utility.ParseSortExpression(columnEnum, orderBy);
			String whereClause = String.Empty;

			if ( parameters != null && ! String.IsNullOrEmpty(parameters.FilterExpression) )
			{
				whereClause = String.Format("where {0}", parameters.FilterExpression);
			}

			// replace dynamic components
			query = String.Format(query, whereClause, sortExpression, start, (start + pageLength));

            DbCommand command = database.GetSqlStringCommand(query);
            command.CommandTimeout = DataRepository.Provider.DefaultCommandTimeout;
            return command;
		}

		#endregion

		private void InitializeProcedureLookupTables()
		{
			lock (syncRoot)
            {

				shortNameProcedures = Hashtable.Synchronized(new Hashtable());
				longNameProcedures = Hashtable.Synchronized(new Hashtable());

				foreach (Procedure procedure in procedures)
				{
					shortNameProcedures[procedure.Name] = procedure;
					longNameProcedures[procedure.Owner + "." + procedure.Name] = procedure;
				}
			}
		}
	}

	/// <summary>
	/// Represents a sql query.
	/// </summary>
	[Serializable()]
	public class Procedure
	{
		/// <summary>
		/// Creates a new <see cref="Procedure"/> instance.
		/// </summary>
		public Procedure()
		{
			parameters = new ArrayList();
		}

		private ArrayList parameters;

		/// <summary>
		/// Gets or sets the parameters.
		/// </summary>
		/// <value></value>
		[XmlArray("parameters")]
		[XmlArrayItem("parameter",typeof(Parameter))]
		public ArrayList Parameters
		{
			get{return parameters;}
			set{parameters = value;}
		}

		private string name;

		/// <summary>
		/// Gets or sets the name.
		/// </summary>
		/// <value></value>
		[XmlAttribute("name")]
		public string Name
		{
			get{ return name;}
			set
			{
				name = value;
			}
		}

		private string owner;

      /// <summary>
      /// Gets or sets the owner.
      /// </summary>
      /// <value></value>
      [XmlAttribute("owner")]
      public string Owner
      {
         get { return owner; }
         set
         {
            owner = value;
         }
      }

		private string comment;

		/// <summary>
		/// Gets or sets the comment.
		/// </summary>
		/// <value></value>
		[XmlElement("comment")]
		public string Comment
		{
			get
			{
				return comment;
			}
			set
			{
				comment = value;
			}
		}

		private string body;

		/// <summary>
		/// Gets or sets the body.
		/// </summary>
		/// <value></value>
		[XmlElement("body")]
		public string Body
		{
			get{return body;}
			set{body = value;}
		}

		/// <summary>
		/// Get the parameter from the specified name of the param.
		/// </summary>
		/// <param name="paramName">Name of the param.</param>
		/// <returns></returns>
		public Parameter Parameter(string paramName)
		{
			foreach(Parameter parameter in parameters)
			{
				if(parameter.Name == paramName)
				{
					return parameter;
				}
			}
			return null;
		}
	}

	/// <summary>
	/// Respresents a query parameter.
	/// </summary>
	[Serializable()]
	public class Parameter
	{
		/// <summary>
		/// Creates a new <see cref="Parameter"/> instance.
		/// </summary>
		public Parameter(){}

		private string name;

		/// <summary>
		/// Gets or sets the Name.
		/// </summary>
		/// <value></value>
		[XmlAttribute("name")]
		public string Name
		{
			get{return name;}
			set{name = value;}
		}

		private string sqltype;
		/// <summary>
		/// Gets or sets the SqlType.
		/// </summary>
		/// <value></value>
		[XmlAttribute("type")]
		public string SqlType
		{
			get{return sqltype;}
			set{sqltype = value;}
		}

		private System.Data.ParameterDirection direction;
		/// <summary>
		/// Gets or sets the Direction.
		/// </summary>
		/// <value></value>
		[XmlAttribute("direction")]
		public System.Data.ParameterDirection Direction
		{
			get{return direction;}
			set{direction = value;}
		}

		private int size;
		/// <summary>
		/// Gets or sets the size.
		/// </summary>
		/// <value></value>
		[XmlAttribute("size")]
		public int Size
		{
			get{return size;}
			set{size = value;}
		}

		private int precision;
		/// <summary>
		/// Gets or sets the precision.
		/// </summary>
		/// <value></value>
		[XmlAttribute("precision")]
		public int Precision
		{
			get{return precision;}
			set{precision = value;}
		}

		private int scale;
		/// <summary>
		/// Gets or sets the scale.
		/// </summary>
		/// <value></value>
		[XmlAttribute("scale")]
		public int Scale
		{
			get{return scale;}
			set{scale = value;}
		}
	}

}


text:
Calculates damping from amplitude ratio

This takes input of two sucessive amplitudes and computes the damping ratio usng logarithmic decrement.

redpajama_set_name: RedPajamaGithub


text:
//
// Generated by JTB 1.2.2++
//

package com.mod_snmp.SmiParser.SyntaxTree;

/**
 * Grammar production:
 * <PRE>
 * -> <SYNTAX_T>
 * type -> Types()
 * </PRE>
 */
public class SyntaxPart implements Node {
    private Node parent;
    public Type type;

    public SyntaxPart(Type n0) {
        type = n0;
        if ( type != null ) type.setParent(this);
    }
    public String toString() {
        return "SYNTAX" + type.toString();
    }
    public int line() {
        return type.line();
    }
    public void setGenericType(Type type) {
        type.setGenericType(type);
    }
    public Type getGenericType() {
        return type.getGenericType();
    }
    public boolean isGenericType() {
        return type.isGenericType();
    }
    public boolean restrictionPresent() {
        return type.restrictionPresent();
    }
    public void accept(com.mod_snmp.SmiParser.Visitor.Visitor v) {
        v.visit(this);
    }
    public Object accept(com.mod_snmp.SmiParser.Visitor.ObjectVisitor v, Object argu) {
        return v.visit(this,argu);
    }
    public void setParent(Node n) { parent = n; }
    public Node getParent()       { return parent; }
}


text:
import pytest
import requests
import shutil
import signal
import subprocess as sp
import time

_proxy_bypass = {
  "http": None,
  "https": None,
}

def start_service(service_name, host, port):
    moto_svr_path = shutil.which("moto_server")
    args = [moto_svr_path, service_name, "-H", host, "-p", str(port)]
    # For debugging
    # args = '{0} {1} -H {2} -p {3} 2>&1 | tee -a /tmp/moto.log'.format(moto_svr_path, service_name, host, port)
    process = sp.Popen(args, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)  # shell=True
    url = "http://{host}:{port}".format(host=host, port=port)

    for i in range(0, 30):
        output = process.poll()
        if output is not None:
            print('moto_server exited status {0}'.format(output))
            stdout, stderr = process.communicate()
            print('moto_server stdout: {0}'.format(stdout))
            print('moto_server stderr: {0}'.format(stderr))
            pytest.fail("Can not start service: {}".format(service_name))

        try:
            # we need to bypass the proxies due to monkeypatches
            requests.get(url, timeout=5, proxies=_proxy_bypass)
            break
        except requests.exceptions.ConnectionError:
            time.sleep(0.5)
    else:
        stop_process(process)  # pytest.fail doesn't call stop_process
        pytest.fail("Can not start service: {}".format(service_name))

    return process

def stop_process(process):
    try:
        process.send_signal(signal.SIGTERM)
        process.communicate(timeout=20)
    except sp.TimeoutExpired:
        process.kill()
        outs, errors = process.communicate(timeout=20)
        exit_code = process.returncode
        msg = "Child process finished {} not in clean way: {} {}" \
            .format(exit_code, outs, errors)
        raise RuntimeError(msg)

@pytest.fixture(scope="session")
def dynamodb2_server():
    host = "localhost"
    port = 5001
    url = "http://{host}:{port}".format(host=host, port=port)
    process = start_service('dynamodb', host, port)
    yield url
    stop_process(process)

@pytest.fixture(scope="session")
def s3_server():
    host = "localhost"
    port = 5002
    url = "http://{host}:{port}".format(host=host, port=port)
    process = start_service('s3', host, port)
    yield url
    stop_process(process)

@pytest.fixture(scope="session")
def kms_server():
    host = "localhost"
    port = 5003
    url = "http://{host}:{port}".format(host=host, port=port)
    process = start_service('kms', host, port)
    yield url
    stop_process(process)


text:
<?xml version="1.0" encoding="utf-8"?>
<reflection>
  <assemblies>
    <assembly name="System.ServiceModel.DomainServices.Server">
      <assemblydata version="4.0.0.0" culture="" key="0024000004800000940000000602000000240000525341310004000001000100B5FC90E7027F67871E773A8FDE8938C81DD402BA65B9201D60593E96C492651E889CC13F1415EBB53FAC1131AE0BD333C5EE6021672D9718EA31A8AEBD0DA0072F25D87DBA6FC90FFD598ED4DA35E44C398C454307E8E33B8426143DAEC9F596836F97C8F74750E5975C64E2189F45DEF46B2A2B1247ADC3652BF5C308055DA9" hash="SHA1" />
      <attributes>
        <attribute>
          <type api="T:System.Reflection.AssemblyDescriptionAttribute" ref="true" />
          <argument>
            <type api="T:System.String" ref="true" />
            <value>System.ServiceModel.DomainServices.Server.dll</value>
          </argument>
        </attribute>
        <attribute>
          <type api="T:System.Runtime.CompilerServices.ExtensionAttribute" ref="true" />
        </attribute>
        <attribute>
          <type api="T:System.Reflection.AssemblyFileVersionAttribute" ref="true" />
          <argument>
            <type api="T:System.String" ref="true" />
            <value>4.1.61829.0</value>
          </argument>
        </attribute>
        <attribute>
          <type api="T:System.Reflection.AssemblyTitleAttribute" ref="true" />
          <argument>
            <type api="T:System.String" ref="true" />
            <value>System.ServiceModel.DomainServices.Server</value>
          </argument>
        </attribute>
        <attribute>
          <type api="T:System.Runtime.InteropServices.GuidAttribute" ref="true" />
          <argument>
            <type api="T:System.String" ref="true" />
            <value>72e74082-7928-4a70-83c1-49806b942fcb</value>
          </argument>
        </attribute>
        <attribute>
          <type api="T:System.Reflection.AssemblyCompanyAttribute" ref="true" />
          <argument>
            <type api="T:System.String" ref="true" />
            <value>Microsoft Corporation</value>
          </argument>
        </attribute>
        <attribute>
          <type api="T:System.Reflection.AssemblyProductAttribute" ref="true" />
          <argument>
            <type api="T:System.String" ref="true" />
            <value>WCF RIA Services</value>
          </argument>
        </attribute>
        <attribute>
          <type api="T:System.Reflection.AssemblyCopyrightAttribute" ref="true" />
          <argument>
            <type api="T:System.String" ref="true" />
            <value>© Microsoft Corporation.  All rights reserved.</value>
          </argument>
        </attribute>
        <attribute>
          <type api="T:System.Reflection.AssemblyTrademarkAttribute" ref="true" />
          <argument>
            <type api="T:System.String" ref="true" />
            <value />
          </argument>
        </attribute>
        <attribute>
          <type api="T:System.Runtime.InteropServices.ComVisibleAttribute" ref="true" />
          <argument>
            <type api="T:System.Boolean" ref="false" />
            <value>False</value>
          </argument>
        </attribute>
        <attribute>
          <type api="T:System.Reflection.AssemblyConfigurationAttribute" ref="true" />
          <argument>
            <type api="T:System.String" ref="true" />
            <value />
          </argument>
        </attribute>
        <attribute>
          <type api="T:System.CLSCompliantAttribute" ref="true" />
          <argument>
            <type api="T:System.Boolean" ref="false" />
            <value>True</value>
          </argument>
        </attribute>
        <attribute>
          <type api="T:System.Resources.NeutralResourcesLanguageAttribute" ref="true" />
          <argument>
            <type api="T:System.String" ref="true" />
            <value>en-US</value>
          </argument>
        </attribute>
      </attributes>
    </assembly>
  </assemblies>
  <apis>
    <api id="N:System.ServiceModel.DomainServices">
      <topicdata group="api" />
      <apidata name="System.ServiceModel.DomainServices" group="namespace" />
      <elements>
        <element api="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" />
        <element api="T:System.ServiceModel.DomainServices.ExternalReferenceAttribute" />
      </elements>
      <file name="180c3887-1604-23ef-2045-1c189a296cb5" />
    </api>
    <api id="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute">
      <topicdata group="api" allMembersTopicId="AllMembers.T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" />
      <apidata name="DomainIdentifierAttribute" group="type" subgroup="class" />
      <typedata visibility="public" serializable="false" />
      <family>
        <ancestors>
          <type api="T:System.Attribute" ref="true" />
          <type api="T:System.Object" ref="true" />
        </ancestors>
        <descendents>
          <type api="T:System.ServiceModel.DomainServices.Server.ApplicationServices.AuthenticationServiceAttribute" ref="true" />
        </descendents>
      </family>
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
        </library>
        <library assembly="System.ServiceModel.DomainServices.Client" module="System.ServiceModel.DomainServices.Client" kind="DynamicallyLinkedLibrary">
          <assemblydata version="2.0.5.0 (4.1.61829.0)" />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
      </containers>
      <attributes>
        <attribute>
          <type api="T:System.AttributeUsageAttribute" ref="true" />
          <argument>
            <type api="T:System.AttributeTargets" ref="false" />
            <enumValue>
              <field name="Class" />
            </enumValue>
          </argument>
          <assignment name="AllowMultiple">
            <type api="T:System.Boolean" ref="false" />
            <value>False</value>
          </assignment>
          <assignment name="Inherited">
            <type api="T:System.Boolean" ref="false" />
            <value>True</value>
          </assignment>
        </attribute>
      </attributes>
      <file name="ac8c99f7-8f0e-751b-3c8b-244769a45ba3" />
    </api>
    <api id="AllMembers.T:System.ServiceModel.DomainServices.DomainIdentifierAttribute">
      <topicdata name="DomainIdentifierAttribute" group="list" subgroup="members" typeTopicId="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" />
      <apidata name="DomainIdentifierAttribute" group="type" subgroup="class" />
      <typedata visibility="public" serializable="false" />
      <elements>
        <element api="M:System.Attribute.Equals(System.Object)" />
        <element api="M:System.Attribute.GetHashCode" />
        <element api="M:System.Attribute.Match(System.Object)" />
        <element api="M:System.Object.Finalize" />
        <element api="M:System.Object.GetType" />
        <element api="M:System.Object.MemberwiseClone" />
        <element api="M:System.Object.ToString" />
        <element api="M:System.ServiceModel.DomainServices.DomainIdentifierAttribute.#ctor(System.String)" />
        <element api="P:System.ServiceModel.DomainServices.DomainIdentifierAttribute.CodeProcessor">
          <libraries>
            <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary" />
          </libraries>
        </element>
        <element api="P:System.ServiceModel.DomainServices.DomainIdentifierAttribute.IsApplicationService" />
        <element api="P:System.ServiceModel.DomainServices.DomainIdentifierAttribute.Name" />
        <element api="P:System.ServiceModel.DomainServices.DomainIdentifierAttribute.TypeId">
          <libraries>
            <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary" />
          </libraries>
        </element>
      </elements>
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
        </library>
        <library assembly="System.ServiceModel.DomainServices.Client" module="System.ServiceModel.DomainServices.Client" kind="DynamicallyLinkedLibrary">
          <assemblydata version="2.0.5.0 (4.1.61829.0)" />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
        <type api="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" />
      </containers>
      <file name="d9b6a717-2186-cd54-edd2-7d4041b986eb" />
    </api>
    <api id="Methods.T:System.ServiceModel.DomainServices.DomainIdentifierAttribute">
      <topicdata name="DomainIdentifierAttribute" group="list" subgroup="Methods" typeTopicId="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" />
      <apidata name="DomainIdentifierAttribute" group="type" subgroup="class" />
      <typedata visibility="public" serializable="false" />
      <elements>
        <element api="M:System.Attribute.Equals(System.Object)" />
        <element api="M:System.Attribute.GetHashCode" />
        <element api="M:System.Attribute.Match(System.Object)" />
        <element api="M:System.Object.Finalize" />
        <element api="M:System.Object.GetType" />
        <element api="M:System.Object.MemberwiseClone" />
        <element api="M:System.Object.ToString" />
      </elements>
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
        </library>
        <library assembly="System.ServiceModel.DomainServices.Client" module="System.ServiceModel.DomainServices.Client" kind="DynamicallyLinkedLibrary">
          <assemblydata version="2.0.5.0 (4.1.61829.0)" />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
        <type api="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" />
      </containers>
      <file name="eaebec55-f429-8793-ca4c-eec87bdef2fe" />
    </api>
    <api id="Properties.T:System.ServiceModel.DomainServices.DomainIdentifierAttribute">
      <topicdata name="DomainIdentifierAttribute" group="list" subgroup="Properties" typeTopicId="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" />
      <apidata name="DomainIdentifierAttribute" group="type" subgroup="class" />
      <typedata visibility="public" serializable="false" />
      <elements>
        <element api="P:System.ServiceModel.DomainServices.DomainIdentifierAttribute.CodeProcessor">
          <libraries>
            <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary" />
          </libraries>
        </element>
        <element api="P:System.ServiceModel.DomainServices.DomainIdentifierAttribute.IsApplicationService" />
        <element api="P:System.ServiceModel.DomainServices.DomainIdentifierAttribute.Name" />
        <element api="P:System.ServiceModel.DomainServices.DomainIdentifierAttribute.TypeId">
          <libraries>
            <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary" />
          </libraries>
        </element>
      </elements>
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
        </library>
        <library assembly="System.ServiceModel.DomainServices.Client" module="System.ServiceModel.DomainServices.Client" kind="DynamicallyLinkedLibrary">
          <assemblydata version="2.0.5.0 (4.1.61829.0)" />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
        <type api="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" />
      </containers>
      <file name="b5378358-7778-f7f5-c2b4-a62db2fc7089" />
    </api>
    <api id="M:System.ServiceModel.DomainServices.DomainIdentifierAttribute.#ctor(System.String)">
      <topicdata group="api" />
      <apidata name=".ctor" group="member" subgroup="constructor" />
      <memberdata visibility="public" special="true" />
      <parameters>
        <parameter name="name">
          <type api="T:System.String" ref="true" />
        </parameter>
      </parameters>
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
          <noAptca />
        </library>
        <library assembly="System.ServiceModel.DomainServices.Client" module="System.ServiceModel.DomainServices.Client" kind="DynamicallyLinkedLibrary">
          <assemblydata version="2.0.5.0 (4.1.61829.0)" />
          <noAptca />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
        <type api="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" ref="true" />
      </containers>
      <file name="33b115ce-2a31-7c87-afb9-fe73b4671b18" />
    </api>
    <api id="P:System.ServiceModel.DomainServices.DomainIdentifierAttribute.CodeProcessor">
      <topicdata group="api" />
      <apidata name="CodeProcessor" group="member" subgroup="property" />
      <memberdata visibility="public" />
      <proceduredata virtual="false" />
      <propertydata get="true" set="true" />
      <getter name="get_CodeProcessor" />
      <setter name="set_CodeProcessor" />
      <returns>
        <type api="T:System.Type" ref="true" />
      </returns>
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
          <noAptca />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
        <type api="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" ref="true" />
      </containers>
      <file name="88d27f0e-7502-8aab-f884-dc5875aab792" />
    </api>
    <api id="P:System.ServiceModel.DomainServices.DomainIdentifierAttribute.IsApplicationService">
      <topicdata group="api" />
      <apidata name="IsApplicationService" group="member" subgroup="property" />
      <memberdata visibility="public" />
      <proceduredata virtual="false" />
      <propertydata get="true" set="true" />
      <getter name="get_IsApplicationService" />
      <setter name="set_IsApplicationService" />
      <returns>
        <type api="T:System.Boolean" ref="false" />
      </returns>
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
          <noAptca />
        </library>
        <library assembly="System.ServiceModel.DomainServices.Client" module="System.ServiceModel.DomainServices.Client" kind="DynamicallyLinkedLibrary">
          <assemblydata version="2.0.5.0 (4.1.61829.0)" />
          <noAptca />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
        <type api="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" ref="true" />
      </containers>
      <file name="b044b964-d803-574c-e9b9-ab0660d9f3b2" />
    </api>
    <api id="P:System.ServiceModel.DomainServices.DomainIdentifierAttribute.Name">
      <topicdata group="api" />
      <apidata name="Name" group="member" subgroup="property" />
      <memberdata visibility="public" />
      <proceduredata virtual="false" />
      <propertydata get="true" />
      <getter name="get_Name" />
      <returns>
        <type api="T:System.String" ref="true" />
      </returns>
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
          <noAptca />
        </library>
        <library assembly="System.ServiceModel.DomainServices.Client" module="System.ServiceModel.DomainServices.Client" kind="DynamicallyLinkedLibrary">
          <assemblydata version="2.0.5.0 (4.1.61829.0)" />
          <noAptca />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
        <type api="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" ref="true" />
      </containers>
      <file name="adbbdce6-4a80-d7a1-555f-e511f13765e0" />
    </api>
    <api id="P:System.ServiceModel.DomainServices.DomainIdentifierAttribute.TypeId">
      <topicdata group="api" />
      <apidata name="TypeId" group="member" subgroup="property" />
      <memberdata visibility="public" />
      <proceduredata virtual="true" />
      <propertydata get="true" />
      <getter name="get_TypeId" />
      <returns>
        <type api="T:System.Object" ref="true" />
      </returns>
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
          <noAptca />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
        <type api="T:System.ServiceModel.DomainServices.DomainIdentifierAttribute" ref="true" />
      </containers>
      <file name="6237d519-db5a-4c2d-70dc-691f0d015ae4" />
    </api>
    <api id="T:System.ServiceModel.DomainServices.ExternalReferenceAttribute">
      <topicdata group="api" allMembersTopicId="AllMembers.T:System.ServiceModel.DomainServices.ExternalReferenceAttribute" />
      <apidata name="ExternalReferenceAttribute" group="type" subgroup="class" />
      <typedata visibility="public" sealed="true" serializable="false" defaultConstructor="M:System.ServiceModel.DomainServices.ExternalReferenceAttribute.#ctor" />
      <family>
        <ancestors>
          <type api="T:System.Attribute" ref="true" />
          <type api="T:System.Object" ref="true" />
        </ancestors>
      </family>
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
        </library>
        <library assembly="System.ServiceModel.DomainServices.Client" module="System.ServiceModel.DomainServices.Client" kind="DynamicallyLinkedLibrary">
          <assemblydata version="2.0.5.0 (4.1.61829.0)" />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
      </containers>
      <attributes>
        <attribute>
          <type api="T:System.AttributeUsageAttribute" ref="true" />
          <argument>
            <type api="T:System.AttributeTargets" ref="false" />
            <enumValue>
              <field name="Property" />
              <field name="Field" />
            </enumValue>
          </argument>
          <assignment name="AllowMultiple">
            <type api="T:System.Boolean" ref="false" />
            <value>False</value>
          </assignment>
          <assignment name="Inherited">
            <type api="T:System.Boolean" ref="false" />
            <value>True</value>
          </assignment>
        </attribute>
      </attributes>
      <file name="8db6f821-babf-7d21-05ee-d596d58f1438" />
    </api>
    <api id="AllMembers.T:System.ServiceModel.DomainServices.ExternalReferenceAttribute">
      <topicdata name="ExternalReferenceAttribute" group="list" subgroup="members" typeTopicId="T:System.ServiceModel.DomainServices.ExternalReferenceAttribute" />
      <apidata name="ExternalReferenceAttribute" group="type" subgroup="class" />
      <typedata visibility="public" sealed="true" serializable="false" defaultConstructor="M:System.ServiceModel.DomainServices.ExternalReferenceAttribute.#ctor" />
      <elements>
        <element api="M:System.Attribute.Equals(System.Object)" />
        <element api="M:System.Attribute.GetHashCode" />
        <element api="M:System.Attribute.Match(System.Object)" />
        <element api="M:System.Object.GetType" />
        <element api="M:System.Object.ToString" />
        <element api="M:System.ServiceModel.DomainServices.ExternalReferenceAttribute.#ctor" />
      </elements>
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
        </library>
        <library assembly="System.ServiceModel.DomainServices.Client" module="System.ServiceModel.DomainServices.Client" kind="DynamicallyLinkedLibrary">
          <assemblydata version="2.0.5.0 (4.1.61829.0)" />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
        <type api="T:System.ServiceModel.DomainServices.ExternalReferenceAttribute" />
      </containers>
      <file name="e1b30259-4031-6c74-f702-c6aa134795a8" />
    </api>
    <api id="Methods.T:System.ServiceModel.DomainServices.ExternalReferenceAttribute">
      <topicdata name="ExternalReferenceAttribute" group="list" subgroup="Methods" typeTopicId="T:System.ServiceModel.DomainServices.ExternalReferenceAttribute" />
      <apidata name="ExternalReferenceAttribute" group="type" subgroup="class" />
      <typedata visibility="public" sealed="true" serializable="false" defaultConstructor="M:System.ServiceModel.DomainServices.ExternalReferenceAttribute.#ctor" />
      <elements>
        <element api="M:System.Attribute.Equals(System.Object)" />
        <element api="M:System.Attribute.GetHashCode" />
        <element api="M:System.Attribute.Match(System.Object)" />
        <element api="M:System.Object.GetType" />
        <element api="M:System.Object.ToString" />
      </elements>
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
        </library>
        <library assembly="System.ServiceModel.DomainServices.Client" module="System.ServiceModel.DomainServices.Client" kind="DynamicallyLinkedLibrary">
          <assemblydata version="2.0.5.0 (4.1.61829.0)" />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
        <type api="T:System.ServiceModel.DomainServices.ExternalReferenceAttribute" />
      </containers>
      <file name="65fd92b7-2eac-a049-125f-9dacc6f30315" />
    </api>
    <api id="M:System.ServiceModel.DomainServices.ExternalReferenceAttribute.#ctor">
      <topicdata group="api" />
      <apidata name=".ctor" group="member" subgroup="constructor" />
      <memberdata visibility="public" special="true" />
      <containers>
        <library assembly="System.ServiceModel.DomainServices.Server" module="System.ServiceModel.DomainServices.Server" kind="DynamicallyLinkedLibrary">
          <assemblydata version="4.0.0.0 (4.1.61829.0)" />
          <noAptca />
        </library>
        <library assembly="System.ServiceModel.DomainServices.Client" module="System.ServiceModel.DomainServices.Client" kind="DynamicallyLinkedLibrary">
          <assemblydata version="2.0.5.0 (4.1.61829.0)" />
          <noAptca />
        </library>
        <namespace api="N:System.ServiceModel.DomainServices" />
        <type api="T:System.ServiceModel.DomainServices.ExternalReferenceAttribute" ref="true" />
      </containers>
      <file name="e8e3f012-ca4e-fec0-13e3-ec18daac5d93" />
    </api>
  </apis>
</reflection>


text:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 ff=unix fenc=utf8: */

/**
 * Page d'un abonné
 *
 * @package      sendui
 * @subpackage   sendui
 * @author       Yves Tannier [grafactory.net]
 * @copyright    2009 Yves Tannier
 * @link         http://www.grafactory.net/sendui
 * @license      http://www.grafactory.net/sendui/licence MIT Licence
 * @version      0.1.0
 */

class subscriberCtrl extends jController {

    // les daos pour abonnés
    protected $dao_subscriber_list = 'common~subscriber_list';
    protected $dao_subscriber_subscriber_list = 'common~subscriber_subscriber_list';
    protected $dao_subscriber = 'common~subscriber';

    // customer
    protected $dao_customer = 'common~customer';

    // formulaire abonné
    protected $form_subscriber = 'sendui~subscriber';

    // {{{ index()

    /**
     * abonné
     *
     * @template    subscriber_index
     * @return      html
     */
    public function index()
    {

        $rep = $this->getResponse('html');

        $rep->params = array(
            'idsubscriber' => $this->param('idsubscriber'),
            'idsubscriber_list' => $this->param('idsubscriber_list'),
        );

        if($this->param('from_page')!='') {
            $rep->action = $this->param('from_page');
        } else {
            $rep->action = 'sendui~subscribers:index';
        }

        if($this->param('idsubscriber')=='' || $this->param('idsubscriber_list')=='') {
            $rep = $this->getResponse('redirect');
            return $rep;
        }

        $session = jAuth::getUserSession();

        $tpl = new jTpl();

        // l'abonné TODO : checker avec le customer !
        $subscriber = jDao::get($this->dao_subscriber);
        $infos_subscriber =  $subscriber->get($this->param('idsubscriber'));
        $tpl->assign('subscriber', $infos_subscriber);

        $rep->title = 'Abonné '.$infos_subscriber->email;

        // marquer le menu
        $rep->body->assign('active_page', 'subscribers');

        // infos sur la liste TODO check avec le customer
        if($this->param('idsubscriber_list')!='') {
            $subscriber_list = jDao::get($this->dao_subscriber_list);
            $subscriber_list_infos = $subscriber_list->get($this->param('idsubscriber_list'));
            $tpl->assign('subscriber_list', $subscriber_list_infos);
            $tpl->assign('idsubscriber_list', $subscriber_list_infos->idsubscriber_list);
        }

        // fil d'arianne
        $navigation = array(
            array('action' => 'sendui~subscribers:index', 'params' => array(), 'title' => 'Listes d\'abonnés'),
            array('action' => 'sendui~subscribers:view', 'params' => array('idsubscriber_list' => $subscriber_list_infos->idsubscriber_list), 'title' => $subscriber_list_infos->name),
            array('action' => '0', 'params' => array(), 'title' => 'Informations sur l\'abonné'),
        );
		$rep->body->assign('navigation', $navigation);

        $rep->body->assign('MAIN', $tpl->fetch('subscriber_index'));

        return $rep;

    }

    // }}}

    // {{{ prepare()

    /**
     * ajouter/modifier un abonné
     *
     * @return      redirect
     */
    public function prepare()
    {

        $rep = $this->getResponse('redirect');

        // formulaire
        if($this->param('idsubscriber')!='') {
            $form_subscriber = jForms::create($this->form_subscriber, $this->param('idsubscriber'));
        } else {
            $form_subscriber = jForms::create($this->form_subscriber);
        }

        // initialiser un message
        if($this->param('idsubscriber')!='') {
            $form_subscriber->initFromDao($this->dao_subscriber);
        }

        $rep->params = array(
            'idsubscriber' => $this->param('idsubscriber'),
            'idsubscriber_list' => $this->param('idsubscriber_list'),
            'from_page' => $this->param('from_page')
        );

        // redirection vers subscriber
        $rep->action = 'sendui~subscriber:edit';

        return $rep;

    }

    // }}}

    // {{{ edit()

    /**
     * ajouter/modifier un abonné => formulaire
     *
     * @template    subscriber_subscriber
     * @return      html
     */
    public function edit()
    {

        // si pas de liste, retour
        if($this->param('idsubscriber_list')=='') {
            $rep = $this->getResponse('redirect');
            $rep->action = 'sendui~subscribers:index';
            return $rep;
        }

        $rep = $this->getResponse('html');

        $rep->title = 'Ajouter des abonnés';

        $tpl = new jTpl();

        // récuperer l'instance de formulaire
        if($this->param('idsubscriber')!='') {
            $form_subscriber = jForms::get($this->form_subscriber, $this->param('idsubscriber'));
        } else {
            $form_subscriber = jForms::get($this->form_subscriber);
        }

        // le créer si il n'existe pas
        if ($form_subscriber === null) {
            $rep = $this->getResponse('redirect');
            $rep->params = array(
                'idsubscriber' => $this->param('idsubscriber'),
                'idsubscriber_list' => $this->param('idsubscriber_list'),
                'from_page' => $this->param('from_page')
            );
            $rep->action = 'sendui~subscribers:preparesubscriber';
            return $rep;
        }

        $tpl->assign('form_subscriber', $form_subscriber);
        $tpl->assign('idsubscriber', $this->param('idsubscriber'));
        $tpl->assign('idsubscriber_list', $this->param('idsubscriber_list'));
        $tpl->assign('from_page', $this->param('from_page'));

        // infos sur la liste TODO check avec le customer
        if($this->param('idsubscriber_list')!='') {
            $subscriber_list = jDao::get($this->dao_subscriber_list);
            $subscriber_list_infos = $subscriber_list->get($this->param('idsubscriber_list'));
            $tpl->assign('subscriber_list', $subscriber_list_infos);
        }

        // infos sur l'utilisateur
        if($this->param('idsubscriber')!='') {
            $subscriber = jDao::get($this->dao_subscriber);
            $tpl->assign('subscriber', $subscriber->get($this->param('idsubscriber')));
        }

        // fil d'arianne
        $navigation = array(
            array('action' => 'sendui~subscribers:index', 'params' => array(), 'title' => 'Listes d\'abonnés'),
            array('action' => 'sendui~subscribers:view', 'params' => array('idsubscriber_list' => $subscriber_list_infos->idsubscriber_list), 'title' => $subscriber_list_infos->name),
            array('action' => '0', 'params' => array(), 'title' => 'Modifier l\'abonné'),
        );
		$rep->body->assign('navigation', $navigation);

        // marquer le menu
        $rep->body->assign('active_page', 'subscribers');

        $rep->body->assign('MAIN', $tpl->fetch('subscriber_edit'));

        return $rep;

    }

    // }}}

    // {{{ save()

    /**
     * ajouter/modifier un abonné => sauvegarder les modifications
     *
     * @template    subscribersave
     * @return      redirect
     */
    public function save()
    {

        // récupere le form
        if($this->param('idsubscriber')!='') {
            $form_subscriber = jForms::fill($this->form_subscriber, $this->param('idsubscriber'));
        } else {
            $form_subscriber = jForms::fill($this->form_subscriber);
        }

        $rep = $this->getResponse('redirect');

        // redirection si erreur
        if (!$form_subscriber->check()) {
            $rep->params = array(
                'idsubscriber' => $this->param('idsubscriber'),
                'idsubscriber_list' => $this->param('idsubscriber_list'),
                'from_page' => $this->param('from_page')
            );
            $rep->action = 'sendui~subscribers:subscriber';
            return $rep;
        }

        // utilisateur
        $session = jAuth::getUserSession();

        // enregistrer
        $result = $form_subscriber->prepareDaoFromControls($this->dao_subscriber);

        if($result['toInsert']) {

            // client pour la sécurité
            $result['daorec']->idcustomer = $session->idcustomer;

            $result['dao']->insert($result['daorec']);

            // identifiant du nouvel abonné
            $idsubscriber = $result['daorec']->idsubscriber;

        } else {
            $update = $result['dao']->update($result['daorec']);
        }

        // si ok, on redirige sur  la page suivante
        if(!empty($idsubscriber) || !empty($update)) {

            // dans le cas update
            if(empty($idsubscriber)) {
                $idsubscriber = $this->param('idsubscriber');
            }

            // si on a idsubscriber_list, enregistrer dans la bonne liste
            if($this->param('idsubscriber_list')!='' && empty($update)) {

                $subscriber_subscriber_list = jDao::get($this->dao_subscriber_subscriber_list);
                $record = jDao::createRecord($this->dao_subscriber_subscriber_list);

                // utilisateur et sa liste
                $record->idsubscriber = $idsubscriber;
                $record->idsubscriber_list = $this->param('idsubscriber_list');

                // client pour la sécurité
                $record->idcustomer = $session->idcustomer;

                $subscriber_subscriber_list->insert($record);
            }

            // détruire le formulaire
            jForms::destroy($this->form_subscriber);

            $rep->params = array(
                'idsubscriber' => $idsubscriber,
                'idsubscriber_list' => $this->param('idsubscriber_list'),
            );

            // rediriger vers la page suivante
            if($this->param('from_page')!='') {
                $rep->action = $this->param('from_page');
            } else {
                $rep->action = 'sendui~subscribers:subscriber';
            }

            return $rep;

        }

    }

    // }}}

    // {{{ subscriberdelete()

    /**
     * Supprimer un utilisateur
     *
     * @return      redirect
     */
    public function delete()
    {

        $rep = $this->getResponse('redirect');

        if($this->param('idsubscriber')!='') {

            // TODO tester aussi sur le customer pour la sécurité ET double vérification
            $subscriber = jDao::get($this->dao_subscriber);

            if($subscriber->delete($this->param('idsubscriber'))) {
                $rep->params = array(
                    'delete_subscriber' => true,
                    'idsubscriber_list' => $this->param('idsubscriber_list'),
                );
            }

        }

        $rep->action = 'sendui~subscribers:view';

        return $rep;

    }

    // }}}

}


text:
using content::BrowserThread;

namespace {

// Name of the badged icon file generated for a given profile.
const char kProfileIconFileName[] = "Google Profile.ico";

// Characters that are not allowed in Windows filenames. Taken from
// http://msdn.microsoft.com/en-us/library/aa365247.aspx
const base::char16 kReservedCharacters[] = L"<>:\"/\\|?*\x01\x02\x03\x04\x05"
    L"\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17"
    L"\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F";

// The maximum number of characters allowed in profile shortcuts' file names.
// Warning: migration code will be needed if this is changed later, since
// existing shortcuts might no longer be found if the name is generated
// differently than it was when a shortcut was originally created.
const int kMaxProfileShortcutFileNameLength = 64;

// The avatar badge size needs to be half of the shortcut icon size because
// the Windows taskbar icon is 32x32 and the avatar icon overlay is 16x16. So to
// get the shortcut avatar badge and the avatar icon overlay to match up, we
// need to preserve those ratios when creating the shortcut icon.
const int kShortcutIconSize = 48;
const int kProfileAvatarBadgeSize = kShortcutIconSize / 2;

const int kCurrentProfileIconVersion = 3;

// 2x sized profile avatar icons. Mirrors |kDefaultAvatarIconResources| in
// profile_info_cache.cc.
const int kProfileAvatarIconResources2x[] = {
  IDR_PROFILE_AVATAR_2X_0,
  IDR_PROFILE_AVATAR_2X_1,
  IDR_PROFILE_AVATAR_2X_2,
  IDR_PROFILE_AVATAR_2X_3,
  IDR_PROFILE_AVATAR_2X_4,
  IDR_PROFILE_AVATAR_2X_5,
  IDR_PROFILE_AVATAR_2X_6,
  IDR_PROFILE_AVATAR_2X_7,
  IDR_PROFILE_AVATAR_2X_8,
  IDR_PROFILE_AVATAR_2X_9,
  IDR_PROFILE_AVATAR_2X_10,
  IDR_PROFILE_AVATAR_2X_11,
  IDR_PROFILE_AVATAR_2X_12,
  IDR_PROFILE_AVATAR_2X_13,
  IDR_PROFILE_AVATAR_2X_14,
  IDR_PROFILE_AVATAR_2X_15,
  IDR_PROFILE_AVATAR_2X_16,
  IDR_PROFILE_AVATAR_2X_17,
  IDR_PROFILE_AVATAR_2X_18,
  IDR_PROFILE_AVATAR_2X_19,
  IDR_PROFILE_AVATAR_2X_20,
  IDR_PROFILE_AVATAR_2X_21,
  IDR_PROFILE_AVATAR_2X_22,
  IDR_PROFILE_AVATAR_2X_23,
  IDR_PROFILE_AVATAR_2X_24,
  IDR_PROFILE_AVATAR_2X_25,
  IDR_PROFILE_AVATAR_2X_26,
};

// Badges |app_icon_bitmap| with |avatar_bitmap| at the bottom right corner and
// returns the resulting SkBitmap.
SkBitmap BadgeIcon(const SkBitmap& app_icon_bitmap,
                   const SkBitmap& avatar_bitmap,
                   int scale_factor) {
  SkBitmap source_bitmap =
      profiles::GetAvatarIconAsSquare(avatar_bitmap, scale_factor);
  int avatar_badge_size = kProfileAvatarBadgeSize;
  if (app_icon_bitmap.width() != kShortcutIconSize) {
    avatar_badge_size =
        app_icon_bitmap.width() * kProfileAvatarBadgeSize / kShortcutIconSize;
  }
  SkBitmap sk_icon = skia::ImageOperations::Resize(
      source_bitmap, skia::ImageOperations::RESIZE_LANCZOS3, avatar_badge_size,
      source_bitmap.height() * avatar_badge_size / source_bitmap.width());

  // Overlay the avatar on the icon, anchoring it to the bottom-right of the
  // icon.
  SkBitmap badged_bitmap;
  badged_bitmap.allocN32Pixels(app_icon_bitmap.width(),
                               app_icon_bitmap.height());
  SkCanvas offscreen_canvas(badged_bitmap);
  offscreen_canvas.clear(SK_ColorTRANSPARENT);

  offscreen_canvas.drawBitmap(app_icon_bitmap, 0, 0);
  offscreen_canvas.drawBitmap(sk_icon,
                              app_icon_bitmap.width() - sk_icon.width(),
                              app_icon_bitmap.height() - sk_icon.height());
  return badged_bitmap;
}

// Updates the preferences with the current icon version on icon creation
// success.
void OnProfileIconCreateSuccess(base::FilePath profile_path) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (!g_browser_process->profile_manager())
    return;
  Profile* profile =
      g_browser_process->profile_manager()->GetProfileByPath(profile_path);
  if (profile) {
    profile->GetPrefs()->SetInteger(prefs::kProfileIconVersion,
                                    kCurrentProfileIconVersion);
  }
}

// Creates a desktop shortcut icon file (.ico) on the disk for a given profile,
// badging the browser distribution icon with the profile avatar.
// Returns a path to the shortcut icon file on disk, which is empty if this
// fails. Use index 0 when assigning the resulting file as the icon. If both
// given bitmaps are empty, an unbadged icon is created.
// Returns the path to the created icon on success and an empty base::FilePath
// on failure.
// TODO(calamity): Ideally we'd just copy the app icon verbatim from the exe's
// resources in the case of an unbadged icon.
base::FilePath CreateOrUpdateShortcutIconForProfile(
    const base::FilePath& profile_path,
    const SkBitmap& avatar_bitmap_1x,
    const SkBitmap& avatar_bitmap_2x) {
  DCHECK_CURRENTLY_ON(BrowserThread::FILE);

  if (!base::PathExists(profile_path)) {
    LOG(ERROR) << "Profile directory " << profile_path.value()
               << " did not exist when trying to create profile icon";
    return base::FilePath();
  }

  scoped_ptr<SkBitmap> app_icon_bitmap(GetAppIconForSize(kShortcutIconSize));
  if (!app_icon_bitmap)
    return base::FilePath();

  gfx::ImageFamily badged_bitmaps;
  if (!avatar_bitmap_1x.empty()) {
    badged_bitmaps.Add(gfx::Image::CreateFrom1xBitmap(
        BadgeIcon(*app_icon_bitmap, avatar_bitmap_1x, 1)));
  }

  scoped_ptr<SkBitmap> large_app_icon_bitmap(
      GetAppIconForSize(IconUtil::kLargeIconSize));
  if (large_app_icon_bitmap && !avatar_bitmap_2x.empty()) {
    badged_bitmaps.Add(gfx::Image::CreateFrom1xBitmap(
        BadgeIcon(*large_app_icon_bitmap, avatar_bitmap_2x, 2)));
  }

  // If we have no badged bitmaps, we should just use the default chrome icon.
  if (badged_bitmaps.empty()) {
    badged_bitmaps.Add(gfx::Image::CreateFrom1xBitmap(*app_icon_bitmap));
    if (large_app_icon_bitmap) {
      badged_bitmaps.Add(
          gfx::Image::CreateFrom1xBitmap(*large_app_icon_bitmap));
    }
  }
  // Finally, write the .ico file containing this new bitmap.
  const base::FilePath icon_path =
      profiles::internal::GetProfileIconPath(profile_path);
  const bool had_icon = base::PathExists(icon_path);

  if (!IconUtil::CreateIconFileFromImageFamily(badged_bitmaps, icon_path)) {
    // This can happen in theory if the profile directory is deleted between the
    // beginning of this function and here; however this is extremely unlikely
    // and this check will help catch any regression where this call would start
    // failing constantly.
    NOTREACHED();
    return base::FilePath();
  }

  if (had_icon) {
    // This invalidates the Windows icon cache and causes the icon changes to
    // register with the taskbar and desktop. SHCNE_ASSOCCHANGED will cause a
    // desktop flash and we would like to avoid that if possible.
    SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
  } else {
    SHChangeNotify(SHCNE_CREATE, SHCNF_PATH, icon_path.value().c_str(), NULL);
  }
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&OnProfileIconCreateSuccess, profile_path));
  return icon_path;
}

// Gets the user and system directories for desktop shortcuts. Parameters may
// be NULL if a directory type is not needed. Returns true on success.
bool GetDesktopShortcutsDirectories(
    base::FilePath* user_shortcuts_directory,
    base::FilePath* system_shortcuts_directory) {
  BrowserDistribution* distribution = BrowserDistribution::GetDistribution();
  if (user_shortcuts_directory &&
      !ShellUtil::GetShortcutPath(ShellUtil::SHORTCUT_LOCATION_DESKTOP,
                                  distribution, ShellUtil::CURRENT_USER,
                                  user_shortcuts_directory)) {
    NOTREACHED();
    return false;
  }
  if (system_shortcuts_directory &&
      !ShellUtil::GetShortcutPath(ShellUtil::SHORTCUT_LOCATION_DESKTOP,
                                  distribution, ShellUtil::SYSTEM_LEVEL,
                                  system_shortcuts_directory)) {
    NOTREACHED();
    return false;
  }
  return true;
}

// Returns the long form of |path|, which will expand any shortened components
// like "foo~2" to their full names.
base::FilePath ConvertToLongPath(const base::FilePath& path) {
  const size_t length = GetLongPathName(path.value().c_str(), NULL, 0);
  if (length != 0 && length != path.value().length()) {
    std::vector<wchar_t> long_path(length);
    if (GetLongPathName(path.value().c_str(), &long_path[0], length) != 0)
      return base::FilePath(&long_path[0]);
  }
  return path;
}

// Returns true if the file at |path| is a Chrome shortcut and returns its
// command line in output parameter |command_line|.
bool IsChromeShortcut(const base::FilePath& path,
                      const base::FilePath& chrome_exe,
                      base::string16* command_line) {
  DCHECK_CURRENTLY_ON(BrowserThread::FILE);

  if (path.Extension() != installer::kLnkExt)
    return false;

  base::FilePath target_path;
  if (!base::win::ResolveShortcut(path, &target_path, command_line))
    return false;
  // One of the paths may be in short (elided) form. Compare long paths to
  // ensure these are still properly matched.
  return ConvertToLongPath(target_path) == ConvertToLongPath(chrome_exe);
}

// Populates |paths| with the file paths of Chrome desktop shortcuts that have
// the specified |command_line|. If |include_empty_command_lines| is true,
// Chrome desktop shortcuts with empty command lines will also be included.
void ListDesktopShortcutsWithCommandLine(const base::FilePath& chrome_exe,
                                         const base::string16& command_line,
                                         bool include_empty_command_lines,
                                         std::vector<base::FilePath>* paths) {
  base::FilePath user_shortcuts_directory;
  if (!GetDesktopShortcutsDirectories(&user_shortcuts_directory, NULL))
    return;

  base::FileEnumerator enumerator(user_shortcuts_directory, false,
                                  base::FileEnumerator::FILES);
  for (base::FilePath path = enumerator.Next(); !path.empty();
       path = enumerator.Next()) {
    base::string16 shortcut_command_line;
    if (!IsChromeShortcut(path, chrome_exe, &shortcut_command_line))
      continue;

    // TODO(asvitkine): Change this to build a CommandLine object and ensure all
    // args from |command_line| are present in the shortcut's CommandLine. This
    // will be more robust when |command_line| contains multiple args.
    if ((shortcut_command_line.empty() && include_empty_command_lines) ||
        (shortcut_command_line.find(command_line) != base::string16::npos)) {
      paths->push_back(path);
    }
  }
}

// Renames the given desktop shortcut and informs the shell of this change.
bool RenameDesktopShortcut(const base::FilePath& old_shortcut_path,
                           const base::FilePath& new_shortcut_path) {
  if (!base::Move(old_shortcut_path, new_shortcut_path))
    return false;

  // Notify the shell of the rename, which allows the icon to keep its position
  // on the desktop when renamed. Note: This only works if either SHCNF_FLUSH or
  // SHCNF_FLUSHNOWAIT is specified as a flag.
  SHChangeNotify(SHCNE_RENAMEITEM, SHCNF_PATH | SHCNF_FLUSHNOWAIT,
                 old_shortcut_path.value().c_str(),
                 new_shortcut_path.value().c_str());
  return true;
}

// Renames an existing Chrome desktop profile shortcut. Must be called on the
// FILE thread.
void RenameChromeDesktopShortcutForProfile(
    const base::string16& old_shortcut_filename,
    const base::string16& new_shortcut_filename) {
  DCHECK_CURRENTLY_ON(BrowserThread::FILE);

  base::FilePath user_shortcuts_directory;
  base::FilePath system_shortcuts_directory;
  if (!GetDesktopShortcutsDirectories(&user_shortcuts_directory,
                                      &system_shortcuts_directory)) {
    return;
  }

  const base::FilePath old_shortcut_path =
      user_shortcuts_directory.Append(old_shortcut_filename);
  const base::FilePath new_shortcut_path =
      user_shortcuts_directory.Append(new_shortcut_filename);

  if (base::PathExists(old_shortcut_path)) {
    // Rename the old shortcut unless a system-level shortcut exists at the
    // destination, in which case the old shortcut is simply deleted.
    const base::FilePath possible_new_system_shortcut =
        system_shortcuts_directory.Append(new_shortcut_filename);
    if (base::PathExists(possible_new_system_shortcut))
      base::DeleteFile(old_shortcut_path, false);
    else if (!RenameDesktopShortcut(old_shortcut_path, new_shortcut_path))
      DLOG(ERROR) << "Could not rename Windows profile desktop shortcut.";
  } else {
    // If the shortcut does not exist, it may have been renamed by the user. In
    // that case, its name should not be changed.
    // It's also possible that a system-level shortcut exists instead - this
    // should only be the case for the original Chrome shortcut from an
    // installation. If that's the case, copy that one over - it will get its
    // properties updated by
    // |CreateOrUpdateDesktopShortcutsAndIconForProfile()|.
    const base::FilePath possible_old_system_shortcut =
        system_shortcuts_directory.Append(old_shortcut_filename);
    if (base::PathExists(possible_old_system_shortcut))
      base::CopyFile(possible_old_system_shortcut, new_shortcut_path);
  }
}

struct CreateOrUpdateShortcutsParams {
  CreateOrUpdateShortcutsParams(
      base::FilePath profile_path,
      ProfileShortcutManagerWin::CreateOrUpdateMode create_mode,
      ProfileShortcutManagerWin::NonProfileShortcutAction action)
      : create_mode(create_mode), action(action), profile_path(profile_path) {}
  ~CreateOrUpdateShortcutsParams() {}

  ProfileShortcutManagerWin::CreateOrUpdateMode create_mode;
  ProfileShortcutManagerWin::NonProfileShortcutAction action;

  // The path for this profile.
  base::FilePath profile_path;
  // The profile name before this update. Empty on create.
  base::string16 old_profile_name;
  // The new profile name.
  base::string16 profile_name;
  // Avatar images for this profile.
  SkBitmap avatar_image_1x;
  SkBitmap avatar_image_2x;
};

// Updates all desktop shortcuts for the given profile to have the specified
// parameters. If |params.create_mode| is CREATE_WHEN_NONE_FOUND, a new shortcut
// is created if no existing ones were found. Whether non-profile shortcuts
// should be updated is specified by |params.action|. Must be called on the FILE
// thread.
void CreateOrUpdateDesktopShortcutsAndIconForProfile(
    const CreateOrUpdateShortcutsParams& params) {
  DCHECK_CURRENTLY_ON(BrowserThread::FILE);

  const base::FilePath shortcut_icon =
      CreateOrUpdateShortcutIconForProfile(params.profile_path,
                                           params.avatar_image_1x,
                                           params.avatar_image_2x);
  if (shortcut_icon.empty() ||
      params.create_mode ==
          ProfileShortcutManagerWin::CREATE_OR_UPDATE_ICON_ONLY) {
    return;
  }

  base::FilePath chrome_exe;
  if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
    NOTREACHED();
    return;
  }

  BrowserDistribution* distribution = BrowserDistribution::GetDistribution();
  // Ensure that the distribution supports creating shortcuts. If it doesn't,
  // the following code may result in NOTREACHED() being hit.
  DCHECK(distribution->CanCreateDesktopShortcuts());

  if (params.old_profile_name != params.profile_name) {
    const base::string16 old_shortcut_filename =
        profiles::internal::GetShortcutFilenameForProfile(
            params.old_profile_name,
            distribution);
    const base::string16 new_shortcut_filename =
        profiles::internal::GetShortcutFilenameForProfile(params.profile_name,
                                                          distribution);
    RenameChromeDesktopShortcutForProfile(old_shortcut_filename,
                                          new_shortcut_filename);
  }

  ShellUtil::ShortcutProperties properties(ShellUtil::CURRENT_USER);
  installer::Product product(distribution);
  product.AddDefaultShortcutProperties(chrome_exe, &properties);

  const base::string16 command_line =
      profiles::internal::CreateProfileShortcutFlags(params.profile_path);

  // Only set the profile-specific properties when |profile_name| is non empty.
  // If it is empty, it means the shortcut being created should be a regular,
  // non-profile Chrome shortcut.
  if (!params.profile_name.empty()) {
    properties.set_arguments(command_line);
    properties.set_icon(shortcut_icon, 0);
  } else {
    // Set the arguments explicitly to the empty string to ensure that
    // |ShellUtil::CreateOrUpdateShortcut| updates that part of the shortcut.
    properties.set_arguments(base::string16());
  }

  properties.set_app_id(
      ShellIntegration::GetChromiumModelIdForProfile(params.profile_path));

  ShellUtil::ShortcutOperation operation =
      ShellUtil::SHELL_SHORTCUT_REPLACE_EXISTING;

  std::vector<base::FilePath> shortcuts;
  ListDesktopShortcutsWithCommandLine(chrome_exe, command_line,
      params.action == ProfileShortcutManagerWin::UPDATE_NON_PROFILE_SHORTCUTS,
      &shortcuts);
  if (params.create_mode == ProfileShortcutManagerWin::CREATE_WHEN_NONE_FOUND &&
      shortcuts.empty()) {
    const base::string16 shortcut_name =
        profiles::internal::GetShortcutFilenameForProfile(params.profile_name,
                                                          distribution);
    shortcuts.push_back(base::FilePath(shortcut_name));
    operation = ShellUtil::SHELL_SHORTCUT_CREATE_IF_NO_SYSTEM_LEVEL;
  }

  for (size_t i = 0; i < shortcuts.size(); ++i) {
    const base::FilePath shortcut_name =
        shortcuts[i].BaseName().RemoveExtension();
    properties.set_shortcut_name(shortcut_name.value());
    ShellUtil::CreateOrUpdateShortcut(ShellUtil::SHORTCUT_LOCATION_DESKTOP,
        distribution, properties, operation);
  }
}

// Returns true if any desktop shortcuts exist with target |chrome_exe|,
// regardless of their command line arguments.
bool ChromeDesktopShortcutsExist(const base::FilePath& chrome_exe) {
  base::FilePath user_shortcuts_directory;
  if (!GetDesktopShortcutsDirectories(&user_shortcuts_directory, NULL))
    return false;

  base::FileEnumerator enumerator(user_shortcuts_directory, false,
                                  base::FileEnumerator::FILES);
  for (base::FilePath path = enumerator.Next(); !path.empty();
       path = enumerator.Next()) {
    if (IsChromeShortcut(path, chrome_exe, NULL))
      return true;
  }

  return false;
}

// Deletes all desktop shortcuts for the specified profile. If
// |ensure_shortcuts_remain| is true, then a regular non-profile shortcut will
// be created if this function would otherwise delete the last Chrome desktop
// shortcut(s). Must be called on the FILE thread.
void DeleteDesktopShortcuts(const base::FilePath& profile_path,
                            bool ensure_shortcuts_remain) {
  DCHECK_CURRENTLY_ON(BrowserThread::FILE);

  base::FilePath chrome_exe;
  if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
    NOTREACHED();
    return;
  }

  const base::string16 command_line =
      profiles::internal::CreateProfileShortcutFlags(profile_path);
  std::vector<base::FilePath> shortcuts;
  ListDesktopShortcutsWithCommandLine(chrome_exe, command_line, false,
                                      &shortcuts);

  for (size_t i = 0; i < shortcuts.size(); ++i) {
    // Use base::DeleteFile() instead of ShellUtil::RemoveShortcuts(), as the
    // latter causes non-profile taskbar shortcuts to be removed since it
    // doesn't consider the command-line of the shortcuts it deletes.
    // TODO(huangs): Refactor with ShellUtil::RemoveShortcuts().
    base::win::UnpinShortcutFromTaskbar(shortcuts[i]);
    base::DeleteFile(shortcuts[i], false);
    // Notify the shell that the shortcut was deleted to ensure desktop refresh.
    SHChangeNotify(SHCNE_DELETE, SHCNF_PATH, shortcuts[i].value().c_str(),
                   NULL);
  }

  // If |ensure_shortcuts_remain| is true and deleting this profile caused the
  // last shortcuts to be removed, re-create a regular non-profile shortcut.
  const bool had_shortcuts = !shortcuts.empty();
  if (ensure_shortcuts_remain && had_shortcuts &&
      !ChromeDesktopShortcutsExist(chrome_exe)) {
    BrowserDistribution* distribution = BrowserDistribution::GetDistribution();
    // Ensure that the distribution supports creating shortcuts. If it doesn't,
    // the following code may result in NOTREACHED() being hit.
    DCHECK(distribution->CanCreateDesktopShortcuts());
    installer::Product product(distribution);

    ShellUtil::ShortcutProperties properties(ShellUtil::CURRENT_USER);
    product.AddDefaultShortcutProperties(chrome_exe, &properties);
    properties.set_shortcut_name(
        profiles::internal::GetShortcutFilenameForProfile(base::string16(),
                                                          distribution));
    ShellUtil::CreateOrUpdateShortcut(
        ShellUtil::SHORTCUT_LOCATION_DESKTOP, distribution, properties,
        ShellUtil::SHELL_SHORTCUT_CREATE_IF_NO_SYSTEM_LEVEL);
  }
}

// Returns true if profile at |profile_path| has any shortcuts. Does not
// consider non-profile shortcuts. Must be called on the FILE thread.
bool HasAnyProfileShortcuts(const base::FilePath& profile_path) {
  DCHECK_CURRENTLY_ON(BrowserThread::FILE);

  base::FilePath chrome_exe;
  if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
    NOTREACHED();
    return false;
  }

  const base::string16 command_line =
      profiles::internal::CreateProfileShortcutFlags(profile_path);
  std::vector<base::FilePath> shortcuts;
  ListDesktopShortcutsWithCommandLine(chrome_exe, command_line, false,
                                      &shortcuts);
  return !shortcuts.empty();
}

// Replaces any reserved characters with spaces, and trims the resulting string
// to prevent any leading and trailing spaces. Also makes sure that the
// resulting filename doesn't exceed |kMaxProfileShortcutFileNameLength|.
// TODO(macourteau): find a way to limit the total path's length to MAX_PATH
// instead of limiting the profile's name to |kMaxProfileShortcutFileNameLength|
// characters.
base::string16 SanitizeShortcutProfileNameString(
    const base::string16& profile_name) {
  base::string16 sanitized = profile_name;
  size_t pos = sanitized.find_first_of(kReservedCharacters);
  while (pos != base::string16::npos) {
    sanitized[pos] = L' ';
    pos = sanitized.find_first_of(kReservedCharacters, pos + 1);
  }

  base::TrimWhitespace(sanitized, base::TRIM_LEADING, &sanitized);
  if (sanitized.size() > kMaxProfileShortcutFileNameLength)
    sanitized.erase(kMaxProfileShortcutFileNameLength);
  base::TrimWhitespace(sanitized, base::TRIM_TRAILING, &sanitized);

  return sanitized;
}

// Returns a copied SkBitmap for the given image that can be safely passed to
// another thread.
SkBitmap GetSkBitmapCopy(const gfx::Image& image) {
  DCHECK(!image.IsEmpty());
  const SkBitmap* image_bitmap = image.ToSkBitmap();
  SkBitmap bitmap_copy;
  image_bitmap->deepCopyTo(&bitmap_copy);
  return bitmap_copy;
}

// Returns a copied SkBitmap for the given resource id that can be safely passed
// to another thread.
SkBitmap GetImageResourceSkBitmapCopy(int resource_id) {
  const gfx::Image image =
      ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
  return GetSkBitmapCopy(image);
}

}  // namespace

namespace profiles {
namespace internal {

base::FilePath GetProfileIconPath(const base::FilePath& profile_path) {
  return profile_path.AppendASCII(kProfileIconFileName);
}

base::string16 GetShortcutFilenameForProfile(
    const base::string16& profile_name,
    BrowserDistribution* distribution) {
  base::string16 shortcut_name;
  if (!profile_name.empty()) {
    shortcut_name.append(SanitizeShortcutProfileNameString(profile_name));
    shortcut_name.append(L" - ");
    shortcut_name.append(l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));
  } else {
    shortcut_name.append(
        distribution->GetShortcutName(BrowserDistribution::SHORTCUT_CHROME));
  }
  return shortcut_name + installer::kLnkExt;
}

base::string16 CreateProfileShortcutFlags(const base::FilePath& profile_path) {
  return base::StringPrintf(L"--%ls=\"%ls\"",
                            base::ASCIIToUTF16(
                                switches::kProfileDirectory).c_str(),
                            profile_path.BaseName().value().c_str());
}

}  // namespace internal
}  // namespace profiles

// static
bool ProfileShortcutManager::IsFeatureEnabled() {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  return command_line->HasSwitch(switches::kEnableProfileShortcutManager) ||
         (BrowserDistribution::GetDistribution()->CanCreateDesktopShortcuts() &&
          !command_line->HasSwitch(switches::kUserDataDir));
}

// static
ProfileShortcutManager* ProfileShortcutManager::Create(
    ProfileManager* manager) {
  return new ProfileShortcutManagerWin(manager);
}

ProfileShortcutManagerWin::ProfileShortcutManagerWin(ProfileManager* manager)
    : profile_manager_(manager) {
  DCHECK_EQ(
      arraysize(kProfileAvatarIconResources2x),
      profiles::GetDefaultAvatarIconCount());

  registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED,
                 content::NotificationService::AllSources());

  profile_manager_->GetProfileInfoCache().AddObserver(this);
}

ProfileShortcutManagerWin::~ProfileShortcutManagerWin() {
  profile_manager_->GetProfileInfoCache().RemoveObserver(this);
}

void ProfileShortcutManagerWin::CreateOrUpdateProfileIcon(
    const base::FilePath& profile_path) {
  CreateOrUpdateShortcutsForProfileAtPath(profile_path,
                                          CREATE_OR_UPDATE_ICON_ONLY,
                                          IGNORE_NON_PROFILE_SHORTCUTS);
}

void ProfileShortcutManagerWin::CreateProfileShortcut(
    const base::FilePath& profile_path) {
  CreateOrUpdateShortcutsForProfileAtPath(profile_path, CREATE_WHEN_NONE_FOUND,
                                          IGNORE_NON_PROFILE_SHORTCUTS);
}

void ProfileShortcutManagerWin::RemoveProfileShortcuts(
    const base::FilePath& profile_path) {
  BrowserThread::PostTask(
      BrowserThread::FILE, FROM_HERE,
      base::Bind(&DeleteDesktopShortcuts, profile_path, false));
}

void ProfileShortcutManagerWin::HasProfileShortcuts(
    const base::FilePath& profile_path,
    const base::Callback<void(bool)>& callback) {
  BrowserThread::PostTaskAndReplyWithResult(
      BrowserThread::FILE, FROM_HERE,
      base::Bind(&HasAnyProfileShortcuts, profile_path), callback);
}

void ProfileShortcutManagerWin::GetShortcutProperties(
    const base::FilePath& profile_path,
    base::CommandLine* command_line,
    base::string16* name,
    base::FilePath* icon_path) {
  base::FilePath chrome_exe;
  if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
    NOTREACHED();
    return;
  }

  const ProfileInfoCache& cache = profile_manager_->GetProfileInfoCache();
  size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
  DCHECK_LT(profile_index, cache.GetNumberOfProfiles());

  // The used profile name should be empty if there is only 1 profile.
  base::string16 shortcut_profile_name;
  if (cache.GetNumberOfProfiles() > 1)
    shortcut_profile_name = cache.GetNameOfProfileAtIndex(profile_index);

  *name = base::FilePath(profiles::internal::GetShortcutFilenameForProfile(
      shortcut_profile_name,
      BrowserDistribution::GetDistribution())).RemoveExtension().value();

  command_line->ParseFromString(L"\"" + chrome_exe.value() + L"\" " +
      profiles::internal::CreateProfileShortcutFlags(profile_path));

  *icon_path = profiles::internal::GetProfileIconPath(profile_path);
}

void ProfileShortcutManagerWin::OnProfileAdded(
    const base::FilePath& profile_path) {
  CreateOrUpdateProfileIcon(profile_path);
  if (profile_manager_->GetProfileInfoCache().GetNumberOfProfiles() == 2) {
    // When the second profile is added, make existing non-profile shortcuts
    // point to the first profile and be badged/named appropriately.
    CreateOrUpdateShortcutsForProfileAtPath(GetOtherProfilePath(profile_path),
                                            UPDATE_EXISTING_ONLY,
                                            UPDATE_NON_PROFILE_SHORTCUTS);
  }
}

void ProfileShortcutManagerWin::OnProfileWasRemoved(
    const base::FilePath& profile_path,
    const base::string16& profile_name) {
  const ProfileInfoCache& cache = profile_manager_->GetProfileInfoCache();
  // If there is only one profile remaining, remove the badging information
  // from an existing shortcut.
  const bool deleting_down_to_last_profile = (cache.GetNumberOfProfiles() == 1);
  if (deleting_down_to_last_profile) {
    // This is needed to unbadge the icon.
    CreateOrUpdateShortcutsForProfileAtPath(cache.GetPathOfProfileAtIndex(0),
                                            UPDATE_EXISTING_ONLY,
                                            IGNORE_NON_PROFILE_SHORTCUTS);
  }

  BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
                          base::Bind(&DeleteDesktopShortcuts,
                                     profile_path,
                                     deleting_down_to_last_profile));
}

void ProfileShortcutManagerWin::OnProfileNameChanged(
    const base::FilePath& profile_path,
    const base::string16& old_profile_name) {
  CreateOrUpdateShortcutsForProfileAtPath(profile_path, UPDATE_EXISTING_ONLY,
                                          IGNORE_NON_PROFILE_SHORTCUTS);
}

void ProfileShortcutManagerWin::OnProfileAvatarChanged(
    const base::FilePath& profile_path) {
  CreateOrUpdateProfileIcon(profile_path);
}

base::FilePath ProfileShortcutManagerWin::GetOtherProfilePath(
    const base::FilePath& profile_path) {
  const ProfileInfoCache& cache = profile_manager_->GetProfileInfoCache();
  DCHECK_EQ(2U, cache.GetNumberOfProfiles());
  // Get the index of the current profile, in order to find the index of the
  // other profile.
  size_t current_profile_index = cache.GetIndexOfProfileWithPath(profile_path);
  size_t other_profile_index = (current_profile_index == 0) ? 1 : 0;
  return cache.GetPathOfProfileAtIndex(other_profile_index);
}

void ProfileShortcutManagerWin::CreateOrUpdateShortcutsForProfileAtPath(
    const base::FilePath& profile_path,
    CreateOrUpdateMode create_mode,
    NonProfileShortcutAction action) {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
         BrowserThread::CurrentlyOn(BrowserThread::UI));
  CreateOrUpdateShortcutsParams params(profile_path, create_mode, action);

  ProfileInfoCache* cache = &profile_manager_->GetProfileInfoCache();
  size_t profile_index = cache->GetIndexOfProfileWithPath(profile_path);
  if (profile_index == std::string::npos)
    return;
  bool remove_badging = cache->GetNumberOfProfiles() == 1;

  params.old_profile_name =
      cache->GetShortcutNameOfProfileAtIndex(profile_index);

  // Exit early if the mode is to update existing profile shortcuts only and
  // none were ever created for this profile, per the shortcut name not being
  // set in the profile info cache.
  if (params.old_profile_name.empty() &&
      create_mode == UPDATE_EXISTING_ONLY &&
      action == IGNORE_NON_PROFILE_SHORTCUTS) {
    return;
  }

  if (!remove_badging) {
    params.profile_name = cache->GetNameOfProfileAtIndex(profile_index);

    // The profile might be using the Gaia avatar, which is not in the
    // resources array.
    bool has_gaia_image = false;
    if (cache->IsUsingGAIAPictureOfProfileAtIndex(profile_index)) {
      const gfx::Image* image =
          cache->GetGAIAPictureOfProfileAtIndex(profile_index);
      if (image) {
        params.avatar_image_1x = GetSkBitmapCopy(*image);
        // Gaia images are 256px, which makes them big enough to use in the
        // large icon case as well.
        DCHECK_GE(image->Width(), IconUtil::kLargeIconSize);
        params.avatar_image_2x = params.avatar_image_1x;
        has_gaia_image = true;
      }
    }

    // If the profile isn't using a Gaia image, or if the Gaia image did not
    // exist, revert to the previously used avatar icon.
    if (!has_gaia_image) {
      const size_t icon_index =
          cache->GetAvatarIconIndexOfProfileAtIndex(profile_index);
      const int resource_id_1x =
          profiles::GetDefaultAvatarIconResourceIDAtIndex(icon_index);
      const int resource_id_2x = kProfileAvatarIconResources2x[icon_index];
      // Make a copy of the SkBitmaps to ensure that we can safely use the image
      // data on the FILE thread.
      params.avatar_image_1x = GetImageResourceSkBitmapCopy(resource_id_1x);
      params.avatar_image_2x = GetImageResourceSkBitmapCopy(resource_id_2x);
    }
  }
  BrowserThread::PostTask(
      BrowserThread::FILE, FROM_HERE,
      base::Bind(&CreateOrUpdateDesktopShortcutsAndIconForProfile, params));

  cache->SetShortcutNameOfProfileAtIndex(profile_index,
                                         params.profile_name);
}

void ProfileShortcutManagerWin::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  switch (type) {
    // This notification is triggered when a profile is loaded.
    case chrome::NOTIFICATION_PROFILE_CREATED: {
      Profile* profile =
          content::Source<Profile>(source).ptr()->GetOriginalProfile();
      if (profile->GetPrefs()->GetInteger(prefs::kProfileIconVersion) <
          kCurrentProfileIconVersion) {
        // Ensure the profile's icon file has been created.
        CreateOrUpdateProfileIcon(profile->GetPath());
      }
      break;
    }
    default:
      NOTREACHED();
      break;
  }
}


text:
package co.ledger.wallet

import junit.framework.Assert

import scala.concurrent.{Promise, Await, Future}
import scala.concurrent.duration.Duration
import scala.util.Try
import scala.concurrent.ExecutionContext.Implicits.global

class InstrumentationTestCase extends android.test.InstrumentationTestCase {

  private[this] var _assertionPromise: Promise[Any] = null

  def await[A](future: Future[A], duration: Duration): A = {
    val promise = Promise[A]()
    _assertionPromise = promise.asInstanceOf[Promise[Any]]
    Await.result(Future.firstCompletedOf(Array(future, promise.future)), duration)
  }

  /** *
    * Ensure assertion to be safely catch by the test thread.
    * @param f The block of code to safely eval
    * @tparam A
    * @return
    */
  def eval[A](f: => A): A = {
      val t = Try(f)
      if (t.isFailure && _assertionPromise != null) {
        if (_assertionPromise != null)
          _assertionPromise.failure(t.failed.get)
        throw t.failed.get
      } else {
        t.get
      }
  }

}


text:
package javax.ws.rs.core;

import javax.ws.rs.ext.RuntimeDelegate;
import java.lang.annotation.Annotation;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

public abstract class Response {

    protected Response() {
    }

    public abstract int getStatus();

    public abstract StatusType getStatusInfo();

    public abstract Object getEntity();

    public abstract <T> T readEntity(Class<T> entityType);

    public abstract <T> T readEntity(GenericType<T> entityType);

    public abstract <T> T readEntity(Class<T> entityType, Annotation[] annotations);

    public abstract <T> T readEntity(GenericType<T> entityType, Annotation[] annotations);

    public abstract boolean hasEntity();

    public abstract boolean bufferEntity();

    public abstract void close();

    public abstract MediaType getMediaType();

    public abstract Locale getLanguage();

    public abstract int getLength();

    public abstract Set<String> getAllowedMethods();

    public abstract Map<String, NewCookie> getCookies();

    public abstract EntityTag getEntityTag();

    public abstract Date getDate();

    public abstract Date getLastModified();

    public abstract URI getLocation();

    public abstract Set<Link> getLinks();

    public abstract boolean hasLink(String relation);

    public abstract Link getLink(String relation);

    public abstract Link.Builder getLinkBuilder(String relation);

    public abstract MultivaluedMap<String, Object> getMetadata();

    public MultivaluedMap<String, Object> getHeaders() {
        return getMetadata();
    }

    public abstract MultivaluedMap<String, String> getStringHeaders();

    public abstract String getHeaderString(String name);

    public static ResponseBuilder fromResponse(Response response) {
        ResponseBuilder b = status(response.getStatus());
        if (response.hasEntity()) {
            b.entity(response.getEntity());
        }
        for (String headerName : response.getHeaders().keySet()) {
            List<Object> headerValues = response.getHeaders().get(headerName);
            for (Object headerValue : headerValues) {
                b.header(headerName, headerValue);
            }
        }
        return b;
    }

    public static ResponseBuilder status(StatusType status) {
        return ResponseBuilder.newInstance().status(status);
    }

    public static ResponseBuilder status(Status status) {
        return status((StatusType) status);
    }

    public static ResponseBuilder status(int status) {
        return ResponseBuilder.newInstance().status(status);
    }

    public static ResponseBuilder ok() {
        return status(Status.OK);
    }

    public static ResponseBuilder ok(Object entity) {
        ResponseBuilder b = ok();
        b.entity(entity);
        return b;
    }

    public static ResponseBuilder ok(Object entity, MediaType type) {
        return ok().entity(entity).type(type);
    }

    public static ResponseBuilder ok(Object entity, String type) {
        return ok().entity(entity).type(type);
    }

    public static ResponseBuilder ok(Object entity, Variant variant) {
        return ok().entity(entity).variant(variant);
    }

    public static ResponseBuilder serverError() {
        return status(Status.INTERNAL_SERVER_ERROR);
    }

    public static ResponseBuilder created(URI location) {
        return status(Status.CREATED).location(location);
    }

    public static ResponseBuilder accepted() {
        return status(Status.ACCEPTED);
    }

    public static ResponseBuilder accepted(Object entity) {
        return accepted().entity(entity);
    }

    public static ResponseBuilder noContent() {
        return status(Status.NO_CONTENT);
    }

    public static ResponseBuilder notModified() {
        return status(Status.NOT_MODIFIED);
    }

    public static ResponseBuilder notModified(EntityTag tag) {
        return notModified().tag(tag);
    }

    @SuppressWarnings("HtmlTagCanBeJavadocTag")
    public static ResponseBuilder notModified(String tag) {
        return notModified().tag(tag);
    }

    public static ResponseBuilder seeOther(URI location) {
        return status(Status.SEE_OTHER).location(location);
    }

    public static ResponseBuilder temporaryRedirect(URI location) {
        return status(Status.TEMPORARY_REDIRECT).location(location);
    }

    public static ResponseBuilder notAcceptable(List<Variant> variants) {
        return status(Status.NOT_ACCEPTABLE).variants(variants);
    }

    public static abstract class ResponseBuilder {

        protected ResponseBuilder() {
        }

        protected static ResponseBuilder newInstance() {
            return RuntimeDelegate.getInstance().createResponseBuilder();
        }

        public abstract Response build();

        @Override
        @SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException")
        public abstract ResponseBuilder clone();

        public abstract ResponseBuilder status(int status);

        public ResponseBuilder status(StatusType status) {
            if (status == null) {
                throw new IllegalArgumentException();
            }
            return status(status.getStatusCode());
        }

        public ResponseBuilder status(Status status) {
            return status((StatusType) status);
        }

        public abstract ResponseBuilder entity(Object entity);

        public abstract ResponseBuilder entity(Object entity, Annotation[] annotations);

        public abstract ResponseBuilder allow(String... methods);

        public abstract ResponseBuilder allow(Set<String> methods);

        public abstract ResponseBuilder cacheControl(CacheControl cacheControl);

        public abstract ResponseBuilder encoding(String encoding);

        public abstract ResponseBuilder header(String name, Object value);

        public abstract ResponseBuilder replaceAll(MultivaluedMap<String, Object> headers);

        public abstract ResponseBuilder language(String language);

        public abstract ResponseBuilder language(Locale language);

        public abstract ResponseBuilder type(MediaType type);

        public abstract ResponseBuilder type(String type);

        public abstract ResponseBuilder variant(Variant variant);

        public abstract ResponseBuilder contentLocation(URI location);

        public abstract ResponseBuilder cookie(NewCookie... cookies);

        public abstract ResponseBuilder expires(Date expires);

        public abstract ResponseBuilder lastModified(Date lastModified);

        public abstract ResponseBuilder location(URI location);

        public abstract ResponseBuilder tag(EntityTag tag);

        @SuppressWarnings("HtmlTagCanBeJavadocTag")
        public abstract ResponseBuilder tag(String tag);

        public abstract ResponseBuilder variants(Variant... variants);

        public abstract ResponseBuilder variants(List<Variant> variants);

        public abstract ResponseBuilder links(Link... links);

        public abstract ResponseBuilder link(URI uri, String rel);

        public abstract ResponseBuilder link(String uri, String rel);
    }

    public interface StatusType {

        public int getStatusCode();

        public Status.Family getFamily();

        public String getReasonPhrase();
    }

    public enum Status implements StatusType {

        OK(200, "OK"),

        CREATED(201, "Created"),

        ACCEPTED(202, "Accepted"),

        NO_CONTENT(204, "No Content"),

        RESET_CONTENT(205, "Reset Content"),

        PARTIAL_CONTENT(206, "Partial Content"),

        MOVED_PERMANENTLY(301, "Moved Permanently"),

        FOUND(302, "Found"),

        SEE_OTHER(303, "See Other"),

        NOT_MODIFIED(304, "Not Modified"),

        USE_PROXY(305, "Use Proxy"),

        TEMPORARY_REDIRECT(307, "Temporary Redirect"),

        BAD_REQUEST(400, "Bad Request"),

        UNAUTHORIZED(401, "Unauthorized"),

        PAYMENT_REQUIRED(402, "Payment Required"),

        FORBIDDEN(403, "Forbidden"),

        NOT_FOUND(404, "Not Found"),

        METHOD_NOT_ALLOWED(405, "Method Not Allowed"),

        NOT_ACCEPTABLE(406, "Not Acceptable"),

        PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"),

        REQUEST_TIMEOUT(408, "Request Timeout"),

        CONFLICT(409, "Conflict"),

        GONE(410, "Gone"),

        LENGTH_REQUIRED(411, "Length Required"),

        PRECONDITION_FAILED(412, "Precondition Failed"),

        REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"),

        REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"),

        UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),

        REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"),

        EXPECTATION_FAILED(417, "Expectation Failed"),

        INTERNAL_SERVER_ERROR(500, "Internal Server Error"),

        NOT_IMPLEMENTED(501, "Not Implemented"),

        BAD_GATEWAY(502, "Bad Gateway"),

        SERVICE_UNAVAILABLE(503, "Service Unavailable"),

        GATEWAY_TIMEOUT(504, "Gateway Timeout"),

        HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported");
        private final int code;
        private final String reason;
        private final Family family;

        public enum Family {

            INFORMATIONAL,

            SUCCESSFUL,

            REDIRECTION,

            CLIENT_ERROR,

            SERVER_ERROR,

            OTHER;

            public static Family familyOf(final int statusCode) {
                switch (statusCode / 100) {
                    case 1:
                        return Family.INFORMATIONAL;
                    case 2:
                        return Family.SUCCESSFUL;
                    case 3:
                        return Family.REDIRECTION;
                    case 4:
                        return Family.CLIENT_ERROR;
                    case 5:
                        return Family.SERVER_ERROR;
                    default:
                        return Family.OTHER;
                }
            }
        }

        Status(final int statusCode, final String reasonPhrase) {
            this.code = statusCode;
            this.reason = reasonPhrase;
            this.family = Family.familyOf(statusCode);
        }

        @Override
        public Family getFamily() {
            return family;
        }

        @Override
        public int getStatusCode() {
            return code;
        }

        @Override
        public String getReasonPhrase() {
            return toString();
        }

        @Override
        public String toString() {
            return reason;
        }

        public static Status fromStatusCode(final int statusCode) {
            for (Status s : Status.values()) {
                if (s.code == statusCode) {
                    return s;
                }
            }
            return null;
        }
    }
}


text:
#pragma once
#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include <fstream>
#include <string>
#include "paddle/fluid/framework/executor.h"
#include "paddle/fluid/inference/analysis/helper.h"

namespace paddle {
namespace inference {

// Read ProgramDesc from a __model__ file, defined in io.cc
extern void ReadBinaryFile(const std::string& filename, std::string* contents);

namespace analysis {

DEFINE_string(inference_model_dir, "", "inference test model dir");

}  // namespace analysis
}  // namespace inference
}  // namespace paddle


text:
package VMOMI::OvfElementInvalidValue;
use parent 'VMOMI::OvfElement';

use strict;
use warnings;

our @class_ancestors = (
    'OvfElement',
    'OvfInvalidPackage',
    'OvfFault',
    'VimFault',
    'MethodFault',
);

our @class_members = (
    ['value', undef, 0, ],
);

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;


text:
package org.apache.commons.text.diff;

import java.util.List;

/**
 * This interface is devoted to handle synchronized replacement sequences.
 *
 * @param <T> object type
 * @see ReplacementsFinder
 * @since 1.0
 */
public interface ReplacementsHandler<T> {

    /**
     * Handle two synchronized sequences.
     *

     * This method is called by a {@link ReplacementsFinder ReplacementsFinder}
     * instance when it has synchronized two sub-sequences of object arrays
     * being compared, and at least one of the sequences is non-empty. Since the
     * sequences are synchronized, the objects before the two sub-sequences are
     * equals (if they exist). This property also holds for the objects after
     * the two sub-sequences.
     *

     * The replacement is defined as replacing the from
     * sub-sequence into the to sub-sequence.
     *
     * @param skipped number of tokens skipped since the last call (i.e. number of
     *                tokens that were in both sequences), this number should be strictly positive
     *                except on the very first call where it can be zero (if the first object of
     *                the two sequences are different)
     * @param from    sub-sequence of objects coming from the first sequence
     * @param to      sub-sequence of objects coming from the second sequence
     */
    void handleReplacement(int skipped, List<T> from, List<T> to);

}


text:
.draw-container {
    display: flex;
    flex-flow: reverse;
}

.tool-panel {
    display: flex;
    flex-direction: column;
    width: 300px;
}

.draw-area {}