text:
% This is "sig-alternate.tex" V2.1 April 2013
% This file should be compiled with V2.5 of "sig-alternate.cls" May 2012
%
% This example file demonstrates the use of the 'sig-alternate.cls'
% V2.5 LaTeX2e document class file. It is for those submitting
% articles to ACM Conference Proceedings WHO DO NOT WISH TO
% STRICTLY ADHERE TO THE SIGS (PUBS-BOARD-ENDORSED) STYLE.
% The 'sig-alternate.cls' file will produce a similar-looking,
% albeit, 'tighter' paper resulting in, invariably, fewer pages.
%
% ----------------------------------------------------------------------------------------------------------------
% This .tex file (and associated .cls V2.5) produces:
%       1) The Permission Statement
%       2) The Conference (location) Info information
%       3) The Copyright Line with ACM data
%       4) NO page numbers
%
% as against the acm_proc_article-sp.cls file which
% DOES NOT produce 1) thru' 3) above.
%
% Using 'sig-alternate.cls' you have control, however, from within
% the source .tex file, over both the CopyrightYear
% (defaulted to 200X) and the ACM Copyright Data
% (defaulted to X-XXXXX-XX-X/XX/XX).
% e.g.
% \CopyrightYear{2007} will cause 2007 to appear in the copyright line.
% \crdata{0-12345-67-8/90/12} will cause 0-12345-67-8/90/12 to appear in the copyright line.
%
% ---------------------------------------------------------------------------------------------------------------
% This .tex source is an example which *does* use
% the .bib file (from which the .bbl file % is produced).
% REMEMBER HOWEVER: After having produced the .bbl file,
% and prior to final submission, you *NEED* to 'insert'
% your .bbl file into your source .tex file so as to provide
% ONE 'self-contained' source file.
%
% ================= IF YOU HAVE QUESTIONS =======================
% Questions regarding the SIGS styles, SIGS policies and
% procedures, Conferences etc. should be sent to
% Adrienne Griscti (griscti@acm.org)
%
% Technical questions _only_ to
% Gerald Murray (murray@hq.acm.org)
% ===============================================================
%
% For tracking purposes - this is V2.0 - May 2012

\documentclass[9pt]{sig-alternate-05-2015}

%\usepackage{color}
\usepackage{url}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\usepackage{listings}
\usepackage{hyperref}
\definecolor{StringRed}{rgb}{.637,0.082,0.082}
\definecolor{CommentGreen}{rgb}{0,0.5,0}
\definecolor{KeywordBlue}{rgb}{0,0,1}
\definecolor{UserTypeTeal}{rgb}{0.1679,0.5664,0.6836}

\lstdefinelanguage{threeextensions}%
  {morekeywords={var,from,select,where,orderby,yield,let,join,on,into,Equal,group,by,ascending,descending,
                 try,catch,finally},
   sensitive,
  }[keywords]%

\lstdefinelanguage{fourextensions}
   {morekeywords={dynamic},
    sensitive
   }[keywords]

\lstdefinelanguage{fiveextensions}
   {morekeywords={await,async},
    sensitive
   }[keywords]

\lstdefinelanguage{CSharpLatest}
                         {language=[Sharp]{C}, %
                          alsolanguage=threeextensions,
                          alsolanguage=fourextensions,
					alsolanguage=fiveextensions,
                          basicstyle=\color{black}\ttfamily\small,
                          showstringspaces=false,
                          keywordstyle=\color{KeywordBlue},
                          commentstyle=\color{CommentGreen},
                          stringstyle=\color{StringRed},
rangebeginprefix=\#region\ ,
rangeendprefix=\#endregion\ ,
includerangemarker=false,
                          columns=flexible
                         }

\lstdefinelanguage{conceptextensions}
   {morekeywords={instance,concept,interface,member,Witness,Trait,abstract,struct},
    sensitive
   }[keywords]
\lstdefinelanguage{FSharp}
                         {language={Caml}, %
                          alsolanguage=conceptextensions,
                          basicstyle=\color{black}\ttfamily\small,
                          showstringspaces=false,
                          keywordstyle=\color{KeywordBlue},
                          commentstyle=\color{CommentGreen},
                          stringstyle=\color{StringRed},
                          columns=flexible
                         }

\lstset{moredelim=[is][\color{UserTypeTeal}]{|}{|}}

\newif\ifclassic
\classicfalse

\begin{document}

\setcopyright{none}
% Copyright
%\setcopyright{acmcopyright}
%\setcopyright{acmlicensed}
%\setcopyright{rightsretained}
%\setcopyright{usgov}
%\setcopyright{usgovmixed}
%\setcopyright{cagov}
%\setcopyright{cagovmixed}

%
% --- Author Metadata here ---
%\conferenceinfo{ML Workshop 2016}{Japan}
%\CopyrightYear{2007} % Allows default copyright year (20XX) to be over-ridden - IF NEED BE.
%\crdata{0-12345-67-8/90/01}  % Allows default copyright data (0-89791-88-6/97/05) to be over-ridden - IF NEED BE.
% --- End of Author Metadata ---

\title{Classes for the Masses (Extended Abstract)}
%\titlenote{A full version of this paper is available as
%\textit{Author's Guide to Preparing ACM SIG Proceedings Using
%\LaTeX$2_\epsilon$\ and BibTeX} at
%\texttt{www.acm.org/eaddress.htm}}}
%
% You need the command \numberofauthors to handle the 'placement
% and alignment' of the authors beneath the title.
%
% For aesthetic reasons, we recommend 'three authors at a time'
% i.e. three 'name/affiliation blocks' be placed beneath the title.
%
% NOTE: You are NOT restricted in how many 'rows' of
% "name/affiliations" may appear. We just ask that you restrict
% the number of 'columns' to three.
%
% Because of the available 'opening page real-estate'
% we ask you to refrain from putting more than six authors
% (two rows with three columns) beneath the article title.
% More than six makes the first-page appear very cluttered indeed.
%
% Use the \alignauthor commands to handle the names
% and affiliations for an 'aesthetic maximum' of six authors.
% Add names, affiliations, addresses for
% the seventh etc. author(s) as the argument for the
% \additionalauthors command.
% These 'additional authors' will be output/set for you
% without further effort on your part as the last section in
% the body of your article BEFORE References or any Appendices.

\numberofauthors{5} %  in this sample file, there are a *total*
% of EIGHT authors. SIX appear on the 'first-page' (for formatting
% reasons) and the remaining two appear in the \additionalauthors section.
%
\author{
% You can go ahead and credit any number of authors here,
% e.g. one 'row of three' or two rows (consisting of one row of three
% and a second row of one, two or three).
%
% The command \alignauthor (no curly braces needed) should
% precede each author name, affiliation/snail-mail address and
% e-mail address. Additionally, tag each line of
% affiliation/address with \affaddr, and tag the
% e-mail address with \email.
%
% 1st. author
\alignauthor
Claudio Russo\\ \affaddr{(Microsoft Research)}
% 2nd. author
\alignauthor
Matt Windsor\\ \affaddr{(University of York)}
\and
\alignauthor
Don Syme\\  \affaddr{(Microsoft Research)}
\alignauthor
Rupert Horlick\\   \affaddr{(University of Cambridge)}
\alignauthor
James Clarke\\ \affaddr{(University of Cambridge)}
}
%\alignauthor
%Claudio Russo\\
%% 2nd. author
%\alignauthor
%Matt Windsor\\
%\alignauthor
%Don Syme\\
%\alignauthor
%Rupert Horlick\\
%\alignauthor
%James Clarke\\
%% 2nd. author
%\and
%\alignauthor
% \affaddr{(Microsoft Research)}\\
%\alignauthor
%  \affaddr{(University of Cambridge)}\\
%\alignauthor
% \affaddr{(University of Cambridge)}\\
%}

\makeatletter
\def\@copyrightspace{\relax}
\makeatother

\maketitle

\begin{abstract}
Type classes are an immensely popular and productive feature of Haskell. They have since been adopted in, and adapted to, numerous other languages, including theorem provers.
We show that type classes have a natural and efficient representation in .NET that paves the way for the extension of F\#, C\# and other .NET languages with type classes.
Our encoding  is type preserving and promises easy and safe cross-language inter-operation.
We have extended the open source C\# compiler and language service, Roslyn, with pervasive support for type classes and  have prototyped a more minimalist design  for F\#.
\end{abstract}

% We no longer use \terms command
%\terms{Theory}

%\renewcommand{\subsection}{1}{}

\section{Introduction}

Haskell's \emph{type classes} \cite{peytonjones:h98,WadlerBlott} are a powerful abstraction mechanism for describing generic algorithms applicable to types that have different representations but common interfaces.
A \emph{type class} is a predicate on types that specifies a set of required operations by their type signatures with  optional, default code.
A type may be declared to be an \emph{instance} of a type class, and must supply an implementation for each of the class' operations.
Type classes may be arranged hierarchically, permitting subsumption and inheritance.
%A default implementation may also be associated with an operation. % allowing its implementations to be omitted.

Many modern languages have adopted features inspired
by type classes, with different implementation techniques.  Scala has
\emph{implicits}\cite{scalaimplicits}, implicit method arguments denoting dictionaries, that
are inferred by the compiler but represented, at run-time, as additional
heap-allocated arguments to methods (with commensurate overhead).  C++ came very
close to adopting \emph{concepts}\cite{cppconcepts}, a rather different extension of the template mechanism,
directly inspired by Haskell's type classes but enforcing  compile-time code specialization for performance. Rust has \emph{traits}\cite{Rust}. Swift has
\emph{protocols}\cite{Swift}.

{\bf Contribution} We describe a simple encoding that allows us to add type classes to
any .NET language, allowing interoperable definitions of type
classes. Our encoding relies on the CLR's distinctive approach to
representing and compiling generic code\cite{genericspldi,genericspopl}. Unlike, for example, the JVM, the CLR
byte-code format is fully generic (all source level type information,
including class and method type parameters, are represented in the
metadata and virtual instruction set).  Parameterized code is JIT-compiled to type passing code,
with type parameters having run-time representations as (second-order)
values.  The JIT compiler uses the reified types to generate
specialized memory representations (for instantiated generic types)
and specialized (and thus more efficient) code for generic
methods. For example, scalar types and compounds of scalars called
structs have natural unboxed representations familiar to C(++)
programmers; generic array manipulating code will manipulate array
elements without boxing when instantiated at scalar types.  This run-time
specialization allows the JIT to avoid the uniform (i.e.\ lowest-common-denominator) representations adopted by many implementations of ML,
Haskell, the JVM and most dynamic languages.

Haskell compilers typically compile type classes using the so-called
\emph{dictionary translation}.  The translation, guided by source
types, inserts evidence terms that justify type class constraints. The evidence terms are dictionaries (i.e.\ records) of functions that provide implementations (and thus proofs) for all of the constraint's methods. Although similar to
object-oriented virtual method tables, dictionaries are not attached to
objects, but passed separately as function arguments.  Because type
classes are resolved statically, aggressive in-lining can remove most,
but not all, indirection through dictionary parameters. This leads to
efficient code with fewer indirect calls and leaner representations of values than full-blown objects. Objects, in contrast, must lug their method-tables wherever they go.

Given the obvious similarity between type passing and dictionary
passing, it is perhaps not surprising that type passing forms an
excellent implementation technique for Haskell's dictionary passing.
This talk will give on overview of the technique that we are applying to provide
efficient, inter-operable type class implementations to both C\# and F\#.

\section{The Representation}

This section sketches our representation of the Haskell'98 type classes on .NET by example.
For each example, we give the Haskell code, underlying .NET code in vanilla C\#, and proposed F\# syntax.
We use vanilla C\# as a more readable proxy for .NET intermediate bytecode and metadata.

%\subsection{Haskell Type Classes}

{\bf Type Classes} A Haskell type class, for example:
\lstset{language={CSharpLatest}}

