text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<META NAME="generator" CONTENT="http://txt2tags.sf.net">

6. ADDING OR IMPROVING A LANGUAGE

Most of the work doesn't need any programming knowledge. Just an understanding of the language, an awareness of its features, patience and attention to detail. Wikipedia is a good source of basic phonetic information, eg http://en.wikipedia.org/wiki/Vowel.

 In many cases it should be fairly easy to add a rough implementation of a new language, hopefully enough to be intelligible. After that it's a gradual process of improvement.

6.1 Language Code

Generally, the language's international ISO 639-1 code is used to identify the language. It is used in the filenames which contain the language's data. In the examples below the code "fr" is used as an example. Replace this with the code of your language.

If the language does not have a 2-letter ISO_639-1 code, then use the 3-letter ISO_639-3 code.  Language codes may differ from country codes.

It is possible to have different variants of a language for different dialects.  For example the sound of some phonemes are changed, or some of the pronunciation rules differ.

6.2 Language Files

The following files are needed for your language.

espeak-data/voices/fr.  The voice file.  This gives the language name and may set some options.

phsource/ph_french.  The phoneme definition file.  This contains phoneme definitions for the vowels and consonants which the language uses.  Usually it will contain mostly vowels.  Most consonants will be inherited from the common phoneme definitions in the master phoneme file, phsource/phonemes.  The master phoneme file needs to be edited to call your new ph_french file.

dictsource/fr_rules.  This contains the spelling-to-phoneme translation rules.

dictsource/fr_list.  This contains pronunciations for numbers, letter and symbol names, and words with exceptional pronunciations.  It also gives attributes such as "unstressed" and "pause" to some common words.

The fr_rules and fr_list files are compiled to produce the file espeak-data/fr_dict, which eSpeak uses when it is speaking.

6.3 Voice File

Each language needs a voice file in espeak-data/voices or espeak-data/voices/test. The filename of the default voice for a language should be the same as the language code (eg. "fr" for French).

Details of the contents of voice files are given in voices.html.

The simplest voice file would contain just 2 lines to give the language name and language code, eg:

  name french
  language fr

This language code specifies which phoneme table and dictionary to use (i.e. phonemetable fr and  espeak-data/fr_dict) to be used. If needed, these can be overridden by phonemes and dictionary attributes in the voice file.  For example you may want to start the implementation of a new language by using the phoneme table of an existing language.

6.4 Phoneme Definition File

You must first decide on the set of phonemes (vowel and consonant sounds) for the language. These should be defined in a phoneme definition file ph_xxxx, where "ph_xxxx" is the name of your language. A reference to this file is then included at the end of the master phoneme file, phsource/phonemes,  eg:

  phonemetable  fr  base
  include  ph_french

This example defines a phoneme table "fr" which inherits the contents of phoneme table "base". Its contents are found in the file ph_french.

The base phoneme table contains definitions of a basic set of consonants, and also some "control" phonemes such as stress marks and pauses. These are defined in phsource/phonemes. The phoneme table for a language will inherit these, or alternatively it may inherit the phoneme table of another language which in turn inherits the base phoneme table.

The phonemes file for the language defines those additional phonemes which are not inherited (generally the vowels and diphthongs, plus any additional consonants that are needed), or phonemes whose definitions differ from the inherited version (eg. the redefinition of a consonant).

Details of phonemes files are given in phontab.html.

The Compile phoneme data function of the espeakedit program compiles the phonemes files of all languages to produce the files espeak-data/phontab, phonindex, and phondata which are used by eSpeak.

For many languages, the consonant phonemes which are already available in eSpeak, together with the available vowel files which can be used to define vowel phonemes, will be sufficient.  At least for an initial implementation.

6.5 Dictionary Files

Once the language's phonemes have been defined, then pronunciation dictionary data can be produced in order to translate the language's source text into phonemes. This consists of two source files: fr_rules (the spelling to phoneme rules) and fr_list (an exceptions list, and attributes of certain words). The corresponding compiled data file is espeak-data/fr_dict which is produced from fr_rules and fr_list sources by the command:

	espeak --compile=fr.

Or by using the espeakedit program.

Details of the contents of the dictionary files are given in dictionary.html.

The fr_list file contains:

Pronunciations which exceptions to the rules in fr_rules, (eg. foreign names).

Pronunciation of letter names, symbol names, and punctuation names.

Pronunciation of numbers.

Attributes for words.  For example, common function words which should not be stressed, or conjunctions which should be preceded by a pause.

6.6 Program Code

The behaviour of the eSpeak program is controlled by various options such as:

Default rules for which syllable of a word has the main stress.

Relative lengths and amplitude of vowels in stressed and unstressed syllables.

Which intonation tunes to use.

Rules for speaking numbers.

The function SetTranslator() at the start of the source code file tr_languages.cpp recognizes the language code and sets the appropriate options.  For a new language, you would add its language code and the required options in SetTranslator(). However, this may not be necessary during testing because most of the options can also be set in the voice file in espeak-data/voices (see Voice files).

6.7 Improving a Language

Listen carefully to the eSpeak voice.  Try to identify what sounds wrong and what needs to be improved.

Make the spelling-to-phoneme translation rules more accurate, including the position of stressed syllables within words. Some languages are easier than others. I expect most are easier than English.

Improve the sounds of the phonemes. It may be that a phoneme should sound different depending on adjacent sounds, or whether it's at the start or the end of a word, between vowels, in a stressed or unstressed syllable, etc. This may consist of making small adjustments to vowel and diphthong quality or length, or adjusting the strength of consonants. Phoneme definitions can include conditional statements which can be used to change the sound of a phoneme depending on its environment.  Bigger changes may be recording new or replacement consonant sounds, or may even need program code to implement new types of sounds.

Some common words should be added to the dictionary (the fr_list file for the language) with an "unstressed" attribute $u or $u+ (eg. in English, words such as "the", "is", "had", "my", "she", "of", "in", "some"), or should be preceded by a short pause (such as "and", "but", "which"), or have other attributes, in order to make the speech flow better.

Improve the rhythm of the speech by adjusting the relative lengths of vowels in different contexts, eg. stressed/unstressed syllable, or depending on the following phonemes. This is important for making the speech sound good for the language.

Make new intonation "tunes" for statements or questions (see Intonation).

If you are interested in working on a language, please contact me so that I can set up the initial data and discuss the features of the language.

