text:
namespace base {
class DictionaryValue;
}

namespace content {
class BrowserContext;
class WebContents;
}

namespace extensions {
class ExtensionPrefs;

class ExtensionActionAPI : public BrowserContextKeyedAPI {
 public:
  class Observer {
   public:
    // Called when there is a change to the given |extension_action|.
    // |web_contents| is the web contents that was affected, and
    // |browser_context| is the associated BrowserContext. (The latter is
    // included because ExtensionActionAPI is shared between normal and
    // incognito contexts, so |browser_context| may not equal
    // |browser_context_|.)
    virtual void OnExtensionActionUpdated(
        ExtensionAction* extension_action,
        content::WebContents* web_contents,
        content::BrowserContext* browser_context);

    // Called when there is a change to the extension action's visibility.
    virtual void OnExtensionActionVisibilityChanged(
        const std::string& extension_id,
        bool is_now_visible);

    // Called when the page actions have been refreshed do to a possible change
    // in count or visibility.
    virtual void OnPageActionsUpdated(content::WebContents* web_contents);

    // Called when the ExtensionActionAPI is shutting down, giving observers a
    // chance to unregister themselves if there is not a definitive lifecycle.
    virtual void OnExtensionActionAPIShuttingDown();

   protected:
    virtual ~Observer();
  };

  explicit ExtensionActionAPI(content::BrowserContext* context);
  ~ExtensionActionAPI() override;

  // Convenience method to get the instance for a profile.
  static ExtensionActionAPI* Get(content::BrowserContext* context);

  static BrowserContextKeyedAPIFactory<ExtensionActionAPI>*
      GetFactoryInstance();

  // Add or remove observers.
  void AddObserver(Observer* observer);
  void RemoveObserver(Observer* observer);

  bool GetBrowserActionVisibility(const std::string& extension_id);
  void SetBrowserActionVisibility(const std::string& extension_id,
                                  bool visible);

  // BrowserContextKeyedAPI implementation.
  // Executes the action of the given |extension| on the |browser|'s active
  // web contents. If |grant_tab_permissions| is true, this will also grant
  // activeTab to the extension (so this should only be done if this is through
  // a direct user action). Returns the action that should be taken.
  ExtensionAction::ShowAction ExecuteExtensionAction(
      const Extension* extension,
      Browser* browser,
      bool grant_active_tab_permissions);

  // Opens the popup for the given |extension| in the given |browser|'s window.
  // If |grant_active_tab_permissions| is true, this grants the extension
  // activeTab (so this should only be done if this is through a direct user
  // action).
  bool ShowExtensionActionPopup(const Extension* extension,
                                Browser* browser,
                                bool grant_active_tab_permissions);

  // Returns true if the given |extension| wants to run on the tab pointed to
  // by |web_contents|.
  bool ExtensionWantsToRun(const Extension* extension,
                           content::WebContents* web_contents);

  // Notifies that there has been a change in the given |extension_action|.
  void NotifyChange(ExtensionAction* extension_action,
                    content::WebContents* web_contents,
                    content::BrowserContext* browser_context);

  // Clears the values for all ExtensionActions for the tab associated with the
  // given |web_contents| (and signals that page actions changed).
  void ClearAllValuesForTab(content::WebContents* web_contents);

  // Notifies that the current set of page actions for |web_contents| has
  // changed, and signals the browser to update.
  void NotifyPageActionsChanged(content::WebContents* web_contents);

  void set_prefs_for_testing(ExtensionPrefs* prefs) {
    extension_prefs_ = prefs;
  }

 private:
  friend class BrowserContextKeyedAPIFactory<ExtensionActionAPI>;

  // Returns the associated extension prefs.
  ExtensionPrefs* GetExtensionPrefs();

  // The DispatchEvent methods forward events to the |context|'s event router.
  void DispatchEventToExtension(content::BrowserContext* context,
                                const std::string& extension_id,
                                const std::string& event_name,
                                scoped_ptr<base::ListValue> event_args);

  // Called when either a browser or page action is executed. Figures out which
  // event to send based on what the extension wants.
  void ExtensionActionExecuted(const ExtensionAction& extension_action,
                               content::WebContents* web_contents);

  // BrowserContextKeyedAPI implementation.
  void Shutdown() override;
  static const char* service_name() { return "ExtensionActionAPI"; }
  static const bool kServiceRedirectedInIncognito = true;

  base::ObserverList<Observer> observers_;

  content::BrowserContext* browser_context_;

  ExtensionPrefs* extension_prefs_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionActionAPI);
};

// Implementation of the browserAction and pageAction APIs.
//
// Divergent behaviour between the two is minimal (pageAction has required
// tabIds while browserAction's are optional, they have different internal
// browser notification requirements, and not all functions are defined for all
// APIs).
class ExtensionActionFunction : public ChromeSyncExtensionFunction {
 public:
  static bool ParseCSSColorString(const std::string& color_string,
                                  SkColor* result);

 protected:
  ExtensionActionFunction();
  ~ExtensionActionFunction() override;
  bool RunSync() override;
  virtual bool RunExtensionAction() = 0;

  bool ExtractDataFromArguments();
  void NotifyChange();
  bool SetVisible(bool visible);

  // All the extension action APIs take a single argument called details that
  // is a dictionary.
  base::DictionaryValue* details_;

  // The tab id the extension action function should apply to, if any, or
  // kDefaultTabId if none was specified.
  int tab_id_;

  // WebContents for |tab_id_| if one exists.
  content::WebContents* contents_;

  // The extension action for the current extension.
  ExtensionAction* extension_action_;
};

//
// Implementations of each extension action API.
//
// pageAction and browserAction bindings are created for these by extending them
// then declaring an EXTENSION_FUNCTION_NAME.
//

// show
class ExtensionActionShowFunction : public ExtensionActionFunction {
 protected:
  ~ExtensionActionShowFunction() override {}
  bool RunExtensionAction() override;
};

// hide
class ExtensionActionHideFunction : public ExtensionActionFunction {
 protected:
  ~ExtensionActionHideFunction() override {}
  bool RunExtensionAction() override;
};

// setIcon
class ExtensionActionSetIconFunction : public ExtensionActionFunction {
 protected:
  ~ExtensionActionSetIconFunction() override {}
  bool RunExtensionAction() override;
};

// setTitle
class ExtensionActionSetTitleFunction : public ExtensionActionFunction {
 protected:
  ~ExtensionActionSetTitleFunction() override {}
  bool RunExtensionAction() override;
};

// setPopup
class ExtensionActionSetPopupFunction : public ExtensionActionFunction {
 protected:
  ~ExtensionActionSetPopupFunction() override {}
  bool RunExtensionAction() override;
};

// setBadgeText
class ExtensionActionSetBadgeTextFunction : public ExtensionActionFunction {
 protected:
  ~ExtensionActionSetBadgeTextFunction() override {}
  bool RunExtensionAction() override;
};

// setBadgeBackgroundColor
class ExtensionActionSetBadgeBackgroundColorFunction
    : public ExtensionActionFunction {
 protected:
  ~ExtensionActionSetBadgeBackgroundColorFunction() override {}
  bool RunExtensionAction() override;
};

// getTitle
class ExtensionActionGetTitleFunction : public ExtensionActionFunction {
 protected:
  ~ExtensionActionGetTitleFunction() override {}
  bool RunExtensionAction() override;
};

// getPopup
class ExtensionActionGetPopupFunction : public ExtensionActionFunction {
 protected:
  ~ExtensionActionGetPopupFunction() override {}
  bool RunExtensionAction() override;
};

// getBadgeText
class ExtensionActionGetBadgeTextFunction : public ExtensionActionFunction {
 protected:
  ~ExtensionActionGetBadgeTextFunction() override {}
  bool RunExtensionAction() override;
};

// getBadgeBackgroundColor
class ExtensionActionGetBadgeBackgroundColorFunction
    : public ExtensionActionFunction {
 protected:
  ~ExtensionActionGetBadgeBackgroundColorFunction() override {}
  bool RunExtensionAction() override;
};

//
// browserAction.* aliases for supported browserAction APIs.
//

class BrowserActionSetIconFunction : public ExtensionActionSetIconFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("browserAction.setIcon", BROWSERACTION_SETICON)

 protected:
  ~BrowserActionSetIconFunction() override {}
};

class BrowserActionSetTitleFunction : public ExtensionActionSetTitleFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("browserAction.setTitle", BROWSERACTION_SETTITLE)

 protected:
  ~BrowserActionSetTitleFunction() override {}
};

class BrowserActionSetPopupFunction : public ExtensionActionSetPopupFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("browserAction.setPopup", BROWSERACTION_SETPOPUP)

 protected:
  ~BrowserActionSetPopupFunction() override {}
};

class BrowserActionGetTitleFunction : public ExtensionActionGetTitleFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("browserAction.getTitle", BROWSERACTION_GETTITLE)

 protected:
  ~BrowserActionGetTitleFunction() override {}
};

class BrowserActionGetPopupFunction : public ExtensionActionGetPopupFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("browserAction.getPopup", BROWSERACTION_GETPOPUP)

 protected:
  ~BrowserActionGetPopupFunction() override {}
};

class BrowserActionSetBadgeTextFunction
    : public ExtensionActionSetBadgeTextFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("browserAction.setBadgeText",
                             BROWSERACTION_SETBADGETEXT)

 protected:
  ~BrowserActionSetBadgeTextFunction() override {}
};

class BrowserActionSetBadgeBackgroundColorFunction
    : public ExtensionActionSetBadgeBackgroundColorFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("browserAction.setBadgeBackgroundColor",
                             BROWSERACTION_SETBADGEBACKGROUNDCOLOR)

 protected:
  ~BrowserActionSetBadgeBackgroundColorFunction() override {}
};

class BrowserActionGetBadgeTextFunction
    : public ExtensionActionGetBadgeTextFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("browserAction.getBadgeText",
                             BROWSERACTION_GETBADGETEXT)

 protected:
  ~BrowserActionGetBadgeTextFunction() override {}
};

class BrowserActionGetBadgeBackgroundColorFunction
    : public ExtensionActionGetBadgeBackgroundColorFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("browserAction.getBadgeBackgroundColor",
                             BROWSERACTION_GETBADGEBACKGROUNDCOLOR)

 protected:
  ~BrowserActionGetBadgeBackgroundColorFunction() override {}
};

class BrowserActionEnableFunction : public ExtensionActionShowFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("browserAction.enable", BROWSERACTION_ENABLE)

 protected:
  ~BrowserActionEnableFunction() override {}
};

class BrowserActionDisableFunction : public ExtensionActionHideFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("browserAction.disable", BROWSERACTION_DISABLE)

 protected:
  ~BrowserActionDisableFunction() override {}
};

class BrowserActionOpenPopupFunction : public ChromeAsyncExtensionFunction,
                                       public content::NotificationObserver {
 public:
  DECLARE_EXTENSION_FUNCTION("browserAction.openPopup",
                             BROWSERACTION_OPEN_POPUP)
  BrowserActionOpenPopupFunction();

 private:
  ~BrowserActionOpenPopupFunction() override {}

  // ExtensionFunction:
  bool RunAsync() override;

  void Observe(int type,
               const content::NotificationSource& source,
               const content::NotificationDetails& details) override;
  void OpenPopupTimedOut();

  content::NotificationRegistrar registrar_;
  bool response_sent_;

  DISALLOW_COPY_AND_ASSIGN(BrowserActionOpenPopupFunction);
};

}  // namespace extensions

//
// pageAction.* aliases for supported pageAction APIs.
//

class PageActionShowFunction : public extensions::ExtensionActionShowFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("pageAction.show", PAGEACTION_SHOW)

 protected:
  ~PageActionShowFunction() override {}
};

class PageActionHideFunction : public extensions::ExtensionActionHideFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("pageAction.hide", PAGEACTION_HIDE)

 protected:
  ~PageActionHideFunction() override {}
};

class PageActionSetIconFunction
    : public extensions::ExtensionActionSetIconFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("pageAction.setIcon", PAGEACTION_SETICON)

 protected:
  ~PageActionSetIconFunction() override {}
};

class PageActionSetTitleFunction
    : public extensions::ExtensionActionSetTitleFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("pageAction.setTitle", PAGEACTION_SETTITLE)

 protected:
  ~PageActionSetTitleFunction() override {}
};

class PageActionSetPopupFunction
    : public extensions::ExtensionActionSetPopupFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("pageAction.setPopup", PAGEACTION_SETPOPUP)

 protected:
  ~PageActionSetPopupFunction() override {}
};

