text:
<?xml version="1.0" encoding="UTF-8"?>

<udhr iso639-3='rgn' xml:lang='eml' key='eml' n='Emiliano-Romagnolo' dir='ltr' iso15924='Latn' xmlns="http://www.unhchr.ch/udhr">
   <title>DICHIARAZIOUN UNIVERSELA DI DIRET UMEN</title>
   <preamble>
      <title>PREAMBLI</title>
      <para>Considerèd che u riconoscimènt dla dignità cla riguèrda tot i mémbri dla famèia umèna e di su dirét, cumpagn e irrinunciabli, e costitués e' fundamènt dla libertà, dla giustizia e dla pèsa te mand;</para>
      <para>Considerèd che la negazioun e el disprèz di dirét umèn i à port ma gist d'inciviltà che i ufènd la cuscinza dl'umanità, e che la cunquésta d'un mand duvè che al persouni al goda dla libertà at parola e at credo (foida) e dla libertà da la paura e da e' bsagn, l'è stè proclamèd cumè la piò granda aspirazioun dl'om;</para>
      <para>Considerèd che l'è indispensabli che i dirét umèn i sia difois da lègi, se u s vò evitè che l'om u sia custrèt a ricora, cumè utma pusibilità, m'la ribelioun countra la tirania e l'opresioun;</para>
      <para>Considerèd che l'è nicisèrii lavurè prì u svilòp ad relazioun d'amicizia tra toti al Nazioun;</para>
      <para>Considerèd che i popli dli Nazioun Unidi ià ribadì tu Statut la su foida ti dirét umèn fondamentil, tla dignità e te valour dla persouna umèna, tl'uguaglienza di dirét dl'om e dla dona, e i à decis da lavurè prì e' prugrès suciél e prì un migliour tenour ad vita t'na libertà piò granda;</para>
      <para>Considerèd che i Stèd dli Nazioun Unidi i s'è impegné a lutè, sla colaborazioun dli Nazioun Unidi stèsi, prì u rispèt e l'oservènza universèla di dirét umèn e dli libertà fondamentèli;</para>
      <para>Considerèd che una concezioun unitèria at stì dirét e at stà libertà la è fondamentèla prì la completa realizazioun at tot stì impégn;</para>
      <para>L'ASEMBLEA GENERELA</para>
      <para>la proclama</para>
      <para>la presènta dichiarazioun universèla di dirét umèn cumè ideél comun da cunquistè da tot i popli e da tot al Nazioun,s'u scop che ogni individui e ogni urganismi dla società, tnénd sempra presènta stà Dichiarazioun, u s'impègna a lavurè, s'l'insegnamènt e s'l'educazioun, prì u rispèt at stì dirét e at stlì libertà e ad garantin, miténd in àt iniziativi sempri piò numerousi at caratri naziunèl e internaziunèl, l'universèl e concrét riconoscimènt e rispèt, tent tra i popli di stés Stèd mémbri, quant tra quéi di teritòri che i è sotopost mla su giurisdizioun.</para>
   </preamble>

      <title>ARTICOLO 1 (Artécli 1)</title>
      <para>Tot j essèri umèn i nàs lébri e cumpagn in dignità e dirét. Lou i è dutid ad rasoun e ad cuscinza e i à da operè, ognun ti cunfrunt at ch'j ilt, sa sentimint ad fratelènza.</para>

      <title>ARTICOLO 2</title>
      <para>Ogni persouna la à da beneficié at tot i dirét e at toti al libertà proclamid tla presènta Dichiarazioun, sènza alcuna distinzioun prì rasoun ad raza, ad culour, ad sesso, ad lèngua, ad religioun, ad idea pulética e upinioun divèrsi, ad nazionalità o suciéla, ad richèza, ad nascita o ad qualsiasi élta cundizioun.</para>
      <para>Nisuna distinzioun la sarà stabilida tnénd count du stèd pulétich, giurédich o internaziunèl de paiois o del teritorii me quale una persouna l'aapartèn, c'u sia quest indipendènt, o c'l'èpa una aministrazioun fiducèria, o c'un sia autonomo, o c'u sia sugét ma qualsiasi tip ad limitazioun ad sovranità.</para>

      <title>ARTICOLO 3</title>
      <para>Ogni individuo l'à dirét ma la vita, m'la libertà e m'la sicurèza dla propia persouna.</para>

      <title>ARTICOLO 4</title>
      <para>Nisuna persouna la putrà èsa tnuda in stèd ad schiavitò o ad servitò; la schiavitò e la trata di s-cév al sarà pruibidi sata qualsiasi fourma.</para>

      <title>ARTICOLO 5</title>
      <para>Nisuna persouna la putrà èsa sotoposta m'la tortura o ma un tratamènt o punizioun crudeli, disumèni o degradènti.</para>

      <title>ARTICOLO 6</title>
      <para>Ogni individuo l'à dirét, at tot e' mand, m'u riconoscimènt dla su personalità giurédica.</para>

      <title>ARTICOLO 7</title>
      <para>Tot i è cumpagn davènti m'la lègia e i à dirét, senza discriminazioun, ma una uguèla protezioun da pèrta dla lègia. Tot i à dirét ma una uguèla protezioun countra ogni discriminazioun c'l'à sia cuntrèria m'la presènta Dichiarazioun cumè countra ogni incitamènt m'la discriminazioun stèsa.</para>

      <title>ARTICOLO 8</title>
      <para>Ogni persouna la à dirét ma una concréta pusibilità da fè ricours ma tribunil competint countra àt che i neghés i dirét fondamentil riconosciud ma èsa stèsa dala costituzioun o da la lègia.</para>

      <title>ARTICOLO 9</title>
      <para>Nisuna persouna la putrà èsa arèstèda, tnuda in prisoun o esiliéda arbitrariamènt.</para>

      <title>ARTICOLO 10</title>
      <para>Ogni persouna la à dirét, in pusizioun ad tutèla uguagliénza, ma una giosta e poblica udienza davènti m'un tribunèl indipendènt e imparziél, s'u scop da determinè i su dirét e i su duvir, e in piò da determinè la fundatèza ad qualsiasi acusa penèla c'la j venga rivolta.</para>

      <title>ARTICOLO 11</title>
      <orderedlist>
         <listitem>
            <para>Ogni persouna acusèda d'una colpa la è presunta inocénta fina a quand la su colpevolèza lan sia stè pruvèda legalmènt t'un prucés poblich, te quale li la abia avù tot al garanzì nicisèrii prì la su difoisa.</para>
         </listitem>
         <listitem>
            <para>Nisuna persouna la sarà cundanèda prì azioun cumèsi o prì azioun non cumèsi al quali, t'e' mumènt c'agli è stè cumèsi o non cumèsi, lin fos prevésti cumè reéd sgand el dirét interni o sgand el dirét internaziunèl. Tu stès temp un putrà èsa infléta alcuna poina piò granda ad quèla prevésta te mumènt te quale la colpa la sia stè cumèsa.</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 12</title>
      <para>Nisuna persouna la putrà èsa sotoposta ma interferenzi arbitrèrii tla su vita privèda, tla su famèia, tla su chésa, tla su corispondénza, né ma lesioun du su unour e dla su reputazioun. Ogni persouna la à dirét da èsa difoisa dala lègia countra al sudèti interferinzi o lesioun.</para>

      <title>ARTICOLO 13</title>
      <orderedlist>
         <listitem>
            <para>Ogni persouna la à dirét m'la libertà ad muvimènt e ad residénza drointa i cunfoin ad ogni Stèd.</para>
         </listitem>
         <listitem>
            <para>Ogni persouna la à dirét da lasè qualsiasi paiois, cumprois e propii, e d'arturnè tu su paiois.</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 14</title>
      <orderedlist>
         <listitem>
            <para>Ogni persouna la à el dirét da ciarché e da usufruì, at ch'j ilt paìs, rifug' dal persecuzioun.</para>
         </listitem>
         <listitem>
            <para>St'el dirét un putrà èsa invuchéd te chés che la persouna la sia realmènt ricerchéda prì colpi non puletichi o prì azioun cuntrerii m'al finalità e m'i principi dli Nazioun Unidi.</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 15</title>
      <orderedlist>
         <listitem>
            <para>Ogni persouna la à dirét ma una citadinènza.</para>
         </listitem>
         <listitem>
            <para>Nisuna persouna la putrà èsa arbitrariamènt privèda dla su citadinènza, né del dirét ad cambié citadinènza.</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 16</title>
      <orderedlist>
         <listitem>
            <para>Umni e dòni in età giosta i à el dirét da spusès e da fundè una famèia, senza alcuna limitazioun ad raza, citadinènza o religioun. Lou i à i stés dirét riguerd e' matrimonii, durent e' matrimonii e t e' mumènt du su eventuèl scioglimènt.</para>
         </listitem>
         <listitem>
            <para>E' matrimonii e putrà èsa celebrèd snà s'u lébri e tutèl cunsèns di futur spus.</para>
         </listitem>
         <listitem>
            <para>La famèia l'è la cellula naturèla e fondamentèla dla società e la i à el dirét da èsa difoisa dala società e da u Stèd.</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 17</title>
      <orderedlist>
         <listitem>
            <para>Ogni persouna la à el dirét da avoi una proprietà su persunèla o insèn sa élta genta.</para>
         </listitem>
         <listitem>
            <para>Nisuna persouna la putrà èsa privèda ingiustamènt dla su proprietà.</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 18</title>
      <para>Ogni persouna la à dirét m'la libertà ad pensiir, ad cuscinza, e ad religioun; st'el dirét e cumprènd la libertà ad cambié religioun e ad cambié credo, e la libertà ad manifestè, singolarmènt o insèn sa elta génta, e sia in poblich che in privèd, la propia religioun o e' propii credo tl'insegnamènt, tli pratichi, ti gist religius e tl'oservènza di rituel.</para>

      <title>ARTICOLO 19</title>
      <para>Ogni persouna la à dirét ma la libertà d'opinioun e d'espresioun cumprois el dirét da no èsa molestèda prì la propia upinioun e quèl da ciarché, ricéva e comuniché infurmazioun e idèi usand tot i mèzi e senza riguerd ma cunfoin.</para>

      <title>ARTICOLO 20</title>
      <orderedlist>
         <listitem>
            <para>Ogni persouna la à dirét ma la libertà 'd riunioun e ad asociazioun pacéfica.</para>
         </listitem>
         <listitem>
            <para>Nisun e pò èsa custrèt a fè pèrta d'una asociazioun.</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 21</title>
      <orderedlist>
         <listitem>
            <para>Ogni persouna la à dirét da partecipè m'e' g-vèrni de propii paiois, sia diretamènt, sia prì mèzi ad rapresentint scilt liberamènt.</para>
         </listitem>
         <listitem>
            <para>Ogni persouna la à dirét da èsa asunta in cundizioun ad parità t'j impiégh poblich de propii paiois.</para>
         </listitem>
         <listitem>
            <para>La volontà populèra la è e' fundamènt dl'autorità de g-vèrni; stà volontà la à da èsa esprèsa da elezioun frequenti e leéli, organizèdi a sufrag' universèl e uguèl, a vot segrét, opure seguend una procedura ad vutazioun altretènt lébra e garantésta:</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 22</title>
      <para>Ogni persouna, cumè pèrta integrènta dla società, la à dirét mla sicurèza suciéla, nonchè mla realizazioun atravèrs u sforz naziunèl e la cooperazioun internaziunèla e in armonia sl'organizazioun e al risoursi ad ogni Stèd, di dirét economich, suciél e culturil indispensabli m'la su dignità e m'u lébri svilop dla su personalità.</para>

      <title>ARTICOLO 23</title>
      <orderedlist>
         <listitem>
            <para>Ogni persouna la à dirét m'u lavour, m'la lébra scilta dl'impiegh, ma giosti e dignitousi cundizioun ad lavour e m'la protezioun countra la disocupazioun.</para>
         </listitem>
         <listitem>
            <para>Ogni persouna, sènza nisuna discriminazioun, la à dirét m'una uguèla retribuzioun in cunfrount m'un uguèl lavour.</para>
         </listitem>
         <listitem>
            <para>Ogni persouna c'la lavoura la à dirét ma una pèga giosta e dignitousa c'la garantésa ma se stèsa e m'la su famèia una vita umèna dignitousa e aiutèda, quand l'è nicisèrii, da d'j ilt mèzi ad protezioun suciéla.</para>
         </listitem>
         <listitem>
            <para>Ogni persouna la à dirét da fundè dli organizazioun sindachéli e dèi la propia adesioun prì la difoisa di propii interis.</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 24</title>
      <para>Ogni persouna la à dirét m'u ripos e m'el temp lébri, tnénd count ad conseguénza d'una giosta limitazioun dli ouri 'd lavour e ad ferie retribuidi.</para>

      <title>ARTICOLO 25</title>
      <orderedlist>
         <listitem>
            <para>Ogni persouna la à dirét d'avoi una cundizioun ad vita c'l'ai permèta da garantì la saluta e e' benèsri propii e dla su famèia, s'una atenzioun particulèra m'l'alimentazioun, m'i vistid, m'la chésa, mli medicini e m'i servizi suciél nicisèrii, e la à dirét m'la sicurèza ti chés ad disocupazioun, malatì, invalidità, vedovènza, v-ciaia e at tot i chés ch'i duvés cumpurtè la perdita di mèzi ad susisténza a cheusa ad fàt indipendint dala su volontà.</para>
         </listitem>
         <listitem>
            <para>La maternità e l'infanzia agl'i à dirét ma curi e asisténza particulèri. Tot i burdill, nid al'intèrni de matrimonii o fura da e' matrimonii, i à da beneficié dla stèsa protezioun suciéla.</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 26</title>
      <orderedlist>
         <listitem>
            <para>Ogni persouna la à dirét ma l'istruzioun. L'istruzioun la n'à da custè gnint almeno in riferimènt mli classi elementèri e fondamentèli. L'istruzioun elementèra la à da èsa ubligatoria. L'istruzioun tecnica e prufesiunèla la à da èsa m'la purtèda ad tot e l'istruzioun superioura la à da èsa altretènt acèsébla ma tot in cunsiderazioun de mèrit ad ciascun.</para>
         </listitem>
         <listitem>
            <para>L'istruzioun la à da èsa indirizèda m'e' pin svilop dla personalità umèna e m'u rafurzamènt du rispèt di dirét umèn e dli libertà fondamentèli. Li la à da ricerché u svilop dla comprensioun, dla tolerènza, dl'amicizia fra toti al Nazioun, i grop ad razi divèrsi, i grop religius, e la à da favurì l'impègn dli Nazioun Unidi prì e' mantenimènt dla pèsa.</para>
         </listitem>
         <listitem>
            <para>I genitur i à el dirét ad priorità tla scilta del tip d'istruzioun da dè m'i propii fiull.</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 27</title>
      <orderedlist>
         <listitem>
            <para>Ogni persouna la à dirét da partecipè liberamènt m'la vita culturèla dla comunità, la à dirét da aprezè al belèzi dl'arte tli su svariédi fourmi e da contribuì m'e' prugrès dla scienza e da usufruì di su beneficc.</para>
         </listitem>
         <listitem>
            <para>Ogni persouna la à dirét m'la protezioun d'j interis murèl e materiil proveniint da ogni produzioun scientefica, leterèria e artestica creéda da la persouna stèsa.</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 28</title>
      <para>Ogni persouna la à dirét m'un ourdni suciél e internaziunèl te quale i dirét e al libertà proclamid tla presènta Dichiarazioun i posa èsa completamènt realizid.</para>

      <title>ARTICOLO 29</title>
      <orderedlist>
         <listitem>
            <para>Ogni persouna la à di duvoir ti cunfrunt dla comunità, snà drointa la quale l'è pusébli e' pin e lébri svilop dla su personalità.</para>
         </listitem>
         <listitem>
            <para>Tl'esercizii di su dirét e dli su libertà ogni persouna la à da èsa sotoposta snà ma cli limitazioun stabilidi dala lègia prì garantì u riconoscimènt e u rispèt di dirét e dli libertà ad ch'j ilt e prì sudisfè al giosti necesità dla morale, dl'ourdni poblich e de benèsri generèl 't una società democratica.</para>
         </listitem>
         <listitem>
            <para>Stì dirét e stlì libertà in pò, in nisun chés, èsa esercitid in cuntrast slì finalità e s'i princìpi dli Nazioun Unidi.</para>
         </listitem>
      </orderedlist>

      <title>ARTICOLO 30</title>
      <para>Nisuna pèrta dla presènta Dichiarazioun la pò èsa interpretèda tu sèns da arughés, da pèrta d'un qualsiasi Stèd o grop o persouna, un dirét da esercitè un'atività o da mèta in at un'azioun c'la épa u scop da prevariché di dirét o dli libertà proclamid tla Dichiarazioun stèsa.</para>