For most of the eSpeak voices, I do not speak or understand the language, and I do not know how it should sound. I can only make improvements as a result of feedback from speakers of that language. If you want to help to improve a language, listen carefully and try to identify individual errors, either in the spelling-to-phoneme translation, the position of stressed syllables within words, or the sound of phonemes, or problems with rhythm and vowel lengths.


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DatilClientLibrary
{

    ///
    /// Clase de la retención
    ///
    public class Retencion
    {
        /// Número de secuencia de la retención.
        public string Secuencial { get; set; }

        ///Fecha de emisión de la retención.
        public DateTimeOffset FechaEmision { get; set; }
        // ToString("yyyy-MM-dd HH':'mm':'ss")

        ///Pruebas: 1.Producción 2..
        public int Ambiente { get; set; }

        ///Emisión normal: 1.  Emisión por indisponibilidad: 2
        public int TipoEmision { get; set; }

        ///Versión del formato de comprobantes electrónicos de SRI. Si no se especifica, se utilizará la última revisión del formato implementada.
        public string Version { get; set; }

        ///La clave de acceso representa un identificador único del comprobante.Si esta información no es provista, Dátil la generará.
        public string ClaveAcceso { get; set; }

        ///Periodo fiscal, en el formato MM/AAAA. Ejemplo: 09/2016
        public string PeriodoFiscal { get; set; }

        ///
        /// Emisor (persona natural o jurídica) del producto o servicio que consta en la retención.
        ///
        /// <see cref="Emisor"/>
        public Emisor Emisor { get; set; }

        ///
        /// Comprador del producto o servicio que consta en la retención.
        ///
        /// <see cref="Comprador"/>
        public Comprador Sujeto { get; set; }

        ///
        /// Lista de impuestos detallados en la retención.
        ///
        /// <see cref="ItemRetencion"/>
        public List<ItemRetencion> items { get; set; }

        ///
        /// Información adicional de la retención.
        ///
        public Dictionary<string, string> InformacionAdicional { get; set; }

        ///
        /// Construir una nueva Retención.
        ///
        public Retencion()
        {
            Version = "1.0.0";
            TipoEmision = 1;
            Ambiente = 1;
            ClaveAcceso = null;
        }

        ///
        /// Consultar información de la retencíón previamente enviada.
        ///
        /// <param name="requestOptions"></param>
        /// <returns>Información de la retención enviada</returns>
        public static string Consultar(RequestOptions requestOptions)
        {
            Console.WriteLine("Consultando Retención");
            var apiRequest = new ApiRequest(requestOptions);
            return apiRequest.Get();

        }

        ///
        /// Convertir el objeto Retención a una representaciòn json
        ///
        /// <returns>La representación Json</returns>
        public string toJson()
        {
            var jsonSettings = new JsonSerializerSettings
            {
                ContractResolver = new SnakeCaseContractResolver(),
                NullValueHandling = NullValueHandling.Ignore

            };
            var json = JsonConvert.SerializeObject(this, jsonSettings);
            return json;
        }

        ///
        /// Enviar información de la retención para generarla electrónicamente.
        ///
        /// <param name="requestOptions"></param>
        /// <returns>Información de la retención enviada</returns>
        public String Enviar(RequestOptions requestOptions)
        {
            Console.WriteLine("Enviando retención");

            var apiRequest = new ApiRequest(requestOptions);
            return apiRequest.Post(this.toJson());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.datastax.oss.driver.internal.core.metadata.token;

import com.datastax.oss.driver.api.core.metadata.Node;
import com.datastax.oss.driver.api.core.metadata.token.Token;
import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap;
import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.jcip.annotations.ThreadSafe;

@ThreadSafe
class LocalReplicationStrategy implements ReplicationStrategy {

  @Override
  public Map<Token, Set<Node>> computeReplicasByToken(
      Map<Token, Node> tokenToPrimary, List<Token> ring) {
    ImmutableMap.Builder<Token, Set<Node>> result = ImmutableMap.builder();
    // Each token maps to exactly one node
    for (Map.Entry<Token, Node> entry : tokenToPrimary.entrySet()) {
      result.put(entry.getKey(), ImmutableSet.of(entry.getValue()));
    }
    return result.build();
  }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Enchir. fung. (Paris) 164 (1886)

#### Original name
Boletus ovinus Schaeff., 1774

### Remarks
null


text:
import React from 'react'
import renderer from 'react-test-renderer'
import { ColorSelect } from './index'
import { Text, Button } from 'kitten'

describe('<ColorSelect />', () => {
  it('should match its snapshot with props', () => {
    const tree = renderer
      .create(
        <ColorSelect
          name="test-color-select"
          onChange={() => {}}
          value="#556954"
          contrastColor="#555"
          contrastRatio={3}
          inputProps={{
            id: 'test-color-select',
            'aria-label': 'Code hexadécimal de la couleur',
          }}
        />,
      )
      .toJSON()

    expect(tree).toMatchSnapshot()
  })
  it('should match its snapshot with props and children', () => {
    const tree = renderer
      .create(
        <ColorSelect
          name="test-color-select"
          onChange={() => {}}
          value="#556954"
          contrastColor="#555"
          contrastRatio={3}
          inputProps={{
            id: 'test-color-select',
            'aria-label': 'Code hexadécimal de la couleur',
          }}
        >
          <div
            className="k-u-flex k-u-flex-alignItems-center k-u-flex-justifyContent-end k-u-flex-gap-single"
            style={{
              '--color-primary-100': '#7ab3ff',
              '--color-primary-300': '#3d8fff',
              '--color-primary-500': '#006cff',
              '--color-primary-700': '#0052c2',
              '--color-primary-900': '#003885',
            }}
          >
            <Text size="small">Rendu :</Text>
            <Button
              modifier="helium"
              rounded
              size="small"
              fit="content"
              type="button"
            >
              S'abonner
            </Button>
          </div>
        </ColorSelect>,
      )
      .toJSON()

    expect(tree).toMatchSnapshot()
  })
})


text:
namespace Cassandra.DataStax.Auth
{
    /// <summary>
    /// Base class for Authenticator implementations that want to make use of
    /// the authentication scheme negotiation in the DseAuthenticator
    /// </summary>
    internal abstract class BaseDseAuthenticator : IAuthenticator
    {
        private readonly string _name;
        private const string DseAuthenticatorName = "com.datastax.bdp.cassandra.auth.DseAuthenticator";

        protected BaseDseAuthenticator(string name)
        {
            _name = name;
        }

        protected abstract byte[] GetMechanism();

        protected abstract byte[] GetInitialServerChallenge();

        public virtual byte[] InitialResponse()
        {
            if (!IsDseAuthenticator())
            {
                //fallback
                return EvaluateChallenge(GetInitialServerChallenge());
            }
            //send the mechanism as a first auth message
            return GetMechanism();
        }

        public abstract byte[] EvaluateChallenge(byte[] challenge);

        protected bool IsDseAuthenticator()
        {
            return _name == BaseDseAuthenticator.DseAuthenticatorName;
        }
    }
}


text:
body {
  font-family: 'Lora', 'Times New Roman', serif;
  font-size: 20px;
  color: #404040;
}
p {
  line-height: 1.5;
  margin: 30px 0;
}
h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-weight: 800;
}
a {
  color: #009ee3;
}
a:hover,
a:focus {
  color: #009ee3;
}
a img:hover,
a img:focus {
  cursor: zoom-in;
}
blockquote {
  color: #808080;
  font-style: italic;
}
hr.small {
  max-width: 100px;
  margin: 15px auto;
  border-width: 4px;
  border-color: white;
}
.navbar-custom {
  background: white;
  position: absolute;
  top: 0;
  margin-left: auto;
  margin-right: auto;
  z-index: 3;
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

@media only screen and (min-width: 750px) {
  .navbar-custom {

     width: 750px;
  }
}

@media only screen and (min-width: 1000px) {
  .navbar-custom {

     width: 1000px;
  }
}

@media only screen and (min-width: 1200px) {
  .navbar-custom {

     width: 1200px;
  }
}

@media only screen and (min-width: 1400px) {
  .navbar-custom {

     width: 1400px;
  }
}

.navbar-custom .navbar-brand {
  font-weight: 800;
}
.navbar-custom .nav li a {
  text-transform: uppercase;
  font-size: 14px;
  font-weight: 600;
}
@media only screen and (min-width: 768px) {
  .navbar-custom {
    background: transparent;
    border-bottom: 1px solid transparent;
  }
  .navbar-custom .navbar-brand {
    color: white;
    padding: 20px;
  }
  .navbar-custom .navbar-brand:hover,
  .navbar-custom .navbar-brand:focus {
    color: rgba(255, 255, 255, 0.8);
  }
  .navbar-custom .nav li a {
    color: #009ee3;
  }
  .navbar-custom .nav li a:hover,
  .navbar-custom .nav li a:focus {
    color: #e5007d;
  }
}
@media only screen and (min-width: 1170px) {
  .navbar-custom {
    -webkit-transition: background-color 0.3s;
    -moz-transition: background-color 0.3s;
    transition: background-color 0.3s;
    /* Force Hardware Acceleration in WebKit */
    -webkit-transform: translate3d(0, 0, 0);
    -moz-transform: translate3d(0, 0, 0);
    -ms-transform: translate3d(0, 0, 0);
    -o-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
  }
  .navbar-custom.is-fixed {
    /* when the user scrolls down, we hide the header right above the viewport */
    position: fixed;
    top: -61px;
    background-color: rgba(255, 255, 255, 0.9);
    border-bottom: 1px solid #f2f2f2;
    -webkit-transition: -webkit-transform 0.3s;
    -moz-transition: -moz-transform 0.3s;
    transition: transform 0.3s;
  }
  .navbar-custom.is-fixed .navbar-brand {
    color: #404040;
  }
  .navbar-custom.is-fixed .navbar-brand:hover,
  .navbar-custom.is-fixed .navbar-brand:focus {
    color: #0085a1;
  }
  .navbar-custom.is-fixed .nav li a {
    color: #404040;
  }
  .navbar-custom.is-fixed .nav li a:hover,
  .navbar-custom.is-fixed .nav li a:focus {
    color: #0085a1;
  }
  .navbar-custom.is-visible {
    /* if the user changes the scrolling direction, we show the header */
    -webkit-transform: translate3d(0, 100%, 0);
    -moz-transform: translate3d(0, 100%, 0);
    -ms-transform: translate3d(0, 100%, 0);
    -o-transform: translate3d(0, 100%, 0);
    transform: translate3d(0, 100%, 0);
  }
}
.navbar-right {
  padding-right: 20px;
}
.intro-header {
  background: no-repeat center center;
  background-color: #808080;
  background-attachment: scroll;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  margin-bottom: 50px;
  margin-top: 79px;
  background-position: top;
}
.intro-header .site-heading,
.intro-header .post-heading,
.intro-header .page-heading {
  padding: 100px 0 50px;
  color: white;
}
@media only screen and (min-width: 768px) {
  .intro-header .site-heading,
  .intro-header .post-heading,
  .intro-header .page-heading {
    padding: 0;
    padding-top: 125px;
    padding-bottom: 160px;
  }
}
.intro-header .site-heading,
.intro-header .page-heading {
  text-align: left;
}
.intro-header .site-heading h1,
.intro-header .page-heading h1 {
  margin-top: 0;
  font-size: 50px;
}
.intro-header .site-heading .subheading,
.intro-header .page-heading .subheading {
    font-size: 25px;
    font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
    font-weight: 600;
    padding-left: 30px;
}

@media only screen and (min-width: 768px) {
  .intro-header .site-heading h1,
  .intro-header .page-heading h1 {
    font-size: 60px;
  }
}
.intro-header .post-heading h1 {
  font-size: 35px;
}
.intro-header .post-heading .subheading,
.intro-header .post-heading .meta {
  line-height: 1.1;
  display: block;
}
.intro-header .post-heading .subheading {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-size: 24px;
  margin: 10px 0 30px;
  font-weight: 600;
}
.intro-header .post-heading .meta {
  font-family: 'Lora', 'Times New Roman', serif;
  font-style: italic;
  font-weight: 300;
  font-size: 20px;
}
.intro-header .post-heading .meta a {
  color: white;
}
@media only screen and (min-width: 768px) {
  .intro-header .post-heading h1 {
    font-size: 42px;
  }
  .intro-header .post-heading .subheading {
    font-size: 25px;
  }
}
.post-preview > a {
  color: #404040;
}
.post-preview > a:hover,
.post-preview > a:focus {
  text-decoration: none;
  color: #0085a1;
}
.post-preview > a > .post-title {
  font-size: 30px;
  margin-top: 30px;
  margin-bottom: 10px;
}
.post-preview > a > .post-subtitle {
  margin: 0;
  font-weight: normal;
  margin-bottom: 10px;
  color: #009ee3;
  display: block;
  margin-left: 0px;
  padding-left: 0px;
  border-bottom: none;
  line-height: auto;
  padding-right: 0px;
}
.post-preview > .post-meta {
  color: #808080;
  font-size: 18px;
  font-style: italic;
  margin-top: 0;
}
.post-preview > .post-meta > a {
  text-decoration: none;
  color: #404040;
}
.post-preview > .post-meta > a:hover,
.post-preview > .post-meta > a:focus {
  color: #0085a1;
  text-decoration: underline;
}
@media only screen and (min-width: 768px) {
  .post-preview > a > .post-title {
    font-size: 36px;
  }
}
.section-heading {
  font-size: 36px;
  margin-top: 60px;
  font-weight: 700;
}
.caption {
  text-align: center;
  font-size: 14px;
  padding: 10px;
  font-style: italic;
  margin: 0;
  display: block;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
}
footer {
  padding: 50px 0 65px;
}
footer .list-inline {
  margin: 0;
  padding: 0;
}
footer .copyright {
  font-size: 14px;
  text-align: center;
  margin-bottom: 0;
}
.floating-label-form-group {
  font-size: 14px;
  position: relative;
  margin-bottom: 0;
  padding-bottom: 0.5em;
  border-bottom: 1px solid #eeeeee;
}
.floating-label-form-group input,
.floating-label-form-group textarea {
  z-index: 1;
  position: relative;
  padding-right: 0;
  padding-left: 0;
  border: none;
  border-radius: 0;
  font-size: 1.5em;
  background: none;
  box-shadow: none !important;
  resize: none;
}
.floating-label-form-group label {
  display: block;
  z-index: 0;
  position: relative;
  top: 2em;
  margin: 0;
  font-size: 0.85em;
  line-height: 1.764705882em;
  vertical-align: middle;
  vertical-align: baseline;
  opacity: 0;
  -webkit-transition: top 0.3s ease,opacity 0.3s ease;
  -moz-transition: top 0.3s ease,opacity 0.3s ease;
  -ms-transition: top 0.3s ease,opacity 0.3s ease;
  transition: top 0.3s ease,opacity 0.3s ease;
}
.floating-label-form-group::not(:first-child) {
  padding-left: 14px;
  border-left: 1px solid #eeeeee;
}
.floating-label-form-group-with-value label {
  top: 0;
  opacity: 1;
}
.floating-label-form-group-with-focus label {
  color: #0085a1;
}
form .row:first-child .floating-label-form-group {
  border-top: 1px solid #eeeeee;
}
.btn {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-size: 14px;
  font-weight: 800;
  letter-spacing: 1px;
  border-radius: 0;
  padding: 15px 25px;
}
.btn-lg {
  font-size: 16px;
  padding: 25px 35px;
}
.btn-default:hover,
.btn-default:focus {
  background-color: #0085a1;
  border: 1px solid #0085a1;
  color: white;
}
.pager {
  margin: 20px 0 0;
}
.pager li > a,
.pager li > span {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-size: 14px;
  font-weight: 800;
  letter-spacing: 1px;
  padding: 10px 5px;
  background-color: white;
  border-radius: 0;
}
@media only screen and (min-width: 768px) {
  .pager li > a,
  .pager li > span {
    font-size: 14px;
    padding: 15px 25px;
  }
}
.pager li > a:hover,
.pager li > a:focus {
  color: white;
  background-color: #0085a1;
  border: 1px solid #0085a1;
}
.pager .disabled > a,
.pager .disabled > a:hover,
.pager .disabled > a:focus,
.pager .disabled > span {
  color: #808080;
  background-color: #404040;
  cursor: not-allowed;
}
::-moz-selection {
  color: white;
  text-shadow: none;
  background: #0085a1;
}
::selection {
  color: white;
  text-shadow: none;
  background: #0085a1;
}
img::selection {
  color: white;
  background: transparent;
}
img::-moz-selection {
  color: white;
  background: transparent;
}
body {
  webkit-tap-highlight-color: #0085a1;
}

.intro-header div.post-heading, header div.site-heading {

  padding-left: 150px !important;
  margin-left: -150px !important;
  background: url('../img/big-pink-stroke.png') 0px 100px no-repeat scroll;
}

.intro-header div.post-heading h1, header div.site-heading h1 {

  color: #ffed00;
}

.intro-header div.post-heading h2, .intro-header .site-heading p {

    background: #009ee3;
    padding: 5px 15px;
    margin-left: 50px !important;
    color: #ffffff;
    border-radius: 7px;
    display: block;
}

.intro-header .site-heading p {

    margin: 0.7em;
}

h2.post-title, h2.section-heading, .page-content h2 {

   display: block;
   background: transparent url('../img/postheadingbg.png') left center repeat-y;
   padding: 10px 10px 10px 120px;
   margin-left: -120px;
   color: #e5007d;
}

.page-content h3, .page-content h4, .page-content h5, .page-content h6, article h3, article h4, article h5, article h6 {

    display: inline-block;
    color: #e5007d;
    margin-left: -66px;
    padding-left: 66px;
    border-bottom: 2px solid #009ee3;
    line-height: 1.5;
    padding-right: 33px;
    margin-bottom: 1em;
}

.logo-div {

    margin-right: 30px !important;
}

.intro-header {

  -webkit-box-shadow: 0px 0px 12px 0px rgba(56,56,56,1);
  -moz-box-shadow: 0px 0px 12px 0px rgba(56,56,56,1);
  box-shadow: 0px 0px 12px 0px rgba(56,56,56,1);
}

article h1 {

    color: #009ee3;
}

.footernav {
  text-align: center;
  margin-top: 1em;
}

.footernav a {
   font-weight: bold;
   text-decoration: none;
   font-size: 0.9em;
}

@media only screen and (min-width: 768px) {
   ul li ul.submenu {

       position: absolute;
       z-index: 99999;
       list-style-type: none;
       display: none;
       padding: 0px;
       padding-bottom: 5px;
       -webkit-border-bottom-right-radius: 7px;
       -webkit-border-bottom-left-radius: 7px;
       -moz-border-radius-bottomright: 7px;
       -moz-border-radius-bottomleft: 7px;
       border-bottom-right-radius: 7px;
       border-bottom-left-radius: 7px;
       background: #ffffff;
       border: 1px solid #009ee3;
       border-top: 0px;
       opacity: 0.9;
   }

   ul li:hover ul.submenu {

     display: inline-block;
   }

   ul.submenu li {
      padding-left: 16px;
      padding-right: 16px;
      padding-top: 2px;
      padding-bottom: 2px;
   }
}

.logo-div img {
}


text:
export function getFileExtension( name : string) : string {
    return /(?:\.([^.]+))?$/.exec(name)[1];
}

export function randcolor() : string {
    return "rgb(" + Math.floor(Math.random()*255)
        + "," + Math.floor(Math.random()*255) + ","
        + Math.floor(Math.random()*255) + ")"
}
export class Dimension {
    width : number;
    height : number;
}
export function getTextDimensions(text : string, font : string) : Dimension {
    var canvas = $("#canvas").get(0) as HTMLCanvasElement;
    var context = canvas.getContext("2d");
    context.font = font;
    var metrics = context.measureText(text);
    return {
        width : metrics.width,
        height: parseInt(window.getComputedStyle(canvas, font).fontSize, 10)
    };
}
export function Uint8ToString(u8a : Uint8Array) : string{
    var CHUNK_SZ = 0x8000;
    var c = "";
    for (var i=0; i < u8a.length; i+=CHUNK_SZ) {
        c += String.fromCharCode.apply(null, u8a.subarray(i, i+CHUNK_SZ));
    }
    return c;
}

export function hexByteStr( hex : number) : string {
    var str = (hex&0xFF).toString(16);
    while( str.length < 2) str = "0"+str;
    return str;
}

export class Queue<T> {
    private data : any[] = [];
    private start = 0;

    getLength() : number { return this.data.length - this.start;}
    isEmpty() : boolean { return (this.data.length == 0);}
    enqueue( entry : T) {this.data.push(entry);}
    dequeue() : T {
        if( this.data.length == 0) return undefined;

        var ret = this.data[this.start++];
        if( this.start*2 >= this.data.length) {
            this.data = this.data.slice(this.start);
            this.start = 0;
        }
        return ret;
    }
    peek() : T {
        return this.data[this.start];
    }
}


text: export * from "./nativescript-fresco.module";


text:
package com.roncoo.adminlte.controller.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.roncoo.adminlte.bean.entity.RcDataDictionaryList;
import com.roncoo.adminlte.bean.entity.RcEmailAccountInfo;
import com.roncoo.adminlte.bean.vo.Result;
import com.roncoo.adminlte.biz.EmailAccountInfoBiz;
import com.roncoo.adminlte.util.base.BaseController;
import com.roncoo.adminlte.util.base.Page;
import com.roncoo.adminlte.util.base.PageBean;

/**
 * 邮件账号controller
 *
 * @author LYQ
 */
@Controller
@RequestMapping(value = "/admin/emailAccountInfo/", method = RequestMethod.POST)
public class EmailAccountInfoController extends BaseController {

	private static final String FIELDCODE = "host_code";

	@Autowired
	private EmailAccountInfoBiz biz;

	/**
	 * 列表
	 */
	@RequestMapping(value = LIST, method = RequestMethod.GET)
	public void list() {
	}

	/**
	 * 分页查询
	 *
	 * @param start
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = PAGE)
	public PageBean<RcEmailAccountInfo> queryForPage(@RequestParam(value = "start", defaultValue = "1") int start, @RequestParam(value = "length", defaultValue = "10") int pageSize,@RequestParam(value="date",required=false)String  date,@RequestParam(value="search",required=false)String search) {
		int pageCurrent = (start / pageSize) + 1;
		Result<Page<RcEmailAccountInfo>> result = biz.listForPage(pageCurrent, pageSize,search,date);
		return new PageBean<>(result.getResultData());
	}

	/**
	 * 添加
	 *
	 * @param modelMap
	 */
	@RequestMapping(value = ADD, method = RequestMethod.GET)
	public void add(ModelMap modelMap) {
		Result<List<RcDataDictionaryList>> result = biz.listByFieldCode(FIELDCODE);
		if (result.isStatus()) {
			modelMap.put("selectList", result.getResultData());
		}
	}

	/**
	 * 保存
	 *
	 * @param info
	 * @return
	 */
	@RequestMapping(value = SAVE)
	public String save(RcEmailAccountInfo info) {
		Result<RcEmailAccountInfo> result = biz.save(info);
		if (result.isStatus()) {
			return "/admin/emailAccountInfo/list";
		}
		return null;
	}

	/**
	 * 删除
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = DELETE, method = RequestMethod.GET)
	public String delete(@RequestParam Long id) {
		Result<RcEmailAccountInfo> result = biz.delete(id);
		if (result.isStatus()) {
			return redirect("/admin/emailAccountInfo/list");
		}
		return "admin/emailAccountInfo/list";
	}

	/**
	 * 查看
	 *
	 * @param id
	 * @param modelMap
	 */
	@RequestMapping(value = VIEW, method = RequestMethod.GET)
	public void view(@RequestParam Long id, ModelMap modelMap) {
		Result<RcEmailAccountInfo> result = biz.query(id);
		if (result.isStatus()) {
			modelMap.put("info", result.getResultData());
		}
	}

	/**
	 * 编辑
	 *
	 * @param id
	 * @param modelMap
	 */
	@RequestMapping(value = EDIT, method = RequestMethod.GET)
	public void edit(@RequestParam Long id, ModelMap modelMap) {
		Result<List<RcDataDictionaryList>> dictionaryListResult = biz.listByFieldCode(FIELDCODE);
		Result<RcEmailAccountInfo> emailAccountResult = biz.query(id);
		if (dictionaryListResult.isStatus()) {
			modelMap.put("selectList", dictionaryListResult.getResultData());
		}
		if (emailAccountResult.isStatus()) {
			modelMap.put("info", emailAccountResult.getResultData());
		}
	}

	/**
	 * 更新
	 *
	 * @param info
	 * @return
	 */
	@RequestMapping(value = UPDATE)
	public String update(@ModelAttribute RcEmailAccountInfo info) {
		Result<RcEmailAccountInfo> result = biz.update(info);
		if (result.isStatus()) {
			return redirect("/admin/emailAccountInfo/list");
		}
		return "admin/emailAccountInfo/list";
	}
}


text:
<?php
#===============================================================================
# DEFINE: Administration
#===============================================================================
const ADMINISTRATION = TRUE;
const AUTHENTICATION = TRUE;

#===============================================================================
# INCLUDE: Initialization
#===============================================================================
require '../../core/application.php';

#===============================================================================
# Get repositories
#===============================================================================
$PageRepository = Application::getRepository('Page');
$UserRepository = Application::getRepository('User');

#===============================================================================
# Pagination
#===============================================================================
$site_size = Application::get('ADMIN.PAGE.LIST_SIZE');
$site_sort = Application::get('ADMIN.PAGE.LIST_SORT');

$count = $PageRepository->getCount();
$lastSite = ceil($count / $site_size);

$currentSite = HTTP::GET('site') ?? 1;
$currentSite = intval($currentSite);

#===============================================================================
# Redirect to page create form if no page exists
#===============================================================================
if(!$count) {
	HTTP::redirect(Application::getAdminURL('page/insert.php'));
}

if($currentSite < 1 OR ($currentSite > $lastSite AND $lastSite > 0)) {
	Application::error404();
}

#===============================================================================
# Get paginated page list
#===============================================================================
$pages = $PageRepository->getPaginated(
	$site_sort,
	$site_size,
	($currentSite-1) * $site_size
);

foreach($pages as $Page) {
	$User = $UserRepository->find($Page->get('user'));
	$templates[] = generatePageItemTemplate($Page, $User);
}

#===============================================================================
# Build document
#===============================================================================
$ListTemplate = Template\Factory::build('page/index');
$ListTemplate->set('LIST', [
	'PAGES' => $templates ?? []
]);

$ListTemplate->set('PAGINATION', [
	'THIS' => $currentSite,
	'LAST' => $lastSite,
	'HTML' => createPaginationTemplate(
		$currentSite, $lastSite, Application::getAdminURL('page/')
	)
]);

$MainTemplate = Template\Factory::build('main');
$MainTemplate->set('NAME', $Language->text('title_page_overview', $currentSite));
$MainTemplate->set('HTML', $ListTemplate);
echo $MainTemplate;


text:
//
//  MeshModel.h
//  Mars
//
//  Created by Daniel M.C. on 16/12/2012.
//  Copyright (c) 2012 Daniel M.C. All rights reserved.
//

#ifndef __Mars__MeshModel__
#define __Mars__MeshModel__

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

#include <map>

#include <glm/glm.hpp>
#include <GL/glew.h>
#include <GL/glfw.h>

#include "Mesh.h"

class MeshModel: public Mesh {
	void indexVBO(std::vector<glm::vec3> & in_vertices,
								std::vector<glm::vec2> & in_uvs,
								std::vector<glm::vec3> & in_normals,

								std::vector<unsigned short> & out_indices,
								std::vector<glm::vec3> & out_vertices,
								std::vector<glm::vec2> & out_uvs,
								std::vector<glm::vec3> & out_normals
);
public:
	MeshModel(const char *);
	void draw();
};

#endif /* defined(__Mars__MeshModel__) */


text:
use std::convert::From;
use std::fmt;

#[derive(Clone, Debug, PartialEq)]
pub struct Response {
    pub status: Status,
    pub headers: Vec<(String, String)>,
    pub body: String,
}

impl Default for Response {
    fn default() -> Self {
        Response {
            status: Status::Ok,
            headers: Vec::new(),
            body: String::new(),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum Status {
    Continue,
    SwitchingProtocols,
    Processing,
    Ok,
    Created,
    Accepted,
    NonAuthoritativeInformation,
    NoContent,
    ResetContent,
    PartialContent,
    MultiStatus,
    AlreadyReported,
    IMUsed,
    MultipleChoices,
    MovedPermanently,
    Found,
    SeeOther,
    NotModified,
    UseProxy,
    TemporaryRedirect,
    PermanentRedirect,
    BadRequest,
    Unauthorized,
    PaymentRequired,
    Forbidden,
    NotFound,
    MethodNotAllowed,
    NotAcceptable,
    ProxyAuthenticationRequired,
    RequestTimeout,
    Conflict,
    Gone,
    LengthRequired,
    PreconditionFailed,
    PayloadTooLarge,
    RequestURITooLong,
    UnsupportedMediaType,
    RequestedRangeNotSatisfiable,
    ExpectationFailed,
    ImATeapot,
    MisdirectedRequest,
    UnprocessableEntity,
    Locked,
    FailedDependency,
    UpgradeRequired,
    PreconditionRequired,
    TooManyRequests,
    RequestHeaderFieldsTooLarge,
    ConnectionClosedWithoutResponse,
    UnavailableForLegalReasons,
    ClientClosedRequest,
    InternalServerError,
    NotImplemented,
    BadGateway,
    ServiceUnavailable,
    GatewayTimeout,
    HTTPVersionNotSupported,
    VariantAlsoNegotiates,
    InsufficientStorage,
    LoopDetected,
    NotExtended,
    NetworkAuthenticationRequired,
    NetworkConnectTimeoutError,
    Custom(String),
}

impl From<usize> for Status {
    fn from(status_code: usize) -> Status {
        match status_code {
            100 => Status::Continue,
            101 => Status::SwitchingProtocols,
            102 => Status::Processing,
            200 => Status::Ok,
            201 => Status::Created,
            202 => Status::Accepted,
            203 => Status::NonAuthoritativeInformation,
            204 => Status::NoContent,
            205 => Status::ResetContent,
            206 => Status::PartialContent,
            207 => Status::MultiStatus,
            208 => Status::AlreadyReported,
            226 => Status::IMUsed,
            300 => Status::MultipleChoices,
            301 => Status::MovedPermanently,
            302 => Status::Found,
            303 => Status::SeeOther,
            304 => Status::NotModified,
            305 => Status::UseProxy,
            307 => Status::TemporaryRedirect,
            308 => Status::PermanentRedirect,
            400 => Status::BadRequest,
            401 => Status::Unauthorized,
            402 => Status::PaymentRequired,
            403 => Status::Forbidden,
            404 => Status::NotFound,
            405 => Status::MethodNotAllowed,
            406 => Status::NotAcceptable,
            407 => Status::ProxyAuthenticationRequired,
            408 => Status::RequestTimeout,
            409 => Status::Conflict,
            410 => Status::Gone,
            411 => Status::LengthRequired,
            412 => Status::PreconditionFailed,
            413 => Status::PayloadTooLarge,
            414 => Status::RequestURITooLong,
            415 => Status::UnsupportedMediaType,
            416 => Status::RequestedRangeNotSatisfiable,
            417 => Status::ExpectationFailed,
            418 => Status::ImATeapot,
            421 => Status::MisdirectedRequest,
            422 => Status::UnprocessableEntity,
            423 => Status::Locked,
            424 => Status::FailedDependency,
            426 => Status::UpgradeRequired,
            428 => Status::PreconditionRequired,
            429 => Status::TooManyRequests,
            431 => Status::RequestHeaderFieldsTooLarge,
            444 => Status::ConnectionClosedWithoutResponse,
            451 => Status::UnavailableForLegalReasons,
            499 => Status::ClientClosedRequest,
            500 => Status::InternalServerError,
            501 => Status::NotImplemented,
            502 => Status::BadGateway,
            503 => Status::ServiceUnavailable,
            504 => Status::GatewayTimeout,
            505 => Status::HTTPVersionNotSupported,
            506 => Status::VariantAlsoNegotiates,
            507 => Status::InsufficientStorage,
            508 => Status::LoopDetected,
            510 => Status::NotExtended,
            511 => Status::NetworkAuthenticationRequired,
            599 => Status::NetworkConnectTimeoutError,
            _ => Status::Custom(format!("{} Custom", status_code)),
        }
    }
}

impl fmt::Display for Status {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let formatted = match self {
            &Status::Continue => "100 Continue",
            &Status::SwitchingProtocols => "101 Switching Protocols",
            &Status::Processing => "102 Processing",
            &Status::Ok => "200 OK",
            &Status::Created => "201 Created",
            &Status::Accepted => "202 Accepted",
            &Status::NonAuthoritativeInformation => "203 Non-Authoritative Information",
            &Status::NoContent => "204 No Content",
            &Status::ResetContent => "205 Reset Content",
            &Status::PartialContent => "206 Partial Content",
            &Status::MultiStatus => "207 Multi-Status",
            &Status::AlreadyReported => "208 Already Reported",
            &Status::IMUsed => "226 IM Used",
            &Status::MultipleChoices => "300 Multiple Choices",
            &Status::MovedPermanently => "301 Moved Permanently",
            &Status::Found => "302 Found",
            &Status::SeeOther => "303 See Other",
            &Status::NotModified => "304 Not Modified",
            &Status::UseProxy => "305 Use Proxy",
            &Status::TemporaryRedirect => "307 Temporary Redirect",
            &Status::PermanentRedirect => "308 Permanent Redirect",
            &Status::BadRequest => "400 Bad Request",
            &Status::Unauthorized => "401 Unauthorized",
            &Status::PaymentRequired => "402 Payment Required",
            &Status::Forbidden => "403 Forbidden",
            &Status::NotFound => "404 Not Found",
            &Status::MethodNotAllowed => "405 Method Not Allowed",
            &Status::NotAcceptable => "406 Not Acceptable",
            &Status::ProxyAuthenticationRequired => "407 Proxy Authentication Required",
            &Status::RequestTimeout => "408 Request Timeout",
            &Status::Conflict => "409 Conflict",
            &Status::Gone => "410 Gone",
            &Status::LengthRequired => "411 Length Required",
            &Status::PreconditionFailed => "412 Precondition Failed",
            &Status::PayloadTooLarge => "413 Payload Too Large",
            &Status::RequestURITooLong => "414 Request-URI Too Long",
            &Status::UnsupportedMediaType => "415 Unsupported Media Type",
            &Status::RequestedRangeNotSatisfiable => "416 Requested Range Not Satisfiable",
            &Status::ExpectationFailed => "417 Expectation Failed",
            &Status::ImATeapot => "418 I'm a teapot",
            &Status::MisdirectedRequest => "421 Misdirected Request",
            &Status::UnprocessableEntity => "422 Unprocessable Entity",
            &Status::Locked => "423 Locked",
            &Status::FailedDependency => "424 Failed Dependency",
            &Status::UpgradeRequired => "426 Upgrade Required",
            &Status::PreconditionRequired => "428 Precondition Required",
            &Status::TooManyRequests => "429 Too Many Requests",
            &Status::RequestHeaderFieldsTooLarge => "431 Request Header Fields Too Large",
            &Status::ConnectionClosedWithoutResponse => "444 Connection Closed Without Response",
            &Status::UnavailableForLegalReasons => "451 Unavailable For Legal Reasons",
            &Status::ClientClosedRequest => "499 Client Closed Request",
            &Status::InternalServerError => "500 Internal Server Error",
            &Status::NotImplemented => "501 Not Implemented",
            &Status::BadGateway => "502 Bad Gateway",
            &Status::ServiceUnavailable => "503 Service Unavailable",
            &Status::GatewayTimeout => "504 Gateway Timeout",
            &Status::HTTPVersionNotSupported => "505 HTTP Version Not Supported",
            &Status::VariantAlsoNegotiates => "506 Variant Also Negotiates",
            &Status::InsufficientStorage => "507 Insufficient Storage",
            &Status::LoopDetected => "508 Loop Detected",
            &Status::NotExtended => "510 Not Extended",
            &Status::NetworkAuthenticationRequired => "511 Network Authentication Required",
            &Status::NetworkConnectTimeoutError => "599 Network Connect Timeout Error",
            &Status::Custom(ref status_code) => status_code,
        };

        write!(f, "{}", formatted)
    }
}


text:
all: devops.csv

devops.xml:
	wget -O devops.xml http://www.devopsweekly.com/archive.xml

devops.csv: devops.xml
	./extract-devopsy-articles.py > devops.csv

clean:
	rm *.csv


text:
/* global describe, it */
/* jshint expr: true */

'use strict';

var expect = require('chai').expect;

describe('Mocha', function () {
  it('should expect true and false', function () {
    expect(true).to.be.true;
    expect(false).to.be.false;
  });
});


text:
#include "RouteCost.h"

namespace WFAPI {

namespace RouteCostPrinter {

WFString routeCostToString(RouteCost routeCost)
{
   switch(routeCost) {
      case TIME:
         return "time";
      case TIME_WITH_TRAFFIC_DISTURBANCES:
         return "time with traffic disturbances";
      case DISTANCE:
         return "distance";
   }

   return "time*";
}

} // End namespace RouteCostPrinter

} // End namespace WFAPI


text:
module Fog
  module Compute
    class Google
      class Mock
        def insert_target_https_proxy(_proxy_name, _description: nil,
                                      _url_map: nil, _ssl_certificates: nil)
          # :no-coverage:
          Fog::Mock.not_implemented
          # :no-coverage:
        end
      end

      class Real
        def insert_target_https_proxy(proxy_name, description: nil,
                                      url_map: nil, ssl_certificates: nil)
          @compute.insert_target_https_proxy(
            @project,
            ::Google::Apis::ComputeV1::TargetHttpsProxy.new(
              name: proxy_name,
              description: description,
              url_map: url_map,
              ssl_certificates: ssl_certificates
            )
          )
        end
      end
    end
  end
end


text:
def title():
    return ''

def content():
    return 'This is a placeholder for plots displaying statistics for weather'


text:
/*	$NetBSD: intr.h,v 1.5 1996/05/13 06:11:28 mycroft Exp $	*/

/*
 * Copyright (c) 1996 Charles M. Hannum.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Charles M. Hannum.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _I386_INTR_H_
#define _I386_INTR_H_

/* Interrupt priority `levels'; not mutually exclusive. */
#define	IPL_BIO		0	/* block I/O */
#define	IPL_NET		1	/* network */
#define	IPL_TTY		2	/* terminal */
#define	IPL_CLOCK	3	/* clock */
#define	IPL_IMP		4	/* memory allocation */
#define	IPL_NONE	5	/* nothing */
#define	IPL_HIGH	6	/* everything */

/* Interrupt sharing types. */
#define	IST_NONE	0	/* none */
#define	IST_PULSE	1	/* pulsed */
#define	IST_EDGE	2	/* edge-triggered */
#define	IST_LEVEL	3	/* level-triggered */

/* Soft interrupt masks. */
#define	SIR_CLOCK	31
#define	SIR_CLOCKMASK	((1 << SIR_CLOCK))
#define	SIR_NET		30
#define	SIR_NETMASK	((1 << SIR_NET) | SIR_CLOCKMASK)
#define	SIR_TTY		29
#define	SIR_TTYMASK	((1 << SIR_TTY) | SIR_CLOCKMASK)
#define	SIR_ALLMASK	(SIR_CLOCKMASK | SIR_NETMASK | SIR_TTYMASK)

#ifndef _LOCORE

volatile int cpl, ipending, astpending;
int imask[7];

extern void Xspllower __P((void));

static __inline int splraise __P((int));
static __inline int spllower __P((int));
static __inline void splx __P((int));
static __inline void softintr __P((int));

/*
 * Add a mask to cpl, and return the old value of cpl.
 */
static __inline int
splraise(ncpl)
	register int ncpl;
{
	register int ocpl = cpl;

	cpl = ocpl | ncpl;
	return (ocpl);
}

/*
 * Restore a value to cpl (unmasking interrupts).  If any unmasked
 * interrupts are pending, call Xspllower() to process them.
 */
static __inline void
splx(ncpl)
	register int ncpl;
{

	cpl = ncpl;
	if (ipending & ~ncpl)
		Xspllower();
}

/*
 * Same as splx(), but we return the old value of spl, for the
 * benefit of some splsoftclock() callers.
 */
static __inline int
spllower(ncpl)
	register int ncpl;
{
	register int ocpl = cpl;

	cpl = ncpl;
	if (ipending & ~ncpl)
		Xspllower();
	return (ocpl);
}

/*
 * Hardware interrupt masks
 */
#define	splbio()	splraise(imask[IPL_BIO])
#define	splnet()	splraise(imask[IPL_NET])
#define	spltty()	splraise(imask[IPL_TTY])
#define	splclock()	splraise(imask[IPL_CLOCK])
#define	splimp()	splraise(imask[IPL_IMP])
#define	splstatclock()	splhigh()

/*
 * Software interrupt masks
 *
 * NOTE: splsoftclock() is used by hardclock() to lower the priority from
 * clock to softclock before it calls softclock().
 */
#define	splsoftclock()	spllower(SIR_CLOCKMASK)
#define	splsoftnet()	splraise(SIR_NETMASK)
#define	splsofttty()	splraise(SIR_TTYMASK)

/*
 * Miscellaneous
 */
#define	splhigh()	splraise(-1)
#define	spl0()		spllower(0)

/*
 * Software interrupt registration
 *
 * We hand-code this to ensure that it's atomic.
 */
static __inline void
softintr(mask)
	register int mask;
{

	__asm __volatile("orl %0,_ipending" : : "ir" (mask));
}

#define	setsoftast()	(astpending = 1)
#define	setsoftclock()	softintr(1 << SIR_CLOCK)
#define	setsoftnet()	softintr(1 << SIR_NET)
#define	setsofttty()	softintr(1 << SIR_TTY)

#endif /* !_LOCORE */

#endif /* !_I386_INTR_H_ */


text:
package com.intellij.openapi.diagnostic;

import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.PathUtilRt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.*;
import java.util.Base64;

public class Attachment {
  private static final Logger LOG = Logger.getInstance(Attachment.class);

  public static final Attachment[] EMPTY_ARRAY = new Attachment[0];

  private final String myPath;
  private final String myDisplayText;
  private final @Nullable byte[] myBytes;
  private final @Nullable File myTemporaryFile;
  private boolean myIncluded;   // opt-out for traces, opt-in otherwise

  public Attachment(@NotNull String name, @NotNull Throwable throwable) {
    this(name + ".trace", ExceptionUtil.getThrowableText(throwable));
    myIncluded = true;
  }

  public Attachment(@NotNull String path, @NotNull String content) {
    this(path, content, content.getBytes(CharsetToolkit.UTF8_CHARSET), null);
  }

  public Attachment(@NotNull String path, @NotNull byte[] bytes, @NotNull String displayText) {
    this(path, displayText, bytes, null);
  }

  public Attachment(@NotNull String path, @NotNull File temporaryFile, @NotNull String displayText) {
    this(path, displayText, null, temporaryFile);
  }

  private Attachment(String path, String displayText, @Nullable byte[] bytes, @Nullable File temporaryFile) {
    assert bytes != null || temporaryFile != null;
    myPath = path;
    myDisplayText = displayText;
    myBytes = bytes;
    myTemporaryFile = temporaryFile;
  }

  @NotNull
  public String getDisplayText() {
    return myDisplayText;
  }

  @NotNull
  public String getPath() {
    return myPath;
  }

  @NotNull
  public String getName() {
    return PathUtilRt.getFileName(myPath);
  }

  @NotNull
  public String getEncodedBytes() {
    return Base64.getEncoder().encodeToString(getBytes());
  }

  @NotNull
  public byte[] getBytes() {
    if (myBytes != null) {
      return myBytes;
    }

    if (myTemporaryFile != null) {
      try {
        return FileUtil.loadFileBytes(myTemporaryFile);
      }
      catch (IOException e) {
        LOG.error("Failed to read attachment content from temp. file " + myTemporaryFile, e);
      }
    }

    return ArrayUtil.EMPTY_BYTE_ARRAY;
  }

  @NotNull
  public InputStream openContentStream() {
    if (myBytes != null) {
      return new ByteArrayInputStream(myBytes);
    }

    if (myTemporaryFile != null) {
      try {
        return new FileInputStream(myTemporaryFile);
      }
      catch (FileNotFoundException e) {
        LOG.error("Failed to read attachment content from temp. file " + myTemporaryFile, e);
      }
    }

    return new ByteArrayInputStream(ArrayUtil.EMPTY_BYTE_ARRAY);
  }

  public boolean isIncluded() {
    return myIncluded;
  }

  public void setIncluded(boolean included) {
    myIncluded = included;
  }
}


text:
package org.apache.causeway.core.metamodel.object;

import java.util.Optional;

import org.apache.causeway.applib.exceptions.unrecoverable.ObjectNotFoundException;
import org.apache.causeway.applib.services.bookmark.Bookmark;
import org.apache.causeway.applib.services.repository.EntityState;
import org.apache.causeway.commons.internal.assertions._Assert;
import org.apache.causeway.commons.internal.base._Blackhole;

import lombok.NonNull;
import lombok.Synchronized;
import lombok.val;
import lombok.extern.log4j.Log4j2;

/**
 * (package private) specialization corresponding to {@link Specialization#ENTITY}
 * @see ManagedObject.Specialization#ENTITY
 */
@Log4j2
final class _ManagedObjectEntityHybrid
extends _ManagedObjectSpecified
implements _Refetchable {

    /**
     * One of {_ManagedObjectEntityTransient, _ManagedObjectEntityBookmarked, _ManagedObjectEntityRemoved}.
     * <p>
     * May dynamically mutate from 'left' to 'right' based on pojo's persistent state.
     * However, the pojo reference must be kept identical, unless the entity becomes 'removed',
     * in which case the pojo reference is invalidated and should no longer be accessible to callers.
     */
    private @NonNull ManagedObject variant;

    private enum MorphState {
        /** Has no bookmark yet; can be transitioned to BOOKMARKED once
         *  for accompanied pojo, an OID becomes available. */
        TRANSIENT,
        /** We have an OID,
         * regardless of the accompanied pojo's persistent state (unless becomes removed). */
        BOOKMARKED,
        /** Final state, that can be entered once after we had an OID. */
        REMOVED;
        public boolean isTransient() { return this == TRANSIENT; }
        public boolean isBookmarked() { return this == BOOKMARKED; }
        public boolean isRemoved() { return this == REMOVED; }
        static MorphState valueOf(final EntityState entityState) {
            return entityState.isRemoved()
                    ? REMOVED
                    : entityState.hasOid()
                        ? BOOKMARKED
                        : TRANSIENT;
        }
    }

    private MorphState morphState;

    _ManagedObjectEntityHybrid(
            final @NonNull _ManagedObjectEntityTransient _transient) {
        super(ManagedObject.Specialization.ENTITY, _transient.getSpecification());
        this.variant = _transient;
        this.morphState = MorphState.TRANSIENT;
    }

    _ManagedObjectEntityHybrid(
            final @NonNull _ManagedObjectEntityBookmarked bookmarked) {
        super(ManagedObject.Specialization.ENTITY, bookmarked.getSpecification());
        this.variant = bookmarked;
        this.morphState = MorphState.BOOKMARKED;
        _Assert.assertTrue(bookmarked.getBookmark().isPresent(),
                ()->"bookmarked entity must have bookmark");
    }

    @Override
    public Optional<Bookmark> getBookmark() {
        return (variant instanceof Bookmarkable)
                ? ((Bookmarkable)variant).getBookmark()
                : Optional.empty();
    }

    @Override
    public boolean isBookmarkMemoized() {
        return (variant instanceof Bookmarkable)
                ? ((Bookmarkable)variant).isBookmarkMemoized()
                : false;
    }

    @Override
    public @NonNull EntityState getEntityState() {

        val entityState = variant.getEntityState();
        val newMorphState = MorphState.valueOf(entityState);

        if(this.morphState!=newMorphState) {
            log.debug("about to transition to {} variant given {}", newMorphState.name(), entityState);
            reassessVariant(entityState, peekAtPojo());
            if(newMorphState.isBookmarked()) {
                _Assert.assertTrue(isVariantBookmarked(), ()->"successful transition");
            } else if(newMorphState.isRemoved()) {
                _Assert.assertTrue(isVariantRemoved(), ()->"successful transition");
            }
            this.morphState = newMorphState;
        }
        return entityState;
    }

    @Override
    public Object getPojo() {
        if(isVariantRemoved()) {
            return null; // don't reassess
        }

        // handle the 'deleted' / 'not found' case gracefully
        try {
            val pojo = variant.getPojo();
            triggerReassessment();
            return pojo;
        } catch (ObjectNotFoundException e) {
            // if object not found, transition to 'removed' state
            makeRemoved();
            return null;
        }
    }

    @Override
    public Object peekAtPojo() {
        return (variant instanceof _Refetchable)
                ? ((_Refetchable)variant).peekAtPojo()
                : null;
    }

    @Override
    protected boolean isInjectionPointsResolved() {
        // overriding the default for optimization, let the EntityFacet handle injection
        // as a side-effect potentially injects if required
        return getSpecification().entityFacetElseFail()
                .isInjectionPointsResolved(peekAtPojo());
    }

    // -- HELPER

    private void triggerReassessment() {
        if(morphState.isTransient()) {
            _Blackhole.consume(getEntityState());
        }
    }

    private boolean isVariantBookmarked() {
        return variant instanceof _ManagedObjectEntityBookmarked;
    }

    private boolean isVariantTransient() {
        return variant instanceof _ManagedObjectEntityTransient;
    }

    private boolean isVariantRemoved() {
        return variant instanceof _ManagedObjectEntityRemoved;
    }

    @Synchronized
    private void reassessVariant(final EntityState entityState, final Object pojo) {
        if(isVariantTransient()
                && entityState.hasOid()) {
            makeBookmarked(pojo);
            return;
        }
        if(isVariantBookmarked()
                && entityState.isRemoved()) {
            makeRemoved();
            return;
        }
    }

    // morph into attached
    private void makeBookmarked(final Object pojo) {
        val attached = new _ManagedObjectEntityBookmarked(getSpecification(), pojo, Optional.empty());
        this.variant = attached;
        _Assert.assertTrue(attached.getBookmark().isPresent(),
                ()->"bookmarked entity must have bookmark");
    }

    // morph into attached
    private void makeRemoved() {
        val removed = new _ManagedObjectEntityRemoved(getSpecification());
        this.variant = removed;
    }

}


text:
@interface UIViewController (XXTelephone)
- (void)xx_telephone:(NSString *)phoneNumber;
@end


text:
package docker

import (
	"crypto/tls"
	"net/http"
	"net/http/httptest"
	"net/url"

	"github.com/tsuru/config"
	"github.com/tsuru/docker-cluster/cluster"
	"github.com/tsuru/tsuru/hc"
	tsuruNet "github.com/tsuru/tsuru/net"
	"gopkg.in/check.v1"
)

func (s *S) TestHealthCheckDockerRegistryV2(c *check.C) {
	var request *http.Request
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		request = r
		w.Write([]byte("{}"))
	}))
	defer server.Close()
	if old, err := config.Get("docker:registry"); err == nil {
		defer config.Set("docker:registry", old)
	} else {
		defer config.Unset("docker:registry")
	}
	config.Set("docker:registry", server.URL+"/")
	err := healthCheckDockerRegistry()
	c.Assert(err, check.IsNil)
	c.Assert(request.URL.Path, check.Equals, "/v2/")
	c.Assert(request.Method, check.Equals, "GET")
}

func (s *S) TestHealthCheckDockerRegistryV1(c *check.C) {
	var request *http.Request
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/v2/" {
			http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
			return
		}
		request = r
		w.Write([]byte("pong"))
	}))
	defer server.Close()
	if old, err := config.Get("docker:registry"); err == nil {
		defer config.Set("docker:registry", old)
	} else {
		defer config.Unset("docker:registry")
	}
	config.Set("docker:registry", server.URL+"/")
	err := healthCheckDockerRegistry()
	c.Assert(err, check.IsNil)
	c.Assert(request.URL.Path, check.Equals, "/v1/_ping")
	c.Assert(request.Method, check.Equals, "GET")
}