class PageActionGetTitleFunction
    : public extensions::ExtensionActionGetTitleFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("pageAction.getTitle", PAGEACTION_GETTITLE)

 protected:
  ~PageActionGetTitleFunction() override {}
};

class PageActionGetPopupFunction
    : public extensions::ExtensionActionGetPopupFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("pageAction.getPopup", PAGEACTION_GETPOPUP)

 protected:
  ~PageActionGetPopupFunction() override {}
};

#endif  // CHROME_BROWSER_EXTENSIONS_API_EXTENSION_ACTION_EXTENSION_ACTION_API_H_


text:
package net.ontopia.presto.jaxb;

public abstract class Document {

    public abstract String getFormat();

    public void setFormat(String format) {
        if (!getFormat().equals(format)) {
            throw new IllegalArgumentException("Invalid format: '" + format + "' Expected: '" + getFormat() + "'");
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Leptosphaeria fuscella var. sydowiana Sacc.

### Remarks
null


text:
author: linpx
date: '2006-01-06 01:26:05'
layout: post
slug: perhaps-love
status: publish
comments: true
title: Perhaps Love
wordpress_id: '246'
categories:
- movie
---

It should be most dulling movie I ever seen before moving into a theater and
taking a look at it by accident when my desiring one is Narnia, or even after
watched the first stage when a stupid Korean guy jumped out of a 70s' bus and
began to dance and sing that moment forced a shit coming out of my mouth,
another night was ruined. And it turned out to prove me wrong again by my
ending at tears.

The story was simple from a literature way, the story of past, presence and in
the movie. A girl fooled around in Beijing the end of 80s, a time western
culture holding a conflict controversial dispute with Confusion in China. She
tried all her means to make herself famous including her body till she made it
during which she, incredibly, fell in love with a Hong Kong student who was
learning movie art then, truly and faithfully. Two faces of young girl made
her lost and disdain herself that resulted in leaving him, which was
unquestionable and foreseeable. However, where one's imagination goes, where
the movie could end. The two Chinese met at last, famous but with indifferent
faces to everything including themselves or far and soon between.

And I always treated art is a way by translating simplicity into complex ones,
the more un-understandable, the more successful it could be or we might say,
it could be regarded. Same rule applies here. The director is a good one,
especially has a right for final cut. I was living in wonderland without
knowing where I was at the begging of the 30 mins. What the hell is he trying
to talk about by inserting the past, presence one by another, as if you were
swimming in tropical area at one time, the next you would have been exposed in
the Antarctica watching those polar bears, naked. Damn it!

But I wouldn't regard it fail. It is good one, two thumbs up. And you were
shown it in Korea that a good sign to know the movie industry in China is
reviving, given the fact another Chinese one also became a blockbuster here.

The story could never happen on us, we regular people, but deserve us to fade
the feeling inside. Perhaps Love, one you should, perhaps sip.

![Image hosted by Photobucket.com](http://i30.photobucket.com/albums/c330/penn
yg/micellaneous/perhapslove.jpg)


text:
/**
 *  Defines CursorId and defines ByLocKey, which pairs up a DiskLoc
 *  and a CursorId and provides a comparison operation.
 */

#pragma once

#include <limits>
#include <map>

#include "mongo/db/diskloc.h"

namespace mongo {

    typedef long long CursorId; /* passed to the client so it can send back on getMore */
    static const CursorId INVALID_CURSOR_ID = -1; // But see SERVER-5726.

    // TODO(acm|mathias): ByLocKey allows constructing a map so we can
    // invalidate or advance all cursors pointing to a DiskLoc when we
    // remove that record. During review of moving this class to this
    // header, Mathias said: "On further thought, I think this need
    // would be better served by an unordered_map<DiskLoc,
    // unordered_map<CursorId, ClientCursor*>>." At which point, this
    // class should be removed.

    struct ByLocKey {

        ByLocKey(const DiskLoc& l, const CursorId& i) : loc(l), id(i) {}

        static ByLocKey min(const DiskLoc& l) {
            return ByLocKey(l, std::numeric_limits<long long>::min());
        }

        static ByLocKey max(const DiskLoc& l) {
            return ByLocKey(l, std::numeric_limits<long long>::max());
        }

        const DiskLoc loc;
        const CursorId id;
    };

    inline bool operator<(const ByLocKey& lhs, const ByLocKey& rhs) {
        int x = lhs.loc.compare(rhs.loc);
        if (x)
            return x < 0;
        return lhs.id < rhs.id;
    }

    class ClientCursor;
    typedef std::map<ByLocKey, ClientCursor*> CCByLoc;

} // namespace mongo


text:
\documentclass[10pt]{beamer}
%souza naves, n 576
\usetheme[everytitleformat=regular]{metropolis}

% Língua e acentos
\usepackage[brazil]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{booktabs}
\usepackage[scale=2]{ccicons}

\usepackage{pgfplots}
\usepgfplotslibrary{dateplot}

\title{Fluxo de potência para sistemas de distribuição}
\subtitle{Considerando redução de barras}
\date{\today}
\author{David Maykon Krepsky Silva}
\institute{Departamento de Engenharia Elétrica}
\titlegraphic{\includegraphics[height=1.cm]{img/logo}}

\usepackage{ragged2e}

\usepackage{pgf-pie}
\usetikzlibrary{ shadows }
\usepackage[authoryear]{natbib}

\usepackage{multirow}
\usepackage{subfig}
\usepackage{longtable}

\begin{document}

\maketitle

\begin{frame}
  \frametitle{Sumário}
  \setbeamertemplate{section in toc}[sections numbered]
  \tableofcontents[hideallsubsections]
\end{frame}

\section{Objetivos}
\begin{frame}{Objetivos do trabalho}
    Objetivos primários:
    \begin{itemize}
        \item Implementação dos métodos \textit{Soma de Correntes} e \textit{Soma de potências} para o cálculo do fluxo de potência.

        \item Comparação de desempenho entre os métodos.

        \item Desenvolvimento e implementação do algoritmo de redução de barras.
    \end{itemize}

    Objetivo secundário:
    \begin{itemize}
        \item Desenvolvimento de programa gráfico para análise de sistemas de distribuição utilizando os algoritmos acima citados.
    \end{itemize}
\end{frame}

\section{Metodologia}

\begin{frame}{Metodologia}

    \begin{itemize}
        \item Uso de linguagem de programação C++.

        \item Desenvolvimento com o \textit{framework} Qt.

        \item Validação dos resultados com seis sistemas diferentes.

        \item Teste de performance dos algoritmos implementados, com e sem a redução.
    \end{itemize}
\end{frame}

\section{Sistema elétrico brasileiro}

\begin{frame}[fragile]
  \frametitle{Consumo de energia elétrica no Brasil}
    \begin{itemize}
        \item Em julho de 2015, foram consumidos \alert{45.149 GWh} de energia elétrica no Brasil \cite{boletimMME}.

        \item As crises hídricas encarecem o custo da energia elétrica, pois estimulam o uso de combustíveis fósseis.

        \item De forma a compensar o custo extra das usinas termo-elétricas, foi instaurado em 2015 o Sistema de Bandeiras Tarifárias.
    \end{itemize}
\end{frame}

\begin{frame}[fragile]
    \frametitle{Perfil do consumo - julho/2015}
    \begin{figure}
        \centering
        \caption{Perfil de consumo de energia elétrica no Brasil, julho de 2015}
        \begin{tikzpicture}
            \pie [radius = 2, rotate = 90, color = {green, cyan, orange, black!20, violet, red}, explode = {0, 0, 0, 0, 0, 0.2}, style = drop shadow, text = pin]{22.4/Residêncial, 31.1/Industrial, 15.0/Comercial, 4.5/Rural, 8.4/Outros, 18.5/Perdas}
        \end{tikzpicture}
        \\
        \small Fonte: Ministério de Minas e Energia \cite{boletimMME}.
        \label{fig:perfil}
        \end{figure}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Ineficiência do sistema}
  \begin{itemize}
      \item Em alguns estados, como no Piauí, as perdas chegam a \alert{29\%} \cite{CostaNorte}.

      \item As perdas técnicas (como as perdas nos cabos e nos transformadores) chegam a 13\% \cite{CostaNorte}, sendo maior que as perdas totais em países como os EUA, a qual fica em torno de 6\% \cite{Queiroz}.

      \item O prejuízo é avaliado em bilhões de reais por ano.

      \item As maiores perdas técnicas se encontram no sistema de distribuição.
    \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Perdas em outros países}
  \begin{figure}
    \centering
    \caption{Perdas elétricas de transmissão e distribuição em \%}
    \includegraphics[width=\textwidth]{img/perdas_mundo}
    \\
    \small Fonte: Autoria própria (dados de \textit{World Development Indicators, 2015}).
    \label{fig:mundo}
  \end{figure}
\end{frame}

\section{O fluxo de potência}

\begin{frame}[fragile]
  \frametitle{O que é}
  \justify
     O fluxo de potência (ou fluxo de carga) é um problema matemático, composto por um conjunto de equações algébricas não lineares, que permite determinar os valores de tensão e potência, bem como as perdas, para um sistema elétrico de potência em regime permanente.

\end{frame}

\begin{frame}{Utilidade}
    \justify
    Provê uma visão detalhada das condições de operação do sistema, permitindo:

    \begin{itemize}
        \item análise de segurança da rede;

        \item o planejamento de redes de transmissão/distribuição mais eficientes;

        \item otimização dos sistemas em operação.
       \end{itemize}
\end{frame}

\begin{frame}{Características dos sistemas de potência}
    \begin{itemize}
        \item Composto por \emph{barras}, geradores, cargas, transformadores, reatores \textit{shunt}, capacitores \textit{shunt} e linhas de transmissão/distribuição.

        \item Barras são do tipo PV, PQ e V$\theta$.

        \item Barras são interligadas por linhas, as quais possuem perdas.
    \end{itemize}
\end{frame}

\begin{frame}{Solução do fluxo de potência}
    \justify
    Devido a natureza não linear do problema, são necessários métodos numéricos iterativos para a determinar uma aproximação das incógnitas nas equações do fluxo de potência.
\end{frame}

\begin{frame}{Métodos para cálculo do fluxo de potência}
    \justify
    Apesar dos métodos de Gauss-Seidel e Newton-Raphson (e seus derivados) serem amplamente utilizados para o calculo do fluxo de potência em sistemas de transmissão de energia elétrica, os mesmos apresentam problemas de convergência e desempenho quando aplicados em sistemas de distribuição \cite{Eminoglu, Alsaadi, Reddy, Yao}.
\end{frame}

\section{Métodos para redes de distribuição}

\begin{frame}{Redes de distribuição}
    Os métodos empregados na solução de redes de distribuição aproveitam a topologia radial \cite{Cespedes}, ou fracamente malhada \cite{ShirmohammadiMono, Shirmohammadi3F}, para resolver o problema do fluxo de potência.
\end{frame}

\begin{frame}{Redes radiais}
\begin{figure}[H]
   \centering
   \caption{Sistema radial.}
   \includegraphics[scale=0.2]{img/70b}
   \label{fig:70b}
\end{figure}
\end{frame}

\begin{frame}{Redes malhadas}
    \begin{figure}[H]
        \centering
        \caption{Sistema malhado.}
        \includegraphics[scale=0.6]{img/malhado}
        \label{fig:malhado}
    \end{figure}
\end{frame}

\begin{frame}{Método Soma de Potências (MSP)}
    Este método, proposto em \citep{Cespedes}, consiste em duas operações, uma a montante e outra a jusante.

    \begin{itemize}
        \item Operação a montante: partindo dos nós finais até o nó inicial, são calculadas as potências equivalentes em cada nó (i.e., somando todas as potências que são alimentadas por cada nó e as suas perdas).

        \item Operação a jusante: dado que a tensão da barra de referência é conhecida, é aplicada a equação \ref{equ:cespedes} para o cálculo da tensão nas barras subsequentes.

        \item O critério de parada é determinado pela variação das perdas totais do sistema (equação \ref{equ:cespedesL}).
    \end{itemize}
\end{frame}

\begin{frame}{Método Soma de Potências}
    Equação para o cálculo das tensões:
    \begin{equation}
      \label{equ:vcespedes2}
      |V_j|^4 + [2 \cdot (PR+QX) -  |V_i|^2] \cdot  |V_j|^2 + (P^2 + Q^2) \cdot (R^2 + X^2) = 0.
    \end{equation}