{
\small
\lstset{language={Haskell}}
\begin{lstlisting}
  class Eq a where
    (==) :: a -> a -> Bool
\end{lstlisting}}
\noindent is naturally represented in C\# as:
\lstset{language={CSharpLatest}}
\begin{lstlisting}
  interface Eq<A> {  bool Equal(A a, A b);  }
\end{lstlisting}

\ifclassic
For new F\# syntax we adopt the keyword \lstinline{concept} (\lstinline{class} is already taken):

\lstset{language={FSharp}}
\begin{lstlisting}
concept Eq 'a where
    (==): 'a -> 'a -> bool
\end{lstlisting}
\else
\noindent\ For F\#, we use a  \lstinline{Trait}-attributed interface declaration:
\lstset{language={FSharp}}
\begin{lstlisting}
 [<Trait>]
 type Eq<'A> = (* an interface *)
   abstract equal: 'A -> 'A -> bool
\end{lstlisting}
\fi

%\subsection{Haskell Overloads}
{\bf  Haskell Overloads} Haskell's declaration of class \lstinline{Eq a} implicitly declares its members as overloaded
operations:

\lstset{language={Haskell}}
\begin{lstlisting}
    (==) :: (Eq a) => a -> a -> Bool
\end{lstlisting}
Observe that the overloaded operation has a more general constrained type \lstinline{(Eq a) => ...}.

This generic operation is captured in C\# by the method:
\lstset{language={CSharpLatest}}
\begin{lstlisting}
static bool Equal<A,EqA>(A a, A b)   EqA: struct, Eq<A>
               =>  default(EqA).Equal(a, b);
\end{lstlisting}
This method has not one, but \emph{two}, type parameters. The first, \lstinline{A}, is just the type parameter from the declaration.
The second, \lstinline{EqA}, is a type parameter that is constrained to be a struct and is evidence for the constraint that \lstinline{A} supports interface \lstinline{Eq<A>}.

The use of the \lstinline{struct} constraint on \lstinline{EqA} is significant and subtle. Structs are stack-allocated so essentially free to create, especially when they contain no fields.
Moreover, every struct type, including a type parameter \lstinline{T} of kind struct, has a default (all-zero) value denoted by
 expression \lstinline{default(T)}.
Invoking a method on a default value of reference type would simply raise a null-reference exception because the receiver is \lstinline{null}.
However, methods on structs (including interface methods) can always be properly invoked
by calling the method on the struct's default value.

Thus an operation over some class can be represented as a static generic method,
parameterized by an additional dictionary type parameter (here \lstinline{EqA}).
Derived operations with type class constraints can be represented by generic methods with suitably constrained type parameters.
Finally, Haskell dictionary \emph{values} correspond to  C\# dictionary \emph{types}.

For F\#, we do not overload a top-level \lstinline{Equal} binding but, instead, allow qualifed access to trait members (e.g.\ \lstinline{Eq.equal}), as in:
\lstset{language={FSharp}}
\begin{lstlisting}
 let equal = Eq.equal  (* defines overloaded equal *)
\end{lstlisting}

%The dictionary type parameter is marked \lstinline{struct} (so stack allocated):
%we can access its operations through a default value (no need to pass dictionary values).

%\subsection{Haskell Instances}
{\bf Instances}
A Haskell instance declaration is represented by the declaration of an empty (field-less) .NET  struct that implements the associated type class (itself an interface).
This gives us a cheap representation of Haskell instances.
%A Haskell instance declaration can be represented by the declaration of a C\# struct type.
%Moreover, the dictionary parameter corresponding to a Haskell type constraint can just be represented by a C\# type parameter; in particular, by a type parameter that is both a struct and implements the corresponding C\# interface.

For example, the Haskell instance declaration:

\lstset{language={Haskell}}
{\small
\begin{lstlisting}
instance Eq Integer where
  x == y  =  x `integerEq` y
\end{lstlisting}
}
can be represented by the C\# structure:
\lstset{language={CSharpLatest}}
\begin{lstlisting}
struct EqInt : Eq<int>
{  public bool Equal(int a, int b)  => a == b;   }
\end{lstlisting}

\ifclassic
For F\#, we introduce the shorter \lstinline{instance} declaration:

\lstset{language={FSharp}}
\begin{lstlisting}
instance Eq int where
  Equal (a, b) = a = b
\end{lstlisting}

Note that the F\# syntax, like Haskell, elides the name of the instance in the more explicit C\# representation.
In Haskell, instances are anonymous.

\else
For F\#, we use a \lstinline{Witness}-attributed struct declaration:

\lstset{language={FSharp}}
\begin{lstlisting}
 [<Witness>]
 type EqInt = (* a struct *)
   interface Eq<int> with  member equal a b = a = b
\end{lstlisting}

Note that the F\# syntax, unlike Haskell, names the instance as in the  C\# representation.
In Haskell, instances are anonymous but names are useful for explicit disambiguation and interoperation with languages that cannot always rely on type argument inference (such as C\#).
\fi

%\subsection{Derived Instances}

{\bf Derived Instances}
This Haskell code defines a family of derived instances: given an equality  type \lstinline{a}, it defines equality over lists of \lstinline{a}.
\lstset{language={Haskell}}
{\small
\begin{lstlisting}
instance (Eq a) => Eq ([a]) where
    nil == nil   = true
   a:as == b:bs  = (a == b) && (as == bs)
      _ == _     = false
\end{lstlisting}
}

We can represent such a Haskell parameterized instance as a \emph{generic} struct:

%\lstset{language={CSharpLatest}}
%\begin{lstlisting}
%struct EqList<A, EqA> : Eq<List<A>>
%       where EqA : struct, Eq<A>  {
%  public bool Equal(List<A> a, List<A> b) {
%    if (a.IsNull != b.IsNull) return true;
%    else if (a.IsCons & b.IsCons)
%         return default(EqA).Equal(a.Head,b.Head)
%                && Equal(a.Tail,b.Tail);
%         else false;
%  }}
%\end{lstlisting}

\lstset{language={CSharpLatest}}
\begin{lstlisting}
struct EqList<A, EqA> : Eq<List<A>>
  where EqA : struct, Eq<A>  {
    public bool Equal(List<A> a, List<A> b)  =>
          (a.IsNull && b.IsNull)
      || (a.IsCons && b.IsCons
           && default(EqA).Equal(a.Head,b.Head)
           && Equal(a.Tail,b.Tail)); }
\end{lstlisting}

This struct implements the interface \lstinline{Eq<List<A>>}, but only when instantiated with a suitable type argument and evidence for constraint \lstinline{Eq<A>}.
Notice that \lstinline{EqList} has, once again, an additional evidence type parameter  \lstinline{EqA} for constraint \lstinline{Eq<A>}.
Instantiations of the generic struct \lstinline{EqList<->}, in turn, construct evidence for \lstinline{Eq<List<A>>}.

\ifclassic
For F\# we adopt the more concise, nameless declaration:

\lstset{language={FSharp}}
\begin{lstlisting}
instance Eq 'a => Eq (List 'a) where
  Equal(a,b) = match a,b with
    | (a::l),(b::m) -> Equal(a,b) && Equal(l,m)
    | [],[] -> true | _,_ -> false
\end{lstlisting}
\else
For F\# we use a parameterized \lstinline{Witness}-declaration:
\lstset{language={FSharp}}
\begin{lstlisting}
 [<Witness>]
 type EqList<'A,'EqA when 'EqA :> Eq<'A>> =  (* a struct *)
   interface Eq<'A list> with
     member equal a b =  match a,b with
       | a::l,b::m -> Eq.equal a b && Eq.equal l m
       | [],[] -> true | _,_ -> false
\end{lstlisting}

\fi
%\subsection{Other features}
{\bf Other features}
We do not have space to describe the representations of other features but suffice to say that we can encode \cite{natural}:
type class operations that themselves have constrained types in their signatures (using interface methods that are generic);
type class hierarchies  using interface inheritance; default operations using shared static methods; instances requiring
polymorphic recursion; instances as data (to constrained term constructors) and multi-parameter type classes. Moreover, choosing to provide named rather than anonymous instances would allow us to selectively support
explicit as well as implicit evidence when preferable.
We cannot support  higher-kinded type classes (like \lstinline{Monad}), because .NET lacks higher-kinded abstraction.
First-order associated types are in reach.
%Much of the concision of Haskell comes not only from the declaration of type class hierarchies but from the implicit solution of constraints during type inference.
For C\#, evidence inference is a mild generalization of type argument inference, with instantiations derived from the pervasive and locally assumed concept hierarchy.
For F\#, we have adapted Haskell's more elaborate techniques for propagating inferred type class constraints, by extension of F\#'s existing constraint system.

%\section{Implementation}
{\bf Implementations} We prioritized our efforts on designing and implementing type classes for C\# in a fork\cite{Roslynfork}  of  Microsoft's open source Roslyn compiler\cite{Roslyn}, adopting a dedicated syntax loosely inspired  by C++ concepts\cite{cppconcepts}.
%This is primarily because of interest from the C\# team, because C\# still has wider reach than F\# and because C\# is arguably in greater need of abstraction facilities.
The F\# design and implementation~\cite{fshack} was the result of a 3-day hackathon aiming for a minimal viable product (with suboptimal syntax).
Performance results are promising - we anticipated  .NET's code specialization to turn virtual calls to dictionary members into direct calls, but the JIT exceeded expectations and aggressively inlined those calls.
The JIT failed to eliminate  dictionary arguments that became dead after inlining; hoist dictionary allocations out of loops or do CSE on dictionary values. Fortunately, the latter two are suitable compiler optimizations.
\vspace{-1em}
\small
\bibliographystyle{abbrv}

\bibliography{sigproc}
\end{document}


text:
namespace oclgrind
{
  class Context;
  class Kernel;
  class Program;
};

class Simulation
{
  enum ArgDataType
  {
    TYPE_NONE,
    TYPE_CHAR,
    TYPE_UCHAR,
    TYPE_SHORT,
    TYPE_USHORT,
    TYPE_INT,
    TYPE_UINT,
    TYPE_LONG,
    TYPE_ULONG,
    TYPE_FLOAT,
    TYPE_DOUBLE,
  };

  public:
    Simulation();
    virtual ~Simulation();

    bool load(const char *filename);
    void run(bool dumpGlobalMemory=false);

  private:
    oclgrind::Context *m_context;
    oclgrind::Kernel *m_kernel;
    oclgrind::Program *m_program;

    oclgrind::Size3 m_ndrange;
    oclgrind::Size3 m_wgsize;

    std::ifstream m_simfile;
    std::string m_parsing;
    size_t m_lineNumber;
    std::istringstream m_lineBuffer;

    struct DumpArg
    {
      size_t address;
      size_t size;
      ArgDataType type;
      std::string name;
    };
    std::list<DumpArg> m_dumpArguments;

    template<typename T>
    void dumpArgument(DumpArg& arg);
    template<typename T>
    void get(T& result);
    void parseArgument(size_t index);
    template<typename T>
    void parseArgumentData(unsigned char *result, size_t size);
    template<typename T>
    void parseFill(unsigned char *result, size_t size,
                   std::istringstream& fill);
    template<typename T>
    void parseRange(unsigned char *result, size_t size,
                    std::istringstream& range);
};

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * This file is part of expectation package.
 *
 * (c) Noritaka Horio <holy.shared.design@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace expectation;

interface DSLInterface
{

    /**
     * @param string $actual
     * @return Evaluator
     */
    public function expect($actual);

}