func (s *S) TestHealthCheckDockerRegistryConfiguredWithoutScheme(c *check.C) {
	var request *http.Request
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		request = r
		w.Write([]byte("{}"))
	}))
	defer server.Close()
	if old, err := config.Get("docker:registry"); err == nil {
		defer config.Set("docker:registry", old)
	} else {
		defer config.Unset("docker:registry")
	}
	serverURL, _ := url.Parse(server.URL)
	config.Set("docker:registry", serverURL.Host)
	err := healthCheckDockerRegistry()
	c.Assert(err, check.IsNil)
	c.Assert(request.URL.Path, check.Equals, "/v2/")
	c.Assert(request.Method, check.Equals, "GET")
}

func (s *S) TestHealthCheckDockerRegistryFailure(c *check.C) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("not pong"))
	}))
	defer server.Close()
	if old, err := config.Get("docker:registry"); err == nil {
		defer config.Set("docker:registry", old)
	} else {
		defer config.Unset("docker:registry")
	}
	config.Set("docker:registry", server.URL)
	err := healthCheckDockerRegistry()
	c.Assert(err, check.NotNil)
	c.Assert(err.Error(), check.Equals, "unexpected status - not pong")
}

func (s *S) TestHealthCheckDockerRegistryUnconfigured(c *check.C) {
	if old, err := config.Get("docker:registry"); err == nil {
		defer config.Set("docker:registry", old)
	}
	config.Unset("docker:registry")
	err := healthCheckDockerRegistry()
	c.Assert(err, check.Equals, hc.ErrDisabledComponent)
}