  onde:
  \begin{itemize}
    \item \emph{i}: nó fonte;
    \item \emph{j}: nó à jusante;
    \item \emph{$V_i$}: módulo da tensão em \emph{i};
    \item \emph{$V_j$}: módulo da tensão em \emph{j};
    \item \emph{P}: potência ativa equivalente da carga em \emph{j};
    \item \emph{Q}: potência reativa equivalente da carga em \emph{j};
    \item \emph{R}: resistência própria da linha;
    \item \emph{X}: reatância própria da linha.
  \end{itemize}

\end{frame}

\begin{frame}{Método Soma de Potências}
    Perdas nas linhas:
    \begin{eqnarray}
    \label{equ:cespedesL}
    L_p = R \frac{(P^2 + Q^2)}{V_j^2} \\
    L_q = X \frac{(P^2 + Q^2)}{V_j^2}
    \end{eqnarray}
\end{frame}

\begin{frame}{Desvantagens}
Desvantagens:
    \begin{itemize}
        \item aplicável somente a sistemas radiais;
        \item não considera o acoplamento entre linhas.
    \end{itemize}
\end{frame}

\begin{frame}{Método Soma de Correntes (MSC)}
    Proposto em \cite{ShirmohammadiMono, Shirmohammadi3F}, também consiste em duas operações, chamadas de varredura para trás (\textit{backward sweep}) e varredura para frente (\textit{forward sweep}).

    \begin{itemize}
        \item Varredura para trás: assumindo um perfil de tensão inicial para as barras, o algoritmo começa calculando as correntes nos nós das camadas finais com a equação \ref{equ:shirmI}. Em seguida, é calculado a corrente da camada anterior, sendo que, a corrente nas barras dessa camada é a soma das correntes que vão e direção a camada seguinte (equação \ref{equ:shirmJ}).

        \item Varredura para frente: Ao chegar na barra de referência (a qual possui tensão e fase conhecidas), o algoritmo calcula a tensão nas barras subsequentes, considerando as correntes previamente calculadas e a queda de tensão nas linhas de distribuição, com a equação \ref{equ:shirmV}.

        \item O critério de parada é determinado pela variação da potência no sistema.
    \end{itemize}
\end{frame}

\begin{frame}{Equações do método Soma de Correntes}
   Corrente nas barras:
    \begin{equation}
    \label{equ:shirmI}
      \left[ \begin{matrix}
      I_{ia} \\
      I_{ib} \\
      I_{ic} \\
      \end{matrix} \right]  =
      \left[ \begin{matrix}
      \left(S_{ia} \big / V_{ia}^{(k-1)} \right)^* \\
      \left(S_{ib} \big / V_{ib}^{(k-1)} \right)^* \\
      \left(S_{ic} \big / V_{ic}^{(k-1)} \right)^* \\
      \end{matrix} \right] -
      \left[ \begin{matrix}
      Y_{ia}^* & & \\
      & Y_{ib}^* & \\
      & & Y_{ic}^* \\
      \end{matrix} \right]
      \left[ \begin{matrix}
      V_{ia} \\
      V_{ib} \\
      V_{ic} \\
      \end{matrix} \right]^{(k-1)}
    \end{equation}

    Corrente nas linhas:
    \begin{equation}
    \label{equ:shirmJ}
     \left[ \begin{matrix}
     J_{la} \\
     J_{lb} \\
     J_{lc} \\
     \end{matrix} \right]^{(k)}  = -
      \left[ \begin{matrix}
      I_{ja} \\
      I_{jb} \\
      I_{jc} \\
      \end{matrix} \right]^{(k)} + \sum_{m \, \in \, M}
       \left[ \begin{matrix}
       J_{ma} \\
       J_{mb} \\
       J_{mc} \\
       \end{matrix} \right]^{k}
    \end{equation}

        Tensão nas barras:
        \begin{equation}
        \label{equ:shirmV}
        \left[ \begin{matrix}
        V_{ja} \\
        V_{jb} \\
        V_{jc} \\
        \end{matrix} \right]^{(k)}  =
        \left[ \begin{matrix}
        V_{ia} \\
        V_{ib} \\
        V_{ic} \\
        \end{matrix} \right]^{(k)} -
        \left[ \begin{matrix}
        Z_{aa,l} & Z_{ab,l} &  Z_{ac,l} \\
        Z_{ba,l} & Z_{bb,l} &  Z_{bc,l} \\
        Z_{ca,l} & Z_{cb,l} &  Z_{cc,l} \\
        \end{matrix} \right]
        \left[ \begin{matrix}
        J_{la} \\
        J_{lb} \\
        J_{lc} \\
        \end{matrix} \right]^{(k)}
        \end{equation}
\end{frame}

\begin{frame}{Equações do método Soma de Correntes}
 Onde:

    \begin{itemize}
    \item $I_{ia}, I_{ib}, I_{ic}$ são as injeções de corrente na barra \emph{i}.

    \item $S_{ia}, S_{ib}, S_{ic}$ são as injeções de potência programadas na barra \emph{i}.

    \item $V_{ia}, V_{ib}, V_{ic}$ são as tensões na barra \emph{i}.

    \item $Y_{ia}, Y_{ib}, Y_{ic}$ são as admitâncias dos elementos \textit{shunt} na barra \emph{i}.

    \item $J_{la}, J_{lb}, J_{lc}$ são as correntes na linha \emph{l}.

    \item \emph{k} é a iteração.
    \end{itemize}

\end{frame}

\begin{frame}{Algoritmo de redução de barras}
    Parte do princípio de que barras inertes podem ser removidas do sistema sem causar divergência no fluxo de potência.
\end{frame}

\begin{frame}{Algoritmo de redução de barras}
    \begin{figure}[h]
      \centering
      \caption{Sistema radial monofásico com 6 barras.}
      \includegraphics[width=\textwidth]{img/barreduc}
      \label{fig:barreduc}

      \small Fonte: Autoria própria.
    \end{figure}
\end{frame}

\begin{frame}{Algoritmo de redução de barras}
 \begin{figure}[h]
   \centering
   \caption{Conexão entre as barras 3 e 5 para o sistema da figura \ref{fig:barreduc}.}
   \includegraphics[scale=0.7]{img/barreduc1}
   \label{fig:barreduc1}

   \small Fonte: Autoria própria.
  \end{figure}
\end{frame}

\begin{frame}{Algoritmo de redução de barras}
    \begin{figure}[h]
      \centering
      \caption{Conexão entre as barras \textit{1} e \textit{3} da figura \ref{fig:barreduc}.}
      \label{fig:barreduc2}

      \subfloat[Com a barra 2.]{%
        \label{fig:barreduc2a}
        \includegraphics[scale=0.35]{img/barreduc2}
      }

      \subfloat[Sem a barra 2.]{%
        \label{fig:barreduc2b}
        \includegraphics[scale=0.35]{img/barreduc3}
      }

      \small Fonte: Autoria própria.
    \end{figure}
\end{frame}

\begin{frame}{Algoritmo de redução de barras}
  \begin{figure}[h]
    \centering
    \caption{Sistema reduzido.}
    \includegraphics[width=\textwidth]{img/barreduc4}
    \label{fig:barreduc4}

    \small Fonte: Autoria própria.
  \end{figure}
\end{frame}

\begin{frame}{Comparação entre os algoritmos - Tensão monofásica}
  Reinsere as barras removidas no sistema, calculando sua tensão.

  Para sistemas monofásicos, não há divergência nos resultados.

  Para sistemas trifásicos, há uma variação nos valores das barras reinseridas.

\end{frame}
\section{Resultados}

\begin{frame}{Comparação entre os algoritmos - Tensão monofásica}
    \begin{longtable}{lllr}
      \caption{Módulo da tensão de linha nas barras do sistema de 14 barras.}\label{tab:14b_v}\\
      \toprule
      \multirow{2}{*}{\textbf{Barra}}& \multicolumn{2}{c}{\textbf{Tensão [V]}}&\multirow{2}{*}{\textbf{$\mathbf{\Delta}$V [\%]}}\\
      & \multicolumn{1}{c}{MSC} & \multicolumn{1}{c}{MSP} & \\
      \midrule
      \endfirsthead

      \multicolumn{4}{c}%
      {{\bfseries \tablename\ \thetable{} -- continuação da página anterior}} \\
      \toprule
      \multirow{2}{*}{\textbf{Barra}}& \multicolumn{2}{c}{\textbf{Tensão [V]}}&\multirow{2}{*}{\textbf{$\mathbf{\Delta}$V [\%]}}\\
      & \multicolumn{1}{c}{MSC} & \multicolumn{1}{c}{MSP} & \\
      \midrule
      \endhead

      \midrule \multicolumn{4}{r}{{Continua na próxima página}} \\
      \endfoot

      \bottomrule \multicolumn{4}{c}{\small Fonte: Autoria própria.}
      \endlastfoot

      0&13279.0562&13279.0562&0\\
      3&13155.1064&13155.1064&0\\
      4&13116.8665&13116.8665&0\\
      5&13093.0194&13093.0194&0\\
      6&13078.4579&13078.4579&0\\
      7&13000.9878&13000.9878&0\\
      8&12894.9325&12894.9325&0\\
      9&12972.5789&12972.5789&0\\
      10&12893.4175&12893.4175&0\\
      11&12870.9415&12870.9415&0\\

    \end{longtable}

\end{frame}

\begin{frame}{Validação dos algoritmos - Perdas monofásicas}
\begin{longtable}{llllr}
  \caption{Comparação entre as perdas nas linhas do sistema de 14 barras.}\label{tab:14b_l}\\
  \toprule
  \multirow{2}{*}{$\mathbf{Barra_i}$}&\multirow{2}{*}{$\mathbf{Barra_f}$}&\multicolumn{2}{c}{$\mathbf{S_{perda} [kVA]}$}&\multirow{2}{*}{$\mathbf{\Delta S_{perda} [kVA]}$}\\
  && \multicolumn{1}{c}{MSC} & \multicolumn{1}{c}{MSP} & \\
  \midrule
  \endfirsthead

  \multicolumn{5}{c}%
  {{\bfseries \tablename\ \thetable{} -- continuação da página anterior}} \\
  \toprule
  \multirow{2}{*}{$\mathbf{Barra_i}$}&\multirow{2}{*}{$\mathbf{Barra_f}$}&\multicolumn{2}{c}{$\mathbf{S_{perda} [kVA]}$}&\multirow{2}{*}{$\mathbf{\Delta}S_{perda} [\%]$}\\
  && \multicolumn{1}{c}{MSC} & \multicolumn{1}{c}{MSP} & \\
  \midrule
  \endhead

  \midrule \multicolumn{5}{r}{{Continua na próxima página}} \\
  \endfoot

  \bottomrule \multicolumn{5}{c}{\small Fonte: Autoria própria.}
  \endlastfoot

  0&3&61.63 + 82.17i&61.63 + 82.17i&0\\
  0&7&278.33 + 278.33i&278.33 + 278.33i&0\\
  0&12&29.07 + 29.07i&29.07 + 29.07i&0\\
  3&4&7.51 + 10.32i&7.51 + 10.32i&0\\
  3&5&11.94 + 23.89i&11.94 + 23.89i&0\\
  5&6&1.52 + 1.52i&1.52 + 1.52i&0\\
  7&8&87.01 + 119.63i&87.01 + 119.63i&0\\
  7&9&2.08 + 2.080i&2.08 + 2.08i&0\\
  8&10&0.71 + 0.710i&0.71 + 0.710i&0\\

\end{longtable}
\end{frame}

\begin{frame}{Comparação entre os algoritmos - Tensão trifásica}
  \begin{longtable}{lllr}
    \caption{Módulo da tensão de linha nas barras do sistema de 34 barras (fase $a$).}\label{tab:34b_va}\\
    \toprule
    \multirow{2}{*}{\textbf{Barra}}& \multicolumn{2}{c}{\textbf{Tensão [V]}}&\multirow{2}{*}{\textbf{$\mathbf{\Delta}$V [\%]}}\\
    & \multicolumn{1}{c}{MSC} & \multicolumn{1}{c}{MSP} & \\
    \midrule
    \endfirsthead

    \multicolumn{4}{c}%
    {{\bfseries \tablename\ \thetable{} -- continuação da página anterior}} \\
    \toprule
    \multirow{2}{*}{\textbf{Barra}}& \multicolumn{2}{c}{\textbf{Tensão [V]}}&\multirow{2}{*}{\textbf{$\mathbf{\Delta}$V [\%]}}\\
    & \multicolumn{1}{c}{MSC} & \multicolumn{1}{c}{MSP} & \\
    \midrule
    \endhead