text:
namespace chromeos {
namespace options {

namespace {

// List of settings that should be changeable by all users.
const char* kNonPrivilegedSettings[] = {
    kSystemTimezone
};

// Returns true if |pref| can be controlled (e.g. by policy or owner).
bool IsSettingPrivileged(const std::string& pref) {
  const char** end = kNonPrivilegedSettings + arraysize(kNonPrivilegedSettings);
  return std::find(kNonPrivilegedSettings, end, pref) == end;
}

// Creates a user info dictionary to be stored in the |ListValue| that is
// passed to Javascript for the |kAccountsPrefUsers| preference.
base::DictionaryValue* CreateUserInfo(const std::string& username,
                                      const std::string& display_email,
                                      const std::string& display_name) {
  base::DictionaryValue* user_dict = new base::DictionaryValue;
  user_dict->SetString("username", username);
  user_dict->SetString("name", display_email);
  user_dict->SetString("email", display_name);

  bool is_owner = UserManager::Get()->GetOwnerEmail() == username;
  user_dict->SetBoolean("owner", is_owner);
  return user_dict;
}

// This function decorates the bare list of emails with some more information
// needed by the UI to properly display the Accounts page.
base::Value* CreateUsersWhitelist(const base::Value *pref_value) {
  const base::ListValue* list_value =
      static_cast<const base::ListValue*>(pref_value);
  base::ListValue* user_list = new base::ListValue();
  UserManager* user_manager = UserManager::Get();

  for (base::ListValue::const_iterator i = list_value->begin();
       i != list_value->end(); ++i) {
    std::string email;
    if ((*i)->GetAsString(&email)) {
      // Translate email to the display email.
      std::string display_email = user_manager->GetUserDisplayEmail(email);
      // TODO(ivankr): fetch display name for existing users.
      user_list->Append(CreateUserInfo(email, display_email, std::string()));
    }
  }
  return user_list;
}

const char kSelectNetworkMessage[] = "selectNetwork";

}  // namespace

CoreChromeOSOptionsHandler::CoreChromeOSOptionsHandler() {
}

CoreChromeOSOptionsHandler::~CoreChromeOSOptionsHandler() {
}

void CoreChromeOSOptionsHandler::RegisterMessages() {
  CoreOptionsHandler::RegisterMessages();
  web_ui()->RegisterMessageCallback(
      kSelectNetworkMessage,
      base::Bind(&CoreChromeOSOptionsHandler::SelectNetworkCallback,
                 base::Unretained(this)));
}

void CoreChromeOSOptionsHandler::InitializeHandler() {
  // This function is both called on the initial page load and on each reload.
  // For the latter case, forget the last selected network.
  proxy_config_service_.SetCurrentNetwork(std::string());
  // And clear the cached configuration.
  proxy_config_service_.UpdateFromPrefs();

  CoreOptionsHandler::InitializeHandler();

  PrefService* profile_prefs = NULL;
  Profile* profile = Profile::FromWebUI(web_ui());
  if (!ProfileHelper::IsSigninProfile(profile)) {
    profile_prefs = profile->GetPrefs();
    ObservePref(prefs::kOpenNetworkConfiguration);
  }
  ObservePref(prefs::kProxy);
  ObservePref(prefs::kDeviceOpenNetworkConfiguration);
  proxy_config_service_.SetPrefs(profile_prefs,
                                 g_browser_process->local_state());
}

base::Value* CoreChromeOSOptionsHandler::FetchPref(
    const std::string& pref_name) {
  if (proxy_cros_settings_parser::IsProxyPref(pref_name)) {
    base::Value *value = NULL;
    proxy_cros_settings_parser::GetProxyPrefValue(
        proxy_config_service_, pref_name, &value);
    if (!value)
      return base::Value::CreateNullValue();

    return value;
  }

  if (!CrosSettings::IsCrosSettings(pref_name)) {
    std::string controlling_pref =
        pref_name == prefs::kUseSharedProxies ? prefs::kProxy : std::string();
    return CreateValueForPref(pref_name, controlling_pref);
  }

  const base::Value* pref_value = CrosSettings::Get()->GetPref(pref_name);
  if (!pref_value)
    return base::Value::CreateNullValue();

  // Decorate pref value as CoreOptionsHandler::CreateValueForPref() does.
  // TODO(estade): seems that this should replicate CreateValueForPref less.
  base::DictionaryValue* dict = new base::DictionaryValue;
  if (pref_name == kAccountsPrefUsers)
    dict->Set("value", CreateUsersWhitelist(pref_value));
  else
    dict->Set("value", pref_value->DeepCopy());

  std::string controlled_by;
  if (IsSettingPrivileged(pref_name)) {
    policy::BrowserPolicyConnectorChromeOS* connector =
        g_browser_process->platform_part()->browser_policy_connector_chromeos();
    if (connector->IsEnterpriseManaged())
      controlled_by = "policy";
    else if (!ProfileHelper::IsOwnerProfile(Profile::FromWebUI(web_ui())))
      controlled_by = "owner";
  }
  dict->SetBoolean("disabled", !controlled_by.empty());
  if (!controlled_by.empty())
    dict->SetString("controlledBy", controlled_by);
  return dict;
}

void CoreChromeOSOptionsHandler::ObservePref(const std::string& pref_name) {
  if (proxy_cros_settings_parser::IsProxyPref(pref_name)) {
    // We observe those all the time.
    return;
  }
  if (!CrosSettings::IsCrosSettings(pref_name))
    return ::options::CoreOptionsHandler::ObservePref(pref_name);

  linked_ptr<CrosSettings::ObserverSubscription> subscription(
      CrosSettings::Get()->AddSettingsObserver(
          pref_name.c_str(),
          base::Bind(&CoreChromeOSOptionsHandler::NotifySettingsChanged,
                     base::Unretained(this),
                     pref_name)).release());
  pref_subscription_map_.insert(make_pair(pref_name, subscription));
}

void CoreChromeOSOptionsHandler::SetPref(const std::string& pref_name,
                                         const base::Value* value,
                                         const std::string& metric) {
  if (proxy_cros_settings_parser::IsProxyPref(pref_name)) {
    proxy_cros_settings_parser::SetProxyPrefValue(
        pref_name, value, &proxy_config_service_);
    base::StringValue proxy_type(pref_name);
    web_ui()->CallJavascriptFunction(
        "options.internet.DetailsInternetPage.updateProxySettings",
        proxy_type);
    ProcessUserMetric(value, metric);
    return;
  }
  if (!CrosSettings::IsCrosSettings(pref_name))
    return ::options::CoreOptionsHandler::SetPref(pref_name, value, metric);
  CrosSettings::Get()->Set(pref_name, *value);

  ProcessUserMetric(value, metric);
}

void CoreChromeOSOptionsHandler::StopObservingPref(const std::string& path) {
  if (proxy_cros_settings_parser::IsProxyPref(path))
    return;  // We unregister those in the destructor.
  // Unregister this instance from observing prefs of chrome os settings.
  if (CrosSettings::IsCrosSettings(path))
    pref_subscription_map_.erase(path);
  else  // Call base class to handle regular preferences.
    ::options::CoreOptionsHandler::StopObservingPref(path);
}

base::Value* CoreChromeOSOptionsHandler::CreateValueForPref(
    const std::string& pref_name,
    const std::string& controlling_pref_name) {
  // The screen lock setting is shared if multiple users are logged in and at
  // least one has chosen to require passwords.
  if (pref_name == prefs::kEnableAutoScreenLock &&
      UserManager::Get()->GetLoggedInUsers().size() > 1 &&
      controlling_pref_name.empty()) {
    PrefService* user_prefs = Profile::FromWebUI(web_ui())->GetPrefs();
    const PrefService::Preference* pref =
        user_prefs->FindPreference(prefs::kEnableAutoScreenLock);

    ash::SessionStateDelegate* delegate =
        ash::Shell::GetInstance()->session_state_delegate();
    if (pref && pref->IsUserModifiable() &&
        delegate->ShouldLockScreenBeforeSuspending()) {
      bool screen_lock = false;
      bool success = pref->GetValue()->GetAsBoolean(&screen_lock);
      DCHECK(success);
      if (!screen_lock) {
        // Screen lock is enabled for the session, but not in the user's
        // preferences. Show the user's value in the checkbox, but indicate
        // that the password requirement is enabled by some other user.
        base::DictionaryValue* dict = new base::DictionaryValue;
        dict->Set("value", pref->GetValue()->DeepCopy());
        dict->SetString("controlledBy", "shared");
        return dict;
      }
    }
  }

  return CoreOptionsHandler::CreateValueForPref(pref_name,
                                                controlling_pref_name);
}

void CoreChromeOSOptionsHandler::GetLocalizedValues(
    base::DictionaryValue* localized_strings) {
  DCHECK(localized_strings);
  CoreOptionsHandler::GetLocalizedValues(localized_strings);

  Profile* profile = Profile::FromWebUI(web_ui());
  AddAccountUITweaksLocalizedValues(localized_strings, profile);

  UserManager* user_manager = UserManager::Get();

  // Check at load time whether this is a secondary user in a multi-profile
  // session.
  User* user = user_manager->GetUserByProfile(profile);
  if (user && user->email() != user_manager->GetPrimaryUser()->email()) {
    const std::string& primary_email = user_manager->GetPrimaryUser()->email();

    // Set secondaryUser to show the shared icon by the network section header.
    localized_strings->SetBoolean("secondaryUser", true);
    localized_strings->SetString("secondaryUserBannerText",
        l10n_util::GetStringFUTF16(
            IDS_OPTIONS_SETTINGS_SECONDARY_USER_BANNER,
            base::ASCIIToUTF16(primary_email)));
    localized_strings->SetString("controlledSettingShared",
        l10n_util::GetStringFUTF16(
            IDS_OPTIONS_CONTROLLED_SETTING_SHARED,
            base::ASCIIToUTF16(primary_email)));
    localized_strings->SetString("controlledSettingsShared",
        l10n_util::GetStringFUTF16(
            IDS_OPTIONS_CONTROLLED_SETTINGS_SHARED,
            base::ASCIIToUTF16(primary_email)));
  } else {
    localized_strings->SetBoolean("secondaryUser", false);
    localized_strings->SetString("secondaryUserBannerText", base::string16());
    localized_strings->SetString("controlledSettingShared", base::string16());
    localized_strings->SetString("controlledSettingsShared", base::string16());
  }

  // Screen lock icon can show up as primary or secondary user.
  localized_strings->SetString("screenLockShared",
      l10n_util::GetStringUTF16(
          IDS_OPTIONS_CONTROLLED_SETTING_SHARED_SCREEN_LOCK));

  policy::BrowserPolicyConnectorChromeOS* connector =
      g_browser_process->platform_part()->browser_policy_connector_chromeos();
  if (connector->IsEnterpriseManaged()) {
    // Managed machines have no "owner".
    localized_strings->SetString("controlledSettingOwner", base::string16());
  } else {
    localized_strings->SetString("controlledSettingOwner",
        l10n_util::GetStringFUTF16(
            IDS_OPTIONS_CONTROLLED_SETTING_OWNER,
            base::ASCIIToUTF16(user_manager->GetOwnerEmail())));
  }
}

void CoreChromeOSOptionsHandler::SelectNetworkCallback(
    const base::ListValue* args) {
  std::string service_path;
  if (args->GetSize() != 1 ||
      !args->GetString(0, &service_path)) {
    NOTREACHED();
    return;
  }
  proxy_config_service_.SetCurrentNetwork(service_path);
  NotifyProxyPrefsChanged();
}

void CoreChromeOSOptionsHandler::OnPreferenceChanged(
    PrefService* service,
    const std::string& pref_name) {
  // Redetermine the current proxy settings and notify the UI if any of these
  // preferences change.
  if (pref_name == prefs::kOpenNetworkConfiguration ||
      pref_name == prefs::kDeviceOpenNetworkConfiguration ||
      pref_name == prefs::kProxy) {
    NotifyProxyPrefsChanged();
    return;
  }
  if (pref_name == prefs::kUseSharedProxies) {
    // kProxy controls kUseSharedProxies and decides if it's managed by
    // policy/extension.
    NotifyPrefChanged(prefs::kUseSharedProxies, prefs::kProxy);
    return;
  }
  ::options::CoreOptionsHandler::OnPreferenceChanged(service, pref_name);
}

void CoreChromeOSOptionsHandler::NotifySettingsChanged(
    const std::string& setting_name) {
  DCHECK(CrosSettings::Get()->IsCrosSettings(setting_name));
  scoped_ptr<base::Value> value(FetchPref(setting_name));
  if (!value.get())
    NOTREACHED();
  DispatchPrefChangeNotification(setting_name, value.Pass());
}

void CoreChromeOSOptionsHandler::NotifyProxyPrefsChanged() {
  proxy_config_service_.UpdateFromPrefs();
  for (size_t i = 0; i < kProxySettingsCount; ++i) {
    base::Value* value = NULL;
    proxy_cros_settings_parser::GetProxyPrefValue(
        proxy_config_service_, kProxySettings[i], &value);
    DCHECK(value);
    scoped_ptr<base::Value> ptr(value);
    DispatchPrefChangeNotification(kProxySettings[i], ptr.Pass());
  }
}

}  // namespace options
}  // namespace chromeos