func (s *S) TestHealthCheckDocker(c *check.C) {
	var request *http.Request
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		request = r
		w.Write([]byte("OK"))
	}))
	defer server.Close()
	var err error
	mainDockerProvisioner.cluster, err = cluster.New(nil, &cluster.MapStorage{}, "", cluster.Node{Address: server.URL})
	c.Assert(err, check.IsNil)
	err = healthCheckDocker()
	c.Assert(err, check.IsNil)
	c.Assert(request.Method, check.Equals, "GET")
	c.Assert(request.URL.Path, check.Equals, "/_ping")
}

func (s *S) TestHealthCheckDockerMultipleNodes(c *check.C) {
	var request *http.Request
	server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		request = r
		w.Write([]byte("OK"))
	}))
	defer server1.Close()
	server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		request = r
		w.Write([]byte("OK"))
	}))
	defer server2.Close()
	var err error
	mainDockerProvisioner.cluster, err = cluster.New(nil, &cluster.MapStorage{}, "",
		cluster.Node{Address: server1.URL}, cluster.Node{Address: server2.URL})
	c.Assert(err, check.IsNil)
	err = healthCheckDocker()
	c.Assert(err, check.Equals, hc.ErrDisabledComponent)
	c.Assert(request, check.IsNil)
}

func (s *S) TestHealthCheckDockerNoNodes(c *check.C) {
	var err error
	mainDockerProvisioner.cluster, err = cluster.New(nil, &cluster.MapStorage{}, "")
	c.Assert(err, check.IsNil)
	err = healthCheckDocker()
	c.Assert(err, check.NotNil)
	c.Assert(err.Error(), check.Equals, "error - no nodes available for running containers")
}