    \midrule \multicolumn{4}{r}{{Continua na próxima página}} \\
    \endfoot

    \bottomrule \multicolumn{4}{c}{\small Fonte: Autoria própria.}
    \endlastfoot

    0&14376.0217&14376.0217&0\\
    2&14328.2494&14317.0068&-0.078465\\
    6&14296.1153&14277.4644&-0.13046\\
    8&13696.3155&13545.2221&-1.1032\\
    10&13696.3155&13545.2221&-1.1032\\
    12&13004.399&12705.208&-2.3007\\
    56&12093.691&11579.1058&-4.255\\
    64&11671.7313&11048.7036&-5.3379\\
    88&11698.3139&11080.3959&-5.2821\\
    90&11658.4819&11025.2575&-5.4314\\
  \end{longtable}
\end{frame}

\begin{frame}{Validação dos algoritmos - Perdas trifásicas}
\begin{longtable}{lllr}
  \caption{Módulo da tensão de linha nas barras do sistema de 34 barras (fase $b$).}\label{tab:34b_vb}\\
  \toprule
  \multirow{2}{*}{\textbf{Barra}}& \multicolumn{2}{c}{\textbf{Tensão [V]}}&\multirow{2}{*}{\textbf{$\mathbf{\Delta}$V [\%]}}\\
  & \multicolumn{1}{c}{MSC} & \multicolumn{1}{c}{MSP} & \\
  \midrule
  \endfirsthead

  \multicolumn{4}{c}%
  {{\bfseries \tablename\ \thetable{} -- continuação da página anterior}} \\
  \toprule
  \multirow{2}{*}{\textbf{Barra}}& \multicolumn{2}{c}{\textbf{Tensão [V]}}&\multirow{2}{*}{\textbf{$\mathbf{\Delta}$V [\%]}}\\
  & \multicolumn{1}{c}{MSC} & \multicolumn{1}{c}{MSP} & \\
  \midrule
  \endhead

  \midrule \multicolumn{4}{r}{{Continua na próxima página}} \\
  \endfoot

  \bottomrule \multicolumn{4}{c}{\small Fonte: Autoria própria.}
  \endlastfoot

  0&14376.0217&14376.0217&0\\
  2&14335.786&14320.2529&-0.10835\\
  6&14309.7979&14283.7781&-0.18183\\
  8&13844.7644&13624.9811&-1.5875\\
  64&11873.0989&11106.6181&-6.4556\\
  88&11918.0186&11151.7078&-6.4299\\
  90&11882.2571&11096.926&-6.6093\\
\end{longtable}
\end{frame}

\begin{frame}{Comparação de desempenho - Tempo}
  \begin{figure}[h!]
    \centering
    \caption{Tempo de execução dos algoritmos do fluxo de potência.}
    \includegraphics[scale=0.5]{img/tempo}
    \label{fig:tempo}

    \small Fonte: Autoria própria.
  \end{figure}
\end{frame}

\begin{frame}{Comparação de desempenho - Iterações}
  \begin{figure}[h!]
    \centering
    \caption{Número de iterações necessárias para convergência dos sistemas de teste.}
    \includegraphics[scale=0.5]{img/itera}
    \label{fig:itera}

    \small Fonte: Autoria própria.
  \end{figure}
\end{frame}

\begin{frame}{Sistemas reduzidos}
    \begin{table}[h]
      \centering
      \caption{Barras removidas.}
      \begin{tabular}{cccc}
        \toprule
        \multicolumn{1}{c}{\textbf{Sistema original}} & \textbf{Barras} & \multicolumn{1}{c}{\textbf{Sistema reduzido}} & \multirow{ 2}{*}{\textbf{Redução [\%]}} \\
        \multicolumn{1}{c}{\textbf{[barras]}}& \textbf{removidas} & \multicolumn{1}{c}{\textbf{[barras]}} & \\
        \midrule
        14		& 0    & 14  & 0 \\
        34		& 5    & 29  & 14,7 \\
        70		& 18   & 52  & 25,7 \\
        136		& 24   & 112 & 17,6 \\
        793		& 428  & 365 & 54,0 \\
        3373  & 2748 & 625 & 81,5 \\
        \bottomrule
      \end{tabular}
      \label{tab:tempootm}

      \small Fonte: Autoria própria.
    \end{table}
\end{frame}

\begin{frame}{Comparação de desempenho com redução - Tempo}
  \begin{figure}[h!]
    \centering
    \caption{Tempo de execução dos algoritmos do fluxo de potência.}
    \includegraphics[scale=0.5]{img/tempootm}
    \label{fig:tempootm}

    \small Fonte: Autoria própria.
  \end{figure}
\end{frame}

\begin{frame}{Comparação de desempenho com redução - Iterações}
  \begin{figure}[h!]
    \centering
    \caption{Número de iterações necessárias para convergência dos sistemas de teste.}
    \includegraphics[scale=0.5]{img/iteraotm}
    \label{fig:iteraotm}

    \small Fonte: Autoria própria.
  \end{figure}
\end{frame}

\begin{frame}{Erro introduzido pela expansão - Monofásico}
  Não há variação nos resultados para os sistemas monofásicos.
\end{frame}

\begin{frame}{Erro introduzido pela expansão - Trifásico}
  \small
\begin{table}[h]
  \centering
  \caption{Erro devido a expansão do sistema reduzido (34 barras).}
  \begin{tabular}{ccccc}
    \toprule
    \multirow{2}{*}{\textbf{Fase}} & \multirow{2}{*}{$ \mathbf{Erro_{máx}^{MSC}\,[V]} $} & \multirow{2}{*}{$ \mathbf{Erro_{máx}^{MSP}\,[V]} $} & $ \mathbf{Erro_{máx}^{MSC}} $ \textbf{em} & $ \mathbf{Erro_{máx}^{MSP}} $ \textbf{em}\\
    &&& \textbf{relação a} $\mathbf{V_{base}}$ \textbf{[\%]}& \textbf{relação a} $\mathbf{V_{base}}$ \textbf{[\%]}\\
    \midrule
    $a$		& 127 & 362  & 0,88 & 2,52 \\
    $b$		& 235 & 2760 & 1,63 & 19,19 \\
    $c$		& 56  & 1.090& 0.39 & 7,58 \\
    \bottomrule
  \end{tabular}
  \label{tab:erro}

  \small Fonte: Autoria própria.
\end{table}
\normalsize
\end{frame}

\begin{frame}{\textit{QuickFlow}}
    \begin{figure}[H]
        \centering
        \caption{Programa \textit{QuickFlow} para projeto e análise de sistemas de distribuição de energia elétrica.}
        \includegraphics[scale=0.22]{img/quickflow}
        \label{fig:quickflow}
    \end{figure}
\end{frame}

\begin{frame}{\textit{QuickFlow}}
    \begin{figure}[H]
        \begin{itemize}
            \item Permite a criação, importação e modificação de sistemas de distribuição energia elétrica trifásicos.

            \item Possibilita o trabalho com várias unidades (metro, kilometro, pés, milhas e etc.).

            \item Permite trabalhar com múltiplos alimentadores.

            \item Realiza o cálculo do fluxo de potência utilizando os dois métodos citados anteriormente.

            \item Aplica a otimização por redução de barras para agilizar os cálculos (em desenvolvimento).

            \item Possui código fonte aberto. Está disponível em \href{http://www.github.com/DKrepsky/QuickFlow}{GitHub/QuickFlow}.

        \end{itemize}
    \end{figure}
\end{frame}

\begin{frame}{Conclusão}
    Foi observado que os métodos de resolução do fluxo de potência, empregados no trabalho, se mostram bastante robustos em relação à convergência. O desempenho dos mesmos é satisfatório, sendo necessário poucos milissegundos, em um computador de uso pessoal, para o cálculo dos parâmetros em sistemas compostos por milhares de barras.

    Em relação a comparação entre os métodos, foi possível observar um melhor desempenho do método da soma das potências, porém, o mesmo não o acoplamento entre as linhas, nos sistemas trifásicos.

    A redução de barras demonstrou uma melhora considerável no desempenho dos algoritmos do fluxo de potência, porém, em sistemas trifásicos, foi produzido um erro significativo para o método MSP.

    Quanto a \textit{interface} gráfica, a mesma se mostrou bastante útil na análise de sistemas de distribuição de energia elétrica, agilizando a avaliação dos resultados e o teste com sistemas diferentes.
\end{frame}

\begin{frame}{Considerações finais}
    O trabalho desenvolvido é um passo inicial no desenvolvimento de uma ferramenta para análise do fluxo de potência. Assim, há a possibilidade de explorar uma grande quantidade de outros algoritmos, tanto de cálculo, como de formas de otimização para o fluxo de potência.
    Uma outra possibilidade é a integração de métodos para o calculo do fluxo de potência ótimo, o qual encontra o melhor estado de operação da rede, de modo a minimizar o custo do kilowatt hora entregue ao consumidor final.
\end{frame}

\begin{frame}[allowframebreaks]

  \frametitle{Referências}

  \bibliography{referencias}
  \bibliographystyle{plain}

\end{frame}

\plain{Muito Obrigado!}

\plain{Perguntas?}

\end{document}


text:
using System;
#if !BRIDGE
using System.Xml;
#endif

namespace XmlBuddy
{
	public abstract class XmlObject
	{
#if !BRIDGE
		public virtual void ParseXmlNode(XmlNode node)
		{
			//what is in this node?
			throw new XmlException(string.Format("Unknown xml node passed to {0}: \"{1}\"", GetType(), node.Name));
		}

		/// <summary>
		/// write this dude out to file
		/// </summary>
		/// <param name="xmlWriter"></param>
		public abstract void WriteXmlNodes(XmlTextWriter xmlWriter);
#endif
	}
}


text:
package com.wonderpush.sdk;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import java.util.HashMap;

public class PromptActivity extends Activity {

    interface Callback {
        void onAccept();
        void onReject(boolean fallbackToSettings);
    }

    private static final int DELAY_TIME_CALLBACK_CALL = 500;
    private static final int WONDERPUSH_PERMISSION_REQUEST_CODE = 2;

    private static boolean waiting, fallbackToSettings, askNoMore;

    private static final String INTENT_EXTRA_PERMISSION_TYPE = "INTENT_EXTRA_PERMISSION_TYPE";
    private static final String INTENT_EXTRA_ANDROID_PERMISSION_STRING = "INTENT_EXTRA_ANDROID_PERMISSION_STRING";
    private static final String INTENT_EXTRA_CALLBACK_CLASS = "INTENT_EXTRA_CALLBACK_CLASS";

    private String permissionRequestType;

    private String androidPermissionString;

    private static final HashMap<String, Callback> callbackMap = new HashMap<>();

    public static void registerCallback(
            @NonNull String permissionType,
            @NonNull Callback callback
    ) {
        callbackMap.put(permissionType, callback);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleExtras(getIntent().getExtras());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleExtras(intent.getExtras());
    }

    private void handleExtras(Bundle extras) {
        if (Build.VERSION.SDK_INT < 23) {
            finish();
            overridePendingTransition(R.anim.wonderpush_fade_in, R.anim.wonderpush_fade_out);
            return;
        }

        registerCallbacks(extras);

        permissionRequestType = extras.getString(INTENT_EXTRA_PERMISSION_TYPE);
        androidPermissionString = extras.getString(INTENT_EXTRA_ANDROID_PERMISSION_STRING);
        requestPermission(androidPermissionString);
    }

    // Required if the app was killed while this prompt was showing
    private void registerCallbacks(Bundle extras) {
        String className = extras.getString(INTENT_EXTRA_CALLBACK_CLASS);
        try {
            // Loads class into memory so it's static initialization block runs
            Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not find callback class: " + className);
        }
    }

    private void requestPermission(String androidPermissionString) {
        if (!waiting) {
            waiting = true;
            askNoMore = !ActivityCompat.shouldShowRequestPermissionRationale(PromptActivity.this, androidPermissionString);
            ActivityCompat.requestPermissions(this, new String[]{androidPermissionString}, WONDERPUSH_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull String permissions[], @NonNull final int[] grantResults) {
        waiting = false;

        if (requestCode == WONDERPUSH_PERMISSION_REQUEST_CODE) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;

                    Callback callback = callbackMap.get(permissionRequestType);
                    if (callback == null)
                        throw new RuntimeException("Missing handler for request type: " + permissionRequestType);

                    if (granted)
                        callback.onAccept();
                    else {
                        callback.onReject(showSettings());
                    }
                }
            }, DELAY_TIME_CALLBACK_CALL);
        }

        finish();
        overridePendingTransition(R.anim.wonderpush_fade_in, R.anim.wonderpush_fade_out);
    }