text:
<!doctype html>

  <title>Optimizely Sizely, Visualizely</title>
  <link rel="stylesheet" href="codemirror.css">
  <link rel="stylesheet" href="webtreemap.css">

    Order by<select id="sortby">
      <option value="size">Size</option>
      <option value="age">Age</option>
    </select>
    <button class="back-to-map">View as map</button>
    <button class="back-to-list">View as list</button>
    <button>Fork me on Github</button>
    <button>What is Optisizely?</button>

Optimizely Sizely, Visualizely

Did you know?

Optimizely bundles together all of your experiment and variation code into one big bundle, and loads it on every page on your site which uses Optimizely.

This is a cool visualization to show how much your Optimizely test adds to page load time.

Add your project id as a querystring, or check out these examples:

Optimizely's optisize

Citrix's optisize

eHow's optisize

Hotwire's optisize

NerdWallet's optisize

Spreadshirt's optisize

Treehouse's optisize

Trulia's optisize

Udemy's optisize

Optisizely is not affiliated with Optimizely.

      <textarea id="source" rows="30" cols="160"></textarea>


text:
function needUser(req, res, next) {
  if (req.session.user) {
    next();
    return;
  }
  //This is pseudocode, just to convey a basic idea...
  res.redirect("/sign-in?next=" + encodeURIComponent(req.path));
}

module.exports = needUser;


text:
title: Koding Subdomains and VHosts
author: Team Koding
categories: [koding features, koding, apache]
---

# Koding Subdomains and VHosts

In this guide we'll go over setting up a Koding subdomain to point to a
directory of your choice.

## Creating Subdomains

To create a subdomain, refer to the [Subdomain Section
here](/faq/vm-hostname/)

## Creating a Virtual Host

First, run the following command, where `mysubdomain` is the name of your subdomain.

```text
sudo touch /etc/apache2/sites-available/mysubdomain.conf
```

Next, open the above file with `nano`, `vim`, or whatever command line
editor you prefer. We're using a command line editor, because files
located in `/etc/apache2/sites-available` are owned by `root`, and
require sudo.

If you used nano, your command should look like this:

```text
sudo nano /etc/apache2/sites-available/mysubdomain.conf
```

Now that you have the file open with your preferred editor, paste in the
following code:

```xml
<Virtualhost *:80>
  ServerName mysubdomain.username.koding.io
  DocumentRoot /var/www/myDirectory
</Virtualhost>
```

There are a two things you're going to have to change here, so lets go over them.

- **ServerName**: The value of `ServerName` should be your full subdomain
  url, without the http.

- **DocumentRoot**: This is the folder location that you want the
  subdomain to direct to. Remember that `/var/www` equals `~/Web`, so in
the given example, `/var/www/myDirectory` equals `~/Web/myDirectory`.

```xml
<Virtualhost *:80>
  ServerName hello.joshmurray.koding.io
  DocumentRoot /var/www/helloworld
</Virtualhost>
```

> type:alert
> The DocumentRoot has to be an absolute path. Relative directories such as `/var/www/../foo` and `~/MyDirectory` will not work.  If you would like to supply an directory *outside* of `~/Web`, use your full home path, eg: `/home/joshmurray/myNotWebDirectory`

## Enable the Subdomain

Lastly, we need to add our "site" and reload apache. Run the following
two commands, replacing `mysubdomain` with the name of your subdomain.

```text
sudo a2ensite mysubdomain
sudo service apache2 reload
```

## Confirming

To confirm you did all the steps completely, connect to
`http://mysubdomain.username.koding.io` and you should see whatever you
have in your directory of choice.

## Troubleshooting

### Apache 404

If you see a plain white page saying **"Not Found"** with mentions of
Apache and Ubuntu, then Apache is correctly loading a directory, but the
directory is empty. Confirm that your `DocumentRoot` is a correct, and an
**absolute** directory.

### Forbidden

By default, Apache is configured to not allow access to directories
outside of `/var/www`. So, if you link to an absolute directory outside
of `/var/www`, such as `/home/joshmurray/hello`, you may see a message
similar to the following.

```
You do not have permission to access / on this server.
```

To resolve this, you can use the `<Directory>` directive inside of your
`VirtualHost` directive from above. Example:

```xml
<Virtualhost *:80>
  ServerName hello.joshmurray.koding.io
  DocumentRoot /home/joshmurray/hello
  <Directory /home/joshmurray/hello/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
  </Directory>
</Virtualhost>
```

Afterwards, don't forget to reload Apache, with the following command.

```text
sudo service apache2 reload
```