func (s *S) TestHealthCheckDockerFailure(c *check.C) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("something went wrong"))
	}))
	defer server.Close()
	var err error
	mainDockerProvisioner.cluster, err = cluster.New(nil, &cluster.MapStorage{}, "", cluster.Node{Address: server.URL})
	c.Assert(err, check.IsNil)
	err = healthCheckDocker()
	c.Assert(err, check.NotNil)
	c.Assert(err.Error(), check.Equals, "ping failed: API error (500): something went wrong")
}

func (s *S) TestHealthCheckDockerRegistryV2TLS(c *check.C) {
	var request *http.Request
	server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		request = r
		w.Write([]byte("{}"))
	}))
	defer server.Close()
	oldTransport := tsuruNet.Dial5Full60ClientNoKeepAlive.Transport
	defer func() { tsuruNet.Dial5Full60ClientNoKeepAlive.Transport = oldTransport }()
	tsuruNet.Dial5Full60ClientNoKeepAlive.Transport = &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}
	if old, err := config.Get("docker:registry"); err == nil {
		defer config.Set("docker:registry", old)
	} else {
		defer config.Unset("docker:registry")
	}
	config.Set("docker:registry", server.URL+"/")
	err := healthCheckDockerRegistry()
	c.Assert(err, check.IsNil)
	c.Assert(request.URL.Path, check.Equals, "/v2/")
	c.Assert(request.Method, check.Equals, "GET")
}