    private boolean showSettings() {
        return fallbackToSettings
                && askNoMore
                && !ActivityCompat.shouldShowRequestPermissionRationale(PromptActivity.this, androidPermissionString);
    }

    static void prompt(
            boolean fallbackCondition,
            String permissionRequestType,
            String androidPermissionString,
            Class<?> callbackClass
    ) {
        if (PromptActivity.waiting)
            return;

        fallbackToSettings = fallbackCondition;
        Activity activity = ActivityLifecycleMonitor.getCurrentActivity();
        if (activity != null && !activity.getClass().equals(PromptActivity.class)) {
            Intent intent = new Intent(activity, PromptActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            intent.putExtra(INTENT_EXTRA_PERMISSION_TYPE, permissionRequestType)
                    .putExtra(INTENT_EXTRA_ANDROID_PERMISSION_STRING, androidPermissionString)
                    .putExtra(INTENT_EXTRA_CALLBACK_CLASS, callbackClass.getName());
            activity.startActivity(intent);
            activity.overridePendingTransition(R.anim.wonderpush_fade_in, R.anim.wonderpush_fade_out);
        } else {
            Log.w(WonderPush.TAG, "Could not start permission activity, probably because you are calling subscribeToNotifications too early, like the onCreate() method of your Application class. You must wait to have an activity resumed before calling this method.");
        }
    }
}


text:
module Homura
  class InstallGenerator < Rails::Generators::Base
    source_root File.expand_path('../templates', __FILE__)

    def copy_locale_file
      template 'layout.en.yml.erb', 'config/locales/layout.en.yml'
    end

    def copy_layout_file
      copy_file 'application.html.slim',
                'app/views/layouts/application.html.slim'
    end

    def app_name
      Rails.root.split.last.to_s.titleize
    end
  end
end


text:
'use strict';

module.exports = function () {
	var fromCodePoint = String.fromCodePoint;
	if (typeof fromCodePoint !== 'function') return false;
	return fromCodePoint(0x1D306, 0x61, 0x1D307) === '\ud834\udf06a\ud834\udf07';
};


text:
package org.apache.tephra.rpc;

/**
 * Defines lifecycle interface for all rpc handlers.
 */
public interface RPCServiceHandler {

  void init() throws Exception;

  void destroy() throws Exception;
}


text:
namespace gpdxl
{
//---------------------------------------------------------------------------
//	@class:
//		CDXLLogicalSelect
//
//	@doc:
//		Class for representing DXL Logical Select operators
//
//---------------------------------------------------------------------------
class CDXLLogicalSelect : public CDXLLogical
{
private:
	// private copy ctor
	CDXLLogicalSelect(CDXLLogicalSelect &);

public:
	// ctor/dtor
	explicit CDXLLogicalSelect(CMemoryPool *);

	// accessors
	Edxlopid GetDXLOperator() const;
	const CWStringConst *GetOpNameStr() const;

	// serialize operator in DXL format
	virtual void SerializeToDXL(CXMLSerializer *xml_serializer,
								const CDXLNode *dxlnode) const;

	// conversion function
	static CDXLLogicalSelect *
	Cast(CDXLOperator *dxl_op)
	{
		GPOS_ASSERT(NULL != dxl_op);
		GPOS_ASSERT(EdxlopLogicalSelect == dxl_op->GetDXLOperator());

		return dynamic_cast<CDXLLogicalSelect *>(dxl_op);
	}

#ifdef GPOS_DEBUG
	// checks whether the operator has valid structure, i.e. number and
	// types of child nodes
	void AssertValid(const CDXLNode *, BOOL validate_children) const;
#endif	// GPOS_DEBUG
};
}  // namespace gpdxl
#endif	// !GPDXL_CDXLLogicalSelect_H

// EOF


text:
#include <set>
#include <iostream>

#include "exception.h"
#include "meshskeleton.h"

REMESHER_NAMESPACE_BEGIN

void
MeshSkeleton::extract (void)
{
  if (this->features.get() == 0)
    throw Exception("MeshSkeleton: No features set");
  if (this->vinfo.get() == 0)
    throw Exception("MeshSkeleton: No vertex info set");

  this->clear();
  this->num_closed = 0;
  this->num_open = 0;

  /*
   * Strategy is as follows:
   * - Find a feature edge E not yet "consumed"
   * - Initially mark backbone as closed
   * - Remember first edge
   * - Iterate...
   *   - First check if second vertex of E is inner-edge
   *   - If not inner-edge, mark backbone as open, set resume flag
   *   - If inner-edge but second vertex equals remembered edge, bail out
   *   - Add the vertex at the end of the backbone list, consume edge
   *   - Advance edge in direction of the second vertex
   * - If resume flag is set, restart with first edge and reverse iterate
   *   - During that pass, push vertices to the front of the backbone
   */

  /* Create a copy of the feature edges for consumption. */
  FeatureEdgesPtr edge_pool(this->features->create_copy());

  /* Start finding a not-yet consumed feature edge. */
  for (std::size_t i = 0; i < this->features->size(); ++i)
  {
    FeatureVertexEdges& edges = this->features[i];
    for (std::size_t j = 0; j < edges.size(); ++j)
      if (edge_pool->is_feature_edge(i, edges[j]))
        this->collect(FeatureEdge(i, edges[j]), edge_pool);
  }
}

/* ---------------------------------------------------------------- */

void
MeshSkeleton::collect (FeatureEdge edge, FeatureEdgesPtr pool)
{
  /* Create a new backbone. */
  this->push_back(MeshBackbone());
  MeshBackbone& b = this->back();
  b.closed = true;
  b.verts.push_back(edge.first);

  FeatureEdge iter = edge;
  while (true)
  {
    /* Insert current (second) vertex. */
    if (b.closed)
      b.verts.push_back(iter.second);
    else
      b.verts.push_front(iter.second);

    /* Consume edge. */
    pool->rm_feature_edge(iter.first, iter.second);

    /* Advance edge. */
    bool has_next = this->advance_edge(iter);

    /* If there's no next edge during reverse mode, it's done. */
    if (!has_next && !b.closed)
      break;

    /* On a corner vertex, mark backbone as open and reverse. */
    if (!has_next)
    {
      b.closed = false;
      iter.first = edge.second;
      iter.second = edge.first;
      b.verts.pop_front();
      continue;
    }

    /* If walked around a closed backbone, bail out. */
    if (iter.second == edge.first)
    {
      pool->rm_feature_edge(iter.first, iter.second);
      break;
    }
  }

  if (b.closed)
    this->num_closed += 1;
  else
    this->num_open += 1;
}

/* ---------------------------------------------------------------- */

bool
MeshSkeleton::advance_edge (FeatureEdge& edge) const
{
  std::size_t i = edge.first;
  std::size_t j = edge.second;

  FeatureVertexEdges const& edges = this->features->get_edges_for_vertex(j);

  /* If it's a corner vertex, indicate that there is no next edge. */
  if (edges.size() != 2)
    return false;

  edge.first = j;
  edge.second = (i == edges[0] ? edges[1] : edges[0]);

  if (this->max_angle != 0)
  {
    MeshVertexList const& verts = this->mesh->get_vertices();
    Vec3f const v[3] = { verts[i], verts[j], verts[edge.second] };
    Vec3f const e[2] = { v[1] - v[0], v[2] - v[1] };
    float cosangle = e[0].scalar(e[1]) / std::sqrt
        (e[0].qlength() * e[1].qlength());
    if (cosangle < std::cos(this->max_angle))
        return false;
  }

  return true;
}

/* ---------------------------------------------------------------- */

std::size_t
MeshSkeleton::get_corner_amount (void) const
{
  /* Collect start and end vertex of each open backbone (no dups!). */
  std::set<std::size_t> corners;
  for (std::size_t i = 0; i < this->size(); ++i)
  {
    if (!this->at(i).closed)
    {
      corners.insert(this->at(i).verts.front());
      corners.insert(this->at(i).verts.back());
    }
  }
  return corners.size();
}

/* ---------------------------------------------------------------- */

void
MeshSkeleton::debug_print (void) const
{
  typedef std::list<std::size_t>::const_iterator VertexIter;
  for (std::size_t i = 0; i < this->size(); ++i)
  {
    MeshBackbone const& b(this->at(i));
    std::cout << (b.closed ? "Closed" : "Open") << " backbone: ";
    for (VertexIter j = b.verts.begin(); j != b.verts.end(); ++j)
      std::cout << *j << " ";
    std::cout << std::endl;
  }
}

REMESHER_NAMESPACE_END


text:
package ninja.metrics;

import com.codahale.metrics.MetricRegistry;

/**
 * Responsible for managing the Ninja Metrics module.
 *
 * @author James Moger
 */
public interface MetricsService {

    String METER_ALL_REQUESTS = "ninja.requests.allRequests";
    String COUNTER_ACTIVE_REQUESTS = "ninja.requests.activeRequests";
    String METER_BAD_REQUESTS = "ninja.requests.badRequests";
    String METER_INTERNAL_SERVER_ERRORS = "ninja.requests.internalServerErrors";
    String METER_ROUTES_NOT_FOUND = "ninja.requests.routesNotFound";

    /**
     * Start the Ninja Metrics service.
     */
    void start();

    /**
     * Stops the Ninja Metrics service.
     */
    void stop();

    /**
     * Returns the metric registry.
     *
     * @return the metric registry
     */
    MetricRegistry getMetricRegistry();

    /**
     * Returns the hostname of the server.
     *
     * @return the hostname
     */
    String getHostname();
}


text:
import moment from 'moment';

import runInParallel from './runInParallel';
import CLIError from '../util/CLIError';
import pluralize from '../util/pluralize';
import momentPreciseDiff from '../util/momentPreciseDiff';

/**
 * Run the given command in parallel, showing a progress bar of results.
 *
 * The provided async function should return an object that at least contains
 * a field called "error" that is truthy if there was a problem, but may contain
 * any other fields.
 */
export default async function runWithProgressBar(
    config, description, files, asyncFn, {runInSeries, allowFailures}={}) {
  let numProcessed = 0;
  let numFailures = 0;
  let numTotal = files.length;
  let startTime = moment();
  let numConcurrentProcesses = runInSeries ? 1 : config.numWorkers;
  console.log(`${description} (${pluralize(numConcurrentProcesses, 'worker')})`);
  let results;
  try {
    results = await runInParallel(files, asyncFn, numConcurrentProcesses, ({result}) => {
      if (result && result.error) {
        if (!allowFailures) {
          throw new CLIError(`Error:\n${result.error}`);
        }
        numFailures++;
      }
      numProcessed++;
      let errorString = numFailures === 0 ? '' : ` (${pluralize(numFailures, 'failure')} so far)`;
      process.stdout.write(`\r${numProcessed}/${numTotal}${errorString}`);
    });
  } finally {
    process.stdout.write('\n');
    let endTime = moment();
    let diffStr = momentPreciseDiff(startTime, endTime) || '0 seconds';
    console.log(`Finished in ${diffStr} (Time: ${moment().format()})`);
  }
  return results;
}


text:
	//variable qui permet de charger une instance Sig différente à chaque éxecution
	var SigLoader = new Array();