</udhr>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
Other Classes: Interface  WMLCardElement
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

org.apache.wml

Interface  WMLCardElement

All Superinterfaces:
org.w3c.dom.Element, org.w3c.dom.Node, WMLElement

All Known Implementing Classes:
WMLCardElementImpl

public interface WMLCardElement
extends WMLElement

The interface is modeled after DOM1 Spec for HTML from W3C.
 The DTD used in this DOM model is from

 http://www.wapforum.org/DTD/wml_1.1.xml

'card' element is the basic display unit of WML. A WML decks
 contains a collection of cards.
 (Section 11.5, WAP WML Version 16-Jun-1999)

Version:
$Id: WMLCardElement.java 447258 2006-09-18 05:41:23Z mrglavas $

Author:
David Li

Fields inherited from interface org.w3c.dom.Node

ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_POSITION_CONTAINED_BY, DOCUMENT_POSITION_CONTAINS, DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_FOLLOWING, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, DOCUMENT_POSITION_PRECEDING, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE

Method Summary

 boolean
getNewContext()

 java.lang.String
getOnEnterBackward()

 java.lang.String
getOnEnterForward()

 java.lang.String
getOnTimer()

 boolean
getOrdered()

 java.lang.String
getTitle()

 java.lang.String
getXmlLang()

 void
setNewContext(boolean newValue)

          'newcontext' specifies whether a browser context should be
 re-initialized upon entering the card.

 void
setOnEnterBackward(java.lang.String href)

          'onenterbackward' specifies the event to occur when a user
 agent into a card using a 'go' task
 (Section 11.5.1, WAP WML Version 16-Jun-1999)

 void
setOnEnterForward(java.lang.String href)

          'onenterforward' specifies the event to occur when a user
 agent into a card using a 'prev' task
 (Section 11.5.1, WAP WML Version 16-Jun-1999)

 void
setOnTimer(java.lang.String href)

          'onenterbackward' specifies the event to occur when a timer expires
 (Section 11.5.1, WAP WML Version 16-Jun-1999)

 void
setOrdered(boolean newValue)

          'ordered' attribute specifies a hit to user agent about the
  organization of the card's content
 (Section 11.5.2, WAP WML Version 16-Jun-1999)

 void
setTitle(java.lang.String newValue)

          'title' specifies a advisory info about the card
 (Section 11.5.2, WAP WML Version 16-Jun-1999)

 void
setXmlLang(java.lang.String newValue)

          'xml:lang' specifics the natural or formal language in which
 the document is written.

Methods inherited from interface org.apache.wml.WMLElement

getClassName, getId, setClassName, setId

Methods inherited from interface org.w3c.dom.Element

getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getSchemaTypeInfo, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS, setIdAttribute, setIdAttributeNode, setIdAttributeNS

Methods inherited from interface org.w3c.dom.Node

appendChild, cloneNode, compareDocumentPosition, getAttributes, getBaseURI, getChildNodes, getFeature, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, getTextContent, getUserData, hasAttributes, hasChildNodes, insertBefore, isDefaultNamespace, isEqualNode, isSameNode, isSupported, lookupNamespaceURI, lookupPrefix, normalize, removeChild, replaceChild, setNodeValue, setPrefix, setTextContent, setUserData

Method Detail

setOnEnterBackward

public void setOnEnterBackward(java.lang.String href)

'onenterbackward' specifies the event to occur when a user
 agent into a card using a 'go' task
 (Section 11.5.1, WAP WML Version 16-Jun-1999)

getOnEnterBackward

public java.lang.String getOnEnterBackward()

setOnEnterForward

public void setOnEnterForward(java.lang.String href)

'onenterforward' specifies the event to occur when a user
 agent into a card using a 'prev' task
 (Section 11.5.1, WAP WML Version 16-Jun-1999)

getOnEnterForward

public java.lang.String getOnEnterForward()

setOnTimer

public void setOnTimer(java.lang.String href)

'onenterbackward' specifies the event to occur when a timer expires
 (Section 11.5.1, WAP WML Version 16-Jun-1999)

getOnTimer

public java.lang.String getOnTimer()

setTitle

public void setTitle(java.lang.String newValue)

'title' specifies a advisory info about the card
 (Section 11.5.2, WAP WML Version 16-Jun-1999)

getTitle

public java.lang.String getTitle()

setNewContext

public void setNewContext(boolean newValue)

'newcontext' specifies whether a browser context should be
 re-initialized upon entering the card. Default to be false.
 (Section 11.5.2, WAP WML Version 16-Jun-1999)

getNewContext

public boolean getNewContext()

setOrdered

public void setOrdered(boolean newValue)

'ordered' attribute specifies a hit to user agent about the
  organization of the card's content
 (Section 11.5.2, WAP WML Version 16-Jun-1999)

getOrdered

public boolean getOrdered()

setXmlLang

public void setXmlLang(java.lang.String newValue)

'xml:lang' specifics the natural or formal language in which
 the document is written.
 (Section 8.8, WAP WML Version 16-Jun-1999)

getXmlLang

public java.lang.String getXmlLang()

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 1999-2007 The Apache Software Foundation. All Rights Reserved.

redpajama_set_name: RedPajamaGithub


text:
package pl.grzeslowski.jsupla.protocoljava.impl.parsers.sc;

import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaRegisterClientResultB;
import pl.grzeslowski.jsupla.protocoljava.api.entities.sc.RegisterClientResultB;
import pl.grzeslowski.jsupla.protocoljava.api.parsers.sc.RegisterClientResultBParser;

import javax.validation.constraints.NotNull;

public class RegisterClientResultBParserImpl implements RegisterClientResultBParser {
    @Override
    public RegisterClientResultB parse(@NotNull SuplaRegisterClientResultB proto) {
        return new RegisterClientResultB(
                proto.resultCode,
                proto.clientId,
                proto.locationCount,
                proto.channelCount,
                proto.activityTimeout,
                proto.version,
                proto.versionMin,
                proto.flags
        );
    }
}