text:
<?php
/**
 * File NumberType.php
 *
 * @author Edward Pfremmer <epfremme@nerdery.com>
 */
namespace Epfremme\Swagger\Entity\Parameters\HeaderParameter;

use Epfremme\Swagger\Entity\Mixin\Primitives;
use Epfremme\Swagger\Entity\Parameters\AbstractTypedParameter;
use Epfremme\Swagger\Type\HeaderParameterInterface;
use Epfremme\Swagger\Type\NumericTypeInterface;

/**
 * Class NumberType
 *
 * @package Epfremme\Swagger
 * @subpackage Entity\Parameters\HeaderParameter
 */
class NumberType extends AbstractTypedParameter implements HeaderParameterInterface, NumericTypeInterface
{
    use Primitives\NumericPrimitiveTrait;
}


text:
Comments

Please enable JavaScript to view the comments powered by Disqus.


text:
package org.apache.camel.component.mail;

import org.apache.camel.spi.Metadata;

public final class MailConstants {

    @Metadata(description = "Subject", javaType = "String")
    public static final String MAIL_SUBJECT = "Subject";
    @Metadata(description = "From", javaType = "String")
    public static final String MAIL_FROM = "From";
    @Metadata(description = "To", javaType = "String")
    public static final String MAIL_TO = "To";
    @Metadata(description = "Cc", javaType = "String")
    public static final String MAIL_CC = "Cc";
    @Metadata(description = "Bcc", javaType = "String")
    public static final String MAIL_BCC = "Bcc";
    @Metadata(description = "Reply to", javaType = "String")
    public static final String MAIL_REPLY_TO = "Reply-To";
    @Metadata(description = "The content type", javaType = "String")
    public static final String MAIL_CONTENT_TYPE = "contentType";
    @Metadata(label = "consumer",
              description = "After processing a mail message, it can be copied to a mail folder with the given name.",
              javaType = "String")
    public static final String MAIL_COPY_TO = "copyTo";
    @Metadata(label = "consumer",
              description = "After processing a mail message, it can be moved to a mail folder with the given name.",
              javaType = "String")
    public static final String MAIL_MOVE_TO = "moveTo";
    @Metadata(label = "consumer", description = "Deletes the messages after they have been processed.", javaType = "boolean")
    public static final String MAIL_DELETE = "delete";
    public static final String MAIL_ALTERNATIVE_BODY = "CamelMailAlternativeBody";
    public static final String MAIL_DEFAULT_FOLDER = "INBOX";
    public static final String MAIL_DEFAULT_FROM = "camel@localhost";
    @Metadata(description = "The message ID.", javaType = "String")
    public static final String MAIL_MESSAGE_ID = "CamelMailMessageId";
    public static final int MAIL_DEFAULT_CONNECTION_TIMEOUT = 30000;

    private MailConstants() {
        // utility class
    }
}


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

#import "Common/GREYStopwatch.h"

#include <mach/mach_time.h>

#import "Common/GREYThrowDefines.h"

@implementation GREYStopwatch {
  /**
   *  The last time GREYStopwatch::start was called on the stopwatch.
   */
  uint64_t _startTime;
  /**
   *  The last time GREYStopwatch::stop was called on the stopwatch.
   */
  uint64_t _stopTime;
  /**
   *  The last time GREYStopwatch::lapAndReturnTime was called on the stopwatch.
   */
  uint64_t _lastLapTime;
  /**
   *  A Boolean to check if GREYStopwatch::start was called without a corresponding
   *  GREYStopwatch::stop.
   */
  BOOL _isRunning;
}

- (void)start {
  _startTime = mach_absolute_time();
  _isRunning = YES;
}

- (void)stop {
  // Save the time first to prevent any performance overhead.
  uint64_t stoppedTime = mach_absolute_time();
  GREYThrowOnFailedConditionWithMessage(_isRunning, @"Stopwatch must have been started.");
  _stopTime = stoppedTime;
  _isRunning = NO;
}

- (NSTimeInterval)elapsedTime {
  // Save the time first to prevent any performance overhead.
  uint64_t elapsedTime = mach_absolute_time();
  GREYThrowOnFailedConditionWithMessage(_startTime != 0, @"Stopwatch was never started.");
  if (_stopTime && _stopTime >= _startTime) {
    return grey_timeIntervalBetween(_startTime, _stopTime);
  } else {
    return grey_timeIntervalBetween(_startTime, elapsedTime);
  }
}

- (NSTimeInterval)lapAndReturnTime {
  // Save the time first to prevent any performance overhead.
  uint64_t lapTime = mach_absolute_time();
  GREYThrowOnFailedConditionWithMessage(_isRunning, @"Stopwatch must have been started.");
  uint64_t startTime = _lastLapTime ? _lastLapTime : _startTime;
  _lastLapTime = lapTime;
  return grey_timeIntervalBetween(startTime, lapTime);
}

#pragma mark - private

/**
 *  Obtain the difference in seconds between two provided times (each in terms of the Mach absolute
 *  time unit).
 *
 *  @param startTime The lesser of the two times to be measured between in terms of the Mach
 *                   absolute time unit.
 *  @param endTime   The greater of the two times being measured between in terms of the Mach
 *                   absolute time unit.
 *
 *  @return an NSTimeInterval with the interval in seconds between @c startTime and @c endTime.
 */
static inline NSTimeInterval grey_timeIntervalBetween(uint64_t startTime, uint64_t endTime) {
  static mach_timebase_info_data_t info;

  if (info.denom == 0) {
    (void) mach_timebase_info(&info);
  }

  NSTimeInterval intervalInSeconds =
      (double)((endTime - startTime) * info.numer) / (info.denom * NSEC_PER_SEC);
  return intervalInSeconds;
}

@end


text:
@interface ARDReviewViewController : UIViewController <SKPaymentTransactionObserver, SKProductsRequestDelegate, UIAlertViewDelegate> {
    IBOutlet UILabel *itemTitle;
    IBOutlet UITextView *itemDescription;
    IBOutlet UILabel *itemPrice;
    SKProductsRequest *productsRequest;
    NSArray *validProducts;
    NSString *didPromote;
    BOOL hasAddObserver;

    IBOutlet UITextView *licenseText;
    IBOutlet UITextView *descriptionText;
    IBOutlet UILabel *titleLabel;
    IBOutlet UILabel *emailLabel;
    IBOutlet UILabel *twitterLabel;
    IBOutlet UILabel *phoneLabel;
    IBOutlet UILabel *iMessageLabel;
    IBOutlet UILabel *appnetLabel;
    IBOutlet UILabel *skypeLabel;
    IBOutlet UILabel *otherNameLabel;
    IBOutlet UILabel *otherHandleLabel;
    IBOutlet UILabel *catagoryLabel;
    IBOutlet UILabel *ageRestrictionLabel;
    IBOutlet UILabel *loginNameLabel;
    IBOutlet UITextView *premissionsLabel;
    NSString *almostLabel;

    //From VC stepOne
    NSString *titleString;
    NSString *licenseString;
    NSString *descriptionString;

    //From VC stepTwo
    NSString *emailString;
    NSString *twitterString;
    NSString *phoneString;
    NSString *iMessageString;
    NSString *appnetString;
    NSString *skypeString;
    NSString *otherNameString;
    NSString *otherHandleString;

    //From VC stepThree
    NSString *premissions;

    //From VC stepFour

}
@property (nonatomic) BOOL hasAddObserver;

@property (nonatomic, strong) NSArray *validProducts;
@property (nonatomic, strong) UILabel *itemTitle;
@property (nonatomic, strong) UITextView *itemDescription;
//@property (retain, nonatomic) SKProduct *product;
@property (strong, nonatomic) NSString *productID;
@property (strong, nonatomic) UILabel *itemPrice;
@property (strong, nonatomic) IBOutlet UIButton *submitButton;