		SigLoader.getSig = function (){

			this.Sig = new Array();

			this.Sig.map = null;
			this.Sig.markersLayer = "";
			this.Sig.tileLayer = null;
			this.Sig.geoJsonCollection = "";

			this.Sig.initParameters = "";

			this.Sig.cssModuleName = "";

			this.Sig.currentFilter = "none";

			this.Sig.icoMarkersTypes = {}; //definition dans map_initializar.js
			this.Sig.icoMarkersTags = {}; //definition dans map_initializar.js

			//mémorise les identifiants des éléments de chaque carte
			this.Sig.listId = new Array();
			this.Sig.listPanel = new Array();
			this.Sig.listPanel.tags = new Array();
			this.Sig.listPanel.types = new Array();

			this.Sig.panelFilter = "all";
			this.Sig.panelFilterType = "all";
			this.Sig.dataMap = {};

			//mémorise les éléments
			this.Sig.elementsMap = new Array();

			//##
			//créer un marker sur la carte, en fonction de sa position géographique
			this.Sig.markerSingleList = new Array();
			this.Sig.popupOpen = false;
			this.Sig.currentMarkerPopupOpen = null;

			this.Sig.mapPolygon = null;
			this.Sig.markerFindPlace = null;

			//##
			//créé une donnée GeoJson (pour les cluster)
			this.Sig.getGeoJsonMarker = function (properties/*json*/, coordinates/*array[lat, lng]*/)
			{
				//console.warn("--------------- getGeoJsonMarker ---------------------");
				properties.visible = false;
				//alert(JSON.stringify(properties));
				return { "type": 'Feature',
						 "properties": properties,
						 "geometry": { type: 'Point',
									 coordinates: coordinates } };
			};

			//##
			//créé un objet L.Marker (sans cluster)
			this.Sig.getMarkerSingle = function(thisMap, options, coordinates)
			{
				//console.warn("--------------- getMarkerSingle ---------------------");
				var thisSig = this;
				var contentString = options.content;
				if(options.content == null) contentString = "";

				var markerOptions = { icon : options.icon };
				if(typeof options.zIndexOffset != "undefined")
					markerOptions["zIndexOffset"] = options.zIndexOffset;

				//console.log("POPUP CONTENT : " + contentString);
				var marker = L.marker(coordinates, markerOptions)
								.addTo(thisMap)
								.bindPopup(contentString);

				this.markerSingleList.push(marker);

				marker.on('click', function(e) {
						marker.openPopup();
						//Sig.markerToBounce = marker;
						//Sig.bounceMarker(0);
						//https://github.com/hosuaby/Leaflet.SmoothMarkerBouncing : bounce pluggin
						thisSig.currentMarkerPopupOpen = this;
				});
				marker.on('mouseover', function(e) {
					if(thisSig.map.getZoom() != thisSig.map.getMaxZoom()){
						marker.openPopup();

						//Sig.markerToBounce = marker;
						//Sig.bounceMarker(0);
						//https://github.com/hosuaby/Leaflet.SmoothMarkerBouncing : bounce pluggin
						thisSig.currentMarkerPopupOpen = this;
					}
				});
				return marker;
			};

			this.Sig.timerbounce = null;
			// EXEMPLE :
			// Sig.bounceMarker(0, { duration: 500, 	//va effectuer un saut pendant 500 miliemes de secondes
			// 				  height: 15,				//d'une hauteur de 15px
			// 				  interval: 2000,			//toutes les 2 secondes
			// 				  occurence:5 });			//5 fois de suite
			this.Sig.bounceMarker = function(i, options){
				//Sig.markerToBounce.bounce({duration: 500, height: 30});
				if(typeof Sig.markerToBounce === "undefined" || Sig.markerToBounce === null) {
					if(typeof this.timerbounce != "undefined")
						clearTimeout(this.timerbounce);
					return;
				}

				i++;
				//console.log(i);
				if(i < options.occurence){
					this.timerbounce = setTimeout(function(){
						if(typeof Sig.markerToBounce != "undefined" && Sig.markerToBounce != null){
							Sig.markerToBounce.bounce({duration: options.duration, height: options.height});
							Sig.bounceMarker(i, options);
						}
					}, options.interval);
				}else{
					clearTimeout(this.timerbounce);
				}
			};

			//##
			//récupère le nom de l'icon en fonction du type de marker souhaité
			this.Sig.getIcoMarkerMap = function(thisData)
			{
				//console.warn("--------------- getIcoMarker *** ---------------------");
				//console.log(thisData);
				if(typeof thisData.author != "undefined") thisData = thisData.author;

				this.allowMouseoverMaker = true;

				var markerName = this.getIcoNameByType(thisData);
				var iconUrl = assetPath+'/images/sig/markers/'+markerName+'.png';
				// console.log(assetPath);
				if(typeof thisData.profilMarkerImageUrl !== "undefined" && thisData.profilMarkerImageUrl != "")
					//Attention commenté par Childé pour livraison car plus d'image sur la carte du module network
					//iconUrl = baseUrl + thisData.profilMarkerImageUrl;
					// console.log(iconUrl);
				return L.icon({
				    iconUrl: iconUrl,
				    iconSize: [53, 60], //38, 95],
				    iconAnchor: [27, 57],//22, 94],
				    popupAnchor: [0, -55]//-3, -76]
				});
			};

			this.Sig.getIcoMarker = function(thisData)
			{
				//console.warn("--------------- getIcoMarker ---------------------");
				var ico = this.getIcoNameByType(thisData);
				var color = this.getIcoColorByType(thisData);

				return L.AwesomeMarkers.icon({icon: ico + " fa-" + color, iconColor:color, prefix: 'fa' });
			};

			//##
			//supprime tous les marker de la carte
			this.Sig.clearMap = function(thisMap, showMe)
			{
				if(typeof showMe == "undefined") showMe = true;

				console.warn("--------------- clearMap ---------------------");
				if(this.markersLayer != "")
					this.markersLayer.clearLayers();

				if(typeof this.myMarker != "undefined")
					this.map.removeLayer(this.myMarker);

				if(this.markerModifyPosition != null)
					this.map.removeLayer(this.markerModifyPosition);

				var thisSig = this;
				if(this.markerSingleList != null)
				$.each(this.markerSingleList, function(){
					thisSig.map.removeLayer(this);
				});

				this.clearPolygon();

				this.listId = new Array();
				this.elementsMap = new Array();
				this.changePagination(1);

				$( this.cssModuleName + " #liste_map_element").html("");

				showMe = false;
				if(showMe)
				this.showMyPosition();

			};

			//##
			//supprime tous les marker de la carte et prépare pour recharger de nouvelles données
			this.Sig.restartMap = function(thisMap)
			{
				//supprime les item panel (sauf all)
				$.each($(this.cssModuleName + " .item_panel_map"), function(){
					if($(this).attr("id") != "item_panel_map_all" && $(this).attr("id") != "item_panel_filter_all")
						$(this).remove();
				});
				$(this.cssModuleName + " #liste_map_element").html();

				this.listPanel.tags = new Array();
				this.listPanel.types = new Array();
				this.panelFilter = "all";
				this.panelFilterType = "all";
				this.clearMap(thisMap);
				this.currentMarkerPopupOpen = null;
			};

			this.Sig.showMyPosition = function(){
				var thisSig = this;
				if(thisSig.myPosition != null){
					//console.log("MYPOSITION !!");
					//console.dir(thisSig.myPosition);
					var center = [thisSig.myPosition.position.latitude,
								  thisSig.myPosition.position.longitude];

					var popup = Sig.getPopupSimple(Sig.userData);
					var properties = { 	id : "0",
										icon : thisSig.getIcoMarkerMap(thisSig.myPosition),
										type : thisSig.myPosition["type"],
										typeSig : thisSig.myPosition["typeSig"],
										faIcon : this.getIcoByType(thisSig.myPosition),
										zIndexOffset: 10000,
										content: popup };

					if(typeof thisSig.myMarker != "undefined") thisSig.map.removeLayer(thisSig.myMarker);
					thisSig.myMarker = thisSig.getMarkerSingle(thisSig.map, properties, center);
					thisSig.createItemRigthListMap(thisSig.userData, thisSig.myMarker, thisSig.map);

					var objectId = thisSig.getObjectId(thisSig.userData);
					this.listId = new Array(objectId);

					$(this.cssModuleName + " .item_map_list_" + objectId).click(function()
					{	thisSig.map.panTo(center, {"animate" : true });
						thisSig.checkListElementMap(thisSig.map);
						thisSig.myMarker.openPopup();
					});

					$( "#btn-home" ).off().click(function (){
							thisSig.map.setView(center, 16);
					});
					$( ".btn-home" ).off().click(function (){
							thisSig.centerSimple(center, 16);
					});
				}
			}
			//gère les dimensions des différentes parties de la carte (carte, panel, etc) en mode full screen
			this.Sig.setFullScreen = function()
			{
				////console.warn("--------------- setFullScreen ---------------------");
				//full screen map
				var mapHeight = $(".subviews.subviews-top").height();// - $(".toolbar").height();
				var rightListHeight = mapHeight - 110;

				$("#mapCanvas" + this.sigKey).css({"height":mapHeight});
				//alert(mapHeight);
				$("#mapCanvas" + this.sigKey).css({"margin-bottom":mapHeight*(-1)});
				$(this.cssModuleName + " #right_tool_map").css({"height":rightListHeight+25});

				$(this.cssModuleName + " #liste_map_element").css({"height":rightListHeight - $(this.cssModuleName + " #map_pseudo_filters").height() - 8*2 /*padding*/ - $(this.cssModuleName + " #chk-scope").height() - 33 });
				$(this.cssModuleName + " #liste_map_element").css({"max-height":rightListHeight - $(this.cssModuleName + " #map_pseudo_filters").height() - 8*2 /*padding*/ - $(this.cssModuleName + " #chk-scope").height() - 33  });

				$(this.cssModuleName + " #right_tool_map").css(		{"left":$("#mapCanvas" + this.sigKey).width() - $("#right_tool_map").width() - 20 });// - $(this.cssModuleName + " #right_tool_map").width()});
				$(this.cssModuleName + " .input-search-place").css( {"left":$("#mapCanvas" + this.sigKey).width() - $("#right_tool_map").width() - $(this.cssModuleName + " #right_tool_map").width() - 20});// - $(this.cssModuleName + " #right_tool_map").width()});

				$(this.cssModuleName + " .panel_map").css({"max-height":rightListHeight - 8*2 /*padding*/ - 33 });

			};

			//gère les dimensions des différentes parties de la carte (carte, panel, etc) en mode normal
			this.Sig.setNoFullScreen = function()
			{
				var mapHeight = this.initParameters.mapHeight;
				var rightListHeight = mapHeight - 100;

				var left = $(this.cssModuleName + " #right_tool_map").position().left - $(this.cssModuleName + " .input-search-place").width() - 20;
				$(this.cssModuleName + " .input-search-place")	.css({"left": left});// - $(this.cssModuleName + " #right_tool_map").width()});
			};

			//gère les dimensions des différentes parties de la carte (carte, panel, etc) en mode normal
			this.Sig.setFullPage = function()
			{
				var mapHeight = $("#mapCanvasBg").height();
				var rightPanelHeight = mapHeight - 140;

				$(this.cssModuleName + " #right_tool_map").css({"height":rightPanelHeight});
				$(this.cssModuleName + " #liste_map_element").css({"height":rightPanelHeight-100});
				$(this.cssModuleName + " #liste_map_element").css({"maxHeight":rightPanelHeight-100});

				$(this.cssModuleName + " .panel_map").css({"max-height":rightPanelHeight - 8*2 /*padding*/ - 45 });

				$(this.cssModuleName + " .tools-btn").css(
					{"left":$("#mapCanvas" + this.sigKey).width() -
					$("#right_tool_map").width() -
					$(this.cssModuleName + " .tools-btn").width() - 20});// - $(this.cssModuleName + " #right_tool_map").width()});

				$(this.cssModuleName + " .input-search-place").css( {"left":90} );

				var left = $(this.cssModuleName + " .tools-btn").position().left;
				var top = $(this.cssModuleName + " .btn-group-map").position().top + $(this.cssModuleName + " #btn-filter").height();

			};

			//modifie la position et la forme des éléments de l'interface de facon dynamique
			this.Sig.constructUI = function()
			{

				if(this.initParameters.useFullScreen){
					this.setFullScreen();
				}
				else{
					this.setNoFullScreen();
				}

				if(this.initParameters.useFullPage){ this.setFullPage(); }

			}

			this.Sig.verifyPanelFilter = function (thisData){
				//console.warn("--------------- verifyPanelFilter ---------------------");

				if(this.panelFilter == "all") return true;

				var thisSig = this;
				//console.log("PANELFILTER" + this.panelFilterType);
				if(this.panelFilterType == "tags" || this.panelFilterType == "all"){
					if(this.usePanel == false) return true;
					//console.log(thisData["tags"] +"=="+ thisSig.panelFilter);

					//si thisData n'a pas de tags
					if("undefined" == typeof thisData["tags"]){
						return (this.panelFilter == "all");
					}

					var inArray = false;
					if(typeof thisData["tags"] != "undefined" && thisData["tags"] != null)
					$.each(thisData["tags"], function(index, value){
						if(value == thisSig.panelFilter) inArray = true;
					});

					if(	inArray //$.inArray(this.panelFilter, thisData["tags"]) > -1 //ne fonctionne pas
						||  this.panelFilter == "all") {
							return true;
					}
					else{ return false; }

				}

				if(this.panelFilterType == "types" || this.panelFilterType == "all"){
					if(this.useFilterType == false) return true;

					//si thisData n'a pas de tags
					if("undefined" == typeof thisData["type"] && "undefined" == typeof thisData["typeSig"]){
						return (this.panelFilter == "all");
					}
					if(		thisData["type"] == thisSig.panelFilter
						||  thisData["typeSig"] == thisSig.panelFilter
						||  this.panelFilter == "all") {
							return true;
					}
					else{ return false; }

				}
			};

			this.Sig.polygonsCollection = new Array();

			this.Sig.addPolygon = function(polygonPoints, options)
			{
				console.log("addPolygon");
				var poly = L.polygon(polygonPoints, {
										color: '#FFF',
										opacity:0.7,
										fillColor: '#71A4B4',
										fillOpacity:0.3,
										weight:'2px',
										smoothFactor:0.5}).addTo(this.map);

				this.polygonsCollection.push(poly);
			};

			this.Sig.clearPolygon = function()
			{
				var thisSig = this;
				$.each(this.polygonsCollection, function(key, poly){
					thisSig.map.removeLayer(poly);
				});
				this.polygonsCollection = new Array();
			};

			this.Sig.showPolygon = function(polygonPoints, options)
			{
				console.log("showPolygon");
				//console.dir(polygonPoints);
				//si le polygone existe déjà on le supprime
				if(this.mapPolygon != null) this.map.removeLayer(this.mapPolygon);
				//puis on charge le nouveau polygone
				this.mapPolygon = L.polygon(polygonPoints, {
										color: '#FFF',
										opacity:0.7,
										fillColor: '#71A4B4',
										fillOpacity:0.3,
										weight:'2px',
										smoothFactor:0.5}).addTo(this.map);
			};

			this.Sig.inversePolygon = function(polygon){
				var inversedPoly = new Array();
				console.log("inversePolygon");
				if(typeof polygon != "undefined" && polygon != null){
					$.each(polygon, function(key, value){
						var lat = value[0];
						var lng = value[1];
						inversedPoly.push(new Array(lng, lat));
					});
				}
				console.dir(inversedPoly);
				return inversedPoly;
			};

			this.Sig.getCoordinates = function(thisData, type)
			{
				//console.warn("--------------- getCoordinates ---------------------");
				//console.dir(thisData);
				//si la donnée est une news, on doit afficher la position de l'auteur
				if( typeof thisData.typeSig !== "undefined"){
					if(thisData.typeSig == "news" && typeof thisData.author !== "undefined"){
						thisData = thisData.author;
					}
				}

				if( typeof thisData.geo !== "undefined" && thisData.geo != null && typeof thisData.geo.longitude !== "undefined"){
					if(type == "markerSingle")
						return new Array (thisData['geo'].latitude, thisData['geo'].longitude);
					else if(type == "markerGeoJson")
						return new Array (thisData['geo'].longitude, thisData['geo'].latitude);
				}
				else if(typeof thisData.geoPosition != "undefined"){
					if(type == "markerSingle"){
						var lat = thisData.geoPosition.coordinates[1];
						var lng = thisData.geoPosition.coordinates[0];
						return new Array (lat, lng);
					} else if(type == "markerGeoJson"){
						return thisData.geoPosition.coordinates;
					}
				}
				else if(typeof thisData.geometry != "undefined"){ //resultat search street on google map
					console.log("thisData.geometry ?");
					console.dir(thisData);
					if(type == "markerSingle"){
						if(typeof thisData.geometry.location != "undefined"){
							console.log(thisData.geometry.location.lat);
							var lat = thisData.geometry.location.lat;
							var lng = thisData.geometry.location.lng;
							console.dir(new Array (lat, lng));
							return new Array (lat, lng);
						}
					} else if(type == "markerGeoJson"){
						if(typeof thisData.geometry.location != "undefined"){
							var lat = thisData.geometry.location.lat;
							var lng = thisData.geometry.location.lng;
							return new Array (lng, lat);
						}
					}
				}
				else{
					return null;
				}
			};

			this.Sig.showOneElementOnMap = function(thisData, thisMap){
				//console.warn("--------------- showOneElementOnMap ---------------------");
				//console.dir(thisData);
				//var objectId = thisData._id ? thisData._id.$id.toString() : null;
				var objectId = this.getObjectId(thisData);
				//console.log("verify id : ", objectId);
				//if(thisData != null && thisData["type"] == "meeting") alert("trouvé !");
				// console.log(thisData);
				if(objectId != null)
				{
					if($.inArray(objectId, this.listId) == -1 || thisData.typeSig == "city")
					{
						if(("undefined" != typeof thisData['geo'] && thisData['geo'] != null) || ("undefined" != typeof thisData['geoPosition'] && thisData['geoPosition'] != null) ||
							("undefined" != typeof thisData['author'] && ("undefined" != typeof thisData['author']['geo'] || "undefined" != typeof thisData['author']['geoPosition']))) {
							if(this.verifyPanelFilter(thisData))
							{
								var type = (typeof thisData["typeSig"] !== "undefined") ? thisData["typeSig"] : thisData["type"];
								//préparation du contenu de la bulle
								var content = this.getPopup(thisData);
								//création de l'icon sur la carte
								var theIcon = this.getIcoMarkerMap(thisData);
								var properties = { 	id : objectId,
													icon : theIcon,
													type : thisData["type"],
													typeSig : type,
													name : thisData["name"],
													faIcon : this.getIcoByType(thisData),
													content: content };
								// console.log(properties);
								var marker;
								var coordinates;

								//si le tag de l'élément est dans la liste des éléments à ne pas mettre dans les clusters
								//on créé un marker simple
								//TODO : refactor notClusteredTag > notClusteredType

								if($.inArray(type, this.notClusteredTag) > -1){
									coordinates = this.getCoordinates(thisData, "markerSingle");
									marker = this.getMarkerSingle(thisMap, properties, coordinates);
								}
								//sinon on crée un nouveau marker pour cluster
								else {
									coordinates = this.getCoordinates(thisData, "markerGeoJson");
									marker = this.getGeoJsonMarker(properties, coordinates);
									this.geoJsonCollection['features'].push(marker);
								}

								if(thisData["type"] == "city"){
									//console.log("geoshapes ?");
									//console.dir(thisData);

									if(typeof thisData["geoShape"] != "undefined" && typeof thisData["geoShape"]["coordinates"] != "undefined"){
										var geoShape = Sig.inversePolygon(thisData["geoShape"]["coordinates"][0]);
										this.addPolygon(geoShape);
									}
								}

								this.elementsMap.push(thisData);
								this.listId.push(objectId);
								this.populatePanel(thisData, objectId); //["tags"]
								this.createItemRigthListMap(thisData, marker, thisMap);

								//ajoute l'événement click sur l'élément de la liste, pour ouvrir la bulle du marker correspondant
								//si le marker n'est pas dans un cluster (sinon le click est géré dans le .geoJson.onEachFeature)
								if($.inArray(type, this.notClusteredTag) > -1)
								$(this.cssModuleName + " .item_map_list_" + objectId).click(function()
								{	thisMap.panTo(coordinates, {"animate" : true });
									thisSig.checkListElementMap(thisMap);
									marker.openPopup();
								});
								//console.log("ok888");

							}
						}
						else{
							if(this.verifyPanelFilter(thisData) && typeof thisData.name != "undefined"){
								this.elementsMap.push(thisData);
								this.listId.push(objectId);
								this.populatePanel(thisData, objectId); //["tags"]
								this.createItemRigthListMap(thisData);
								$(this.cssModuleName + " .item_map_list_" + objectId).click(function(){
									//toastr.success('click on element not in map');
									//console.dir(thisData);
									thisSig.showModalItemNotLocated(thisData);
								});
							}
						}

					}

					//affiche les MEMBERS
					var thisSig = this;
					if(thisData.links != null)
						if(thisData.links.members != null){
							$.each(thisData.links.members, function(i, thisMember)  {
								thisMember._id = { $id : i };
								thisSig.showOneElementOnMap(thisMember, thisMap);
							});
						}

					}else {
						if(thisData == null) return false;

						//console.warn("--------------- PAS D'ID ---------------------");
						//console.dir(thisData);

						if("undefined" != typeof thisData["chartOptions"]){
							//console.warn("--------------- LOAD CHART ---------------------");
							this.addChart(thisData)
						}
						return false;
					}

			};

			this.Sig.showFilterOnMap = function(data, thisFilter, thisMap){
				//console.warn("--------------- showFilterOnMap ***%%% ---------------------");
				var thisSig = this;
				var dataFilter = (data != null) ? data[thisFilter] : thisFilter;	//alert(JSON.stringify(dataFilter));

				if($.isArray(dataFilter)){
					$.each(dataFilter, function(i, thisData)  {
						////console.warn("--------------- show each thisData ---------------------");
						////console.dir(thisData);

						thisSig.showOneElementOnMap(thisData, thisMap);
					});
				}
				else{
					thisSig.showOneElementOnMap(dataFilter, thisMap);
				}
			};

			this.Sig.showMapElements = function(thisMap, data)
			{
				console.warn("--------------- showMapElements ---------------------");
				// console.log(data);
				if(data == null) return;

				var filterPanelValue = "citoyens";
				//enregistre les dernières données dans une variable locale
				this.dataMap = data;
				//alert("datas : " + JSON.stringify(this.dataMap));
				//efface les elements de la carte si elle n'est pas vide
				if(this.markersLayer != "") this.clearMap(thisMap);

				//conteneur de marker cluster
				this.markersLayer = new L.MarkerClusterGroup({"maxClusterRadius" : 40});
				thisMap.addLayer(this.markersLayer);

				//collection de marker geojson
				this.geoJsonCollection = { type: 'FeatureCollection', features: new Array() };

				//this.showIcoLoading(true);

				//on affiche les data filtre par filtre
				var thisSig = this;
				//var array = new Array();

				var len = 0;

				$.each(data, function (key, value){ len++; });//alert("len : " + len);
				if(len >= 1){
					$.each(data, function (key, value){
						var oneData = key;
						if((value.typeSig == "news" || value.typeSig == "activityStream") && typeof value.author !== "undefined")
							oneData = key.author;
						thisSig.showFilterOnMap(data, key, thisMap);
					});

				}else{
					thisSig.showOneElementOnMap(data, thisMap);
				}

				var points = L.geoJson(this.geoJsonCollection, {				//Pour les clusters seulement :
						onEachFeature: function (feature, layer) {				//sur chaque marker
							layer.bindPopup(feature["properties"]["content"]); 	//ajoute la bulle d'info avec les données
							layer.setIcon(feature["properties"]["icon"]);	   	//affiche l'icon demandé
							layer.on('mouseover', function(e) {
								//si le mouseover n'est pas autorisé
								//ou si le zoom de la carte est = au zoom maximum (== ouverture cluster spiral)
								if(thisSig.allowMouseoverMaker == false  ||
								   thisSig.map.getZoom() == thisSig.map.getMaxZoom()) return;

								layer.openPopup();
								thisSig.currentMarkerPopupOpen = layer;
							});
							layer.on('click', function(e) {
								thisSig.currentMarkerPopupOpen = layer;
								thisMap.panTo(layer.getLatLng());
								layer.openPopup();

							});

							//au click sur un element de la liste de droite, on zoom pour déclusturiser, et on ouvre la bulle
							$(thisSig.cssModuleName + " .item_map_list_" + feature.properties.id).click(function(){
								thisSig.allowMouseoverMaker = false;
								var coordinates =  [feature.geometry.coordinates[1],
													feature.geometry.coordinates[0]];
								thisMap.panTo(coordinates, {"animate" : false });

								var visibleOne = null;
								if(typeof layer != "undefined")
									visibleOne = Sig.markersLayer.getVisibleParent(layer);

								if(typeof visibleOne != "undefined"){
									if(typeof visibleOne._childCount != "undefined"){
										var i = 0;
										while(typeof visibleOne._childCount != "undefined" && i<5){
											coordinates = visibleOne.getLatLng();
											thisMap.panTo(coordinates, {"animate" : false });
											visibleOne.fire("click");
											if(typeof layer != "undefined")
												visibleOne = Sig.markersLayer.getVisibleParent(layer);
											thisSig.currentParentToOpen = visibleOne;
											i++;
										}
									}
									else{
										if(typeof visibleOne._spiderLeg == "undefined")	{
											thisMap.fire("click");
											thisMap.setZoom(15, {"animate" : false });
											thisMap.panTo(coordinates, {"animate" : false });
											thisSig.currentParentToOpen = null;

										}
									}
								}
								thisSig.checkListElementMap(thisMap);
								thisSig.currentMarkerToOpen = layer;
								thisSig.currentMarkerPopupOpen = layer;
								setTimeout("Sig.openCurrentMarker()", 700);
							});
						}

					});
					////console.warn("--------------- showMapElements  onEachFeature OK ---------------------");

					this.markersLayer.addLayer(points); 		// add it to the cluster group
					thisMap.addLayer(this.markersLayer);		// add it to the map

					$('#ico_reload').removeClass("fa-spin");
					$('#ico_reload').css({"display":"none"});

					if(this.initParameters.usePanel)
						this.updatePanel(thisMap);

					this.checkListElementMap(thisMap);

					//console.log("fitBounds");
					//console.dir(this.markersLayer.getBounds());
					if("undefined" != typeof this.markersLayer.getBounds() &&
					   "undefined" != typeof this.markersLayer.getBounds()._northEast ){
						thisMap.fitBounds(this.markersLayer.getBounds(), { 'maxZoom' : 14 });
						thisMap.zoomOut();
					}

					thisSig.constructUI();

					this.showIcoLoading(false);

		};

		//##
		this.Sig.openCurrentMarker = function(){
			if(typeof this.currentParentToOpen != "undefined" && this.currentParentToOpen != null)
				this.currentParentToOpen.fire("click");

			if(typeof this.currentMarkerToOpen != "undefined" && this.currentMarkerToOpen != null)
				this.currentMarkerToOpen.openPopup();

			this.allowMouseoverMaker = true;
		};

		//##
		//##	LOAD MAP	##
		//##

		//##
		//chargement de la carte
	 	this.Sig.loadMap = function(canvasId, initParams)
	 	{

			console.warn("--------------- loadMap ---------------------");
			canvasId += initParams.sigKey;
			if(this.map == null){
				$("#"+canvasId).html("");
				$("#"+canvasId).css({"background-color": this.mapColor});

				//initialisation des variables de départ de la carte
				if(canvasId != "")
				var map = L.map(canvasId, { "zoomControl" : false,
											"scrollWheelZoom":true,
											"center" : [51.505, -0.09],
											"zoom" : 4,
											"worldCopyJump" : false });
			}else{
				var map = this.map;
			}
			//initialisation de l'interface
			Sig.initEnvironnement(map, initParams);
			if(canvasId == "") return;

			Sig.tileLayer = L.tileLayer(initParams.mapTileLayer, { //'http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png', {
				//attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
				attribution: 'Map tiles by ' + initParams.mapAttributions, //'Map tiles by <a href="http://stamen.com">Stamen Design</a>',
				//subdomains: 'abc',
				minZoom: 3,
				maxZoom: 20
			});

			Sig.tileLayer.setOpacity(initParams.mapOpacity).addTo(map);

			Sig.roadTileLayer = L.tileLayer('//stamen-tiles-{s}.a.ssl.fastly.net/toner-lines/{z}/{x}/{y}.{ext}', {
                            ext: 'png',
                            attribution: 'Tiles Courtesy of <a href="http://www.mapquest.com/">MapQuest</a> — Map data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
                            subdomains: 'abcd',
                            zIndex:2,
                            opacity: 0.7,
                            minZoom:12,
                            maxZoom: 20
                        });
            Sig.roadTileLayer.addTo(map);
			Sig.StamenTonerLabels = L.tileLayer('http://stamen-tiles-{s}.a.ssl.fastly.net/toner-labels/{z}/{x}/{y}.{ext}', {
                                    attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
                                    subdomains: 'abcd',
                                    opacity: 0.7,
                                    zIndex:3,
                                    minZoom: 12,
                                    maxZoom: 20,
                                    ext: 'png'
                                });
            Sig.StamenTonerLabels.addTo(map);
			//rafraichi les tiles après le redimentionnement du mapCanvas
			map.invalidateSize(false);
			return map;
		};

		//show a modal when an item in the right list has no geoLocation on the map
		this.Sig.showModalItemNotLocated = function(data){
			$("#modalItemNotLocated").modal('show');
			$("#modalItemNotLocated .modal-body").html("<i class='fa fa-spin fa-reload'></i>");

			var objectId = this.getObjectId(data);
			var popup = this.getPopupSimple(data);
			$("#modalItemNotLocated .modal-body").html(popup);
			$("#modalItemNotLocated #btn-open-details").click(function(){
				$("#popup"+objectId).click();
			});

			$("#modalItemNotLocated #popup"+objectId).click(function(){
				$("#modalItemNotLocated").modal('hide');
			});
		}

		this.Sig = this.getSigInitializer(this.Sig);

		console.log("load");

		this.Sig = this.getSigPanel(this.Sig);
		this.Sig = this.getSigRightList(this.Sig);
		this.Sig = this.getSigPopupContent(this.Sig);
		this.Sig = this.getSigFindPlace(this.Sig);
		this.Sig = this.getSigCharts(this.Sig);

		return this.Sig;
	};


text:
The [Cloud Native Computing Foundation](https://www.cncf.io/community) (CNCF) defines
the legal status of the contributed code in two different types of _Contributor License Agreements_
(CLAs), [individual contributors](https://github.com/cncf/cla/blob/master/individual-cla.pdf) and [corporations](https://github.com/cncf/cla/blob/master/corporate-cla.pdf).

Kubernetes can only accept original source code from CLA signatories.

This policy does not apply to [third_party](https://git.k8s.io/kubernetes/third_party)
and [vendor](https://git.k8s.io/kubernetes/vendor).

It is important to read and understand this legal agreement.

## How do I sign?

If your work is done as an employee of your company, contact your company's legal department and ask to be put on the list of approved contributors for the CNCF CLA. Below, we have included steps for "Corporation signup" in case your company does not have a company agreement and would like to have one.

#### 1. Log in to the Linux Foundation ID Portal with Github

Click one of:
  * [Individual signup](https://identity.linuxfoundation.org/projects/cncf) to
  sign up as an individual or as an employee of a signed organization.
  * [Corporation signup](https://identity.linuxfoundation.org/node/285/organization-signup)
  to sign as a corporation representative and manage signups from your organization.

Once you get to the sign in form, click "Log in with Github":

![CNCFCLA1](http://i.imgur.com/tEk2x3j.png)

#### 2. Create Linux Foundation ID Portal account with correct e-mail address

Ensure that the e-mail address you use when completing this form matches the one
you will use for your commits.

If you are signing up as an employee, you must use your official
person@organization.domain email address in the CNCF account registration page.

![CNCFCLA2](http://i.imgur.com/t3WAtrz.png)

#### 3. Complete signing process

After creating your account, follow the instructions to complete the
signing process through HelloSign.

If you did not receive an email from HelloSign, [then request it here](https://identity.linuxfoundation.org/projects/cncf).

#### 4. Ensure your Github e-mail address matches address used to sign CLA

Your Github email address __must match__ the same address you use when signing
the CLA. Github has [documentation](https://help.github.com/articles/setting-your-commit-email-address-on-github/)
on setting email addresses.

You must also set your [git e-mail](https://help.github.com/articles/setting-your-email-in-git)
to match this e-mail address as well.

If you already submitted a PR you can correct your user.name and user.email
and then use `git commit --amend --reset-author` and then `git push --force` to
correct the PR.

#### 5. Look for an email indicating successful signup.

> The Linux Foundation
>
> Hello,
>
> You have signed CNCF Individual Contributor License Agreement.
> You can see your document anytime by clicking View on HelloSign.
>

Once you have this, the CLA authorizer bot will authorize your PRs.

![CNCFCLA3](http://i.imgur.com/C5ZsNN6.png)

## Changing your Affiliation

If you've changed employers and still contribute to Kubernetes, your affiliation
needs to be updated. The Cloud Native Computing Foundation uses [gitdm](https://github.com/cncf/gitdm)
to track who is contributing and from where. Create a pull request on the [gitdm](https://github.com/cncf/gitdm)
repository with a change to the corresponding developer affiliation text file.
Your entry should look similar to this:

```
Jorge O. Castro*: jorge!heptio.com, jorge!ubuntu.com, jorge.castro!gmail.com
Heptio
Canonical until 2017-03-31
```

## Troubleshooting

If you encounter any problems signing the CLA, log a ticket with the Linux
Foundation ID group through the [Linux Foundation Support Site].

Should you have any issues using the LF Support Site, send a message to the
backup e-mail support address <login-issues@jira.linuxfoundation.org>

Someone from the CNCF will respond to your ticket to help.

## Setting up the CNCF CLA check

If you are a Kubernetes GitHub organization or repo owner and would like to setup
the Linux Foundation CNCF CLA check for your repositories, [read the docs on setting up the CNCF CLA check](/github-management/setting-up-cla-check.md)

[Linux Foundation Support Site]: https://support.linuxfoundation.org/


text:
using System;

namespace LWAS.Extensible.Exceptions
{
	public class MissingBindingElementException : Exception
	{
		private string _message;
		public override string Message
		{
			get
			{
				return this._message;
			}
		}
		public MissingBindingElementException(string missing)
		{
			this._message = string.Format("Binding cannot be performed. Missing {0}", missing);
		}
	}
}


text:
/**
 * Using Rails-like standard naming convention for endpoints.
 * GET     /api/assets              ->  index
 * POST    /api/assets              ->  create
 * GET     /api/assets/:id          ->  show
 * PUT     /api/assets/:id          ->  update
 * DELETE  /api/assets/:id          ->  destroy
 */

'use strict';

var _ = require('lodash');
var sqldb = require('../../sqldb');
var Asset = sqldb.Asset;

function handleError(res, statusCode) {
  statusCode = statusCode || 500;
  return function(err) {
    res.status(statusCode).send(err);
  };
}

function responseWithResult(res, statusCode) {
  statusCode = statusCode || 200;
  return function(entity) {
    if (entity) {
      res.status(statusCode).json(entity);
    }
  };
}

function handleEntityNotFound(res) {
  return function(entity) {
    if (!entity) {
      res.status(404).end();
      return null;
    }
    return entity;
  };
}

function saveUpdates(updates) {
  return function(entity) {
    return entity.updateAttributes(updates)
      .then(function(updated) {
        return updated;
      });
  };
}

function removeEntity(res) {
  return function(entity) {
    if (entity) {
      return entity.destroy()
        .then(function() {
          res.status(204).end();
        });
    }
  };
}

// Gets a list of Assets
exports.index = function(req, res) {
  Asset.findAll()
    .then(responseWithResult(res))
    .catch(handleError(res));
};

// Gets a single Asset from the DB
exports.show = function(req, res) {
  Asset.find({
    where: {
      _id: req.params.id
    }
  })
    .then(handleEntityNotFound(res))
    .then(responseWithResult(res))
    .catch(handleError(res));
};

// Creates a new Asset in the DB
exports.create = function(req, res) {
  Asset.create(req.body)
    .then(responseWithResult(res, 201))
    .catch(handleError(res));
};

// Updates an existing Asset in the DB
exports.update = function(req, res) {
  if (req.body._id) {
    delete req.body._id;
  }
  Asset.find({
    where: {
      _id: req.params.id
    }
  })
    .then(handleEntityNotFound(res))
    .then(saveUpdates(req.body))
    .then(responseWithResult(res))
    .catch(handleError(res));
};

// Deletes a Asset from the DB
exports.destroy = function(req, res) {
  Asset.find({
    where: {
      _id: req.params.id
    }
  })
    .then(handleEntityNotFound(res))
    .then(removeEntity(res))
    .catch(handleError(res));
};

/**
 * Get asset commnets
 */

exports.comments = function(req, res) {
  Asset.find({
      where: {
        _id: req.params.id
      }
    })
    .then(function(asset) {
      if (!asset) {
        return res.status(401).end();
      }
      asset.getComments().then(function (comments) {
        res.json(comments);
      });
    })
    .catch(function(err) {
      return next(err);
    });
};

/**
 * Get asset user
 */

exports.user = function(req, res) {
  Asset.find({
      where: {
        _id: req.params.id
      }
    })
    .then(function(asset) {
      if (!asset) {
        return res.status(401).end();
      }
      asset.getUser().then(function (user) {
        res.json(user);
      });
    })
    .catch(function(err) {
      return next(err);
    });
};