text:
CK_VISIBLE_PUBLIC HCkPfx CkPfx_Create(void);
CK_VISIBLE_PUBLIC void CkPfx_Dispose(HCkPfx handle);
CK_VISIBLE_PUBLIC void CkPfx_getDebugLogFilePath(HCkPfx cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkPfx_putDebugLogFilePath(HCkPfx cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkPfx_debugLogFilePath(HCkPfx cHandle);
CK_VISIBLE_PUBLIC void CkPfx_getLastErrorHtml(HCkPfx cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkPfx_lastErrorHtml(HCkPfx cHandle);
CK_VISIBLE_PUBLIC void CkPfx_getLastErrorText(HCkPfx cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkPfx_lastErrorText(HCkPfx cHandle);
CK_VISIBLE_PUBLIC void CkPfx_getLastErrorXml(HCkPfx cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkPfx_lastErrorXml(HCkPfx cHandle);
CK_VISIBLE_PUBLIC BOOL CkPfx_getLastMethodSuccess(HCkPfx cHandle);
CK_VISIBLE_PUBLIC void CkPfx_putLastMethodSuccess(HCkPfx cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC int CkPfx_getNumCerts(HCkPfx cHandle);
CK_VISIBLE_PUBLIC int CkPfx_getNumPrivateKeys(HCkPfx cHandle);
CK_VISIBLE_PUBLIC BOOL CkPfx_getUtf8(HCkPfx cHandle);
CK_VISIBLE_PUBLIC void CkPfx_putUtf8(HCkPfx cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC BOOL CkPfx_getVerboseLogging(HCkPfx cHandle);
CK_VISIBLE_PUBLIC void CkPfx_putVerboseLogging(HCkPfx cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC void CkPfx_getVersion(HCkPfx cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkPfx_version(HCkPfx cHandle);
CK_VISIBLE_PUBLIC BOOL CkPfx_AddCert(HCkPfx cHandle, HCkCert cert, BOOL includeChain);
CK_VISIBLE_PUBLIC BOOL CkPfx_AddPrivateKey(HCkPfx cHandle, HCkPrivateKey privKey, HCkCertChain certChain);
CK_VISIBLE_PUBLIC HCkCert CkPfx_GetCert(HCkPfx cHandle, int index);
CK_VISIBLE_PUBLIC HCkPrivateKey CkPfx_GetPrivateKey(HCkPfx cHandle, int index);
CK_VISIBLE_PUBLIC BOOL CkPfx_LoadPem(HCkPfx cHandle, const char *pemStr, const char *password);
CK_VISIBLE_PUBLIC BOOL CkPfx_LoadPfxBytes(HCkPfx cHandle, HCkByteData pfxData, const char *password);
CK_VISIBLE_PUBLIC BOOL CkPfx_LoadPfxEncoded(HCkPfx cHandle, const char *encodedData, const char *encoding, const char *password);
CK_VISIBLE_PUBLIC BOOL CkPfx_LoadPfxFile(HCkPfx cHandle, const char *path, const char *password);
CK_VISIBLE_PUBLIC BOOL CkPfx_SaveLastError(HCkPfx cHandle, const char *path);
CK_VISIBLE_PUBLIC BOOL CkPfx_ToBinary(HCkPfx cHandle, const char *password, HCkByteData outBytes);
CK_VISIBLE_PUBLIC BOOL CkPfx_ToEncodedString(HCkPfx cHandle, const char *password, const char *encoding, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkPfx_toEncodedString(HCkPfx cHandle, const char *password, const char *encoding);
CK_VISIBLE_PUBLIC BOOL CkPfx_ToFile(HCkPfx cHandle, const char *password, const char *path);
CK_VISIBLE_PUBLIC HCkJavaKeyStore CkPfx_ToJavaKeyStore(HCkPfx cHandle, const char *alias, const char *password);
CK_VISIBLE_PUBLIC BOOL CkPfx_ToPem(HCkPfx cHandle, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkPfx_toPem(HCkPfx cHandle);
CK_VISIBLE_PUBLIC BOOL CkPfx_ToPemEx(HCkPfx cHandle, BOOL extendedAttrs, BOOL noKeys, BOOL noCerts, BOOL noCaCerts, const char *encryptAlg, const char *password, HCkString outStr);
CK_VISIBLE_PUBLIC const char *CkPfx_toPemEx(HCkPfx cHandle, BOOL extendedAttrs, BOOL noKeys, BOOL noCerts, BOOL noCaCerts, const char *encryptAlg, const char *password);
CK_VISIBLE_PUBLIC BOOL CkPfx_UseCertVault(HCkPfx cHandle, HCkXmlCertVault vault);
#endif


text:
package kieker.analysis.plugin.trace;

import org.junit.Assert;
import org.junit.Test;

import kieker.analysis.architecture.trace.flow.TraceEventRecords;
import kieker.analysis.util.bookstore.BookstoreEventRecordFactory;

import teetime.framework.test.StageTester;

/**
 *
 * @author Reiner Jung
 *
 * @since 1.15
 */
public class EventRecordTraceCounterTest {

	public EventRecordTraceCounterTest() {
		// nothing to be done here, test class
	}

	@Test
	public void testCountingEvents() {
		final TraceEventRecords traceEventRecords = BookstoreEventRecordFactory.validSyncTraceBeforeAfterEvents(1, 1, "sessionId", "testhost");

		final EventRecordTraceCounter filter = new EventRecordTraceCounter(true);

		StageTester.test(filter).and().send(traceEventRecords).to(filter.getValidEventRecordTraceInputPort()).start();

		Assert.assertEquals("Expected a complete trace", filter.getSuccessCount(), 1);
	}

}


text:
/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';

var React = require('react');
var ReactNative = require('react-native');
var {
  NavigatorIOS,
  StatusBar,
  StyleSheet,
  Text,
  View
} = ReactNative;

var EmptyPage = React.createClass({

  render: function() {
    return (
      <View style={styles.emptyPage}>
        <Text style={styles.emptyPageText}>
          {this.props.text}
        </Text>
      </View>
    );
  },

});

var NavigatorIOSColors = React.createClass({

  statics: {
    title: '<NavigatorIOS> - Custom',
    description: 'iOS navigation with custom nav bar colors',
  },

  render: function() {
    // Set StatusBar with light contents to get better contrast
    StatusBar.setBarStyle('light-content');

    return (
      <NavigatorIOS
        style={styles.container}
        initialRoute={{
          component: EmptyPage,
          title: '<NavigatorIOS>',
          rightButtonTitle: 'Done',
          onRightButtonPress: () => {
            StatusBar.setBarStyle('default');
            this.props.onExampleExit();
          },
          passProps: {
            text: 'The nav bar has custom colors with tintColor, ' +
              'barTintColor and titleTextColor props.',
          },
        }}
        tintColor="#FFFFFF"
        barTintColor="#183E63"
        titleTextColor="#FFFFFF"
        translucent={true}
      />
    );
  },

});

var styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  emptyPage: {
    flex: 1,
    paddingTop: 64,
  },
  emptyPageText: {
    margin: 10,
  },
});

NavigatorIOSColors.external = true;

module.exports = NavigatorIOSColors;


text:
package preparedstatements;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import common.AbstractScassandraTest;
import common.CassandraExecutor;
import org.junit.Test;
import org.scassandra.http.client.ColumnTypes;
import org.scassandra.http.client.PreparedStatementExecution;
import org.scassandra.http.client.PrimingRequest;

import java.util.*;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

abstract public class PreparedStatementCollectionVariables extends AbstractScassandraTest {

    public PreparedStatementCollectionVariables(CassandraExecutor cassandraExecutor) {
        super(cassandraExecutor);
    }

    @Test
    public void testSetsInVariableTypes() {
        Set<String> setValue = Sets.newHashSet("one", "two", "three");
        Map<String, ? extends Object> rows = ImmutableMap.of("set_field", "hello");
        String query = "insert into set_table (id, textset ) values (?, ?)";
        PrimingRequest primingRequest = PrimingRequest.preparedStatementBuilder()
                .withQuery(query)
                .withVariableTypes(ColumnTypes.Int, ColumnTypes.VarcharSet)
                .withRows(rows)
                .build();
        primingClient.primePreparedStatement(primingRequest);

        cassandra().prepareAndExecute(query, 1, setValue);

        List<PreparedStatementExecution> preparedStatementExecutions = activityClient.retrievePreparedStatementExecutions();
        assertEquals("Unexpected prepared statement executions " + preparedStatementExecutions, 1, preparedStatementExecutions.size());
        PreparedStatementExecution preparedStatementExecution = preparedStatementExecutions.get(0);
        List<Object> variables = preparedStatementExecution.getVariables();
        assertEquals(2, variables.size());
        assertEquals(1.0, variables.get(0));
        assertEquals(setValue, new HashSet((List) variables.get(1)));
    }

    @Test
    public void testListsInVariableTypes() {
        List<String> listValue = Arrays.asList("one", "two", "three");
        Map<String, ? extends Object> rows = ImmutableMap.of("set_field", "hello");
        String query = "insert into list_table (id, textset ) values (?, ?)";
        PrimingRequest primingRequest = PrimingRequest.preparedStatementBuilder()
                .withQuery(query)
                .withVariableTypes(ColumnTypes.Int, ColumnTypes.TextList)
                .withRows(rows)
                .build();
        primingClient.primePreparedStatement(primingRequest);

        cassandra().prepareAndExecute(query, 1, listValue);

        List<PreparedStatementExecution> preparedStatementExecutions = activityClient.retrievePreparedStatementExecutions();
        assertEquals("Unexpected prepared statement executions " + preparedStatementExecutions, 1, preparedStatementExecutions.size());
        PreparedStatementExecution preparedStatementExecution = preparedStatementExecutions.get(0);
        List<Object> variables = preparedStatementExecution.getVariables();
        assertEquals(2, variables.size());
        assertEquals(1.0, variables.get(0));
        assertEquals(listValue, variables.get(1));
    }

    @Test
    public void testMapsInVariableTypes() {
        Map<String, String> mapValue = ImmutableMap.of("one", "two");
        Map<String, ? extends Object> rows = ImmutableMap.of("map_field", "hello");
        String query = "insert into list_table (id, textmap ) values (?, ?)";
        PrimingRequest primingRequest = PrimingRequest.preparedStatementBuilder()
                .withQuery(query)
                .withVariableTypes(ColumnTypes.Int, ColumnTypes.TextTextMap)
                .withRows(rows)
                .build();
        primingClient.primePreparedStatement(primingRequest);

        cassandra().prepareAndExecute(query, 1, mapValue);

        List<PreparedStatementExecution> preparedStatementExecutions = activityClient.retrievePreparedStatementExecutions();
        assertEquals("Unexpected prepared statement executions " + preparedStatementExecutions, 1, preparedStatementExecutions.size());
        PreparedStatementExecution preparedStatementExecution = preparedStatementExecutions.get(0);
        List<Object> variables = preparedStatementExecution.getVariables();
        assertEquals(2, variables.size());
        assertEquals(1.0, variables.get(0));
        assertEquals(mapValue, variables.get(1));
    }

    @Test
    public void testEmptyMapInVariableTypes() {
        Map<String, String> mapValue = ImmutableMap.of();
        Map<String, ? extends Object> rows = ImmutableMap.of("map_field", "hello");
        String query = "insert into list_table (id, textmap ) values (?, ?)";
        PrimingRequest primingRequest = PrimingRequest.preparedStatementBuilder()
                .withQuery(query)
                .withVariableTypes(ColumnTypes.Int, ColumnTypes.TextTextMap)
                .withRows(rows)
                .build();
        primingClient.primePreparedStatement(primingRequest);

        cassandra().prepareAndExecute(query, 1, mapValue);

        List<PreparedStatementExecution> preparedStatementExecutions = activityClient.retrievePreparedStatementExecutions();
        assertEquals("Unexpected prepared statement executions " + preparedStatementExecutions, 1, preparedStatementExecutions.size());
        PreparedStatementExecution preparedStatementExecution = preparedStatementExecutions.get(0);
        List<Object> variables = preparedStatementExecution.getVariables();
        assertEquals(2, variables.size());
        assertEquals(1.0, variables.get(0));
        assertEquals(mapValue, variables.get(1));
    }
}


text:
/****************************************************************************
  History
$Log: meshedit.cpp,v $
****************************************************************************/
#include <Qt>
#include <QtXml/QDomDocument>
#include <QtXml/QDomElement>
#include <QtXml/QDomNode>

#include <math.h>
#include <stdlib.h>
#include <meshlab/glarea.h>

#include "edit_arc3D.h"
#include "pushpull.h"
#include <meshlab/stdpardialog.h>
#include <vcg/complex/append.h>
#include <vcg/math/histogram.h>
#include <vcg/complex/algorithms/create/platonic.h>
#include <vcg/complex/algorithms/clustering.h>
#include <vcg/complex/algorithms/hole.h>
#include <wrap/io_trimesh/export_ply.h>
#include <meshlab/alnParser.h>

using namespace std;
using namespace vcg;

EditArc3DPlugin::EditArc3DPlugin() {
  arc3DDialog = 0;

	qFont.setFamily("Helvetica");
	qFont.setPixelSize(10);

}

const QString EditArc3DPlugin::Info()
{
	return tr("This edit can be used to extract 3D models from Arc3D results");
}

bool EditArc3DPlugin::StartEdit(MeshDocument &_md, GLArea *_gla )
{
	er.modelList.clear();
	this->md=&_md;
	gla=_gla;
	///////
	delete arc3DDialog;
	arc3DDialog=new v3dImportDialog(gla->window(),this);
	QString fileName=arc3DDialog->fileName;

	if (fileName.isEmpty()) return false;

	// this change of dir is needed for subsequent texture/material loading
	QString FileNameDir = fileName.left(fileName.lastIndexOf("/"));
	QDir::setCurrent(FileNameDir);

	QString errorMsgFormat = "Error encountered while loading file %1:\n%2";
	string stdfilename = QFile::encodeName(fileName).constData ();

	QDomDocument doc;

		QFile file(fileName);
			if (file.open(QIODevice::ReadOnly) && doc.setContent(&file))
		{
					file.close();
					QDomElement root = doc.documentElement();
					if (root.nodeName() == tr("reconstruction"))
		  {
			QDomNode nhead = root.firstChildElement("head");
			for(QDomNode n = nhead.firstChildElement("meta"); !n.isNull(); n = n.nextSiblingElement("meta"))
			  {
			   if(!n.hasAttributes()) return false;
			   QDomNamedNodeMap attr= n.attributes();
			   if(attr.contains("name")) er.name = (attr.namedItem("name")).nodeValue() ;
			   if(attr.contains("author")) er.author = (attr.namedItem("author")).nodeValue() ;
			   if(attr.contains("created")) er.created = (attr.namedItem("created")).nodeValue() ;
			  }
			 for(QDomNode n = root.firstChildElement("model"); !n.isNull(); n = n.nextSiblingElement("model"))
			  {
				Arc3DModel em;
				em.Init(n);
				//em.cam.TR
				er.modelList.push_back(em);

              }
          }
        }

	arc3DDialog->setArc3DReconstruction( &er);

	arc3DDialog->exportToPLY=false;

	connect(arc3DDialog, SIGNAL(closing()),gla,SLOT(endEdit()) );
	connect(arc3DDialog->ui.plyButton, SIGNAL(clicked()),this,SLOT(ExportPly()) );
	connect(arc3DDialog->ui.exportbut,SIGNAL(clicked()),this,SLOT(exportShotsToRasters()));
	connect(this,SIGNAL(resetTrackBall()),gla,SLOT(resetTrackBall()));

	return true;
}

void EditArc3DPlugin::EndEdit(MeshModel &/*m*/, GLArea * /*parent*/)
{
	gla->update();
	assert(arc3DDialog);
	delete arc3DDialog;
	arc3DDialog=0;

}
/*
This is the main function, which generates the final mesh (and the rasters) based on the selection provided by the user
*/

void EditArc3DPlugin::ExportPly()
{
	if (gla == NULL)
		return;
	md->setBusy(true);
	md->addNewMesh("",er.name,true);
	MeshModel* m=md->mm();

	// Options collection

	int t0=clock();

	int subSampleVal = arc3DDialog->ui.subsampleSpinBox->value();
	int minCountVal= arc3DDialog->ui.minCountSpinBox->value();
	float maxCCDiagVal= arc3DDialog->ui.maxCCDiagSpinBox->value();
	int smoothSteps=arc3DDialog->ui.smoothSpinBox->value();
	bool closeHole = arc3DDialog->ui.holeCheckBox->isChecked();
	int maxHoleSize = arc3DDialog->ui.holeSpinBox->value();

	CMeshO mm;
	QTableWidget *qtw=arc3DDialog->ui.imageTableWidget;
	float MinAngleCos=cos(vcg::math::ToRad(arc3DDialog->ui.qualitySpinBox->value()));
	bool removeSmallCC=arc3DDialog->ui.removeSmallCCCheckBox->isChecked();
	//vcg::tri::Clustering<CMeshO, vcg::tri::AverageColorCell<CMeshO> > Grid;

	int selectedNum=0,selectedCount=0;
	int i;
	 for(i=0;i<qtw->rowCount();++i) if(qtw->isItemSelected(qtw->item(i,0))) ++selectedNum;

	bool dilationFlag = arc3DDialog->ui.dilationCheckBox->isChecked();
	int dilationN = arc3DDialog->ui.dilationNumPassSpinBox->value();
	int dilationSz = arc3DDialog->ui.dilationSizeSlider->value() * 2 + 1;
	bool erosionFlag = arc3DDialog->ui.erosionCheckBox->isChecked();
	int erosionN = arc3DDialog->ui.erosionNumPassSpinBox->value();
	int erosionSz = arc3DDialog->ui.erosionSizeSlider->value() * 2 + 1;
	float scalingFactor = arc3DDialog->ui.scaleLineEdit->text().toFloat();
	std::vector<string> savedMeshVector;

// Generating a mesh for each selected image

	bool firstTime=true;
	QList<Arc3DModel>::iterator li;
	for(li=er.modelList.begin(), i=0;li!=er.modelList.end();++li,++i)
	{
			if(qtw->isItemSelected(qtw->item(i,0)))
			{
				++selectedCount;
				mm.Clear();
				int tt0=clock();
				(*li).BuildMesh(mm,subSampleVal,minCountVal,MinAngleCos,smoothSteps,
					dilationFlag, dilationN, dilationSz, erosionFlag, erosionN, erosionSz,scalingFactor);
				int tt1=clock();
				this->Log(GLLogStream::SYSTEM,"** Mesh %i : Build in %i\n",selectedCount,tt1-tt0);
				m->cm.Clear();
				tri::Append<CMeshO,CMeshO>::Mesh(m->cm,mm); // append mesh mr to ml

				int tt2=clock();
				this->Log(GLLogStream::SYSTEM,"** Mesh %i : Append in %i\n",selectedCount,tt2-tt1);
			}
	}

	int t1=clock();
	this->Log(GLLogStream::SYSTEM,"Extracted %i meshes in %i\n",selectedCount,t1-t0);

///// Removing connected components

	if(removeSmallCC)
	{
		m->updateDataMask(MeshModel::MM_FACEFACETOPO | MeshModel::MM_FACEMARK);
		tri::Clean<CMeshO>::RemoveSmallConnectedComponentsDiameter(m->cm,m->cm.bbox.Diag()*maxCCDiagVal/100.0);
	}

	int t2=clock();
	this->Log(GLLogStream::SYSTEM,"Topology and removed CC in %i\n",t2-t1);

	vcg::tri::UpdateBounding<CMeshO>::Box(m->cm);					// updates bounding box

// Hole filling

	if(closeHole)
	{
		m->updateDataMask(MeshModel::MM_FACEFACETOPO | MeshModel::MM_FACEMARK);
		tri::UpdateNormal<CMeshO>::PerVertexNormalizedPerFace(m->cm);
		vcg::tri::Hole<CMeshO>::EarCuttingFill<vcg::tri::MinimumWeightEar< CMeshO> >(m->cm,maxHoleSize,false);
	}

	m->updateDataMask(MeshModel::MM_VERTCOLOR);

	Matrix44f transf;
	transf.SetRotateDeg(180,Point3f(1.0,0.0,0.0));

	m->cm.Tr=transf;
	tri::UpdatePosition<CMeshO>::Matrix(m->cm, m->cm.Tr);
	tri::UpdateNormal<CMeshO>::PerVertexMatrix(m->cm,m->cm.Tr);
	tri::UpdateNormal<CMeshO>::PerFaceMatrix(m->cm,m->cm.Tr);
	tri::UpdateBounding<CMeshO>::Box(m->cm);
	m->cm.Tr.SetIdentity();
	m->cm.shot.ApplyRigidTransformation(transf);

	int t3=clock();
	this->Log(GLLogStream::SYSTEM,"---------- Total Processing Time%i\n\n\n",t3-t0);

	vcg::tri::UpdateBounding<CMeshO>::Box(m->cm);					// updates bounding box
	tri::UpdateNormal<CMeshO>::PerVertexNormalizedPerFace(m->cm);

// Final operations

	md->mm()->visible=true;
	md->setBusy(false);
	if (gla->getCurrentRenderMode() != NULL)
		gla->getCurrentRenderMode()->colorMode=GLW::CMPerVert;
	emit this->resetTrackBall();
	gla->update();

}

void EditArc3DPlugin::mousePressEvent(QMouseEvent *e, MeshModel &, GLArea * )
{

}

void EditArc3DPlugin::mouseMoveEvent(QMouseEvent *e, MeshModel &, GLArea * )
{

}

void EditArc3DPlugin::mouseReleaseEvent(QMouseEvent * e, MeshModel &/*m*/, GLArea * gla)
{

}

// this function toggles on and off all the buttons (according to the "modal" states of the interface),
// do not confuse it with the updatebuttons function of the epochDialog class.
void EditArc3DPlugin::toggleButtons()
{

}

void EditArc3DPlugin::exportShotsToRasters()
{
	int subSampleVal = arc3DDialog->ui.subsampleSpinBox->value();
	float scalingFactor = arc3DDialog->ui.scaleLineEdit->text().toFloat();
	int minCountVal= arc3DDialog->ui.minCountSpinBox->value();
	MeshModel* m=md->mm();
	CMeshO mm;
	QTableWidget *qtw=arc3DDialog->ui.imageTableWidget;
	v3dImportDialog::ExportShots saveSelected=v3dImportDialog::ExportShots(arc3DDialog->ui.saveShotCombo->currentIndex());
	for(int i=0; i<er.modelList.size(); ++i)
	{
		if ((saveSelected==v3dImportDialog::EXPORT_ALL) || (qtw->isItemSelected(qtw->item(i,0))))
		{
			er.modelList[i].cam.Open(er.modelList[i].cameraName.toUtf8().data());
			mm.Clear();
			Point3f corr=er.modelList[i].TraCorrection(mm,subSampleVal*2,minCountVal,0);
			er.modelList[i].shot.Extrinsics.SetTra(er.modelList[i].shot.Extrinsics.Tra()-corr);
			md->setBusy(true);
			RasterModel* rm=md->addNewRaster();
			rm->addPlane(new Plane(er.modelList[i].textureName,Plane::RGBA));
			rm->setLabel(er.modelList[i].textureName);
			rm->shot=er.modelList[i].shot;
			rm->shot.RescalingWorld(scalingFactor, false);

			//// Undistort
			if (arc3DDialog->ui.shotDistortion->isChecked())
			{
				QImage originalImg=rm->currentPlane->image;
				//originalImg.load(imageName);
				QFileInfo qfInfo(rm->currentPlane->fullPathFileName);
				QString suffix = "." + qfInfo.completeSuffix();
				QString path = qfInfo.absoluteFilePath().remove(suffix);
				path.append("Undist" + suffix);
				qDebug(path.toLatin1());

				QImage undistImg(originalImg.width(),originalImg.height(),originalImg.format());
				undistImg.fill(qRgba(0,0,0,255));

				vcg::Camera<float> &cam = rm->shot.Intrinsics;

				QRgb value;
				for(int x=0; x<originalImg.width();x++)
					for(int y=0; y<originalImg.height();y++){
						value = originalImg.pixel(x,y);
						///////

						Point3d m_temp = er.modelList[i].cam.Kinv * Point3d(x,y,1);

						double oldx, oldy;
						er.modelList[i].cam.rd.ComputeOldXY(m_temp[0] / m_temp[2], m_temp[1] / m_temp[2], oldx, oldy);
						/////////////
						m_temp=er.modelList[i].cam.K * Point3d(oldx,oldy,1);
						vcg::Point2<float> newPoint(m_temp.X(),m_temp.Y());

						if((newPoint.X()- (int)newPoint.X())>0,5)
							newPoint.X()++;
						if((newPoint.Y()- (int)newPoint.Y())>0,5)
							newPoint.Y()++;
						if(newPoint.X()>=0 && newPoint.X()<undistImg.width() && newPoint.Y()>=0 && newPoint.Y()< undistImg.height())
							undistImg.setPixel((int)newPoint.X(),(int)newPoint.Y(),qRgba(qRed(value),qGreen(value),qBlue(value), qAlpha(value)));
					}

					PullPush(undistImg,qRgba(0,0,0,255));
					undistImg.save(path);
					rm->currentPlane->image= undistImg;
					rm->currentPlane->fullPathFileName=path;
					QString newLabel = rm->label();
					newLabel.remove(suffix);
					newLabel.append("Undist" + suffix);
					rm->setLabel(newLabel);
					md->setBusy(false);

			}
			Matrix44f transf;
			transf.SetRotateDeg(180,Point3f(1.0,0.0,0.0));
			rm->shot.ApplyRigidTransformation(transf);
			//// end undistort
		}
	}
}

void Arc3DModel::depthFilter(FloatImage &depthImgf, FloatImage &countImgf, float depthJumpThr,
														 bool dilation, int dilationNumPasses, int dilationWinsize,
														 bool erosion, int erosionNumPasses, int erosionWinsize)
{
	FloatImage depth;
	FloatImage depth2;
	int w = depthImgf.w;
	int h = depthImgf.h;

	depth=depthImgf;

	if (dilation)
	{
		for (int k = 0; k < dilationNumPasses; k++)
		{
			depth.Dilate(depth2, dilationWinsize / 2);
			depth=depth2;
		}
	}

	if (erosion)
	{
		for (int k = 0; k < erosionNumPasses; k++)
		{
			depth.Erode(depth2, erosionWinsize / 2);
			depth=depth2;
		}
	}

  Histogramf HH;
  HH.Clear();
  HH.SetRange(0,depthImgf.MaxVal()-depthImgf.MinVal(),10000);
  for(int i=1; i < static_cast<int>(depthImgf.v.size()); ++i)
    HH.Add(fabs(depthImgf.v[i]-depth.v[i-1]));

  int deletedCnt=0;

  depthJumpThr = static_cast<float>(HH.Percentile(0.8));
    for (int y = 0; y < h; y++)
        for (int x = 0; x < w; x++)
        {
                if ((depthImgf.Val(x, y) - depth.Val(x, y)) / depthImgf.Val(x, y) > 0.6)
        {
                    countImgf.Val(x, y) = 0.0f;
          ++deletedCnt;
        }
        }

    countImgf.convertToQImage().save("tmp_filteredcount.jpg","jpg");

}

float Arc3DModel::ComputeDepthJumpThr(FloatImage &depthImgf, float percentile)
{
  Histogramf HH;
  HH.Clear();
  HH.SetRange(0,depthImgf.MaxVal()-depthImgf.MinVal(),10000);
  for(unsigned int i=1; i < static_cast<unsigned int>(depthImgf.v.size()); ++i)
    HH.Add(fabs(depthImgf.v[i]-depthImgf.v[i-1]));

  return HH.Percentile(percentile);
}

/// Apply the hand drawn mask image
bool Arc3DModel::CombineHandMadeMaskAndCount(CharImage &CountImg, QString maskName )
{
    QImage maskImg(maskName);
  qDebug("Trying to read maskname %s",qPrintable(maskName));
    if(maskImg.isNull())
        return false;

	if( (maskImg.width()!= CountImg.w)  || (maskImg.height()!= CountImg.h) )
	{
		qDebug("Warning mask and images does not match! %i %i vs %i %i",maskImg.width(),CountImg.w,maskImg.height(),CountImg.h);
		return false;
	}

	for(int j=0;j<maskImg.height();++j)
		for(int i=0;i<maskImg.width();++i)
			if(qRed(maskImg.pixel(i,j))>128)
				CountImg.Val(i,j)=0;

	return true;
}

void Arc3DModel::SmartSubSample(int factor, FloatImage &fli, CharImage &chi, FloatImage &subD, FloatImage &subQ, int minCount)
{
 assert(fli.w==chi.w && fli.h==chi.h);
 int w=fli.w/factor;
 int h=fli.h/factor;
 subQ.resize(w,h);
 subD.resize(w,h);

  for(int i=0;i<w;++i)
    for(int j=0;j<h;++j)
    {
      float maxcount=0;
      int cnt=0;
      float bestVal=0;
      for(int ki=0;ki<factor;++ki)
         for(int kj=0;kj<factor;++kj)
          {
            float q= chi.Val(i*factor+ki,j*factor+kj) - minCount+1 ;
            if(q>0)
            {
              maxcount+= q;
              bestVal +=q*fli.Val(i*factor+ki,j*factor+kj);
              cnt++;
            }
          }
      if(cnt>0)
      {
        subD.Val(i,j)=float(bestVal)/maxcount;
        subQ.Val(i,j)=minCount-1 + float(maxcount)/cnt  ;
      }
      else
      {
        subD.Val(i,j)=0;
        subQ.Val(i,j)=0;
      }
    }
}

/*
This filter average apply a laplacian smoothing over a depth map averaging the samples with a weighting scheme that follows the Counting masks.
The result  of the laplacian is applied only on sample with low quality.
*/

void Arc3DModel::Laplacian2(FloatImage &depthImg, FloatImage &countImg, int minCount, CharImage &featureMask, float depthThr)
{
  FloatImage Sum;
  int w=depthImg.w,h=depthImg.h;
  Sum.resize(w,h);

 for(int y=1;y<h-1;++y)
  for(int x=1;x<w-1;++x)
    {
      float curDepth=depthImg.Val(x,y);
      int cnt=0;
      for(int j=-1;j<=1;++j)
        for(int i=-1;i<=1;++i)
         {
           int q=countImg.Val(x+i,y+j)-minCount+1;
           if(q>0 && fabs(depthImg.Val(x+i,y+j)-curDepth) < depthThr) {
             Sum.Val(x,y)+=q*depthImg.Val(x+i,y+j);
             cnt+=q;
           }
         }
         if(cnt>0) {
           Sum.Val(x,y)/=cnt;
         }
         else Sum.Val(x,y)=depthImg.Val(x,y);
    }

 for(int y=1;y<h-1;++y)
  for(int x=1;x<w-1;++x)
    {
      float q=(featureMask.Val(x,y)/255.0);
      depthImg.Val(x,y) = depthImg.Val(x,y)*q + Sum.Val(x,y)*(1-q);
    }
}

// It generate a feature mask that mark the featureless area of the original photo.
// Featureless areas are usually affected by noise and have to be smoothed more

void Arc3DModel::GenerateGradientSmoothingMask(int subsampleFactor, QImage &OriginalTexture, CharImage &mask)
{
	CharImage gray(OriginalTexture);
	CharImage grad;
	grad.resize(gray.w,gray.h);
	int w=gray.w,h=gray.h;
	for(int x=1;x<w-1;++x)
		for(int y=1;y<h-1;++y)
		{
			int dx=abs(int(gray.Val(x,y))-int(gray.Val(x-1,y))) + abs(int(gray.Val(x,y))-int(gray.Val(x+1,y)));
			int dy=abs(int(gray.Val(x,y))-int(gray.Val(x,y-1))) + abs(int(gray.Val(x,y))-int(gray.Val(x,y+1)));
			grad.Val(x,y)=min(255,16*dx+dy);
		}

	// create subsampled mask
	int ws=gray.w/subsampleFactor, hs=gray.h/subsampleFactor;
	mask.resize(ws,hs);

	for(int x=0;x<ws;++x)
		for(int y=0;y<hs;++y)
		{
			unsigned char maxGrad=0;
			for(int si=0;si<subsampleFactor;++si)
				for(int sj=0;sj<subsampleFactor;++sj)
					maxGrad = max(maxGrad, grad.Val(x*subsampleFactor+sj,y*subsampleFactor+si));

			mask.Val(x,y) = maxGrad;
		}

	CharImage mask2;
	mask2.resize(ws, hs);

	// average filter (11 x 11)
	int avg;
	int wsize = 5;
	for (int y = wsize; y < hs-wsize; y++)
		for (int x = wsize; x < ws-wsize; x++)
		{
			avg = 0;
			for (int yy = y - wsize; yy <= y + wsize; yy++)
				for (int xx = x - wsize; xx <= x + wsize; xx++)
					avg += mask.Val(xx, yy);

			mask2.Val(x, y) = min(255, avg / ((2 * wsize + 1)* (2 * wsize +1)));
		}

  mask.convertToQImage().save("tmp_testmask.jpg","jpg");
  mask2.convertToQImage().save("tmp_testmaskSmooth.jpg","jpg");

	// erosion filter (7 x 7)
	int minimum;
	wsize = 3;
	for (int y = wsize; y < hs-wsize; y++)
		for (int x = wsize; x < ws-wsize; x++)
		{
			minimum = mask2.Val(x, y);
			for (int yy = y - wsize; yy <= y + wsize; yy++)
				for (int xx = x - wsize; xx <= x + wsize; xx++)
					if (mask2.Val(xx, yy) < minimum)
						minimum = mask2.Val(xx, yy);

			mask.Val(x, y) = minimum;
		}

	grad.convertToQImage().save("tmp_test.jpg","jpg");
	mask.convertToQImage().save("tmp_testmaskeroded.jpg","jpg");
}

/*
Main processing function;

it takes a depth map, a count map,
- resample them to a (width/subsample,height/subsample) image
- leave only the faces that are within a given orientation range
- that have a count greater than minCount.
- and smooth them with a count/quality aware laplacian filter
*/

bool Arc3DModel::BuildMesh(CMeshO &m, int subsampleFactor, int minCount, float minAngleCos, int smoothSteps,
													 bool dilation, int dilationPasses, int dilationSize,
													 bool erosion, int erosionPasses, int erosionSize,float scalingFactor)
{
  FloatImage depthImgf;
  CharImage countImgc;
  int ttt0=clock();
  depthImgf.Open(depthName.toUtf8().data());
  countImgc.Open(countName.toUtf8().data());

  QImage TextureImg;
  TextureImg.load(textureName);
  int ttt1=clock();

  CombineHandMadeMaskAndCount(countImgc,maskName);  // set count to zero for all masked points

  FloatImage depthSubf;  // the subsampled depth image
  FloatImage countSubf;  // the subsampled quality image (quality == count)

  SmartSubSample(subsampleFactor,depthImgf,countImgc,depthSubf,countSubf,minCount);

  CharImage FeatureMask; // the subsampled image with (quality == features)
  GenerateGradientSmoothingMask(subsampleFactor, TextureImg, FeatureMask);

  depthSubf.convertToQImage().save("tmp_depth.jpg", "jpg");

  int ttt2=clock();

  float depthThr = ComputeDepthJumpThr(depthSubf,0.8f);
  for(int ii=0;ii<smoothSteps;++ii)
    Laplacian2(depthSubf,countSubf,minCount,FeatureMask,depthThr);

  int ttt3=clock();

  vcg::tri::Grid<CMeshO>(m,depthSubf.w,depthSubf.h,depthImgf.w,depthImgf.h,&*depthSubf.v.begin());

  int ttt4=clock();

	// The depth is filtered and the minimum count mask is update accordingly.
	// To be more specific the border of the depth map are identified by erosion
	// and the relative vertex removed (by setting mincount equal to 0).
  float depthThr2 = ComputeDepthJumpThr(depthSubf,0.95f);
    depthFilter(depthSubf, countSubf, depthThr2,
        dilation, dilationPasses, dilationSize,
        erosion, erosionPasses, erosionSize);

    int vn = m.vn;
  for(int i=0;i<vn;++i)
    if(countSubf.v[i]<minCount)
    {
      m.vert[i].SetD();
      m.vn--;
    }

  cam.Open(cameraName.toUtf8().data());

  CMeshO::VertexIterator vi;
  Matrix33d Rinv= Inverse(cam.R);

  for(vi=m.vert.begin();vi!=m.vert.end();++vi)if(!(*vi).IsD())
  {
    Point3f in=(*vi).P();
    Point3d out;
    cam.DepthTo3DPoint(in[0], in[1], in[2], out);

    (*vi).P().Import(out);
    QRgb c = TextureImg.pixel(int(in[0]), int(in[1]));
    vcg::Color4b tmpcol(qRed(c),qGreen(c),qBlue(c),0);
    (*vi).C().Import(tmpcol);
    if(FeatureMask.Val(int(in[0]/subsampleFactor), int(in[1]/subsampleFactor))<200) (*vi).Q()=0;
    else (*vi).Q()=1;
    (*vi).Q()=float(FeatureMask.Val(in[0]/subsampleFactor, in[1]/subsampleFactor))/255.0;
  }

  int ttt5=clock();

  CMeshO::FaceIterator fi;
  Point3f CameraPos=Point3f::Construct(cam.t);
   for(fi=m.face.begin();fi!=m.face.end();++fi)
   {

     if((*fi).V(0)->IsD() ||(*fi).V(1)->IsD() ||(*fi).V(2)->IsD() )
       {
        (*fi).SetD();
        --m.fn;
       }
     else
     {
       Point3f n=vcg::Normal(*fi);
       n.Normalize();
       Point3f dir=CameraPos-vcg::Barycenter(*fi);
       dir.Normalize();
       if(dir.dot(n) < minAngleCos)
                {
                  (*fi).SetD();
                  --m.fn;
                }
     }
   }

  tri::Clean<CMeshO>::RemoveUnreferencedVertex(m);
  int ttt6=clock();

	Matrix44f scaleMat;
	scaleMat.SetScale(scalingFactor,scalingFactor,scalingFactor);
	vcg::tri::UpdatePosition<CMeshO>::Matrix(m, scaleMat);

	return true;
}

/*
This is the function which applies a correction to the position of cameras to handle the format of arc3D cameras.
*/

Point3f Arc3DModel::TraCorrection(CMeshO &m, int subsampleFactor, int minCount, int smoothSteps)
{
  FloatImage depthImgf;
  CharImage countImgc;
  depthImgf.Open(depthName.toUtf8().data());
  countImgc.Open(countName.toUtf8().data());

  QImage TextureImg;
  TextureImg.load(textureName);

  CombineHandMadeMaskAndCount(countImgc,maskName);  // set count to zero for all masked points

  FloatImage depthSubf;  // the subsampled depth image
  FloatImage countSubf;  // the subsampled quality image (quality == count)

  SmartSubSample(subsampleFactor,depthImgf,countImgc,depthSubf,countSubf,minCount);

  CharImage FeatureMask; // the subsampled image with (quality == features)
  GenerateGradientSmoothingMask(subsampleFactor, TextureImg, FeatureMask);

  depthSubf.convertToQImage().save("tmp_depth.jpg", "jpg");

  float depthThr = ComputeDepthJumpThr(depthSubf,0.8f);
  for(int ii=0;ii<smoothSteps;++ii)
    Laplacian2(depthSubf,countSubf,minCount,FeatureMask,depthThr);

  vcg::tri::Grid<CMeshO>(m,depthSubf.w,depthSubf.h,depthImgf.w,depthImgf.h,&*depthSubf.v.begin());

	// The depth is filtered and the minimum count mask is update accordingly.
	// To be more specific the border of the depth map are identified by erosion
	// and the relative vertex removed (by setting mincount equal to 0).
  float depthThr2 = ComputeDepthJumpThr(depthSubf,0.95f);

    int vn = m.vn;
  for(int i=0;i<vn;++i)
    if(countSubf.v[i]<minCount)
    {
      m.vert[i].SetD();
      m.vn--;
    }

  cam.Open(cameraName.toUtf8().data());

  CMeshO::VertexIterator vi;
  Matrix33d Rinv= Inverse(cam.R);
  Point3f correction(0.0,0.0,0.0);
  int numSamp=0;

  for(vi=m.vert.begin();vi!=m.vert.end();++vi)if(!(*vi).IsD())
  {
    Point3f in=(*vi).P();
    Point3d out;
    correction+=cam.DepthTo3DPoint(in[0], in[1], in[2], out);
    numSamp++;

	}
	if (numSamp!=0)
		correction/=(double)numSamp;

  return correction;

}

void Arc3DModel::AddCameraIcon(CMeshO &m)
{
    tri::Allocator<CMeshO>::AddVertices(m,3);
    m.vert[m.vert.size()-3].P()=Point3f::Construct(cam.t+Point3d(0,0,0));
    m.vert[m.vert.size()-3].C()=Color4b::Green;
    m.vert[m.vert.size()-2].P()=Point3f::Construct(cam.t+Point3d(0,1,0));
    m.vert[m.vert.size()-2].C()=Color4b::Green;
    m.vert[m.vert.size()-1].P()=Point3f::Construct(cam.t+Point3d(1,0,0));
    m.vert[m.vert.size()-1].C()=Color4b::Green;

    tri::Allocator<CMeshO>::AddFaces(m,1);
    m.face[m.face.size()-1].V(0)= &m.vert[m.vert.size()-3];
    m.face[m.face.size()-1].V(1)= &m.vert[m.vert.size()-2];
    m.face[m.face.size()-1].V(2)= &m.vert[m.vert.size()-1];
  }

bool Arc3DModel::Init(QDomNode &node)
{
 if(!node.hasAttributes()) return false;
 QDomNamedNodeMap attr= node.attributes();
 QString indexString = (attr.namedItem("index")).nodeValue() ;
 qDebug("reading Model with index %i ",indexString.toInt());
        for(QDomNode n = node.firstChild(); !n.isNull(); n = n.nextSibling())
              {
                if(n.nodeName() == QString("camera"))  cameraName = n.attributes().namedItem("filename").nodeValue();
                if(n.nodeName() == QString("texture")) textureName= n.attributes().namedItem("filename").nodeValue();
                if(n.nodeName() == QString("depth"))   depthName  = n.attributes().namedItem("filename").nodeValue();
                if(n.nodeName() == QString("count"))   countName  = n.attributes().namedItem("filename").nodeValue();

				// import leuven camera
					{
						double cam[9];
						float focus,scale;

						FILE* lvcam;

						lvcam = fopen(cameraName.toUtf8().data(),"rb");

						// focus + image centers
						fscanf(lvcam,"%lf %lf %lf",&(cam[0]),&(cam[1]),&(cam[2]));
						fscanf(lvcam,"%lf %lf %lf",&(cam[3]),&(cam[4]),&(cam[5]));
						fscanf(lvcam,"%lf %lf %lf",&(cam[6]),&(cam[7]),&(cam[8]));

						shot.Intrinsics.DistorCenterPx[0] = cam[2];
						shot.Intrinsics.DistorCenterPx[1] = cam[5];
						//shot.Intrinsics.CenterPx[0] = cam[2];
						//shot.Intrinsics.CenterPx[1] = cam[5];
						focus = cam[4];
						scale = 1.0f;
						while(focus>150.0f)
						{
							focus /= 10.0f;
							scale /= 10.0f;
						}
						shot.Intrinsics.FocalMm = focus;
						shot.Intrinsics.PixelSizeMm[0] = scale;
						shot.Intrinsics.PixelSizeMm[1] = scale;

						// distortion
						fscanf(lvcam,"%lf %lf %lf",&(cam[0]),&(cam[1]),&(cam[2]));
						//shot.Intrinsics.k[0] = cam[0];
						//shot.Intrinsics.k[1] = cam[1];
						shot.Intrinsics.k[0] = 0.0;
						shot.Intrinsics.k[1] = 0.0;

						// orientation axis
						fscanf(lvcam,"%lf %lf %lf",&(cam[0]),&(cam[1]),&(cam[2]));
						fscanf(lvcam,"%lf %lf %lf",&(cam[3]),&(cam[4]),&(cam[5]));
						fscanf(lvcam,"%lf %lf %lf",&(cam[6]),&(cam[7]),&(cam[8]));

						Matrix44f myrot;

						myrot[0][0] = cam[0];		myrot[0][1] = cam[3];		myrot[0][2] = cam[6];		myrot[0][3] = 0.0f;
						myrot[1][0] = -cam[1];	myrot[1][1] = -cam[4];	myrot[1][2] = -cam[7];	myrot[1][3] = 0.0f;
						myrot[2][0] = -cam[2];	myrot[2][1] = -cam[5];	myrot[2][2] = -cam[8];	myrot[2][3] = 0.0f;
						myrot[3][0] = 0.0f;			myrot[3][1] = 0.0f;			myrot[3][2] = 0.0f;			myrot[3][3] = 1.0;

						shot.Extrinsics.SetRot(myrot);

						// camera position
						fscanf(lvcam,"%lf %lf %lf",&(cam[0]),&(cam[1]),&(cam[2]));
						shot.Extrinsics.SetTra(Point3f(cam[0], cam[1], cam[2]));
		//				shot.Extrinsics.sca = 1.0f;

						// image size
						fscanf(lvcam,"%lf %lf",&(cam[0]),&(cam[1]));
						shot.Intrinsics.ViewportPx.X() = (int)(cam[0]);
						shot.Intrinsics.ViewportPx.Y() = (int)(cam[1]);
						shot.Intrinsics.CenterPx[0] = (double)shot.Intrinsics.ViewportPx[0]/2.0;
						shot.Intrinsics.CenterPx[1] = (double)shot.Intrinsics.ViewportPx[1]/2.0;
						//shot.Intrinsics.DistorCenterPx[0]=shot.Intrinsics.CenterPx[0];
						//shot.Intrinsics.DistorCenterPx[1]=shot.Intrinsics.CenterPx[1];

						fclose(lvcam);
					}
			}

  QString tmpName=textureName.left(textureName.length()-4);
  maskName = tmpName.append(".mask.png");
  return true;
}

QString Arc3DModel::ThumbName(QString &_imageName)
{
  QString tmpName=_imageName.left(_imageName.length()-4);
  return tmpName.append(".thumb.jpg");
}


text:
<?php

$searchValue = '';
if (isset($_GET['outfit'])){
    $searchValue = 'value="' .$_GET['outfit'] . '"';
}

?>

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation

                    </button>
                    <a class="navbar-brand" href="<?php echo HOME_PAGE; ?>"><img src="<?php echo HOME_ROOT; ?>css/images/logo.png">

                    <form id="search-form" class="navbar-form navbar-left" role="search">

                            <input id="search-bar" type="text" class="form-control input-search" placeholder="Stop searching, Start finding" <?php echo $searchValue; ?> />

                        <button type="submit" id="seach-bar-icon" class="btn btn-default search-btn icon-svg2"></button>

                        <?php if (isset($homepage) && $homepage){ ?>
                            <button class="btn btn-clositt-theme filter-btn icomoon-filter-3"></button>
                        <?php } ?>

                    </form>

                <?php if (isset($homepage) && $homepage){ ?>
                    <button class="btn btn-clositt-theme filter-btn filter-btn-sm icomoon-filter-3"></button>
                <?php } ?>


text:
"""
Train Class1 pan-allele models.
"""
import argparse
import os
from os.path import join
import signal
import sys
import time
import traceback
import random
import pprint
import hashlib
import pickle
import uuid
from functools import partial

import numpy
import pandas
import yaml
import tqdm  # progress bar
tqdm.monitor_interval = 0  # see https://github.com/tqdm/tqdm/issues/481

from .class1_affinity_predictor import Class1AffinityPredictor
from .class1_neural_network import Class1NeuralNetwork
from .common import configure_logging
from .local_parallelism import (
    add_local_parallelism_args,
    worker_pool_with_gpu_assignments_from_args,
    call_wrapped_kwargs)
from .cluster_parallelism import (
    add_cluster_parallelism_args,
    cluster_results_from_args)
from .allele_encoding import AlleleEncoding
from .encodable_sequences import EncodableSequences

# To avoid pickling large matrices to send to child processes when running in
# parallel, we use this global variable as a place to store data. Data that is
# stored here before creating the thread pool will be inherited to the child
# processes upon fork() call, allowing us to share large data with the workers
# via shared memory.
GLOBAL_DATA = {}

# Note on parallelization:
# It seems essential currently (tensorflow==1.4.1) that no processes are forked
# after tensorflow has been used at all, which includes merely importing
# keras.backend. So we must make sure not to use tensorflow in the main process
# if we are running in parallel.

parser = argparse.ArgumentParser(usage=__doc__)

parser.add_argument(
    "--data",
    metavar="FILE.csv",
    help=(
        "Training data CSV. Expected columns: "
        "allele, peptide, measurement_value"))
parser.add_argument(
    "--pretrain-data",
    metavar="FILE.csv",
    help=(
        "Pre-training data CSV. Expected columns: "
        "allele, peptide, measurement_value"))
parser.add_argument(
    "--out-models-dir",
    metavar="DIR",
    required=True,
    help="Directory to write models and manifest")
parser.add_argument(
    "--hyperparameters",
    metavar="FILE.json",
    help="JSON or YAML of hyperparameters")
parser.add_argument(
    "--held-out-measurements-per-allele-fraction-and-max",
    type=float,
    metavar="X",
    nargs=2,
    default=[0.25, 100],
    help="Fraction of measurements per allele to hold out, and maximum number")
parser.add_argument(
    "--ignore-inequalities",
    action="store_true",
    default=False,
    help="Do not use affinity value inequalities even when present in data")
parser.add_argument(
    "--num-folds",
    type=int,
    default=4,
    metavar="N",
    help="Number of training folds.")
parser.add_argument(
    "--num-replicates",
    type=int,
    metavar="N",
    default=1,
    help="Number of replicates per (architecture, fold) pair to train.")
parser.add_argument(
    "--max-epochs",
    type=int,
    metavar="N",
    help="Max training epochs. If specified here it overrides any 'max_epochs' "
    "specified in the hyperparameters.")
parser.add_argument(
    "--allele-sequences",
    metavar="FILE.csv",
    help="Allele sequences file.")
parser.add_argument(
    "--verbosity",
    type=int,
    help="Keras verbosity. Default: %(default)s",
    default=0)
parser.add_argument(
    "--debug",
    action="store_true",
    default=False,
    help="Launch python debugger on error")
parser.add_argument(
    "--continue-incomplete",
    action="store_true",
    default=False,
    help="Continue training models from an incomplete training run. If this is "
    "specified then the only required argument is --out-models-dir")
parser.add_argument(
    "--only-initialize",
    action="store_true",
    default=False,
    help="Do not actually train models. The initialized run can be continued "
    "later with --continue-incomplete.")

add_local_parallelism_args(parser)
add_cluster_parallelism_args(parser)

def assign_folds(df, num_folds, held_out_fraction, held_out_max):
    """
    Split training data into multple test/train pairs, which we refer to as
    folds. Note that a given data point may be assigned to multiple test or
    train sets; these folds are NOT a non-overlapping partition as used in cross
    validation.

    A fold is defined by a boolean value for each data point, indicating whether
    it is included in the training data for that fold. If it's not in the
    training data, then it's in the test data.

    Folds are balanced in terms of allele content.

    Parameters
    ----------
    df : pandas.DataFrame
        training data
    num_folds : int
    held_out_fraction : float
        Fraction of data to hold out as test data in each fold
    held_out_max
        For a given allele, do not hold out more than held_out_max number of
        data points in any fold.

    Returns
    -------
    pandas.DataFrame
        index is same as df.index, columns are "fold_0", ... "fold_N" giving
        whether the data point is in the training data for the fold
    """
    result_df = pandas.DataFrame(index=df.index)

    for fold in range(num_folds):
        result_df["fold_%d" % fold] = True
        for (allele, sub_df) in df.groupby("allele"):
            medians = sub_df.groupby("peptide").measurement_value.median()

            low_peptides = medians[medians < medians.median()].index.values
            high_peptides = medians[medians >= medians.median()].index.values

            held_out_count = int(
                min(len(medians) * held_out_fraction, held_out_max))

            held_out_peptides = set()
            if held_out_count == 0:
                pass
            elif held_out_count < 2:
                held_out_peptides = set(
                    medians.index.to_series().sample(n=held_out_count))
            else:
                held_out_low_count = min(
                    len(low_peptides),
                    int(held_out_count / 2))
                held_out_high_count = min(
                    len(high_peptides),
                    held_out_count - held_out_low_count)

                held_out_low = pandas.Series(low_peptides).sample(
                    n=held_out_low_count) if held_out_low_count else set()
                held_out_high = pandas.Series(high_peptides).sample(
                    n=held_out_high_count) if held_out_high_count else set()
                held_out_peptides = set(held_out_low).union(set(held_out_high))

            result_df.loc[
                sub_df.index[sub_df.peptide.isin(held_out_peptides)],
                "fold_%d" % fold
            ] = False

    print("Training points per fold")
    print(result_df.sum())

    print("Test points per fold")
    print((~result_df).sum())
    return result_df

def pretrain_data_iterator(
        filename,
        master_allele_encoding,
        peptides_per_chunk=1024):
    """
    Step through a CSV file giving predictions for a large number of peptides
    (rows) and alleles (columns).

    Parameters
    ----------
    filename : string
    master_allele_encoding : AlleleEncoding
    peptides_per_chunk : int

    Returns
    -------
    Generator of (AlleleEncoding, EncodableSequences, float affinities) tuples

    """
    empty = pandas.read_csv(filename, index_col=0, nrows=0)
    usable_alleles = [
        c for c in empty.columns
        if c in master_allele_encoding.allele_to_sequence
    ]
    print("Using %d / %d alleles" % (len(usable_alleles), len(empty.columns)))
    print("Skipped alleles: ", [
        c for c in empty.columns
        if c not in master_allele_encoding.allele_to_sequence
    ])

    allele_encoding = AlleleEncoding(
        numpy.tile(usable_alleles, peptides_per_chunk),
        borrow_from=master_allele_encoding)

    while True:
        synthetic_iter = pandas.read_csv(
            filename, index_col=0, chunksize=peptides_per_chunk)
        for (k, df) in enumerate(synthetic_iter):
            if len(df) != peptides_per_chunk:
                continue

            df = df[usable_alleles]
            encodable_peptides = EncodableSequences(
                numpy.repeat(
                    df.index.values,
                    len(usable_alleles)))

            yield (allele_encoding, encodable_peptides, df.stack().values)

def run(argv=sys.argv[1:]):
    # On sigusr1 print stack trace
    print("To show stack trace, run:\nkill -s USR1 %d" % os.getpid())
    signal.signal(signal.SIGUSR1, lambda sig, frame: traceback.print_stack())

    args = parser.parse_args(argv)

    if args.debug:
        try:
            return main(args)
        except Exception as e:
            print(e)
            import ipdb  # pylint: disable=import-error
            ipdb.set_trace()
            raise
    else:
        return main(args)

def main(args):
    print("Arguments:")
    print(args)

    args.out_models_dir = os.path.abspath(args.out_models_dir)
    configure_logging(verbose=args.verbosity > 1)

    if not args.continue_incomplete:
        initialize_training(args)

    if not args.only_initialize:
        train_models(args)

def initialize_training(args):
    required_arguments = [
        "data",
        "out_models_dir",
        "hyperparameters",
        "num_folds",
    ]
    for arg in required_arguments:
        if getattr(args, arg) is None:
            parser.error("Missing required arg: %s" % arg)

    print("Initializing training.")
    hyperparameters_lst = yaml.load(open(args.hyperparameters))
    assert isinstance(hyperparameters_lst, list)
    print("Loaded hyperparameters list:")
    pprint.pprint(hyperparameters_lst)

    allele_sequences = pandas.read_csv(
        args.allele_sequences, index_col=0).iloc[:,0]

    df = pandas.read_csv(args.data)
    print("Loaded training data: %s" % (str(df.shape)))
    df = df.loc[
        (df.peptide.str.len() >= 8) & (df.peptide.str.len() <= 15)
    ]
    print("Subselected to 8-15mers: %s" % (str(df.shape)))

    df = df.loc[~df.measurement_value.isnull()]
    print("Dropped NaNs: %s" % (str(df.shape)))

    df = df.loc[df.allele.isin(allele_sequences.index)]
    print("Subselected to alleles with sequences: %s" % (str(df.shape)))

    print("Data inequalities:")
    print(df.measurement_inequality.value_counts())

    if args.ignore_inequalities and "measurement_inequality" in df.columns:
        print("Dropping measurement_inequality column")
        del df["measurement_inequality"]
    # Allele names in data are assumed to be already normalized.
    print("Training data: %s" % (str(df.shape)))

    (held_out_fraction, held_out_max) = (
        args.held_out_measurements_per_allele_fraction_and_max)

    folds_df = assign_folds(
        df=df,
        num_folds=args.num_folds,
        held_out_fraction=held_out_fraction,
        held_out_max=held_out_max)

    allele_sequences_in_use = allele_sequences[
        allele_sequences.index.isin(df.allele)
    ]
    print("Will use %d / %d allele sequences" % (
        len(allele_sequences_in_use), len(allele_sequences)))

    # All alleles, not just those with training data.
    full_allele_encoding = AlleleEncoding(
        alleles=allele_sequences.index.values,
        allele_to_sequence=allele_sequences.to_dict()
    )

    # Only alleles with training data. For efficiency we perform model training
    # using only these alleles in the neural network embedding layer.
    allele_encoding = AlleleEncoding(
        alleles=allele_sequences_in_use.index.values,
        allele_to_sequence=allele_sequences_in_use.to_dict())

    if not os.path.exists(args.out_models_dir):
        print("Attempting to create directory: %s" % args.out_models_dir)
        os.mkdir(args.out_models_dir)
        print("Done.")

    predictor = Class1AffinityPredictor(
        allele_to_sequence=allele_encoding.allele_to_sequence,
        metadata_dataframes={
            'train_data': pandas.merge(
                df,
                folds_df,
                left_index=True,
                right_index=True)
        })

    work_items = []
    for (h, hyperparameters) in enumerate(hyperparameters_lst):
        if 'n_models' in hyperparameters:
            raise ValueError("n_models is unsupported")

        if args.max_epochs:
            hyperparameters['max_epochs'] = args.max_epochs

        if hyperparameters.get("train_data", {}).get("pretrain", False):
            if not args.pretrain_data:
                raise ValueError("--pretrain-data is required")

        for fold in range(args.num_folds):
            for replicate in range(args.num_replicates):
                work_dict = {
                    'work_item_name': str(uuid.uuid4()),
                    'architecture_num': h,
                    'num_architectures': len(hyperparameters_lst),
                    'fold_num': fold,
                    'num_folds': args.num_folds,
                    'replicate_num': replicate,
                    'num_replicates': args.num_replicates,
                    'hyperparameters': hyperparameters,
                    'pretrain_data_filename': args.pretrain_data,
                }
                work_items.append(work_dict)

    training_init_info = {}
    training_init_info["train_data"] = df
    training_init_info["folds_df"] = folds_df
    training_init_info["allele_encoding"] = allele_encoding
    training_init_info["full_allele_encoding"] = full_allele_encoding
    training_init_info["work_items"] = work_items

    # Save empty predictor (for metadata)
    predictor.save(args.out_models_dir)

    # Write training_init_info.
    with open(join(args.out_models_dir, "training_init_info.pkl"), "wb") as fd:
        pickle.dump(training_init_info, fd, protocol=pickle.HIGHEST_PROTOCOL)

    print("Done initializing training.")

def train_models(args):
    global GLOBAL_DATA

    print("Beginning training.")
    predictor = Class1AffinityPredictor.load(
        args.out_models_dir, optimization_level=0)
    print("Loaded predictor with %d networks" % len(predictor.neural_networks))

    with open(join(args.out_models_dir, "training_init_info.pkl"), "rb") as fd:
        GLOBAL_DATA.update(pickle.load(fd))
    print("Loaded training init info.")

    all_work_items = GLOBAL_DATA["work_items"]
    complete_work_item_names = [
        network.fit_info[-1]["training_info"]["work_item_name"] for network in
        predictor.neural_networks
    ]
    work_items = [
        item for item in all_work_items
        if item["work_item_name"] not in complete_work_item_names
    ]
    print("Found %d work items, of which %d are incomplete and will run now." % (
        len(all_work_items), len(work_items)))

    serial_run = not args.cluster_parallelism and args.num_jobs == 0

    # The estimated time to completion is more accurate if we randomize
    # the order of the work.
    random.shuffle(work_items)
    for (work_item_num, item) in enumerate(work_items):
        item['work_item_num'] = work_item_num
        item['num_work_items'] = len(work_items)
        item['progress_print_interval'] = 60.0 if not serial_run else 5.0
        item['predictor'] = predictor if serial_run else None
        item['save_to'] = args.out_models_dir if serial_run else None
        item['verbose'] = args.verbosity
        if args.pretrain_data:
            item['pretrain_data_filename'] = args.pretrain_data

    start = time.time()

    worker_pool = None
    if serial_run:
        # Run in serial. Every worker is passed the same predictor,
        # which it adds models to, so no merging is required. It also saves
        # as it goes so no saving is required at the end.
        print("Processing %d work items in serial." % len(work_items))
        for _ in tqdm.trange(len(work_items)):
            item = work_items.pop(0)  # want to keep freeing up memory
            work_predictor = train_model(**item)
            assert work_predictor is predictor
        assert not work_items
        results_generator = None
    elif args.cluster_parallelism:
        # Run using separate processes HPC cluster.
        results_generator = cluster_results_from_args(
            args,
            work_function=train_model,
            work_items=work_items,
            constant_data=GLOBAL_DATA,
            result_serialization_method="save_predictor")
    else:
        worker_pool = worker_pool_with_gpu_assignments_from_args(args)
        print("Worker pool", worker_pool)
        assert worker_pool is not None

        print("Processing %d work items in parallel." % len(work_items))
        assert not serial_run

        for item in work_items:
            item['constant_data'] = GLOBAL_DATA

        results_generator = worker_pool.imap_unordered(
            partial(call_wrapped_kwargs, train_model),
            work_items,
            chunksize=1)

    if results_generator:
        for new_predictor in tqdm.tqdm(results_generator, total=len(work_items)):
            save_start = time.time()
            (new_model_name,) = predictor.merge_in_place([new_predictor])
            predictor.save(
                args.out_models_dir,
                model_names_to_write=[new_model_name],
                write_metadata=False)
            print(
                "Saved predictor (%d models total) with 1 new models"
                "in %0.2f sec to %s" % (
                    len(predictor.neural_networks),
                    time.time() - save_start,
                    args.out_models_dir))

    # We want the final predictor to support all alleles with sequences, not
    # just those we actually used for model training.
    predictor.allele_to_sequence = (
        GLOBAL_DATA['full_allele_encoding'].allele_to_sequence)
    predictor.clear_cache()
    predictor.save(args.out_models_dir)
    print("Done.")

    print("*" * 30)
    training_time = time.time() - start
    print("Trained affinity predictor with %d networks in %0.2f min." % (
        len(predictor.neural_networks), training_time / 60.0))
    print("*" * 30)

    if worker_pool:
        worker_pool.close()
        worker_pool.join()

    print("Predictor written to: %s" % args.out_models_dir)

def train_model(
        work_item_name,
        work_item_num,
        num_work_items,
        architecture_num,
        num_architectures,
        fold_num,
        num_folds,
        replicate_num,
        num_replicates,
        hyperparameters,
        pretrain_data_filename,
        verbose,
        progress_print_interval,
        predictor,
        save_to,
        constant_data=GLOBAL_DATA):

    df = constant_data["train_data"]
    folds_df = constant_data["folds_df"]
    allele_encoding = constant_data["allele_encoding"]

    if predictor is None:
        predictor = Class1AffinityPredictor(
            allele_to_sequence=allele_encoding.allele_to_sequence)

    numpy.testing.assert_equal(len(df), len(folds_df))

    train_data = df.loc[
        folds_df["fold_%d" % fold_num]
    ].sample(frac=1.0)

    train_peptides = EncodableSequences(train_data.peptide.values)
    train_alleles = AlleleEncoding(
        train_data.allele.values, borrow_from=allele_encoding)

    progress_preamble = (
        "[task %2d / %2d]: "
        "[%2d / %2d folds] "
        "[%2d / %2d architectures] "
        "[%4d / %4d replicates] " % (
            work_item_num + 1,
            num_work_items,
            fold_num + 1,
            num_folds,
            architecture_num + 1,
            num_architectures,
            replicate_num + 1,
            num_replicates))

    print("%s [pid %d]. Hyperparameters:" % (progress_preamble, os.getpid()))
    pprint.pprint(hyperparameters)

    train_params = dict(hyperparameters.get("train_data", {}))

    def get_train_param(param, default):
        if param in train_params:
            result = train_params.pop(param)
            if verbose:
                print("Train param", param, "=", result)
        else:
            result = default
            if verbose:
                print("Train param", param, "=", result, "[default]")
        return result

    if get_train_param("pretrain", False):
        pretrain_patience = get_train_param("pretrain_patience", 10)
        pretrain_min_delta = get_train_param("pretrain_min_delta", 0.0)
        pretrain_steps_per_epoch = get_train_param(
            "pretrain_steps_per_epoch", 10)
        pretrain_max_epochs = get_train_param("pretrain_max_epochs", 1000)
        pretrain_min_epochs = get_train_param("pretrain_min_epochs", 0)
        pretrain_peptides_per_step = get_train_param(
            "pretrain_peptides_per_step", 1024)
        max_val_loss = get_train_param("pretrain_max_val_loss", None)

        if verbose:
            print("Unused train params", train_params)

        attempt = 0
        while True:
            attempt += 1
            print("Pre-training attempt %d" % attempt)
            if attempt > 10:
                print("Too many pre-training attempts! Stopping pretraining.")
                break

            model = Class1NeuralNetwork(**hyperparameters)
            assert model.network() is None
            generator = pretrain_data_iterator(
                pretrain_data_filename,
                allele_encoding,
                peptides_per_chunk=pretrain_peptides_per_step)

            model.fit_generator(
                generator,
                validation_peptide_encoding=train_peptides,
                validation_affinities=train_data.measurement_value.values,
                validation_allele_encoding=train_alleles,
                validation_inequalities=train_data.measurement_inequality.values,
                patience=pretrain_patience,
                min_delta=pretrain_min_delta,
                steps_per_epoch=pretrain_steps_per_epoch,
                epochs=pretrain_max_epochs,
                min_epochs=pretrain_min_epochs,
                verbose=verbose,
                progress_preamble=progress_preamble + "PRETRAIN",
                progress_print_interval=progress_print_interval,
            )
            model.fit_info[-1].setdefault(
                "training_info", {})["pretrain_attempt"] = attempt
            if not max_val_loss:
                break
            final_val_loss = model.fit_info[-1]["val_loss"][-1]
            if final_val_loss >= max_val_loss:
                print("Val loss %f >= max val loss %f. Pre-training again." % (
                    final_val_loss, max_val_loss))
            else:
                print("Val loss %f < max val loss %f. Done pre-training." % (
                    final_val_loss, max_val_loss))
                break

        # Use a smaller learning rate for training on real data
        learning_rate = model.fit_info[-1]["learning_rate"]
        model.hyperparameters['learning_rate'] = learning_rate / 10
    else:
        model = Class1NeuralNetwork(**hyperparameters)

    model.fit(
        peptides=train_peptides,
        affinities=train_data.measurement_value.values,
        allele_encoding=train_alleles,
        inequalities=(
            train_data.measurement_inequality.values
            if "measurement_inequality" in train_data.columns else None),
        progress_preamble=progress_preamble,
        progress_print_interval=progress_print_interval,
        verbose=verbose)

    # Save model-specific training info
    train_peptide_hash = hashlib.sha1()
    for peptide in sorted(train_data.peptide.values):
        train_peptide_hash.update(peptide.encode())

    model.fit_info[-1].setdefault("training_info", {}).update({
        "fold_num": fold_num,
        "num_folds": num_folds,
        "replicate_num": replicate_num,
        "num_replicates": num_replicates,
        "architecture_num": architecture_num,
        "num_architectures": num_architectures,
        "train_peptide_hash": train_peptide_hash.hexdigest(),
        "work_item_name": work_item_name,
    })

    numpy.testing.assert_equal(
        predictor.manifest_df.shape[0], len(predictor.class1_pan_allele_models))
    predictor.add_pan_allele_model(model, models_dir_for_save=save_to)
    numpy.testing.assert_equal(
        predictor.manifest_df.shape[0], len(predictor.class1_pan_allele_models))
    predictor.clear_cache()

    # Delete the network to release memory
    model.clear_allele_representations()
    model.update_network_description()  # save weights and config
    model._network = None  # release tensorflow network
    return predictor

if __name__ == '__main__':
    run()


text:
import re

from six import u, PY2

from . import base
from ..utils import UnixCommandNotFound, catch_exception_and_warn

class ThermalSensor(base.InLoopPollText):
    """Widget to display temperature sensor information

    For using the thermal sensor widget you need to have lm-sensors installed.
    You can get a list of the tag_sensors executing "sensors" in your terminal.
    Then you can choose which you want, otherwise it will display the first
    available.
    """
    orientations = base.ORIENTATION_HORIZONTAL
    defaults = [
        ('metric', True, 'True to use metric/C, False to use imperial/F'),
        ('show_tag', False, 'Show tag sensor'),
        ('update_interval', 2, 'Update interval in seconds'),
        ('tag_sensor', None,
            'Tag of the temperature sensor. For example: "temp1" or "Core 0"'),
        (
            'threshold',
            70,
            'If the current temperature value is above, '
            'then change to foreground_alert colour'
        ),
        ('foreground_alert', 'ff0000', 'Foreground colour alert'),
    ]

    def __init__(self, **config):
        base.InLoopPollText.__init__(self, **config)
        self.add_defaults(ThermalSensor.defaults)
        self.sensors_temp = re.compile(
            u(r"""
            ([\w ]+):   # Sensor tag name
            \s+[+|-]    # temp signed
            (\d+\.\d+)  # temp value
            ({degrees}  # ° match
            [C|F])      # Celsius or Fahrenheit
            """.format(degrees="\xc2\xb0" if PY2 else "\xb0")),
            re.UNICODE | re.VERBOSE
        )
        self.value_temp = re.compile("\d+\.\d+")
        temp_values = self.get_temp_sensors()
        self.foreground_normal = self.foreground

        if temp_values is None:
            self.data = "sensors command not found"
        elif len(temp_values) == 0:
            self.data = "Temperature sensors not found"
        elif self.tag_sensor is None:
            for k in temp_values:
                self.tag_sensor = k
                break

    @catch_exception_and_warn(warning=UnixCommandNotFound, excepts=OSError)
    def get_temp_sensors(self):
        """calls the unix `sensors` command with `-f` flag if user has specified that
        the output should be read in Fahrenheit.
        """
        command = ["sensors", ]
        if not self.metric:
            command.append("-f")
        sensors_out = self.call_process(command)
        return self._format_sensors_output(sensors_out)

    def _format_sensors_output(self, sensors_out):
        """formats output of unix `sensors` command into a dict of
        {<sensor_name>: (<temperature>, <temperature symbol>), ..etc..}
        """
        temperature_values = {}
        for name, temp, symbol in self.sensors_temp.findall(sensors_out):
            name = name.strip()
            temperature_values[name] = temp, symbol
        return temperature_values

    def poll(self):
        temp_values = self.get_temp_sensors()
        if temp_values is None:
            return False
        text = ""
        if self.show_tag and self.tag_sensor is not None:
            text = self.tag_sensor + ": "
        text += "".join(temp_values.get(self.tag_sensor, ['N/A']))
        temp_value = float(temp_values.get(self.tag_sensor, [0])[0])
        if temp_value > self.threshold:
            self.layout.colour = self.foreground_alert
        else:
            self.layout.colour = self.foreground_normal
        return text


text:
set -e

SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

if [ "$#" -ne 2 ]; then
  echo "Usage: $0 <js-version> <rc-num>"
  exit
fi

js_version=$1
rc=$2

tag=apache-arrow-js-${js_version}
tagrc=${tag}-rc${rc}

echo "Preparing source for tag ${tag}"

tarball=${tag}.tar.gz

# cd to $ARROW_HOME/js
cd $SOURCE_DIR/../../js
JS_SRC_DIR="$PWD"
# npm pack the js source files
npm install

npm version --no-git-tag-version $js_version
git add package.json
git commit -m "[Release] Apache Arrow JavaScript $js_version"
git tag -a ${tag}

release_hash=`git rev-list $tag 2> /dev/null | head -n 1 `

if [ -z "$release_hash" ]; then
  echo "Cannot continue: unknown git tag: $tag"
  exit
fi

echo "Using commit $release_hash"

cd $SOURCE_DIR

rm -rf js-tmp
# `npm pack` writes the .tgz file to the current dir, so cd into js-tmp
mkdir -p js-tmp
cd js-tmp
# run npm pack on `arrow/js`
npm pack ${JS_SRC_DIR}
# unzip and remove the npm pack tarball
tar -xzf *.tgz && rm *.tgz
# `npm pack` puts files in a dir called "package"
cp $JS_SRC_DIR/../NOTICE.txt package
cp $JS_SRC_DIR/../LICENSE.txt package
# rename "package" to $tag
mv package ${tag}
tar czf ${tarball} ${tag}
rm -rf ${tag}

${SOURCE_DIR}/run-rat.sh ${tarball}

# sign the archive
gpg --armor --output ${tarball}.asc --detach-sig ${tarball}
gpg --print-md MD5 ${tarball} > ${tarball}.md5
sha1sum $tarball > ${tarball}.sha1
sha256sum $tarball > ${tarball}.sha256
sha512sum $tarball > ${tarball}.sha512

# check out the arrow RC folder
svn co --depth=empty https://dist.apache.org/repos/dist/dev/arrow js-rc-tmp

# add the release candidate for the tag
mkdir -p js-rc-tmp/${tagrc}
cp ${tarball}* js-rc-tmp/${tagrc}
svn add js-rc-tmp/${tagrc}
svn ci -m 'Apache Arrow JavaScript ${version} RC${rc}' js-rc-tmp/${tagrc}

cd -

# clean up
rm -rf js-tmp

echo "Success! The release candidate is available here:"
echo "  https://dist.apache.org/repos/dist/dev/arrow/${tagrc}"
echo ""
echo "Commit SHA1: ${release_hash}"


text:
/*
20170830 logfile processing

You are given a log file with the bandwidth information of users in several lines.
Bandwidth info for a certain user may be repeated.
User:A Bandwidth:50 CountryCode:IND
User:B Bandwidth:60 CountryCode:USA
User:A Bandwidth:70 CountryCode:IND
(i) Find total amount of bandwidth consumed per user
(ii) Suppose there are 4 country codes, for every country code, find the top 5 users which consumed maximum bandwidth sorted.

New stuff learned:
- map and array struct values are initialized zero values, which are not nil!
- after getting an object from map, if the object is modified, it needs to be set into the map again!
- reflect.DeepEqual() is helpful for comparing results vs. expected
*/
package main

import (
	"fmt"
	"reflect"
)

func main() {

	users := []user{
		user{"A_IND", 50, "IND"},
		user{"B_USA", 60, "USA"},
		user{"C_IND", 20, "IND"},
		user{"B_USA", 70, "USA"},
		user{"D_IND", 10, "IND"},
		user{"E_IND", 90, "IND"},
		user{"F_IND", 70, "IND"},
		user{"G_IND", 120, "IND"},
		user{"H_USA", 70, "USA"},
		user{"I_USA", 85, "USA"},
	}

	expectedBandwidthByUser := map[string]int{
		"B_USA": 130,
		"A_IND": 50,
		"C_IND": 20,
		"D_IND": 10,
		"E_IND": 90,
		"F_IND": 70,
		"G_IND": 120,
		"H_USA": 70,
		"I_USA": 85,
	}

	input := users
	checkTotalBandwidthByUser(input, expectedBandwidthByUser)

	expectedTop5 := map[string][5]user{
		"IND": [5]user{
			user{"G_IND", 120, "IND"},
			user{"E_IND", 90, "IND"},
			user{"F_IND", 70, "IND"},
			user{"A_IND", 50, "IND"},
			user{"C_IND", 20, "IND"},
		},
		"USA": [5]user{
			user{"B_USA", 60, "USA"},
			user{"I_USA", 85, "USA"},
			user{"H_USA", 70, "USA"},
		},
	}
	checkTop5BandwidthUsersByCountryCode(input, expectedTop5)

}

type user struct {
	name        string
	bandWidth   int
	countryCode string
}

//TODO: Try out file IO

func checkTotalBandwidthByUser(input []user, expected map[string]int) {
	result := totalBandwidthByUser(input)
	fmt.Printf("input %v \n result %v \n expected  \n %v match %t \n\n",
		input,
		result,
		expected,
		reflect.DeepEqual(expected, result))
}

func checkTop5BandwidthUsersByCountryCode(input []user, expected map[string][5]user) {
	result := top5BandwidthUsersByCountryCode(input)
	t := result["test"]
	fmt.Printf("test %v \n", t)
	fmt.Println()
	fmt.Printf("input %v \n result %v \n expected  %v \n match %t \n\n",
		input,
		result,
		expected,
		reflect.DeepEqual(expected, result))
}

func top5BandwidthUsersByCountryCode(input []user) map[string][5]user {

	bandwidthByUser := totalBandwidthByUser(input)
	top5ByCountry := map[string][5]user{}
	encounteredUser := map[string]bool{}

inputLoop:
	for _, aUser := range input {
		if encounteredUser[aUser.name] {
			continue
		}
		encounteredUser[aUser.name] = true

		countryUsers := top5ByCountry[aUser.countryCode]

		top5ByCountry[aUser.countryCode] = countryUsers
		fmt.Printf("Current top 5 for %v -> %-v  %-v %-v \n", aUser.countryCode, countryUsers, len(countryUsers), top5ByCountry)

		var toInsert user
		for idx2, aUser2 := range countryUsers {
			fmt.Println()

			if toInsert.name != "" {
				tmpUser := countryUsers[idx2]
				countryUsers[idx2] = toInsert
				toInsert = tmpUser
				fmt.Printf("Inserting %-v to idx %v %-v \n", countryUsers[idx2], idx2, countryUsers)
				top5ByCountry[aUser.countryCode] = countryUsers
				if toInsert.name == "" {
					continue inputLoop
				}
			} else if aUser2.name == "" {
				countryUsers[idx2] = aUser
				top5ByCountry[aUser.countryCode] = countryUsers
				fmt.Printf("Setting %-v to empty value to %-v  %-v \n", countryUsers[idx2], countryUsers, top5ByCountry)
				continue inputLoop
			} else if bandwidthByUser[aUser.name] > bandwidthByUser[aUser2.name] {
				toInsert = aUser2
				countryUsers[idx2] = aUser
				top5ByCountry[aUser.countryCode] = countryUsers
				fmt.Printf("Inserting %-v to %v because bandwidth > current's  %-v \n", countryUsers[idx2], idx2, countryUsers)
			}
		}

		fmt.Printf("After processing %v -> %-v  %v \n", aUser.countryCode, countryUsers, len(countryUsers))
	}

	return top5ByCountry
}

func totalBandwidthByUser(users []user) map[string]int {
	result := map[string]int{}

	for _, user := range users {
		result[user.name] += user.bandWidth
	}

	return result
}


text:
'use strict';

define(['angular'], function(angular){
    var app = angular.module('bugattiApp.controller.admin.systemModule', []);

    app.controller('SystemCtrl', ['$scope', 'growl', 'SystemService', function($scope, growl, SystemService) {
        $scope.app.breadcrumb='系统配置';
        $scope.ldapAuthentication = false;

        SystemService.load(function(data) {
            $scope.ldapAuthentication = data.ldapAuthentication;
            $scope.ldap = data.ldap;
        });

        $scope.applyChange = function(ldap) {
            var settings = {ldapAuthentication: $scope.ldapAuthentication, ldap: ldap}
            SystemService.update(angular.toJson(settings), function(data) {
                if (data.r === 'ok') {
                    growl.addSuccessMessage("修改成功");
                }
            });
        }

    }]);
});