@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic,strong) NSString *userID;
@property (nonatomic,strong) NSString *didPromote;

@property (nonatomic,strong) UITextView *licenseText;
@property (nonatomic,strong) UITextView *descriptionText;
@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic,strong) UILabel *emailLabel;
@property (nonatomic,strong) UILabel *twitterLabel;
@property (nonatomic,strong) UILabel *phoneLabel;
@property (nonatomic,strong) UILabel *iMessageLabel;
@property (nonatomic,strong) UILabel *appnetLabel;
@property (nonatomic,strong) UILabel *skypeLabel;
@property (nonatomic,strong) UILabel *otherNameLabel;
@property (nonatomic,strong) UILabel *otherHandleLabel;
@property (nonatomic,strong) UILabel *catagoryLabel;
@property (nonatomic,strong) UILabel *ageRestrictionLabel;
@property (nonatomic, strong) UILabel *loginNameLabel;
@property (nonatomic,strong) UITextView *premissionsLabel;
@property (nonatomic, strong) NSString *almostLabel;
@property (nonatomic, strong) UIAlertView *alertsuccessful;

//From VC stepOne
@property (nonatomic, strong) NSString *titleString;
@property (nonatomic, strong) NSString *licenseString;
@property (nonatomic, strong) NSString *descriptionString;

//From VC stepTwo
@property (nonatomic, strong) NSString *emailString;
@property (nonatomic, strong) NSString *twitterString;
@property (nonatomic, strong) NSString *phoneString;
@property (nonatomic, strong) NSString *iMessageString;
@property (nonatomic, strong) NSString *appnetString;
@property (nonatomic, strong) NSString *skypeString;
@property (nonatomic, strong) NSString *otherNameString;
@property (nonatomic, strong) NSString *otherHandleString;

//From VC stepThree
@property (nonatomic, strong) NSString *premissions;

//From VC stepFour
@property (nonatomic, strong) NSString *catagoryString;
@property (nonatomic, strong) NSString *ageRestrictionString;

- (IBAction)purchase:(id)sender;
- (void)fetchAvailableProducts;
- (BOOL)canMakePurchases;
- (void)purchaseMyProduct:(SKProduct*)product;

@end


text:
<?php
$_in_account_page=True;
require('_header.php');

$clean = array();
$clean['username'] = isset($_POST['username']) ? $_POST['username'] : '';
$clean['password'] = isset($_POST['password']) ? $_POST['password'] : '';
//$clean['expired'] = isset($_GET['expired']) ? $_GET['expired'] : '';

	if ($_SERVER['REQUEST_METHOD'] == 'POST')
	{
		if ($clean['username'] != '' /*&& $clean['password'] != ''*/)
		{
			db_connect();

			$sql = sprintf("SELECT ID, username, auth FROM t_user WHERE username = '%s' AND (auth = -2 OR pass = '%s');",
						    db_escape_string($clean['username']),
						    db_escape_string(md5($clean['password'])));
			$rs = db_runQuery($sql) or die(mysql_error());
			if (mysql_num_rows($rs) == 1)
			{
				$row = mysql_fetch_assoc($rs);
				if($row['auth'] == 0)
				{
					$error = 'Your account has not been activated.
Please open the email that we sent and click on the activation link';
				}
				if($row['auth'] == -1)
				{
					$error = 'Your account has been blocked.
Please contact us';
				}
				else
				{
                    if ($row['auth'] == -2)
                        redirectTo("reset.php?ID=".$row['ID']."&key=$noauthkey");
                    else
                    {
                        setLoggedUser($clean['username']);
                        redirectTo("index.php");
                    }
					// reset any authcode to stop links in emails
					$sql = sprintf("UPDATE t_user SET last_access = NOW() WHERE ID='%s';",
								db_escape_string($row['ID']));
					$update = db_runQuery($sql) or die(mysql_error());
				}
			}
			else {
				$error = 'Login failed. Please check your username and password';
			}
		}
		else {
			$error = 'Please enter both your username and password to access your account';
		}
	}
	elseif ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['expired']))
		$error = '
You have been logged out due to inactivity. Please log in again
';