**Important**: It is recommended that you review the [Directory directive
documentation](http://httpd.apache.org/docs/current/mod/core.html#directory),
as there are security implications to allowing directory access, that you
should understand.

### I don't have a Subdomain

If you do not already have a Subdomain, you need to create one with the
same name that you used in your [Virtual Host
configuration](#creating-a-virtual-host).

To do this, from Koding navigate to your IDE window and go to your VM
Settings. This will appear as little circle next to your VM Name in the
left sidebar of Koding. From the settings menu, Click "More", and add any
subdomains that you need.

For a more indepth explanation of this process, refer to the [Subdomain
Section here](/faq/vm-hostname/).


text:
package org.jboss.pnc.datastore.repositories;

import org.jboss.pnc.datastore.repositories.internal.AbstractRepository;
import org.jboss.pnc.datastore.repositories.internal.ProductSpringRepository;
import org.jboss.pnc.model.Product;
import org.jboss.pnc.spi.datastore.repositories.ProductRepository;

import javax.ejb.Stateless;
import javax.inject.Inject;

@Stateless
public class ProductRepositoryImpl extends AbstractRepository<Product, Integer> implements ProductRepository {

    /**
     * @deprecated Created for CDI.
     */
    @Deprecated
    public ProductRepositoryImpl() {
        super(null, null);
    }

    @Inject
    public ProductRepositoryImpl(ProductSpringRepository productSpringRepository) {
        super(productSpringRepository, productSpringRepository);
    }
}


text:
package com.twitter.finagle.exp

import com.twitter.conversions.time._
import com.twitter.finagle.benchmark.StdBenchAnnotations
import com.twitter.finagle.util.WindowedAdder
import org.openjdk.jmh.annotations._
import org.openjdk.jmh.infra.Blackhole

@State(Scope.Benchmark)
@Threads(Threads.MAX)
class LatencyHistogramBench extends StdBenchAnnotations {

  @Param(Array("1000"))
  var maxDurationMs = 1000L

  @Param(Array("-1.0", "0.01", "0.05"))
  var error = 0.0

  var i = 0L

  var histo: LatencyHistogram = _

  @Setup
  def setup(): Unit = {
    val err = if (error <= 0.0) 0.0 else error

    histo = new LatencyHistogram(
      maxDurationMs,
      err,
      1.minute.inMillis,
      LatencyHistogram.DefaultSlices,
      WindowedAdder.systemMs)

    // give it some data to start with
    0L.until(maxDurationMs).foreach(histo.add)
  }

  @Benchmark
  def add(hole: Blackhole): Unit = {
    hole.consume(histo.add(i % maxDurationMs))
    i += 1
  }

  @Benchmark
  def quantile(): Long = {
    histo.quantile(95)
  }

}


text:
package ipvs

import (
	"fmt"
	"sync"
	"time"

	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/klog/v2"
	utilipvs "k8s.io/kubernetes/pkg/util/ipvs"
)

const (
	rsCheckDeleteInterval = 1 * time.Minute
)

// listItem stores real server information and the process time.
// If nothing special happened, real server will be delete after process time.
type listItem struct {
	VirtualServer *utilipvs.VirtualServer
	RealServer    *utilipvs.RealServer
}

// String return the unique real server name(with virtual server information)
func (g *listItem) String() string {
	return GetUniqueRSName(g.VirtualServer, g.RealServer)
}

// GetUniqueRSName return a string type unique rs name with vs information
func GetUniqueRSName(vs *utilipvs.VirtualServer, rs *utilipvs.RealServer) string {
	return vs.String() + "/" + rs.String()
}

type graceTerminateRSList struct {
	lock sync.Mutex
	list map[string]*listItem
}

// add push an new element to the rsList
func (q *graceTerminateRSList) add(rs *listItem) bool {
	q.lock.Lock()
	defer q.lock.Unlock()

	uniqueRS := rs.String()
	if _, ok := q.list[uniqueRS]; ok {
		return false
	}

	klog.V(5).InfoS("Adding real server to graceful delete real server list", "realServer", rs)
	q.list[uniqueRS] = rs
	return true
}

// remove remove an element from the rsList
func (q *graceTerminateRSList) remove(rs *listItem) bool {
	q.lock.Lock()
	defer q.lock.Unlock()

	uniqueRS := rs.String()
	if _, ok := q.list[uniqueRS]; ok {
		delete(q.list, uniqueRS)
		return true
	}
	return false
}

func (q *graceTerminateRSList) flushList(handler func(rsToDelete *listItem) (bool, error)) bool {
	success := true
	for name, rs := range q.list {
		deleted, err := handler(rs)
		if err != nil {
			klog.ErrorS(err, "Error in deleting real server", "realServer", name)
			success = false
		}
		if deleted {
			klog.InfoS("Removed real server from graceful delete real server list", "realServer", name)
			q.remove(rs)
		}
	}
	return success
}

// exist check whether the specified unique RS is in the rsList
func (q *graceTerminateRSList) exist(uniqueRS string) (*listItem, bool) {
	q.lock.Lock()
	defer q.lock.Unlock()

	if rs, ok := q.list[uniqueRS]; ok {
		return rs, true
	}
	return nil, false
}

// GracefulTerminationManager manage rs graceful termination information and do graceful termination work
// rsList is the rs list to graceful termination, ipvs is the ipvsinterface to do ipvs delete/update work
type GracefulTerminationManager struct {
	rsList graceTerminateRSList
	ipvs   utilipvs.Interface
}

// NewGracefulTerminationManager create a gracefulTerminationManager to manage ipvs rs graceful termination work
func NewGracefulTerminationManager(ipvs utilipvs.Interface) *GracefulTerminationManager {
	l := make(map[string]*listItem)
	return &GracefulTerminationManager{
		rsList: graceTerminateRSList{
			list: l,
		},
		ipvs: ipvs,
	}
}

// InTerminationList to check whether specified unique rs name is in graceful termination list
func (m *GracefulTerminationManager) InTerminationList(uniqueRS string) bool {
	_, exist := m.rsList.exist(uniqueRS)
	return exist
}

// GracefulDeleteRS to update rs weight to 0, and add rs to graceful terminate list
func (m *GracefulTerminationManager) GracefulDeleteRS(vs *utilipvs.VirtualServer, rs *utilipvs.RealServer) error {
	// Try to delete rs before add it to graceful delete list
	ele := &listItem{
		VirtualServer: vs,
		RealServer:    rs,
	}
	deleted, err := m.deleteRsFunc(ele)
	if err != nil {
		klog.ErrorS(err, "Error in deleting real server", "realServer", ele)
	}
	if deleted {
		return nil
	}
	rs.Weight = 0
	err = m.ipvs.UpdateRealServer(vs, rs)
	if err != nil {
		return err
	}
	klog.V(5).InfoS("Adding real server to graceful delete real server list", "realServer", ele)
	m.rsList.add(ele)
	return nil
}

func (m *GracefulTerminationManager) deleteRsFunc(rsToDelete *listItem) (bool, error) {
	klog.V(5).InfoS("Trying to delete real server", "realServer", rsToDelete)
	rss, err := m.ipvs.GetRealServers(rsToDelete.VirtualServer)
	if err != nil {
		return false, err
	}
	for _, rs := range rss {
		if rsToDelete.RealServer.Equal(rs) {
			// For UDP and SCTP traffic, no graceful termination, we immediately delete the RS
			//     (existing connections will be deleted on the next packet because sysctlExpireNoDestConn=1)
			// For other protocols, don't delete until all connections have expired)
			if utilipvs.IsRsGracefulTerminationNeeded(rsToDelete.VirtualServer.Protocol) && rs.ActiveConn+rs.InactiveConn != 0 {
				klog.V(5).InfoS("Skip deleting real server till all connection have expired", "realServer", rsToDelete, "activeConnection", rs.ActiveConn, "inactiveConnection", rs.InactiveConn)
				return false, nil
			}
			klog.V(5).InfoS("Deleting real server", "realServer", rsToDelete)
			err := m.ipvs.DeleteRealServer(rsToDelete.VirtualServer, rs)
			if err != nil {
				return false, fmt.Errorf("delete destination %q err: %w", rs.String(), err)
			}
			return true, nil
		}
	}
	return true, fmt.Errorf("failed to delete rs %q, can't find the real server", rsToDelete.String())
}

func (m *GracefulTerminationManager) tryDeleteRs() {
	if !m.rsList.flushList(m.deleteRsFunc) {
		klog.ErrorS(nil, "Try flush graceful termination list error")
	}
}

// MoveRSOutofGracefulDeleteList to delete an rs and remove it from the rsList immediately
func (m *GracefulTerminationManager) MoveRSOutofGracefulDeleteList(uniqueRS string) error {
	rsToDelete, find := m.rsList.exist(uniqueRS)
	if !find || rsToDelete == nil {
		return fmt.Errorf("failed to find rs: %q", uniqueRS)
	}
	err := m.ipvs.DeleteRealServer(rsToDelete.VirtualServer, rsToDelete.RealServer)
	if err != nil {
		return err
	}
	m.rsList.remove(rsToDelete)
	return nil
}

// Run start a goroutine to try to delete rs in the graceful delete rsList with an interval 1 minute
func (m *GracefulTerminationManager) Run() {
	go wait.Until(m.tryDeleteRs, rsCheckDeleteInterval, wait.NeverStop)
}


text:
// Author: jmaessen@google.com (Jan Maessen)

#include "net/instaweb/rewriter/public/javascript_code_block.h"

#include "net/instaweb/rewriter/public/javascript_library_identification.h"
#include "net/instaweb/util/public/google_message_handler.h"
#include "net/instaweb/util/public/gtest.h"
#include "net/instaweb/util/public/md5_hasher.h"
#include "net/instaweb/util/public/scoped_ptr.h"
#include "net/instaweb/util/public/simple_stats.h"
#include "net/instaweb/util/public/statistics.h"
#include "net/instaweb/util/public/string_util.h"
#include "pagespeed/kernel/base/thread_system.h"
#include "pagespeed/kernel/js/js_tokenizer.h"
#include "pagespeed/kernel/util/platform.h"

namespace net_instaweb {

namespace {

// This sample code comes from Douglas Crockford's jsmin example.
// The same code is used to test jsminify in pagespeed.
// We've added some leading and trailing whitespace here just to
// test our treatment of those cases (we used to erase this stuff
// even if the file wasn't minifiable).
const char kBeforeCompilation[] =
    "     \n"
    "// is.js\n"
    "\n"
    "// (c) 2001 Douglas Crockford\n"
    "// 2001 June 3\n"
    "\n"
    "\n"
    "// is\n"
    "\n"
    "// The -is- object is used to identify the browser.  "
    "Every browser edition\n"
    "// identifies itself, but there is no standard way of doing it, "
    "and some of\n"
    "// the identification is deceptive. This is because the authors of web\n"
    "// browsers are liars. For example, Microsoft's IE browsers claim to be\n"
    "// Mozilla 4. Netscape 6 claims to be version 5.\n"
    "\n"
    "var is = {\n"
    "    ie:      navigator.appName == 'Microsoft Internet Explorer',\n"
    "    java:    navigator.javaEnabled(),\n"
    "    ns:      navigator.appName == 'Netscape',\n"
    "    ua:      navigator.userAgent.toLowerCase(),\n"
    "    version: parseFloat(navigator.appVersion.substr(21)) ||\n"
    "             parseFloat(navigator.appVersion),\n"
    "    win:     navigator.platform == 'Win32'\n"
    "}\n"
    "is.mac = is.ua.indexOf('mac') >= 0;\n"
    "if (is.ua.indexOf('opera') >= 0) {\n"
    "    is.ie = is.ns = false;\n"
    "    is.opera = true;\n"
    "}\n"
    "if (is.ua.indexOf('gecko') >= 0) {\n"
    "    is.ie = is.ns = false;\n"
    "    is.gecko = true;\n"
    "}\n"
    "     \n";

const char kLibraryUrl[] = "//example.com/test_library.js";

const char kTruncatedComment[] =
    "// is.js\n"
    "\n"
    "// (c) 2001 Douglas Crockford\n"
    "// 2001 June 3\n"
    "\n"
    "\n"
    "// is\n"
    "\n"
    "/* The -is- object is used to identify the browser.  "
    "Every browser edition\n"
    "   identifies itself, but there is no standard way of doing it, "
    "and some of\n";

// Again we add some leading whitespace here to check for handling of this issue
// in otherwise non-minifiable code.  We've elected not to strip the whitespace.
const char kTruncatedString[] =
    "     \n"
    "var is = {\n"
    "    ie:      navigator.appName == 'Microsoft Internet Explo";

const char kAfterCompilationOld[] =
    "var is={ie:navigator.appName=='Microsoft Internet Explorer',"
    "java:navigator.javaEnabled(),ns:navigator.appName=='Netscape',"
    "ua:navigator.userAgent.toLowerCase(),version:parseFloat("
    "navigator.appVersion.substr(21))||parseFloat(navigator.appVersion)"
    ",win:navigator.platform=='Win32'}\n"
    "is.mac=is.ua.indexOf('mac')>=0;if(is.ua.indexOf('opera')>=0){"
    "is.ie=is.ns=false;is.opera=true;}\n"  // Note trailing \n
    "if(is.ua.indexOf('gecko')>=0){is.ie=is.ns=false;is.gecko=true;}";

const char kAfterCompilationNew[] =
    "var is={ie:navigator.appName=='Microsoft Internet Explorer',"
    "java:navigator.javaEnabled(),ns:navigator.appName=='Netscape',"
    "ua:navigator.userAgent.toLowerCase(),version:parseFloat("
    "navigator.appVersion.substr(21))||parseFloat(navigator.appVersion)"
    ",win:navigator.platform=='Win32'}\n"
    "is.mac=is.ua.indexOf('mac')>=0;if(is.ua.indexOf('opera')>=0){"
    "is.ie=is.ns=false;is.opera=true;}"  // Note lack of trailing \n
    "if(is.ua.indexOf('gecko')>=0){is.ie=is.ns=false;is.gecko=true;}";

const char kJsWithGetElementsByTagNameScript[] =
    "// this shouldn't be altered"
    "  var scripts = document.getElementsByTagName('script'),"
    "      script = scripts[scripts.length - 1];"
    "  var some_url = document.createElement(\"a\");";

const char kJsWithJQueryScriptElementSelection[] =
    "// this shouldn't be altered either"
    "  var scripts = $(\"script\"),"
    "      script = scripts[scripts.length - 1];"
    "  var some_url = document.createElement(\"a\");";

const char kBogusLibraryMD5[] = "ltVVzzYxo0";

const char kBogusLibraryUrl[] =
    "//www.example.com/js/bogus_library.js";

// Sample JSON code from http://json.org/example with tons of whitespace.
// Modified to include even more whitespace between special characters and
// in string values/keys.
const char kJsonBeforeCompilation[] =
    "\n\n{\n"
    "    \"glossary    \": {\n"
    "        \"title\": 'example glossary',\n"
    "\t\t \"GlossDiv\": {\n"
    "            \"title\": \"S\",\n"
    "\t\t\t\"GlossList\"  : {\n"
    "                \"GlossEntry\": {\n"
    "                    \"ID\": \"SGML\"   ,\t\n"
    "\t\t\t\t\t\t\"SortAs\": \"SGML\",\n"
    "\t\t\t\t\t\t\t\t\"GlossTerm\": \"Standard Generalized Markup Language\",\n"
    "\t\t\t\t\t\t\t\t\t\t\t     \t       \t\t   \t  \"Acronym\": \"SGML\",\n"
    "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  \t        \"Abbrev\": \"ISO 8879:1986\",\n"
    "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t         \"GlossDef\": {\n"
    "                        \"para\": \"A meta-markup language, used to create"
    " markup languages such as DocBook.\",\n"
    "\t\t\t\t   \t       \t\t      \"GlossSeeAlso\": [\"GML\", \"XML\"]\n"
    "                    },\n"
    "\t\t\t\t\t\t\"GlossSee\": \"markup\"\n"
    "                }\n"
    "            }\n"
    "        }\n"
    "    }\n"
    "}\n\n\n";

const char kJsonAfterCompilation[] =
    "{\"glossary    \":{\"title\":'example glossary',\"GlossDiv\":{\"title\":"
    "\"S\",\"GlossList\":{\"GlossEntry\":{\"ID\":\"SGML\",\"SortAs\":\"SGML\","
    "\"GlossTerm\":\"Standard Generalized Markup Language\",\"Acronym\":"
    "\"SGML\",\"Abbrev\":\"ISO 8879:1986\",\"GlossDef\":{\"para\":\"A "
    "meta-markup language, used to create markup languages such as DocBook.\","
    "\"GlossSeeAlso\":[\"GML\",\"XML\"]},\"GlossSee\":\"markup\"}}}}}";

class JsCodeBlockTest : public ::testing::Test,
                        public ::testing::WithParamInterface<bool> {
 protected:
  JsCodeBlockTest()
      : thread_system_(Platform::CreateThreadSystem()),
        stats_(thread_system_.get()),
        use_experimental_minifier_(GetParam()),
        after_compilation_(use_experimental_minifier_
                           ? kAfterCompilationNew
                           : kAfterCompilationOld) {
    JavascriptRewriteConfig::InitStats(&stats_);
    config_.reset(new JavascriptRewriteConfig(
        &stats_, true, use_experimental_minifier_, &libraries_,
        &js_tokenizer_patterns_));
    // Register a bogus library with a made-up md5 and plausible canonical url
    // that doesn't occur in our tests, but has the same size as our canonical
    // test case.
    EXPECT_TRUE(libraries_.RegisterLibrary(strlen(after_compilation_),
                                           kBogusLibraryMD5, kBogusLibraryUrl));
  }

  void ExpectStats(int blocks_minified, int minification_failures,
                   int total_bytes_saved, int total_original_bytes,
                   int num_reducing_uses) {
    EXPECT_EQ(blocks_minified, config_->blocks_minified()->Get());
    EXPECT_EQ(minification_failures, config_->minification_failures()->Get());
    EXPECT_EQ(total_bytes_saved, config_->total_bytes_saved()->Get());
    EXPECT_EQ(total_original_bytes, config_->total_original_bytes()->Get());
    EXPECT_EQ(num_reducing_uses, config_->num_reducing_uses()->Get());
    // Note: We cannot compare num_uses() because we only use it in
    // javascript_filter.cc, not javascript_code_block.cc.
  }

  void DisableMinification() {
    config_.reset(new JavascriptRewriteConfig(
        &stats_, false, use_experimental_minifier_, &libraries_,
        &js_tokenizer_patterns_));
  }

  // Must be called after DisableMinification if we call both.
  void DisableLibraryIdentification() {
    config_.reset(new JavascriptRewriteConfig(
        &stats_, config_->minify(), use_experimental_minifier_, NULL,
        &js_tokenizer_patterns_));
  }

  void RegisterLibrariesIn(JavascriptLibraryIdentification* libs) {
    MD5Hasher md5(JavascriptLibraryIdentification::kNumHashChars);
    GoogleString after_md5 = md5.Hash(after_compilation_);
    EXPECT_TRUE(libs->RegisterLibrary(strlen(after_compilation_),
                                      after_md5, kLibraryUrl));
    EXPECT_EQ(JavascriptLibraryIdentification::kNumHashChars,
              after_md5.size());
  }

  void RegisterLibraries() {
    RegisterLibrariesIn(&libraries_);
  }

  JavascriptCodeBlock* TestBlock(StringPiece code) {
    return new JavascriptCodeBlock(code, config_.get(), "Test", &handler_);
  }

  void SingleBlockRewriteTest(const char* before_compilation,
                              const char* after_compilation) {
    scoped_ptr<JavascriptCodeBlock> block(TestBlock(before_compilation));
    EXPECT_TRUE(block->Rewrite());
    EXPECT_TRUE(block->successfully_rewritten());
    EXPECT_EQ(after_compilation, block->rewritten_code());
    ExpectStats(1, 0,
                strlen(before_compilation) - strlen(after_compilation),
                strlen(before_compilation), 1);
  }

  GoogleMessageHandler handler_;
  scoped_ptr<ThreadSystem> thread_system_;
  SimpleStats stats_;
  JavascriptLibraryIdentification libraries_;
  const pagespeed::js::JsTokenizerPatterns js_tokenizer_patterns_;
  scoped_ptr<JavascriptRewriteConfig> config_;

  const bool use_experimental_minifier_;
  const char* after_compilation_;

 private:
  DISALLOW_COPY_AND_ASSIGN(JsCodeBlockTest);
};

TEST_P(JsCodeBlockTest, Config) {
  EXPECT_TRUE(config_->minify());
  ExpectStats(0, 0, 0, 0, 0);
}

TEST_P(JsCodeBlockTest, Rewrite) {
  SingleBlockRewriteTest(kBeforeCompilation, after_compilation_);
}

TEST_P(JsCodeBlockTest, RewriteNoIdentification) {
  // Make sure library identification setting doesn't change minification.
  DisableLibraryIdentification();
  SingleBlockRewriteTest(kBeforeCompilation, after_compilation_);
}

TEST_P(JsCodeBlockTest, UnsafeToRename) {
  EXPECT_TRUE(JavascriptCodeBlock::UnsafeToRename(
      kJsWithGetElementsByTagNameScript));
  EXPECT_TRUE(JavascriptCodeBlock::UnsafeToRename(
      kJsWithJQueryScriptElementSelection));
  EXPECT_FALSE(JavascriptCodeBlock::UnsafeToRename(
      kBeforeCompilation));
}

TEST_P(JsCodeBlockTest, NoRewrite) {
  scoped_ptr<JavascriptCodeBlock> block(TestBlock(after_compilation_));
  EXPECT_FALSE(block->Rewrite());
  // Note: Minifier succeeded, but no minification was applied and thus
  // no bytes saved (nor original bytes marked).
  ExpectStats(1, 0, 0, 0, 0);
}

TEST_P(JsCodeBlockTest, TruncatedComment) {
  scoped_ptr<JavascriptCodeBlock> block(TestBlock(kTruncatedComment));
  EXPECT_FALSE(block->Rewrite());
  ExpectStats(0, 1, 0, 0, 0);
}

TEST_P(JsCodeBlockTest, TruncatedString) {
  scoped_ptr<JavascriptCodeBlock> block(TestBlock(kTruncatedString));
  EXPECT_FALSE(block->Rewrite());
  ExpectStats(0, 1, 0, 0, 0);
}

TEST_P(JsCodeBlockTest, NoMinification) {
  DisableMinification();
  DisableLibraryIdentification();
  EXPECT_FALSE(config_->minify());
  scoped_ptr<JavascriptCodeBlock> block(TestBlock(kBeforeCompilation));
  EXPECT_FALSE(block->Rewrite());
  ExpectStats(0, 0, 0, 0, 0);
}

TEST_P(JsCodeBlockTest, DealWithSgmlComment) {
  // Based on actual code seen in the wild; the surprising part is this works at
  // all (due to xhtml in the source document)!
  static const char kOriginal[] = "  <!--  \nvar x = 1;\n  //-->  ";
  static const char kExpected[] = "var x=1;";
  scoped_ptr<JavascriptCodeBlock> block(TestBlock(kOriginal));
  EXPECT_TRUE(block->Rewrite());
  EXPECT_EQ(kExpected, block->rewritten_code());
  ExpectStats(1, 0,
              STATIC_STRLEN(kOriginal) - STATIC_STRLEN(kExpected),
              STATIC_STRLEN(kOriginal), 1);
}

TEST_P(JsCodeBlockTest, IdentifyUnminified) {
  RegisterLibraries();
  scoped_ptr<JavascriptCodeBlock> block(TestBlock(kBeforeCompilation));
  block->Rewrite();
  EXPECT_EQ(kLibraryUrl, block->ComputeJavascriptLibrary());
}

TEST_P(JsCodeBlockTest, IdentifyMerged) {
  JavascriptLibraryIdentification other_libraries;
  RegisterLibrariesIn(&other_libraries);
  libraries_.Merge(other_libraries);
  scoped_ptr<JavascriptCodeBlock> block(TestBlock(kBeforeCompilation));
  block->Rewrite();
  EXPECT_EQ(kLibraryUrl, block->ComputeJavascriptLibrary());
}

TEST_P(JsCodeBlockTest, IdentifyMergedDuplicate) {
  RegisterLibraries();
  JavascriptLibraryIdentification other_libraries;
  RegisterLibrariesIn(&other_libraries);
  libraries_.Merge(other_libraries);
  scoped_ptr<JavascriptCodeBlock> block(TestBlock(kBeforeCompilation));
  block->Rewrite();
  EXPECT_EQ(kLibraryUrl, block->ComputeJavascriptLibrary());
}

TEST_P(JsCodeBlockTest, IdentifyMinified) {
  RegisterLibraries();
  scoped_ptr<JavascriptCodeBlock> block(TestBlock(after_compilation_));
  block->Rewrite();
  EXPECT_EQ(kLibraryUrl, block->ComputeJavascriptLibrary());
}

TEST_P(JsCodeBlockTest, IdentifyNoMinification) {
  DisableMinification();
  RegisterLibraries();
  scoped_ptr<JavascriptCodeBlock> block(TestBlock(kBeforeCompilation));
  block->Rewrite();
  EXPECT_EQ(kLibraryUrl, block->ComputeJavascriptLibrary());
  EXPECT_FALSE(block->successfully_rewritten());
  ExpectStats(1, 0, 0, 0, 0);
}

TEST_P(JsCodeBlockTest, IdentifyNoMatch) {
  RegisterLibraries();
  scoped_ptr<JavascriptCodeBlock> block(
      TestBlock(kJsWithGetElementsByTagNameScript));
  block->Rewrite();
  EXPECT_EQ("", block->ComputeJavascriptLibrary());
}

TEST_P(JsCodeBlockTest, LibrarySignature) {
  RegisterLibraries();
  GoogleString signature;
  libraries_.AppendSignature(&signature);
  MD5Hasher md5(JavascriptLibraryIdentification::kNumHashChars);
  GoogleString after_md5 = md5.Hash(after_compilation_);
  GoogleString expected_signature =
      StrCat("S:", Integer64ToString(strlen(after_compilation_)),
             "_H:", after_md5, "_J:", kLibraryUrl,
             StrCat("_H:", kBogusLibraryMD5, "_J:", kBogusLibraryUrl));
  EXPECT_EQ(expected_signature, signature);
}

TEST_P(JsCodeBlockTest, RewriteJson) {
  SingleBlockRewriteTest(kJsonBeforeCompilation, kJsonAfterCompilation);
}

TEST_P(JsCodeBlockTest, InvalidJsonValidJs) {
  // The JS minifier cannot detect invalid JSON which is also valid JS, so we
  // expect this to work.
  SingleBlockRewriteTest(
      "{'foo': bar, baz :}",
      "{'foo':bar,baz:}");
}

TEST_P(JsCodeBlockTest, BogusLibraryRegistration) {
  RegisterLibraries();
  // Try to register a library with a bad md5 string.
  EXPECT_FALSE(libraries_.RegisterLibrary(73, "@$%@^#&#$^!%@#$",
                                          "//www.example.com/test.js"));
  // Try to register a library with a bad url.
  EXPECT_FALSE(libraries_.RegisterLibrary(47, kBogusLibraryMD5,
                                          "totally://bogus.protocol/"));
  EXPECT_FALSE(libraries_.RegisterLibrary(74, kBogusLibraryMD5,
                                          "totally:bogus.protocol"));

  // Don't allow non-standard protocols either.
  EXPECT_FALSE(libraries_.RegisterLibrary(138, kBogusLibraryMD5,
                                          "mailto:johndoe@example.com"));
  EXPECT_FALSE(libraries_.RegisterLibrary(150, kBogusLibraryMD5,
                                          "ftp://www.example.com/test.js"));
  EXPECT_FALSE(libraries_.RegisterLibrary(222, kBogusLibraryMD5,
                                          "file:///etc/passwd"));
  EXPECT_FALSE(libraries_.RegisterLibrary(234, kBogusLibraryMD5,
                                          "data:text/plain,Hello-world"));
}

// We test with use_experimental_minifier == GetParam() as both true and false.
INSTANTIATE_TEST_CASE_P(JsCodeBlockTestInstance, JsCodeBlockTest,
                        ::testing::Bool());

}  // namespace

}  // namespace net_instaweb


text:
package ts.eclipse.ide.internal.ui.preferences;

import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;

import ts.eclipse.ide.core.utils.PreferencesHelper;
import ts.eclipse.ide.ui.TypeScriptUIPlugin;
import ts.eclipse.ide.ui.preferences.TypeScriptUIPreferenceConstants;

/**
 * Eclipse preference initializer for TypeScript UI.
 *
 */
public class TypeScriptUIPreferenceInitializer extends AbstractPreferenceInitializer {

	@Override
	public void initializeDefaultPreferences() {
		IEclipsePreferences node = PreferencesHelper
				.getWorkspaceDefaultPreferences(TypeScriptUIPlugin.PLUGIN_ID);

		// initialize properties for TextMate using
		initializeTextMatePreferences(node);

		// initialize properties for editor save actions
		initializeEditorSaveActionsPreferences(node);

		// initialize properties for editor codelens
		initializeEditorCodeLensPreferences(node);
	}

	/**
	 * initialize properties for TextMate using
	 *
	 * @param node
	 */
	private void initializeTextMatePreferences(IEclipsePreferences node) {
		node.putBoolean(TypeScriptUIPreferenceConstants.USE_TEXMATE_FOR_SYNTAX_COLORING, false);
	}

	/**
	 * initialize properties for editor save actions
	 *
	 * @param node
	 */
	private void initializeEditorSaveActionsPreferences(IEclipsePreferences node) {
		node.putBoolean(TypeScriptUIPreferenceConstants.EDITOR_SAVE_ACTIONS, false);
		node.putBoolean(TypeScriptUIPreferenceConstants.EDITOR_SAVE_ACTIONS_FORMAT, true);
	}

	private void initializeEditorCodeLensPreferences(IEclipsePreferences node) {
		node.putBoolean(TypeScriptUIPreferenceConstants.EDITOR_ACTIVATE_CODELENS, false);
	}

}


text:
The median of M numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average number of the middle 2 numbers (again after sorting) if M is even. You have an empty number list at first. Then you can add or remove some number from the list. For each add or remove operation, output the median of numbers in the list.

**Example :**

For a set of M = 5 numbers {9, 2, 8, 4, 1} the median is the third number in sorted set {1, 2, 4, 8, 9} which is 4. Similarly for set of M = 4, {5, 2, 10, 4}, the median is the average of second and the third element in the sorted set {2, 4, 5, 10} which is (4+5)/2 = 4.5.

**Input:**

The first line is an integer N indicates the number of operations. Each of the next N lines is either a x or r x which indicates the operation is add or remove.

**Output:**

For each operation: If the operation is add output the median after adding x in a single line. If the operation is remove and the number x is not in the list, output Wrong! in a single line. If the operation is remove and the number x is in the list, output the median after deleting x in a single line. (if the result is an integer DO NOT output decimal point. And if the result is a real number , DO NOT output trailing 0s.)

**Note**

When calculating median in even case if your output is 3.0 print only 3 and if it is 3.50 print only 3.5. Whenever you need to print the median and the list is empty, print Wrong!

**Constraints:**

0 < N <= 100,000

For each a x or r x, x will always be an integer which will fit in 32 bit signed integer.

**Sample Input:**

		7
		r 1
		a 1
		a 2
		a 1
		r 1
		r 2
		r 1

**Sample Output:**

		Wrong!
		1
		1.5
		1
		1.5
		1
		Wrong!

**Note:** As evident from the last line of the input, if after remove operation the list becomes empty you have to print Wrong!.


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInitc00307ad914001c472d9d48a76007f88::getLoader();


text:
"""Benchmark the interpolation Situation Assessment algorithm

Produce Observation, Interpolation and Prediction figures
 """

#  Copyright (c) 2020, CNRS-LAAS
#  All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#
#  * Redistributions of source code must retain the above copyright notice, this
#  list of conditions and the following disclaimer.
#
#  * Redistributions in binary form must reproduce the above copyright notice,
#  this list of conditions and the following disclaimer in the documentation
#  and/or other materials provided with the distribution.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
#  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#
#
#
import datetime
import logging
import os
import sys
import typing as ty

import pytz
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm
import matplotlib.patches
import skimage.io
import skimage.draw
import skimage.measure
import scipy.interpolate

from fire_rs.geodata.geo_data import GeoData
import fire_rs.geodata.environment as g_environment
import fire_rs.geodata.display as display
import fire_rs.rbf
import fire_rs.geodata.wildfire

import fire_rs.monitoring.supersaop
from fire_rs.monitoring.supersaop import SituationAssessment

from fire_rs.geodata.geo_data import GeoData
from fire_rs.firemodel.propagation import Environment, FirePropagation, TimedPoint

from itertools import tee, islice, chain
from functools import reduce

from skimage.segmentation import flood_fill, flood

def previous_and_next(some_iterable):
    prevs, items, nexts = tee(some_iterable, 3)
    prevs = chain([None], prevs)
    nexts = chain(islice(nexts, 1, None), [None])
    return zip(prevs, items, nexts)

################################################################################
# World initialization

FIRERS_DATA_FOLDER = os.environ["FIRERS_DATA"]
FIRERS_DEM_DATA = os.path.join(FIRERS_DATA_FOLDER, 'dem')
FIRERS_WIND_DATA = os.path.join(FIRERS_DATA_FOLDER, 'wind')
FIRERS_LANDCOVER_DATA = os.path.join(FIRERS_DATA_FOLDER, 'landcover')

THE_WORLD = g_environment.World(elevation_path=FIRERS_DEM_DATA,
                                wind_path=FIRERS_WIND_DATA,
                                landcover_path=FIRERS_LANDCOVER_DATA, wind_mesh_resolution='fine',
                                landcover_to_fuel_remap=g_environment.EVERYTHING_FUELMODEL_REMAP)
THE_WORLD.dem_wind_tile_split = 1
time_start = datetime.datetime(2020, 1, 1, 0, 0, 0, 0)
ignition_center = TimedPoint(2776825.0, 2212175.0, time_start.timestamp())
area_default = ((ignition_center[0] - 2500, ignition_center[0] + 1500),
                (ignition_center[1] - 1500, ignition_center[1] + 2500))

def create_wildfire_propagation(area, ignition: ty.Sequence[TimedPoint], wind_speed=1.,
                                wind_direction=3 * np.pi / 4, world=THE_WORLD) -> FirePropagation:
    """Reference wildfire propagation"""
    fire_env = Environment(area, wind_speed, wind_direction, world)

    fire_prop = FirePropagation(fire_env)
    for ig in ignition:
        fire_prop.set_ignition_point(ig)

    propagation_end_time = np.inf
    fire_prop.propagate(propagation_end_time)

    return fire_prop

def fig_fire_propagation(fire_prop: FirePropagation,
                         original_ignition: ty.Sequence[TimedPoint],
                         max_time: float = np.inf) -> display.GeoDataDisplay:
    """Reference fire display
    Figure terrain + ignition contour + ignition point"""
    gdd = display.GeoDataDisplay.pyplot_figure(
        fire_prop.environment.raster.combine(fire_prop.ignitions().slice(["ignition"])),
        frame=(0., 0.))
    # gdd.draw_elevation_shade(with_colorbar=False, cmap=matplotlib.cm.terrain)
    # gdd.draw_wind_quiver()
    gdd.draw_ignition_shade(time_range=(0, max_time))
    gdd.draw_ignition_contour(with_labels=True, cmap=matplotlib.cm.plasma, time_range=(0, max_time))
    for o in original_ignition:
        gdd.draw_ignition_points(o)
    return gdd

def observe_contour(firemap: GeoData, contour: float, n_uavs, uav_speed, duty_cycle=0.25):
    """Extract a contour and then simulate it is observed by N UAVs.
    Each UAV gets an equal size chunk and observed a contigous portion of it (duty_cycle)
    The observation time is estimated from the speed
    speed is in m/s"""

    def perimeter_length_cumulated(observed_cells):
        perimeter_l = 0.
        first_c = next(observed_cells.keys().__iter__())
        for prev_c, c, next_c in previous_and_next(observed_cells.keys()):
            if next_c is not None:
                perimeter_l += np.sqrt((next_c[0] - c[0]) ** 2 + (next_c[1] - c[1]) ** 2)
            else:
                perimeter_l += np.sqrt((first_c[0] - c[0]) ** 2 + (first_c[1] - c[1]) ** 2)
        perimeter_l *= firemap.cell_width
        return perimeter_l

    def chunks(lst, n):
        """Yield successive n-sized chunks from lst."""
        for i in range(0, len(lst), n):
            yield lst[i:i + n]

    # Create contour with scikit-image
    wf_perimeter = fire_rs.geodata.wildfire.Perimeter(firemap, contour)
    observed_cells = wf_perimeter.cells.copy()
    perimeter_length = perimeter_length_cumulated(observed_cells)
    # TODO: Actually changed the observed time according to the UAV speed and stuff
    # Until then, keep the real ignition time
    per_uav_lenght = perimeter_length / n_uavs
    per_uav_observed_lenght = per_uav_lenght * duty_cycle

    chs = list(chunks(list(observed_cells.items()), int(len(observed_cells) / n_uavs)))
    effective_chunks = []
    for n_uav, chunk in zip(range(n_uavs), chs):
        effective_chunks.append(list(chunks(chunk, int(len(chunk) * duty_cycle)))[0])

    effective_chunks_dict = list(map(lambda x: dict(x), effective_chunks))
    return observed_cells, effective_chunks_dict

def fig_observation_contour(base_propagation: FirePropagation,
                            cells: ty.Mapping[ty.Tuple[int, int], float],
                            cmap="Greens_r", binary=True, gdd=None) -> display.GeoDataDisplay:
    gd = GeoData.full_like(base_propagation.prop_data, np.inf)
    for cell, time in cells.items():
        gd.data["ignition"][cell] = time if not binary else 1.0
    if not gdd:
        gdd = display.GeoDataDisplay.pyplot_figure(gd, frame=(0., 0.))
    gdd.draw_ignition_shade(cmap=cmap, geodata=gd)
    return gdd

def add_custom_legend(gdd: display.GeoDataDisplay, colors, labels):
    colors = colors
    # create a patch (proxy artist) for every color
    patches = [matplotlib.patches.Patch(color=colors[i], label=labels[i]) for i in
               range(len(colors))]
    # put those patched as legend-handles into the legend
    gdd.figure.legend(handles=patches)

def perform_situation_assessment(fire_prop_env: Environment,
                                 observations_dict: ty.Mapping[ty.Tuple[int, int], float],
                                 desired_perimeter: float):
    """Find an interpolation function that reconstructs the evolution of the fire
    given current and histroic partial information."""
    c_ass_wf = SituationAssessment.WildfireCurrentAssessment(
        fire_prop_env, observations_dict,
        perimeter_time=datetime.datetime.fromtimestamp(desired_perimeter))
    return c_ass_wf

def perform_future_situation_assessment(fire_prop_env: Environment,
                                        current_assessment: SituationAssessment.WildfireCurrentAssessment,
                                        last_future: float):
    f_ass_wf = fire_rs.monitoring.supersaop.SituationAssessment.WildfireFuturePropagation(
        fire_prop_env, current_assessment.perimeter, {},
        current_assessment.geodata, datetime.datetime.fromtimestamp(last_future))
    return f_ass_wf

def fig_fire_assessment(assessment: SituationAssessment.WildfireCurrentAssessment,
                        original_ignition: ty.Sequence[TimedPoint],
                        max_time: float = np.inf) -> display.GeoDataDisplay:
    """Assessed wildfire map"""
    gdd = display.GeoDataDisplay.pyplot_figure(assessment.geodata, frame=(0., 0.))
    # gdd.draw_elevation_shade(with_colorbar=False, cmap=matplotlib.cm.terrain)
    # gdd.draw_wind_quiver()
    gdd.draw_ignition_shade(time_range=(0, max_time))
    gdd.draw_ignition_contour(with_labels=True, cmap=matplotlib.cm.plasma, time_range=(0, max_time))
    for o in original_ignition:
        gdd.draw_ignition_points(o)
    return gdd

def difference_area_perimeters(base_propagation, perimeter1_cells, perimeter2_cells,
                               flood_initial_cell):
    gd1 = np.ones(base_propagation.prop_data.data.shape) * 0
    gd2 = np.ones(base_propagation.prop_data.data.shape) * 0
    for cell, time in perimeter1_cells.items():
        gd1.data[cell] = 1
    for cell, time in perimeter2_cells.items():
        gd2.data[cell] = 1

    surface1 = flood(gd1, flood_initial_cell, connectivity=1)
    surface2 = flood(gd2, flood_initial_cell, connectivity=1)
    area1 = np.count_nonzero(
        surface1) * propagation_env.prop_data.cell_width * propagation_env.prop_data.cell_height
    area2 = np.count_nonzero(
        surface2) * propagation_env.prop_data.cell_width * propagation_env.prop_data.cell_height
    difference_surface = flood(gd1, flood_initial_cell, connectivity=1) ^ flood(gd2,
                                                                                flood_initial_cell,
                                                                                connectivity=1)
    difference_area = np.count_nonzero(
        difference_surface) * propagation_env.prop_data.cell_width * propagation_env.prop_data.cell_height
    return difference_surface, difference_area, area1, area2

def create_logger(file_path: ty.Optional[str]):
    _logger = logging.getLogger(__name__)
    _logger.setLevel(logging.DEBUG)

    # Setup logging for this benchmark run
    log_formatter = logging.Formatter(
        '%(asctime)-23s %(levelname)s: %(message)s')

    # Set configuration for the default logger (inherited by others)
    root_logger = logging.getLogger()
    # Print INFO level messages
    log_stdout_hldr = logging.StreamHandler(sys.stdout)
    log_stdout_hldr.setLevel(logging.INFO)
    log_stdout_hldr.setFormatter(log_formatter)
    root_logger.addHandler(log_stdout_hldr)
    # Log everithing to file
    if file_path:
        log_file_hldr = logging.FileHandler(file_path)
        log_file_hldr.setFormatter(log_formatter)
        log_file_hldr.setLevel(logging.INFO)
        root_logger.addHandler(log_file_hldr)

    return _logger

if __name__ == "__main__":
    benchmark_id = run_id = datetime.datetime.now(pytz.timezone('UTC')).isoformat()

    output_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output", benchmark_id)

    if not os.path.exists(output_path):
        # logger.info("Output path did not exist previoulsy. Making it...")
        os.makedirs(output_path)
    logger = create_logger(os.path.join(output_path, "output.log"))
    logger.info("Output path: {}".format(output_path))

    image_format = "pdf"
    if image_format == 'eps' or image_format == 'pdf':
        matplotlib.rcParams['font.family'] = 'sans-serif'
        matplotlib.rcParams['text.usetex'] = True
    save_fig_options = {'dpi': 200, 'bbox_inches': 'tight'}
    propagation_plot_name = ".".join(("real_fire", image_format))
    assessment_plot_name = ".".join(("assessment_current", image_format))
    observed_plot_name = ".".join(("observed", image_format))
    contours_real_and_assessment = ".".join(("assessment_contour_comparison", image_format))

    CURRENT_TIME = time_start.timestamp() + 15 * 60 * 60

    include_start_point_in_assessment = True

    ignition_list = [
        TimedPoint(ignition_center[0], ignition_center[1], time_start.timestamp()),
        # TimedPoint(ignition_center[0] - 1000, ignition_center[1] + 1000, time_start.timestamp()),
    ]

    propagation_env = create_wildfire_propagation(
        area_default, ignition_list, wind_speed=1., wind_direction=0.65 * np.pi, world=THE_WORLD)
    propagation_plot = fig_fire_propagation(propagation_env, ignition_list,
                                            max_time=CURRENT_TIME)
    propagation_plot.figure.savefig(os.path.join(output_path, propagation_plot_name),
                                    **save_fig_options)

    # Time, n_uavs, coverage
    observation_passes = [
        # {"time": time_start.timestamp() + 3 * 60 * 60, "number_uavs": 3, "coverage": 0.5},
        # {"time": time_start.timestamp() + 5 * 60 * 60, "number_uavs": 3, "coverage": 0.75},
        {"time": time_start.timestamp() + 15 * 60 * 60, "number_uavs": 3, "coverage": 0.5}
    ]
    all_perimeter_cells = {}
    all_obs_flattened = {propagation_env.prop_data.array_index(ignition[0:2]): ignition[2] for
                         ignition in ignition_list} if include_start_point_in_assessment else {}
    obs_flattened_per_observation_pass = []
    outermost_perimeter_cells = {}
    for i, curr_obs_pass in enumerate(observation_passes):
        curr_perimeter_cells, obs_chuncks = observe_contour(
            propagation_env.ignitions(), curr_obs_pass["time"], curr_obs_pass["number_uavs"], 20.0,
            curr_obs_pass["coverage"])
        obs_flattened_per_observation_pass.append(reduce(lambda x, y: {**x, **y}, obs_chuncks))
        all_obs_flattened = {**all_obs_flattened, **obs_flattened_per_observation_pass[-1]}
        outermost_perimeter_cells = curr_perimeter_cells
        all_perimeter_cells = {**all_perimeter_cells, **outermost_perimeter_cells}

    logger.info("FIRE ID: {}".format(benchmark_id))
    logger.info("Size: ({:d},{:d})".format(propagation_env.prop_data.data.shape[0],
                                           propagation_env.prop_data.data.shape[1]))
    for ignition in ignition_list:
        logger.info("Ignition: ({}, {}) {:%Y-%m-%d %H:%M}".format(
            *propagation_env.prop_data.array_index(ignition[0:2]),
            datetime.datetime.fromtimestamp(ignition[2])))
    for curr_obs_pass in observation_passes:
        logger.info("Observe contour {:%Y-%m-%d %H:%M}: {:d} UAV, {:.2f}% Coverage".format(
            datetime.datetime.fromtimestamp(curr_obs_pass["time"]),
            curr_obs_pass["number_uavs"], curr_obs_pass["coverage"] * 100))
    try:
        assessment = perform_situation_assessment(propagation_env.environment, all_obs_flattened,
                                                  CURRENT_TIME)
        assessment_gdd = fig_fire_assessment(assessment, ignition_list, max_time=CURRENT_TIME)
        assessment_gdd.figure.savefig(os.path.join(output_path, assessment_plot_name),
                                      **save_fig_options)

        obs_uav_cells_fig = fig_observation_contour(propagation_env, all_obs_flattened)
        obs_uav_cells_fig.figure.savefig(os.path.join(output_path, observed_plot_name),
                                         **save_fig_options)
        obs_uav_cells_fig2 = fig_observation_contour(propagation_env, outermost_perimeter_cells)
        obs_uav_cells_fig2 = fig_observation_contour(propagation_env, assessment.perimeter.cells,
                                                     cmap="Oranges_r", binary=True,
                                                     gdd=obs_uav_cells_fig2)
        add_custom_legend(obs_uav_cells_fig2, ["g", "orange"], ["test1", "test2"])
        obs_uav_cells_fig2.figure.savefig(
            os.path.join(output_path, contours_real_and_assessment), **save_fig_options)
        matrix, surface_diff, surface1, surface2 = difference_area_perimeters(
            propagation_env, assessment.perimeter.cells, outermost_perimeter_cells,
            propagation_env.prop_data.array_index(ignition_center[0:2]))

        logger.info("SITUATION ASSESSMENT (CURRENT):")
        logger.info("Time: {:%Y-%m-%d %H:%M}".format(datetime.datetime.fromtimestamp(CURRENT_TIME)))
        logger.info("Surface of real fire: {:.3f}km²".format(surface1 / 1000 / 1000))
        logger.info("Surface of the estimated fire: {:.3f}km²".format(surface2 / 1000 / 1000))
        logger.info("Absolute error: {:.3f}km²".format(surface_diff / 1000 / 1000))
        logger.info("Relative error: {:.2f}%".format(surface_diff / surface1 * 100))
    except Exception as e:
        logger.error("Situation Assessment (Current) failed with error: {}".format(str(e)))
    # future_assessment = perform_future_situation_assessment(propagation_env, assessment, CURRENT_TIME+100*60*60)

    print("END")


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>href - gradient element reference</title>
<body>
  <svg width="300" height="300" viewBox="0 0 300 300"
       xmlns:xlink="http://www.w3.org/1999/xlink">
    <linearGradient id="MyGradient">
      <stop offset="5%"  stop-color="green"/>
      <stop offset="95%" stop-color="gold"/>
    </linearGradient>
    <rect fill="url(#MyGradient)" stroke="black" x="0" y="0"
          width="100" height="100"/>

    <radialGradient id="MyRadialGradient">
      <stop offset="0%" stop-color="red"/>
      <stop offset="100%" stop-color="blue"/>
    </radialGradient>
    <rect x="110" y="0" rx="15" ry="15" width="100" height="100"
          fill="url(#MyRadialGradient)"/>
  </svg>
</body>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Muelleria 7:274. 1990

#### Original name
null

### Remarks
null


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Network.Models;

namespace Azure.ResourceManager.Network
{
    /// <summary> A class representing the ExpressRoutePortsLocation data model. </summary>
    public partial class ExpressRoutePortsLocationData : NetworkTrackedResourceData
    {
        /// <summary> Initializes a new instance of ExpressRoutePortsLocationData. </summary>
        public ExpressRoutePortsLocationData()
        {
            AvailableBandwidths = new ChangeTrackingList<ExpressRoutePortsLocationBandwidths>();
        }

        /// <summary> Initializes a new instance of ExpressRoutePortsLocationData. </summary>
        /// <param name="id"> Resource ID. </param>
        /// <param name="name"> Resource name. </param>
        /// <param name="resourceType"> Resource type. </param>
        /// <param name="location"> Resource location. </param>
        /// <param name="tags"> Resource tags. </param>
        /// <param name="address"> Address of peering location. </param>
        /// <param name="contact"> Contact details of peering locations. </param>
        /// <param name="availableBandwidths"> The inventory of available ExpressRoutePort bandwidths. </param>
        /// <param name="provisioningState"> The provisioning state of the express route port location resource. </param>
        internal ExpressRoutePortsLocationData(ResourceIdentifier id, string name, ResourceType? resourceType, AzureLocation? location, IDictionary<string, string> tags, string address, string contact, IList<ExpressRoutePortsLocationBandwidths> availableBandwidths, NetworkProvisioningState? provisioningState) : base(id, name, resourceType, location, tags)
        {
            Address = address;
            Contact = contact;
            AvailableBandwidths = availableBandwidths;
            ProvisioningState = provisioningState;
        }

        /// <summary> Address of peering location. </summary>
        public string Address { get; }
        /// <summary> Contact details of peering locations. </summary>
        public string Contact { get; }
        /// <summary> The inventory of available ExpressRoutePort bandwidths. </summary>
        public IList<ExpressRoutePortsLocationBandwidths> AvailableBandwidths { get; }
        /// <summary> The provisioning state of the express route port location resource. </summary>
        public NetworkProvisioningState? ProvisioningState { get; }
    }
}


text:
package com.swetha.easypark;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import android.util.Log;

/**
 *
 * @author Swetha Venkatachari Sundarajan
 * This class makes an HTTP post request to the URL with the post params
 *
 */

public class EasyParkHttpClient {

	public static final int HTTP_TIMEOUT = 100 * 1000; // milliseconds
	private static HttpClient mHttpClient;
	static JSONObject jObj = null;
    static String json = "";
    static InputStream is = null;

	 private static HttpClient getHttpClient() {

	  if (mHttpClient == null) {
	   mHttpClient = new DefaultHttpClient();

	   final HttpParams params = mHttpClient.getParams();
	   HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
	   HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
	   ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
	  }

	  return mHttpClient;
	 }
	 /**
	  * @param url of the website and the post request
	  * @return http response in string */
	 public static String executeHttpPost(String url,ArrayList<NameValuePair> postParameters) throws Exception {

	 		BufferedReader in = null;

		  try {

		   HttpClient client = getHttpClient();

		   HttpPost request = new HttpPost(url);

		   UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(

		     postParameters);

		   request.setEntity(formEntity);
		Log.i("CustomHttpClient", "before sending request" +request);
		   HttpResponse response = client.execute(request);
			Log.i("CustomHttpClient", "after sending request" +response.toString());
			//Log.i("CustomHttpClient", "after sending request response in to string" +response.getEntity().getContent().toString());

			  in = new BufferedReader(new InputStreamReader(response.getEntity()

					     .getContent()));

					   StringBuffer sb = new StringBuffer("");

					   String line = "";

					   String NL = System.getProperty("line.separator");

					   while ((line = in.readLine()) != null) {

					    sb.append(line + NL);

					   }

		 in.close();

		   String result = sb.toString();

		   return result;

		   }

		  finally {

			  if (in != null) {

				    try {

				     in.close();

				    } catch (IOException e) {

				     Log.e("log_tag", "Error converting result "+e.toString());

				     e.printStackTrace();

	  }

			  }
		  }

	 }

}


text:
<?php
$file = system("sudo python gpio_clean.py");
?>