if (isset($error))
{
	print <<

Exisiting Users: please log in to your account

    <form action="<?=$_SERVER['PHP_SELF']?>" name="loginform" id ="loginform" method="post">

			Username:
			<input type="text" id="username" name="username" size="20" maxlength="50" value="" tabindex="1"/>
			 	[ Forgotton your username? ]

			Password:
			<input type="password" id="password" name="password" size="20" maxlength="20" value="" tabindex="2"/>
			 	[ Forgotton your password? ]

	<input type='submit' value='Login' tabindex="3" />
</form>

New Users: if you do not have an account...

	[ register ] a new account.

<?
include('_footer.php');
?>


text:
define([
  'jquery',
  'backbone',
  'hogan',
  'text!templates/videoList.html',
  'text!templates/video.html',
  'js/view/playlistView',
], function($, Backbone, Hogan, VideoListTemplate, VideoTemplate, PlaylistView) {

  return Backbone.View.extend({
    initialize: function (options) {
      if(options != null && options.id != undefined) {
      console.log("TRUE");
        this.nameSelection = options.id;
        this.videoSelection = [];
        this.displayVideos(this.nameSelection);
      } else {
        this.displayVideos();
      }

        this.list = options.list;
        this.playlist = options.playlist;
    },

    events: {
      'click .picture': 'playVideo',
      'click .add': 'addToPlaylist',
      'click .playSelection': 'playSelection',
      'click .rm': 'removeVideo'
    },

    playVideo: function (e) {
      var className = e.currentTarget.className.split(' ');
      var id = className[0].trim();
      router.navigate('play/' + id, true);
    },

    playSelection: function() {
      this.playlist.reset();
      while(this.list.length > 0) {
        this.playlist.add(this.list.shift());
      }
      router.navigate('play', true);
    },

    addToPlaylist: function(e) {
      var className = e.currentTarget.className.split(' ');
      var id = className[0].trim();
      var video = this.list.findWhere({videoId: id});
      this.playlist.add(video);
    },

    displayVideos: function (idSelection) {
    var self = this;
      $('.videoList').empty();//Clean all

      if(idSelection == undefined) {
        $.ajax({
          url: "/listvideos",
          type: "GET",
          success: function (data) {
            console.log(data);
            data.forEach(function (el) {
              var link2Picture = 'img/' + el.videoId+ '.jpg';
              self.list.add({site: el.site, videoId: el.videoId, title: el.title});
              $('.videoList').append(Hogan.compile(VideoTemplate).render({
                site: el.site,
                id: el.videoId,
                title: el.title,
                pictureLink: link2Picture
              }));
            });
            self.displayRemoveOption();
          },
          error: function(err) {
            console.log(err);
          }
        });
      } else {
        this.videoSelection = [];
        $.ajax({
          url: "/getselection",
          type: "GET",
          data: {
            idSelection: idSelection
          },
          success: function (data) {
            console.log(data);
            displayRemoveOption();
          },
          error: function(err) {
            console.log(err);
          }
        });
      }
    },

    displayRemoveOption: function() {
      if(sessionStorage.getItem("login") && sessionStorage.getItem("password")) {
        //Change CSS to display links and infos
        $('.rm', this.el).css('visibility', 'visible');
      } else {
        $('.rm', this.el).css('visibility', 'hidden');
      }
    },

    removeVideo: function(e) {
      var className = e.currentTarget.className.split(' ');
      var id = className[0].trim();

      $.ajax({
        url: "/remove",
        type: "GET",
        data: {
          video: id
        },
        success: function (data) {
          //Remove video from the view
          $('.' + id + '').remove();
        },
        error: function(err) {
          console.log(err);
        }
      });

    },

    render: function () {
      this.$el.html(Hogan.compile(VideoListTemplate).render({

      }));
      return this;
    }
  });

});


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

#include "chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h"

#include "base/feature_list.h"
#include "base/test/metrics/user_action_tester.h"
#include "build/build_config.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/views/extensions/extensions_menu_button.h"
#include "chrome/browser/ui/views/extensions/extensions_menu_item_view.h"
#include "chrome/browser/ui/views/extensions/extensions_toolbar_container.h"
#include "chrome/browser/ui/views/extensions/extensions_toolbar_unittest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "ui/views/view_utils.h"

namespace {

// A scoper that manages a Browser instance created by BrowserWithTestWindowTest
// beyond the default instance it creates in SetUp.
class AdditionalBrowser {
 public:
  explicit AdditionalBrowser(std::unique_ptr<Browser> browser)
      : browser_(std::move(browser)),
        browser_view_(BrowserView::GetBrowserViewForBrowser(browser_.get())) {}

  ~AdditionalBrowser() {
    // Tear down `browser_`, similar to TestWithBrowserView::TearDown.
    browser_.release();
    browser_view_->GetWidget()->CloseNow();
  }

  ExtensionsToolbarContainer* extensions_container() {
    return browser_view_->toolbar()->extensions_container();
  }

 private:
  std::unique_ptr<Browser> browser_;
  BrowserView* browser_view_;
};

std::vector<std::string> GetNamesFromInstalledItems(
    std::vector<ExtensionsMenuItemView*> installed_items) {
  std::vector<std::string> names;
  names.resize(installed_items.size());
  std::transform(
      installed_items.begin(), installed_items.end(), names.begin(),
      [](ExtensionsMenuItemView* item) {
        return base::UTF16ToUTF8(item->primary_action_button_for_testing()
                                     ->label_text_for_testing());
      });
  return names;
}

}  // namespace

class ExtensionsTabbedMenuViewUnitTest : public ExtensionsToolbarUnitTest {
 public:
  ExtensionsTabbedMenuViewUnitTest();
  ~ExtensionsTabbedMenuViewUnitTest() override = default;
  ExtensionsTabbedMenuViewUnitTest(const ExtensionsTabbedMenuViewUnitTest&) =
      delete;
  ExtensionsTabbedMenuViewUnitTest& operator=(
      const ExtensionsTabbedMenuViewUnitTest&) = delete;

  ExtensionsToolbarButton* extensions_button() {
    return extensions_container()
        ->GetExtensionsToolbarControls()
        ->extensions_button();
  }
  ExtensionsToolbarButton* site_access_button() {
    return extensions_container()
        ->GetExtensionsToolbarControls()
        ->site_access_button_for_testing();
  }
  ExtensionsTabbedMenuView* extensions_tabbed_menu() {
    return ExtensionsTabbedMenuView::GetExtensionsTabbedMenuViewForTesting();
  }
  std::vector<ExtensionsMenuItemView*> installed_items() {
    return ExtensionsTabbedMenuView::GetExtensionsTabbedMenuViewForTesting()
        ->GetInstalledItemsForTesting();
  }

  // Asserts there is exactly 1 menu item and then returns it.
  ExtensionsMenuItemView* GetOnlyInstalledMenuItem();

  // Returns a list of the views of the currently pinned extensions, in order
  // from left to right.
  std::vector<ToolbarActionView*> GetPinnedExtensionViews();

  // Returns a list of the names of the currently pinned extensions, in order
  // from left to right.
  std::vector<std::string> GetPinnedExtensionNames();

  void ShowTabbedMenu();

  void ClickSiteAccessButton();
  void ClickExtensionsButton();
  void ClickPinButton(ExtensionsMenuItemView* installed_item);
  void ClickContextMenuButton(ExtensionsMenuItemView* installed_item);

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

ExtensionsTabbedMenuViewUnitTest::ExtensionsTabbedMenuViewUnitTest() {
  scoped_feature_list_.InitAndEnableFeature(
      features::kExtensionsMenuAccessControl);
}

ExtensionsMenuItemView*
ExtensionsTabbedMenuViewUnitTest::GetOnlyInstalledMenuItem() {
  std::vector<ExtensionsMenuItemView*> items = installed_items();
  if (items.size() != 1u) {
    ADD_FAILURE() << "Not exactly one item; size is: " << items.size();
    return nullptr;
  }
  return *items.begin();
}

std::vector<ToolbarActionView*>
ExtensionsTabbedMenuViewUnitTest::GetPinnedExtensionViews() {
  std::vector<ToolbarActionView*> result;
  for (views::View* child : extensions_container()->children()) {
    // Ensure we don't downcast the ExtensionsToolbarButton.
    if (views::IsViewClass<ToolbarActionView>(child)) {
      ToolbarActionView* const action = static_cast<ToolbarActionView*>(child);
#if defined(OS_MAC)
      // TODO(crbug.com/1045212): Use IsActionVisibleOnToolbar() because it
      // queries the underlying model and not GetVisible(), as that relies on an
      // animation running, which is not reliable in unit tests on Mac.
      const bool is_visible = extensions_container()->IsActionVisibleOnToolbar(
          action->view_controller());
#else
      const bool is_visible = action->GetVisible();
#endif
      if (is_visible)
        result.push_back(action);
    }
  }
  return result;
}

std::vector<std::string>
ExtensionsTabbedMenuViewUnitTest::GetPinnedExtensionNames() {
  std::vector<ToolbarActionView*> views = GetPinnedExtensionViews();
  std::vector<std::string> result;
  result.resize(views.size());
  std::transform(
      views.begin(), views.end(), result.begin(), [](ToolbarActionView* view) {
        return base::UTF16ToUTF8(view->view_controller()->GetActionName());
      });
  return result;
}

void ExtensionsTabbedMenuViewUnitTest::ShowTabbedMenu() {
  ExtensionsTabbedMenuView::ShowBubble(
      extensions_button(), browser(), extensions_container(),
      ExtensionsToolbarButton::ButtonType::kExtensions, true);
}

void ExtensionsTabbedMenuViewUnitTest::ClickSiteAccessButton() {
  ClickButton(site_access_button());
  LayoutContainerIfNecessary();
}

void ExtensionsTabbedMenuViewUnitTest::ClickExtensionsButton() {
  ClickButton(extensions_button());
  LayoutContainerIfNecessary();
}

void ExtensionsTabbedMenuViewUnitTest::ClickPinButton(
    ExtensionsMenuItemView* installed_item) {
  ClickButton(installed_item->pin_button_for_testing());
  WaitForAnimation();
}

void ExtensionsTabbedMenuViewUnitTest::ClickContextMenuButton(
    ExtensionsMenuItemView* installed_item) {
  ClickButton(installed_item->context_menu_button_for_testing());
}

TEST_F(ExtensionsTabbedMenuViewUnitTest, ButtonOpensAndClosesCorrespondingTab) {
  content::WebContentsTester* web_contents_tester =
      AddWebContentsAndGetTester();

  // Load an extension with all urls permissions so the site access button is
  // visible.
  InstallExtensionWithHostPermissions("all_urls", {"<all_urls>"});

  // Navigate to an url where the extension should have access to.
  const GURL url("http://www.a.com");
  web_contents_tester->NavigateAndCommit(url);
  WaitForAnimation();
  EXPECT_TRUE(site_access_button()->GetVisible());
  EXPECT_FALSE(ExtensionsTabbedMenuView::IsShowing());

  // Click on the extensions button when the menu is closed. Extensions menu
  // should open in the installed extensions tab.
  ClickExtensionsButton();
  EXPECT_TRUE(ExtensionsTabbedMenuView::IsShowing());
  EXPECT_EQ(extensions_tabbed_menu()->GetSelectedTabIndex(), 1u);

  // Click on the extensions button when the menu is open. Extensions menu
  // should be closed.
  ClickExtensionsButton();
  EXPECT_FALSE(ExtensionsTabbedMenuView::IsShowing());

  // Click on the site access button when the menu is closed. Extensions menu
  // should open in the site access tab.
  ClickSiteAccessButton();
  EXPECT_TRUE(ExtensionsTabbedMenuView::IsShowing());
  EXPECT_EQ(extensions_tabbed_menu()->GetSelectedTabIndex(), 0u);

  // Click on the site access button when the menu is open. Extensions menu
  // should close.
  ClickSiteAccessButton();
  EXPECT_FALSE(ExtensionsTabbedMenuView::IsShowing());
}

TEST_F(ExtensionsTabbedMenuViewUnitTest, TogglingButtonsClosesMenu) {
  content::WebContentsTester* web_contents_tester =
      AddWebContentsAndGetTester();

  // Load an extension with all urls permissions so the site access button is
  // visible.
  InstallExtensionWithHostPermissions("all_urls", {"<all_urls>"});

  // Navigate to an url where the extension should have access to.
  const GURL url("http://www.a.com");
  web_contents_tester->NavigateAndCommit(url);
  WaitForAnimation();
  EXPECT_TRUE(site_access_button()->GetVisible());
  EXPECT_FALSE(ExtensionsTabbedMenuView::IsShowing());

  // Click on the extensions button when the menu is closed. Extensions menu
  // should open.
  ClickExtensionsButton();
  EXPECT_TRUE(ExtensionsTabbedMenuView::IsShowing());

  // Click on the site access button when the menu is open. Extensions menu
  // should close since the button click is treated as a click outside the menu,
  // and therefore closing the menu, instead of triggering the button's click
  // action.
  // TODO(crbug.com/1263311): Toggle to the corresponding tab when clicking on
  // the other control when the menu is open.
  ClickSiteAccessButton();
  EXPECT_FALSE(ExtensionsTabbedMenuView::IsShowing());

  // Click on the site access button when the menu is closed. Extensions menu
  // should open.
  ClickSiteAccessButton();
  EXPECT_TRUE(ExtensionsTabbedMenuView::IsShowing());

  // Click on the extensions button when the menu is open. Extensions menu
  // should close, as explained previously.
  ClickExtensionsButton();
  EXPECT_FALSE(ExtensionsTabbedMenuView::IsShowing());
}

TEST_F(ExtensionsTabbedMenuViewUnitTest,
       InstalledExtensionsAreShownInInstalledTab) {
  // To start, there should be no extensions in the menu.
  EXPECT_EQ(installed_items().size(), 0u);

  // Add an extension, and verify that it's added to the menu.
  constexpr char kExtensionName[] = "Test 1";
  InstallExtension(kExtensionName);

  ShowTabbedMenu();

  ASSERT_EQ(installed_items().size(), 1u);
  EXPECT_EQ(base::UTF16ToUTF8((*installed_items().begin())
                                  ->primary_action_button_for_testing()
                                  ->label_text_for_testing()),
            kExtensionName);
}

TEST_F(ExtensionsTabbedMenuViewUnitTest,
       InstalledTab_InstalledExtensionsAreSorted) {
  constexpr char kExtensionZName[] = "Z Extension";
  InstallExtension(kExtensionZName);
  constexpr char kExtensionAName[] = "A Extension";
  InstallExtension(kExtensionAName);
  constexpr char kExtensionBName[] = "b Extension";
  InstallExtension(kExtensionBName);
  constexpr char kExtensionCName[] = "C Extension";
  InstallExtension(kExtensionCName);

  ShowTabbedMenu();

  std::vector<ExtensionsMenuItemView*> items = installed_items();
  ASSERT_EQ(items.size(), 4u);

  // Basic std::sort would do A,C,Z,b however we want A,b,C,Z
  EXPECT_THAT(GetNamesFromInstalledItems(items),
              testing::ElementsAre(kExtensionAName, kExtensionBName,
                                   kExtensionCName, kExtensionZName));
}

TEST_F(ExtensionsTabbedMenuViewUnitTest,
       InstalledTab_PinnedExtensionAppearsInToolbar) {
  constexpr char kName[] = "Test Name";
  InstallExtension(kName);

  ShowTabbedMenu();

  ExtensionsMenuItemView* installed_item = GetOnlyInstalledMenuItem();
  ASSERT_TRUE(installed_item);
  ToolbarActionViewController* controller = installed_item->view_controller();
  EXPECT_FALSE(extensions_container()->IsActionVisibleOnToolbar(controller));
  EXPECT_THAT(GetPinnedExtensionNames(), testing::IsEmpty());

  ClickPinButton(installed_item);

  EXPECT_TRUE(extensions_container()->IsActionVisibleOnToolbar(controller));
  EXPECT_THAT(GetPinnedExtensionNames(), testing::ElementsAre(kName));

  ClickPinButton(installed_item);  // Unpin.

  EXPECT_FALSE(extensions_container()->IsActionVisibleOnToolbar(
      installed_item->view_controller()));
  EXPECT_THAT(GetPinnedExtensionNames(), testing::IsEmpty());
}

TEST_F(ExtensionsTabbedMenuViewUnitTest,
       InstalledTab_NewPinnedExtensionAppearsToTheRightOfPinnedExtensions) {
  constexpr char kExtensionA[] = "A Extension";
  InstallExtension(kExtensionA);
  constexpr char kExtensionB[] = "B Extension";
  InstallExtension(kExtensionB);
  constexpr char kExtensionC[] = "C Extension";
  InstallExtension(kExtensionC);

  ShowTabbedMenu();

  std::vector<ExtensionsMenuItemView*> items = installed_items();
  EXPECT_EQ(items.size(), 3u);

  // Verify the order of the extensions is A,B,C.
  ASSERT_THAT(GetNamesFromInstalledItems(items),
              testing::ElementsAre(kExtensionA, kExtensionB, kExtensionC));

  ClickPinButton(items.at(0));
  EXPECT_THAT(GetPinnedExtensionNames(), testing::ElementsAre(kExtensionA));

  // Pinning a second extension should add it to the right of the current pinned
  // extensions.
  ClickPinButton(items.at(1));
  EXPECT_THAT(GetPinnedExtensionNames(),
              testing::ElementsAre(kExtensionA, kExtensionB));

  // Pinning a third extension should add it to the right of the current pinned
  // extensions.
  ClickPinButton(items.at(2));
  EXPECT_THAT(GetPinnedExtensionNames(),
              testing::ElementsAre(kExtensionA, kExtensionB, kExtensionC));

  // Unpinning the middle extension should remove it from the toolbar without
  // affecting the order of the other pinned extensions.
  ClickPinButton(items.at(1));
  EXPECT_THAT(GetPinnedExtensionNames(),
              testing::ElementsAre(kExtensionA, kExtensionC));

  // Pinning an extension should add it to the right of the current pinned
  // extensions, even if it was pinned and unpinned previously.
  ClickPinButton(items.at(1));
  EXPECT_THAT(GetPinnedExtensionNames(),
              testing::ElementsAre(kExtensionA, kExtensionC, kExtensionB));
}

TEST_F(ExtensionsTabbedMenuViewUnitTest,
       InstalledTab_PinnedExtensionAppearsInAnotherWindow) {
  InstallExtension("Test Name");

  ShowTabbedMenu();

  AdditionalBrowser browser2(
      CreateBrowser(browser()->profile(), browser()->type(),
                    /* hosted_app */ false, /* browser_window */ nullptr));

  ExtensionsMenuItemView* installed_item = GetOnlyInstalledMenuItem();
  ASSERT_TRUE(installed_item);
  ClickPinButton(installed_item);

  // Window that was already open gets the pinned extension.
  EXPECT_TRUE(browser2.extensions_container()->IsActionVisibleOnToolbar(
      installed_item->view_controller()));

  AdditionalBrowser browser3(
      CreateBrowser(browser()->profile(), browser()->type(),
                    /* hosted_app */ false, /* browser_window */ nullptr));

  // Brand-new window also gets the pinned extension.
  EXPECT_TRUE(browser3.extensions_container()->IsActionVisibleOnToolbar(
      installed_item->view_controller()));
}

TEST_F(ExtensionsTabbedMenuViewUnitTest, WindowTitle) {
  InstallExtension("Test Extension");

  ShowTabbedMenu();

  ExtensionsTabbedMenuView* menu = extensions_tabbed_menu();
  EXPECT_FALSE(menu->GetWindowTitle().empty());
  EXPECT_TRUE(menu->GetAccessibleWindowTitle().empty());
}