text:
import fetch from 'isomorphic-fetch';
import { checkStatus, parseJSON } from './utils';
require('es6-promise').polyfill();

const headers = {
  Authorization: `Basic ${process.env.REACT_APP_API_KEY}`,
  'Content-Type': 'application/json',
};

export const fetchTickets = projectId => {
  return fetch(`${process.env.REACT_APP_API_URL}/v1/tickets/${projectId}`, { headers }).then(checkStatus).then(parseJSON);
}

export const fetchTicketNotes = ticketId => {
  const headers = {
    Authorization: `Basic ${process.env.REACT_APP_API_KEY}`,
  };
  return fetch(`${process.env.REACT_APP_API_URL}/v1/ticket/${ticketId}/notes`, { headers }).then(checkStatus).then(parseJSON);
}

export const fetchTicketById = ticketId => {
  const headers = {
    Authorization: `Basic ${process.env.REACT_APP_API_KEY}`,
  };
  return fetch(`${process.env.REACT_APP_API_URL}/v1/ticket/${ticketId}`, { headers }).then(checkStatus).then(parseJSON);
}

export const fetchTicketScheduleEntryIds = ticketId => {
  const headers = {
    Authorization: `Basic ${process.env.REACT_APP_API_KEY}`,
  };
  return fetch(`${process.env.REACT_APP_API_URL}/v1/ticket/${ticketId}/scheduleentries`, { headers }).then(checkStatus).then(parseJSON);
}

export const fetchScheduleEntryById = entryId => {
  const headers = {
    Authorization: `Basic ${process.env.REACT_APP_API_KEY}`,
  };
  return fetch(`${process.env.REACT_APP_API_URL}/v1/schedule/entries/${entryId}`, { headers }).then(checkStatus).then(parseJSON);
}

export const fetchTicketTimeEntryIds = ticketId => {
  const headers = {
    Authorization: `Basic ${process.env.REACT_APP_API_KEY}`,
  };
  return fetch(`${process.env.REACT_APP_API_URL}/v1/ticket/${ticketId}/timeentries`, { headers }).then(checkStatus).then(parseJSON);
}

export const fetchTimeEntryById = entryId => {
  const headers = {
    Authorization: `Basic ${process.env.REACT_APP_API_KEY}`,
  };
  return fetch(`${process.env.REACT_APP_API_URL}/v1/time/entries/${entryId}`, { headers }).then(checkStatus).then(parseJSON);
};

export const dispatchTickets = params => {
  return fetch(`${process.env.REACT_APP_API_URL}/v1/dispatch`, {
    headers,
    method: 'POST',
    body: JSON.stringify(params),
  }).then(checkStatus).then(parseJSON);
};

export const updateTicketStatus = params => {
  return fetch(`${process.env.REACT_APP_API_URL}/v1/ticketStatus`, {
    headers,
    method: 'POST',
    body: JSON.stringify(params),
  }).then(checkStatus).then(parseJSON);
};

export const updateTicketDetails = params => {
  return fetch(`${process.env.REACT_APP_API_URL}/v1/ticket/${params.ticketId}`, {
    headers,
    method: 'PATCH',
    body: JSON.stringify(params),
  }).then(checkStatus).then(parseJSON);
};

export const createTicket = params => {
  return fetch(`${process.env.REACT_APP_API_URL}/v1/ticket`, {
    headers,
    method: 'POST',
    body: JSON.stringify(params),
  }).then(checkStatus).then(parseJSON);
};

export const createWorkplan = params => {
  const headers = {
    Authorization: `Basic ${process.env.REACT_APP_API_KEY}`,
    'Content-Type': 'application/json',
  };

  return fetch(`${process.env.REACT_APP_API_URL}/v1/workplan`, {
    headers,
    method: 'POST',
    body: JSON.stringify(params),
  }).then(checkStatus).then(parseJSON);
};

export const searchTimesheets = params => {
  return fetch(`${process.env.REACT_APP_API_URL}/v1/timesheets/${params.members}`, {
    headers,
    method: 'GET',
  }).then(checkStatus).then(parseJSON);
};


text:
/* Generated SBE (Simple Binary Encoding) message codec */

#pragma warning disable 1591 // disable warning on missing comments
using System;
using Org.SbeTool.Sbe.Dll;

namespace Baseline
{
    public sealed partial class VarStringEncoding
    {
        private DirectBuffer _buffer;
        private int _offset;
        private int _actingVersion;

        public void Wrap(DirectBuffer buffer, int offset, int actingVersion)
        {
            _offset = offset;
            _actingVersion = actingVersion;
            _buffer = buffer;
        }

        public const int Size = -1;

        public const uint LengthNullValue = 4294967295U;
        public const uint LengthMinValue = 0U;
        public const uint LengthMaxValue = 1073741824U;

        public uint Length
        {
            get
            {
                return _buffer.Uint32GetLittleEndian(_offset + 0);
            }
            set
            {
                _buffer.Uint32PutLittleEndian(_offset + 0, value);
            }
        }

        public const byte VarDataNullValue = (byte)255;
        public const byte VarDataMinValue = (byte)0;
        public const byte VarDataMaxValue = (byte)254;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.litesuits.orm.db.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 非空约束
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNull {}


text:
(function (data) {

    var seedData = require('./seedData');
    var database = require('./database');

    data.getNotesCategories = function (next) {
        next(null, seedData.initialNotes);
    }

    function seedDatabase() {
        database.getDb(function (err, db) {
            if (err) {
                console.log("Can't connect to the DB " + err);
            } else {
                // test to see if data exists
                db.notes.count(function(err, count) {
                    if (err) {
                        console.log("Can''t retrive data from the DB " + err);
                    } else {
                        if (count == 0) {
                            console.log("Seeding the Database");
                            seedData.initialNotes.forEach(function (item) {
                                db.notes.insert(item, function (err) {
                                    if (err) {
                                        console.log("Can't insert nore to db " + err)
                                    }
                                });
                            })
                        } else {
                            console.log("The database already seeded")
                        }
                    }
                });
            }
        })
    }

    seedDatabase();

})(module.exports)


text:
package com.navercorp.pinpoint.profiler;

import com.navercorp.pinpoint.bootstrap.instrument.RetransformEventListener;

import java.lang.instrument.ClassFileTransformer;

/**
 * @author emeroad
 */
public interface ClassFileRetransformer extends ClassFileTransformer, RetransformEventListener {

}


text:
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('claim-care-team', 'Unit | Serializer | Claim_CareTeam', {
  needs: [
    'serializer:claim-care-team',
    'model:reference',
    'model:codeable-concept',
    'model:meta',
    'model:narrative',
    'model:resource',
    'model:extension'
  ]
});

test('it serializes records', function(assert) {
  const record = this.subject(),
    serializeRecord = record.serialize();

  assert.ok(serializeRecord);
});


text:
/* blake2-impl.h
 *
 * Copyright (C) 2006-2015 wolfSSL Inc.
 *
 * This file is part of wolfSSL. (formerly known as CyaSSL)
 *
 * wolfSSL is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * wolfSSL is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#ifndef CTAOCRYPT_BLAKE2_IMPL_H
#define CTAOCRYPT_BLAKE2_IMPL_H

#include <cyassl/ctaocrypt/types.h>
#include <wolfssl/wolfcrypt/blake2_impl.h>

#endif  /* CTAOCRYPT_BLAKE2_IMPL_H */


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>kdtree</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

Module kdtree

Classes

    KDTree
    Rectangle

Functions

    distance_matrix
    minkowski_distance
    minkowski_distance_p

[hide private]


text:
sap.ui.define([
	"sap/ui/core/Element"
], function(Element) {
	"use strict";

	// The aggregation to feed details actions for datapoint selection in the mdc chart
	/**
     * Constructor for a new SelectionDetailsActions.
     *
     * @param {string} [sId] ID for the new control, generated automatically if no ID is given
     * @param {object} [mSettings] Initial settings for the new control
     * @extends sap.ui.core.Element
     * @author SAP SE
     * @class The SelectionDetailsActions are used to provide additional functionality to the Details popover.
     * @ui5-restricted sap.fe
     * @MDC_PUBLIC_CANDIDATE
     * @experimental
     * @since 1.88
     * @alias sap.ui.mdc.chart.SelectionDetailsActions
     */
	var SelectionDetailsActions = Element.extend("sap.ui.mdc.chart.SelectionDetailsActions", {

		metadata: {
			library: "sap.ui.mdc",
			aggregations: {
				detailsItemActions: {
					type: "sap.ui.core.Item",
					multiple: true
				},
				detailsActions: {
					type: "sap.ui.core.Item",
					multiple: true
				},
				actionGroups: {
					type: "sap.ui.core.Item",
					multiple: true
				}
			}
		}
	});

	return SelectionDetailsActions;
});


text:
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-directive-drag-jquery</title>

  <script src="../../components/jquery-3.1.1/jquery.js"></script>
  <script src="../../../angular.js"></script>
  <script src="script.js"></script>

</head>
<body ng-app="dragModule">
  <span my-draggable>Drag Me</span>
</body>
</html>


text:
package server.http.android.androidhttpserver.server;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class MyServer extends NanoHTTPD {
    private final static int PORT = 8080;
    public static String PATH;

    public MyServer(String x) throws IOException {
        super(PORT);
        start();
        PATH = x;
        System.out.println("\nRunning! Point your browers to http://localhost:8080/ \n");
    }

    private Response createResponse(Response.Status status, String mimeType, InputStream message){
        Response res = new Response(status, mimeType, message);
        res.addHeader("Accept-Ranges", "bytes");
        return res;
    }

    @Override
    public Response serve(String uri, Method method,
                          Map<String, String> header, Map<String, String> parameters,
                          Map<String, String> files) {
        String answer = "";

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(PATH);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new NanoHTTPD.Response(Response.Status.OK, "audio/mpeg", fis);
    }
}


text:
package uk.ac.imperial.doc.igpepa.representation.components;

import java.util.LinkedList;
import java.util.List;

import uk.ac.imperial.doc.gpepa.representation.components.AbstractPrefix;
import uk.ac.imperial.doc.gpepa.representation.components.Choice;
import uk.ac.imperial.doc.gpepa.representation.components.PEPAComponent;
import uk.ac.imperial.doc.gpepa.representation.components.PEPAComponentDefinitions;
import uk.ac.imperial.doc.jexpressions.expressions.AbstractExpression;

public class iChoice extends Choice
{
	@Override
	public List<AbstractPrefix> getPrefixes
        (PEPAComponentDefinitions definitions)
    {
        if (!(definitions instanceof iPEPAComponentDefinitions))
        {
            throw new Error ("iChoice used with incompatible definitions.");
        }
		List<AbstractPrefix> ret = new LinkedList<AbstractPrefix> ();
		for (AbstractPrefix p : choices)
        {
			PEPAComponent newContinuation = definitions.getShorthand
                (p.getContinuation());
            try
            {
			    ret.add (p.getClass().getDeclaredConstructor
                        (String.class, AbstractExpression.class,
                                AbstractExpression.class, PEPAComponent.class,
                                List.class)
                    .newInstance(p.getAction(), p.getRate(), p.getWeight(),
                            newContinuation,
                            ((iPEPAPrefix) p).getImmediatesRawCopy()));
            }
            catch (Exception ex)
            {
                ex.printStackTrace ();
            }
		}
		return ret;
	}

    public iChoice (List<AbstractPrefix> choices)
    {
        super (choices);
    }

    public ImmediatePrefix getImmediate ()
    {
        for (AbstractPrefix choice : choices)
        {
            if (choice instanceof ImmediatePrefix)
            {
                return (ImmediatePrefix)choice;
            }
        }
        return null;
    }
}


text:
Fabíola Faria

## Perfil

Mentora para SEO - Search Engine Optimization e Web Analytics

## Links

* Linkedin: https://www.linkedin.com/in/fabiolafaria
* Facebook: https://www.facebook.com/fabiola.faria
* Twitter: @fabiola_faria

## Gostaria de retribuir a ajuda da Mentora Fabíola?

Mande um abraço para ela no email fabiola.analytics@gmail.com ou nas redes sociais.


text:
.. _proc_lp:

nmrglue.proc_lp
===============

.. automodule:: nmrglue.process.proc_lp

This module is imported as nmrglue.proc_lp and can be called as such.

User Functions
--------------

.. autosummary::
    :toctree: generated/

    lp
    lp_svd
    lp_qr
    lp_cho
    lp_tls
    lp2d
    cadzow
    lp_model

Developer Functions
-------------------

.. include:: ../../../nmrglue/process/proc_lp.py
    :start-line: 5
    :end-line: 20

These functions are called by high-level function are and most users will not
use them in common processing scripts.  Developers may be interested in them.

.. autosummary::
    :toctree: generated/

    lp_1d
    extrapolate_2d
    make_lp2d_Dd
    cadzow_single
    root2damp
    root2freq
    cof2amp
    cof2phase
    make_D
    make_little_d
    make_Dd
    make_mirror
    find_lpc
    find_lpc_svd
    pinv_diagsvd
    find_lpc_qr
    find_lpc_cholesky
    find_lpc_tls
    find_lpc_fb
    find_lpc_bf
    find_lproots_hsvd
    find_roots
    find_coeff
    reverse_filter
    fix_roots
    extrapolate


text:
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { _, Autowired, Component } from "@ag-grid-community/core";
var RichSelectRow = /** @class */ (function (_super) {
    __extends(RichSelectRow, _super);
    function RichSelectRow(params) {
        var _this = _super.call(this, /* html */ "

") || this;
        _this.params = params;
        return _this;
    }
    RichSelectRow.prototype.setState = function (value, valueFormatted, selected) {
        var rendererSuccessful = this.populateWithRenderer(value, valueFormatted);
        if (!rendererSuccessful) {
            this.populateWithoutRenderer(value, valueFormatted);
        }
        _.addOrRemoveCssClass(this.getGui(), 'ag-rich-select-row-selected', selected);
    };
    RichSelectRow.prototype.populateWithoutRenderer = function (value, valueFormatted) {
        var valueFormattedExits = valueFormatted !== null && valueFormatted !== undefined;
        var valueToRender = valueFormattedExits ? valueFormatted : value;
        if (_.exists(valueToRender) && valueToRender !== '') {
            // not using innerHTML to prevent injection of HTML
            // https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations
            this.getGui().textContent = valueToRender.toString();
        }
        else {
            // putting in blank, so if missing, at least the user can click on it
            this.getGui().innerHTML = ' ';
        }
    };
    RichSelectRow.prototype.populateWithRenderer = function (value, valueFormatted) {
        var _this = this;
        // bad coder here - we are not populating all values of the cellRendererParams
        var params = {
            value: value,
            valueFormatted: valueFormatted,
            api: this.gridOptionsWrapper.getApi()
        };
        var cellRendererPromise = this.userComponentFactory.newCellRenderer(this.params, params);
        if (cellRendererPromise != null) {
            _.bindCellRendererToHtmlElement(cellRendererPromise, this.getGui());
        }
        else {
            this.getGui().innerText = params.valueFormatted != null ? params.valueFormatted : params.value;
        }
        if (cellRendererPromise) {
            cellRendererPromise.then(function (childComponent) {
                _this.addDestroyFunc(function () {
                    _this.getContext().destroyBean(childComponent);
                });
            });
            return true;
        }
        return false;
    };
    __decorate([
        Autowired('userComponentFactory')
    ], RichSelectRow.prototype, "userComponentFactory", void 0);
    return RichSelectRow;
}(Component));
export { RichSelectRow };


text:
namespace Bungie.Responses
{
    using System.Collections.Generic;
    using Models;

    public class SearchPlayersResponse : List<UserInfo>
    {
    }
}


text:
<?php
	include_once('views/student/student_login.php');
?>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hatapp.comandas.entity;

import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 *
 * @author ivan
 */
@Entity
@Table(name = "cuentas")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Cuentas.findAll", query = "SELECT c FROM Cuentas c"),
    @NamedQuery(name = "Cuentas.findById", query = "SELECT c FROM Cuentas c WHERE c.id = :id")})
public class Cuentas implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "id")
    private Integer id;
    @JoinTable(name = "cuentas_has_mesas", joinColumns = {
        @JoinColumn(name = "Cuentas_id", referencedColumnName = "id")}, inverseJoinColumns = {
        @JoinColumn(name = "Mesas_id", referencedColumnName = "id")})
    @ManyToMany
    private List<Mesas> mesasList;
    @JoinColumn(name = "Usuario", referencedColumnName = "username")
    @ManyToOne(optional = false)
    private Usuarios usuario;
    @JoinColumn(name = "cliente", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Clientes cliente;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "cuenta")
    private List<Pedidos> pedidosList;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "cuenta")
    private List<Facturas> facturasList;

    public Cuentas() {
    }

    public Cuentas(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @XmlTransient
    public List<Mesas> getMesasList() {
        return mesasList;
    }

    public void setMesasList(List<Mesas> mesasList) {
        this.mesasList = mesasList;
    }

    public Usuarios getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuarios usuario) {
        this.usuario = usuario;
    }

    public Clientes getCliente() {
        return cliente;
    }

    public void setCliente(Clientes cliente) {
        this.cliente = cliente;
    }

    @XmlTransient
    public List<Pedidos> getPedidosList() {
        return pedidosList;
    }

    public void setPedidosList(List<Pedidos> pedidosList) {
        this.pedidosList = pedidosList;
    }

    @XmlTransient
    public List<Facturas> getFacturasList() {
        return facturasList;
    }

    public void setFacturasList(List<Facturas> facturasList) {
        this.facturasList = facturasList;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Cuentas)) {
            return false;
        }
        Cuentas other = (Cuentas) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.hatapp.comandas.entity.Cuentas[ id=" + id + " ]";
    }

}


text:
/**
 * lyric parser
 */

class ScriptEvent {
  constructor (domain, text, beat) {
    this.domain = domain
    this.text = text;
    this.beat = beat;
  }

  toString() {
    return `[${this.domain}] this.text`;
  }
}

class Script {
  constructor() {
    this._lyrics = new Map();
  }

  _set(beat, lyrics) {
    this._lyrics.set(beat, lyrics);
  }

  get(beat) {
    return this._lyrics.get(beat);
  }
}

const _spaces = '\\s*';
const _number = '\\d+(\\.\\d+)?';
const _text = '[^:\\]\\[]+';
const _surround = (l, r = null) => pattern => `${l}${pattern}${r != null ? r : l}`;
const _ignoreSpace = _surround(_spaces);
const _withBrace   = _surround('\\[', '\\]');

const doesMatch = regex => string => string.match(regex) != null;
const isComment = doesMatch(new RegExp(`^${_spaces}#`));
const isEmptyLine = doesMatch(new RegExp(`^${_spaces}$`));
const isTimeStamp = doesMatch(new RegExp(
  '^' + _ignoreSpace(_number) +':' + _ignoreSpace(_withBrace(_text)) + _text
));

export default function (string) {
  const initialState = new Script();

  return string.split('\n').reduce((state, line) => {
    if (isComment(line)) return state;
    else if (isEmptyLine(line)) return state;
    else if (isTimeStamp(line)) {
      let [beat, event] = line.split(':').map(s => s.trim());
      let [domain, text] = event.substr(1).split(']').map(s => s.trim());
      let parsedBeat = parseFloat(beat, 10);
      state._set(parsedBeat, new ScriptEvent(domain, text, parsedBeat));
      return state;
    }
    else {
      throw new Error(`unknown parser state for line '${line}'`);
    }
  }, initialState);
}


text:
<?php
// © 2017 Rob Schlüter. For licensing details see the LICENSE file.
use kwebble\wiki\Config;
use kwebble\wiki\WikiException;
use kwebble\wiki\GeneratorFinder;

// Run the build steps.
require_once 'bootstrap.php';

try {
    Bootstrapper::initialize();
    (new GeneratorFinder())->generateRegistrationCode();
} catch (WikiException $e) {
    echo 'Configuration of this application is not complete. Please set the application key in config.php first.';
}


text:
body,h1,h2,h3,p,quote,small,form,input,ul,li,ol,label{
	/* Simple page reset */
	margin:0;
	padding:0;
}

body{
	/* Setting default text color, background and a font stack */
	color:#cccccc;
	font-size:0.825em;
	background-color: #1e2428;
	font-family:Arial, Helvetica, sans-serif;
}

.tabContainer{
	/* The UL */
	float:right;
	padding-right:13px;
}

#contentHolder{
	background-color:#EEEEEE;
	border:2px solid #FFFFFF;
	height:300px;
	margin:20px;

	color:#444444;
	padding:15px;
}

#tabContent{
	background-color:#333;
	border:1px solid #444;
	margin-top:-15px;
	width:100%;
}

#tabContent, .tabContainer li a,#contentHolder{
	-webkit-box-shadow:0 0 2px black;
	-moz-box-shadow:0 0 2px black;
	box-shadow:0 0 2px black;
}

.tabContainer li{
	/* This will arrange the LI-s next to each other */
	display:inline;
}

.tabContainer li a,.tabContainer li a:visited{
	/* Styling the hyperlinks of the tabs as colorful buttons */

	float:left;
	font-size:18px;

	/* display:block allows for additinal CSS rules to take effect, such as paddings: */
	display:block;

	padding:7px 16px 1px;
	margin:4px 5px;
	height:29px;

	/* Giving positioning */
	position:relative;

	/* CSS3 text-shadow */
	text-shadow:1px 1px 1px #CCCCCC;
}

#overLine{
	/* The line above the active button. */
	position:absolute;

	height:1px;
	background-color:white;
	width:90px;

	float:left;
	left:1px;
	top:-5px;
	overflow:hidden;
}

#main{
	margin:0 auto;
	position:relative;
	width:700px;
}

ul .left{
	/* The left span in the hyperlink */

	height:37px;
	left:0;
	position:absolute;
	top:0;
	width:10px;
}

ul .right{
	/* The right span in the hyperlink */

	height:37px;
	right:0;
	position:absolute;
	top:0;
	width:10px;
}

/* Styling the colors individually: */

ul a.green{	background:url(img/green_mid.png) repeat-x top center;	color:#24570f;}
ul a.green span.left{ background:url(img/green_left.png) no-repeat left top;}
ul a.green span.right{ background:url(img/green_right.png) no-repeat right top;}

ul a.blue{	background:url(img/blue_mid.png) repeat-x top center;	color:#03426e;}
ul a.blue span.left{ background:url(img/blue_left.png) no-repeat left top;}
ul a.blue span.right{ background:url(img/blue_right.png) no-repeat right top;}

ul a.orange{	background:url(img/orange_mid.png) repeat-x top center;	color:#724104;}
ul a.orange span.left{ background:url(img/orange_left.png) no-repeat left top;}
ul a.orange span.right{ background:url(img/orange_right.png) no-repeat right top;}

ul a.red{	background:url(img/red_mid.png) repeat-x top center;	color:#6f0100;}
ul a.red span.left{ background:url(img/red_left.png) no-repeat left top;}
ul a.red span.right{ background:url(img/red_right.png) no-repeat right top;}

/* The hover states: */
ul a:hover{	background-position:bottom center; text-decoration:none;}
ul a:hover span.left{ background-position:left bottom;}
ul a:hover span.right{ background-position:right bottom;}

.preloader{
	display:block;
	margin:120px auto;
}

.clear{
	/* Old-school clear fix hack to clear the floats: */
	clear:both;
	height:1px;
	overflow:hidden;
}

/* The styles below are only necessary for the styling of the demo page: */

h1{
	background:#121b21;
	border-bottom:1px solid black;
	font-size:1.5em;
	font-weight:normal;
	margin-bottom:15px;
	padding:15px;
	text-align:center;
}

h2 {
	font-size:0.9em;
	font-weight:normal;
	padding-right:40px;
	position:relative;
	right:0;
	text-align:right;
	text-transform:uppercase;
	top:-48px;
}

a, a:visited {
	color:#0196e3;
	text-decoration:none;
	outline:none;
}

a:hover{
	text-decoration:underline;
}

p.tutInfo{
	/* The tutorial info on the bottom of the page */
	padding:10px 0;
	text-align:center;
	position:fixed;
	bottom:0px;
	background:#121b21;
	border-top:1px solid black;
	width:100%;
}

h1,h2,p.tutInfo{
	font-family:"Myriad Pro",Arial,Helvetica,sans-serif;
}


text:
package com.emoon.balance.Model;

import java.util.Date;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

public class Transaction extends RealmObject{

    @PrimaryKey
    private String id;
    private Date date;
    private EarnBurn earnBurn;
    private int unitCost;
    private String costType;

    public Transaction(){

    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public EarnBurn getEarnBurn() {
        return earnBurn;
    }

    public void setEarnBurn(EarnBurn earnBurn) {
        this.earnBurn = earnBurn;
    }

    public int getUnitCost() {
        return unitCost;
    }

    public void setUnitCost(int unitCost) {
        this.unitCost = unitCost;
    }

    public String getCostType() {
        return costType;
    }

    public void setCostType(String costType) {
        this.costType = costType;
    }
}


text:
package ch.eiafr.knx.utils;

public class DatapointDescription {

	private String m_Action;
	private String m_Id;
	private String m_Description;
	private String m_DatapointDescription;
	private int m_BitsSize;

	public DatapointDescription(String p_Action, String p_Id, String p_Description, String p_DatapointDescription, int p_BitsSize){
		m_Action = p_Action;
		m_Id = p_Id;
		m_Description = p_Description;
		m_DatapointDescription = p_DatapointDescription;
		m_BitsSize = p_BitsSize;
	}

	public String getAction(){
		return m_Action;
	}

	public String getId(){
		return m_Id;
	}

	public String getDescription(){
		return m_Description;
	}

	public String getDatapointDescription(){
		return m_DatapointDescription;
	}

	public int getBitsSize(){
		return m_BitsSize;
	}

}


text:
build-essential Cookbook CHANGELOG
==================================
This file is used to list changes made in each version of the build-essential cookbook.

v2.0.4 (2014-06-06)
-------------------
* [COOK-4661] added patch package to _rhel recipe

v2.0.2 (2014-05-02)
-------------------
- Updated documentation about older Chef versions
- Added new SVG badges to the README
- Fix a bug where `potentially_at_compile_time` fails on non-resources

v2.0.0 (2014-03-13)
-------------------
- Updated tested harnesses to use latest ecosystem tools
- Added support for FreeBSD
- Added support for installing XCode Command Line Tools on OSX (10.7, 10.8, 10.9)
- Created a DSL method for wrapping compile_time vs runtime execution
- Install additional developement tools on some platforms
- Add nicer log and warning messages with helpful information

**Potentially Breaking Changes**

- Dropped support for OSX 10.6
- OSX no longer downloads OSX GCC and uses XCode CLI tools instead
- `build_essential` -> `build-essential` in node attributes
- `compiletime` -> `compile_time` in node attributes
- Cookbook version 2.x no longer supports Chef 10.x

v1.4.4 (2014-02-27)
-------------------
- [COOK-4245] Wrong package name used for developer tools on OS X 10.9

v1.4.2
------
### Bug
- **[COOK-3318](https://tickets.opscode.com/browse/COOK-3318)** - Use Mixlib::ShellOut instead of Chef::ShellOut

### New Feature
- **[COOK-3093](https://tickets.opscode.com/browse/COOK-3093)** - Add OmniOS support

### Improvement
- **[COOK-3024](https://tickets.opscode.com/browse/COOK-3024)** - Use newer package on SmartOS

v1.4.0
------
This version splits up the default recipe into recipes included based on the node's platform_family.

- [COOK-2505] - backport omnibus builder improvements

v1.3.4
------
- [COOK-2272] - Complete `platform_family` conversion in build-essential

v1.3.2
------
- [COOK-2069] - build-essential will install osx-gcc-installer when XCode is present

v1.3.0
------
- [COOK-1895] - support smartos

v1.2.0
------
- Add test-kitchen support (source repo only)
- [COOK-1677] - build-essential cookbook support for OpenSuse and SLES
- [COOK-1718] - build-essential cookbook metadata should include scientific
- [COOK-1768] - The apt-get update in build-essentials needs to be renamed

v1.1.2
------
- [COOK-1620] - support OS X 10.8

v1.1.0
------
- [COOK-1098] - support amazon linux
- [COOK-1149] - support Mac OS X
- [COOK-1296] - allow for compile-time installation of packages through an attribute (see README)

v1.0.2
------
- [COOK-1098] - Add Amazon Linux platform support
- [COOK-1149] - Add OS X platform support


text:
#ifndef __EVIAS_DOCBOT_WEB_APPLICATION__
#define __EVIAS_DOCBOT_WEB_APPLICATION__

#include <Wt/WApplication>
#include <Wt/Dbo/Types>
#include <boost/shared_ptr.hpp>

#include "core/models/model.hpp"
#include "web/interface.hpp"

namespace evias {
namespace web {
    class application
        : public Wt::WApplication
    {
    public:
        application(const Wt::WEnvironment&);
        ~application();

    private:
        boost::shared_ptr<evias::interface> view_;
    };

}
};

#endif /** __EVIAS_DOCBOT_WEB_APPLICATION__ **/


text:
package Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation::Smart_wormbase;

use warnings ;
use vars qw(@ISA);
use strict;

use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation;

@ISA = qw(Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation);

###################
# analysis methods
###################

=head2 run_analysis

 Title    : run_program
 Usage    : $self->program
 Function : makes the system call to program
 Example  :
 Returns  :
 Args     :
 Throws   :

=cut

sub run_analysis {
    my ($self) = @_;

    # run program
    print STDERR "running ".$self->program." against ".$self->database."\n";

    print STDERR "FILENAME: ".$self->queryfile."\n";

    my $cmd = $self->program .' '.
	      $self->analysis->parameters .' '.
	      $self->database .' '.
	      $self->queryfile .' '.
              '> ' . $self->resultsfile;
    print STDERR "$cmd\n";

    $self->throw ("Error running Smart_wormbase ".$self->program." on ".$self->queryfile)
     unless ((system ($cmd)) == 0);

}

=head2 parse_results

 Title    :  parse_results
 Usage    :  $self->parse_results ($filename)
 Function :  parses program output to give a set of features
 Example  :
 Returns  :
 Args     : filename (optional, can be filename, filehandle or pipe, not implemented)
 Throws   :

=cut

sub parse_results {
  my ($self) = @_;

  my $filehandle;
  my $resfile = $self->resultsfile();
  my @fps;

  if (-e $resfile) {
    if (-z $resfile) {
      print STDERR "Smart didn't find any hits\n";
      return;
    } else {
      open (CPGOUT, "<$resfile") or $self->throw("Error opening ", $resfile, " \n"); #
    }
  }

  my $id;
  while (<CPGOUT>) {
    chomp;

    print "$_\n";

    last if /^Alignments of top-scoring domains/;
    next if (/^Model/ || /^\-/ || /^$/);
    if (/^Query sequence:\s+(\S+)/) {
      $id = $1;
    }

    if (my ($hid, $start, $end, $hstart, $hend, $score, $evalue) = /^(\S+)\s+\S+\s+(\d+)\s+(\d+)\s+\S+\s+(\d+)\s+(\d+)\s+\S+\s+(\S+)\s+(\S+)/) {

      print "matched\n";
      my $percentIdentity = 0;

      my $fp= $self->create_protein_feature($start, $end, $score, $id, $hstart, $hend, $hid, $self->analysis, $evalue, $percentIdentity);
      push @fps, $fp;
    }
  }
  close (CPGOUT);
  $self->output(\@fps);
}

1;


text:
PacketCaptureObj = new PacketCapture();
var packetCaptureRuleIndex = 0;
function PacketCapture() {
    //Variable definitions
    var ddDomain, ddProject, ddIPOptions; //Dropdowns
    var gridAnalyzer; //Grids
    var btnCreateAnalyzer, btnDeleteAnalyzer, btnCreateAnalyzerCancel, btnCreateAnalyzerOK, btnAddRule, btnDeleteRule, btnCnfDelAnalyzerPopupOK, btnCnfDelAnalyzerPopupCancel; //Buttons
    var txtPolicyName, txtAnalyzerName; //Textboxes
    var msAssociatedNetworks; //Multiselects
    var dlVirtualNetwork; //Droplist
    var windowCreateAnalyzer, confirmDelete; //Windows
    var isAnalyzerImageAvailable = false;
    var isAnalyzerImageCheckDone = false;

    //Method definitions
    this.load = load;
    this.init = init;
    this.initComponents = initComponents;
    this.initActions = initActions;
    this.fetchData = fetchData;
    this.fetchDataForGridAnalyzer = fetchDataForGridAnalyzer;
    this.populateDomains = populateDomains;
    this.handleDomains = handleDomains;
    this.populateProjects = populateProjects;
    this.handleProjects = handleProjects;
    this.gridAnalyzerRowChange = gridAnalyzerRowChange;
    this.showAnalyzerEditWindow = showAnalyzerEditWindow;
    this.closeCreateAnalyzerWindow = closeCreateAnalyzerWindow;
    this.successHandlerForGridAnalyzer = successHandlerForGridAnalyzer;
    this.failureHandlerForGridAnalyzer = failureHandlerForGridAnalyzer;
    this.createAnalyzerSuccessCB = createAnalyzerSuccessCB;
    this.createAnalyzerFailureCB = createAnalyzerFailureCB;
    this.createPolicySuccessCB = createPolicySuccessCB;
    this.createPolicyFailureCB = createPolicyFailureCB;
    this.validate = validate;
    this.destroy = destroy;
};

function load() {
    var configTemplate = Handlebars.compile($("#analyzer-config-template").html());
    $(contentContainer).empty();
    $(contentContainer).html(configTemplate);
    currTab = 'config_net_policies';
    init();
};

function init() {
    this.initComponents();
    this.initActions();
    this.fetchData();
    initWidgetBoxes();
};

function fetchData() {
    fetchDomains("populateDomains");
};

function initComponents() {

    $("#gridAnalyzer").contrailGrid({
    	header : {
			title : {
				text : 'Analyzers'
			},
			customControls: ['',
	                            '',
	                            'Project:
',
	                            'Domain:
']
		},
		columnHeader : {
			columns : [
			{
				id: 'AnalyzerName',
				field: 'AnalyzerName',
				name: 'Analyzer Name',
				width: 200,
				sortable: true
			},
			{
				id: "VirtualNetwork",
				field: "VirtualNetwork",
				name: "Virtual Network",
				width: 150
			},
			{
				id:"AssociatedNetwork",
				field:"AssociatedNetwork",
				name:"Associated Networks",
				width: 150,
				formatter: function(r, c, v, cd, dc) {
					var returnString = '';
					if(typeof dc.AssociatedNetworks === "object") {
						for(var i=0;i < dc.AssociatedNetworks.length,i<2;i++) {
							if(typeof dc.AssociatedNetworks[i] !== "undefined") {
								returnString += dc.AssociatedNetworks[i] + '
';
							}
						}
						if(dc.AssociatedNetworks.length > 2) {
							returnString += '(' + (dc.AssociatedNetworks.length - 2) + ' more) \
							';
						}
					}
					return returnString;
				},
				exportConfig: {
					allow: true,
					advFormatter: function(dc) {
						return dc.AssociatedNetworks.join(',');
					}
				}
			},
			{
				id:"PolicyRules",
				field:"PolicyRules",
				name:"Analyzer Rules",
				width: 500,
				formatter: function(r, c, v, cd, dc) {
					var returnString = '';
					if(typeof dc.PolicyRules === "object") {
						for(var i=0;i < dc.PolicyRules.length,i<2;i++) {
							if(typeof dc.PolicyRules[i] !== "undefined") {
								returnString += dc.PolicyRules[i] + '
';
							}
						}

						if(dc.PolicyRules.length > 2) {
							returnString += '(' + (dc.PolicyRules.length-2) + ' more) \
							';
						}
					}

					return returnString;
				},
				exportConfig: {
					allow: true,
					advFormatter: function(dc) {
						return dc.PolicyRules.join(',');
					}
				}
			},
			{
				id:"vmStatus",
				field:"vmStatus",
				width: 100,
				name:"Status",
				formatter: function(r, c, v, cd, dc) {
					var vmStatus = dc.vmStatus;
					return '' + vmStatus;
				},
				exportConfig: {
					allow: true,
					stdFormatter: false
				}
			}
			]
		},
		body : {
			options : {
				autoHeight : true,
				checkboxSelectable: {
					onNothingChecked: function(e){
						$('#btnDeleteAnalyzer').addClass('disabled-link');
					},
					onSomethingChecked: function(e){
						$('#btnDeleteAnalyzer').removeClass('disabled-link');
					}
				},
				forceFitColumns: true,
				actionCell: [
					{
						title: 'Edit',
						iconClass: 'icon-edit',
						onClick: function(rowIndex){
							showAnalyzerEditWindow('edit',rowIndex);
						}
					},
					{
						title: 'View Analyzer',
						iconClass: 'icon-list-alt',
						onClick: function(rowIndex){
							launchAnalyzer(rowIndex);
						}
					},
					{
						title: 'Delete',
						iconClass: 'icon-trash',
						onClick: function(rowIndex){
							showRemoveWindow(rowIndex);
						}
					}
				],
				detail: {
					template: $('#analyzerDetailTemplate').html()
				}
			},
			dataSource : {
				data : []
			},
			statusMessages: {
				loading: {
					text: 'Loading Analyzers...',
				},
				empty: {
					text: 'No Analyzers Found.'
				},
				errorGettingData: {
					type: 'error',
					iconClasses: 'icon-warning',
					text: 'Error in getting Data.'
				}
			}
		},
		footer : {
			pager : {
				type : 'client',
				options : {
					pageSize : 50,
					pageSizeSelect : [5, 10, 50, 100]
				}
			}
		}
	});

    gridAnalyzer = $('#gridAnalyzer').data('contrailGrid');

    btnCreateAnalyzer = $("#btnCreateAnalyzer");
    btnDeleteAnalyzer = $("#btnDeleteAnalyzer");
    btnAddRule = $("#btnAddRule");
    btnDeleteRule = $("#btnDeleteRule");
    btnCreateAnalyzerCancel = $("#btnCreateAnalyzerCancel");
    btnCreateAnalyzerOK = $("#btnCreateAnalyzerOK");
    btnCnfDelAnalyzerPopupOK = $('#btnCnfDelAnalyzerPopupOK');
    btnCnfDelAnalyzerPopupCancel = $('#btnCnfDelAnalyzerPopupCancel');

    txtPolicyName = $("#txtPolicyName");
    txtAnalyzerName = $("#txtAnalyzerName");

    $("#ddDomainSwitcher").contrailDropdown({
        change: handleDomains,
        dataTextField:"text",
        dataValueField:"value"
    });
    ddDomain = $("#ddDomainSwitcher").data('contrailDropdown');

    $("#ddProjectSwitcher").contrailDropdown({
        change:handleProjects,
        dataTextField:"text",
        dataValueField:"value"
    });
    ddProject = $("#ddProjectSwitcher").data('contrailDropdown');

    msAssociatedNetworks = $("#msAssociatedNetworks").contrailMultiselect({placeholder:"Select Networks..."});
    $("#dlVirtualNetwork").contrailDropdown({placeholder: "Select Network..."});
    // Use dropdownCssClass : 'select2-large-width' when initialzing ContrailDropDown to specify width of dropdown for Contrail Dropdown
    // Adding a custom CSS class is also possible. Just add a custom class to the contrail.custom.css file
    dlVirtualNetwork = $("#dlVirtualNetwork").data('contrailDropdown');

    gridAnalyzer.showGridMessage('loading');

    windowCreateAnalyzer = $("#windowCreateAnalyzer");
    windowCreateAnalyzer.on("hide", closeCreateAnalyzerWindow);
    windowCreateAnalyzer.modal({backdrop:'static', keyboard: false, show:false});

    $('body').append($("#confirmDelete"));
    confirmDelete = $("#confirmDelete");
    confirmDelete.modal({backdrop:'static', keyboard: false, show:false});
};

function showRemoveWindow(rowIndex) {
    $.contrailBootstrapModal({
       id: 'confirmRemove',
       title: 'Delete Analyzer',
       body: '
Do you want to delete the analyzer?
',
       footer: [{
           title: 'Cancel',
           onclick: 'close',
       },
       {
           id: 'btnRemovePopupOK',
           title: 'Confirm',
           onclick: function(){
               var selected_rows = gridAnalyzer._dataView.getItem(rowIndex);
               deleteAnalyzers([selected_rows]);
               $('#confirmRemove').modal('hide');
           },
           className: 'btn-primary'
       }
       ]
   });
 }

function deleteAnalyzers(selectedRows){
	var deleteAjaxs = [];
    if (selectedRows && selectedRows.length > 0) {
        for (var i = 0; i < selectedRows.length; i++) {
        	deleteAjaxs[i] = $.ajax({
                url:"/api/tenants/config/service-instance/" + selectedRows[i]["AnalyzerUUID"] + "?policyId=" + selectedRows[i]["PolicyUUID"],
                type:"DELETE"
            });
        }

    	var selectedRowIds = [];
    	$.each(selectedRows, function(key,val) {
    		selectedRowIds.push(val.cgrid);
    	});

    	gridAnalyzer._dataView.deleteDataByIds(selectedRowIds);

    	$.when.apply($, deleteAjaxs).then(
            function () {
                //all success
                var results = arguments;
                fetchDataForGridAnalyzer();
            },
            function () {
                //If atleast one api fails
                var results = arguments;
                fetchDataForGridAnalyzer();
            }
      	);
    }
    $("#vnc-console-widget").find('.icon-remove').click();
}

function initActions() {
    btnCreateAnalyzer.click(function (e) {
        if($(this).hasClass('disabled-link')) {
            return;
        }
        e.preventDefault();
        if(PacketCaptureObj.isAnalyzerImageCheckDone) {
            if(PacketCaptureObj.isAnalyzerImageAvailable) {
                showAnalyzerEditWindow("add");
            } else {
                showInfoWindow("Analyzer image is not found. Please ensure that a valid image of name analyzer is present.", "Warning");
            }
        } else {
            showInfoWindow("Waiting to get the analyzer image. Please try again after few seconds.", "Message");
        }
        return false;
    });

    btnDeleteAnalyzer.click(function (a) {
    	if(!$(this).hasClass('disabled-link')){
            confirmDelete.find('.modal-header-title').text("Confirm");
            confirmDelete.modal('show');
    	}
    });

    btnCnfDelAnalyzerPopupOK.click(function (a) {
        var selected_rows = gridAnalyzer.getCheckedRows();
        deleteAnalyzers(selected_rows);
        confirmDelete.modal('hide');
    });

    btnCnfDelAnalyzerPopupCancel.click(function(a){
    	confirmDelete.modal('hide');
    });

    btnCreateAnalyzerCancel.click(function (a) {
        windowCreateAnalyzer.hide();
    });

    btnCreateAnalyzerOK.click(function () {
        if (validate()) {
            var analyzerPolicy, analyzer;
            if (txtAnalyzerName[0].disabled == true) {
                mode = "edit";
                analyzerPolicy = getAnalyzerPolicy();
                var policyUUID = jsonPath(configObj, "$.network-policys[?(@.fq_name[2]=='" + txtPolicyName.val() + "')]")[0].uuid;
                doAjaxCall("/api/tenants/config/policy/" + policyUUID, "PUT", JSON.stringify(analyzerPolicy), "createPolicySuccessCB", "createPolicyFailureCB");
            } else {
                mode = "add";
                analyzer = getAnalyzer();
                doAjaxCall("/api/tenants/config/service-instances", "POST", JSON.stringify(analyzer), "createAnalyzerSuccessCB", "createAnalyzerFailureCB");
            }
        }
    });
};

function appendRuleEntry(who, defaultRow) {
    var ruleEntry = createRuleEntry();
    if (defaultRow) {
        $("#ruleTuples").prepend(ruleEntry);
    } else {
        var parentEl = who.parentNode.parentNode.parentNode;
        parentEl.parentNode.insertBefore(ruleEntry, parentEl.nextSibling);
    }
};

function createRuleEntry(rule) {
	packetCaptureRuleIndex++;
    var selectProtocol = document.createElement("div");
    $(selectProtocol).attr('id','selectProtocol-' + packetCaptureRuleIndex);
    selectProtocol.className = "span2 pull-left";
    var selectProtocolData = ['Any', 'TCP', 'UDP', 'ICMP'];

    var selectSrcNetwork = document.createElement("div");
    selectSrcNetwork.className = "span2 pull-left selectSrcNetwork";
    $(selectSrcNetwork).attr('id','selectSrcNetwork-' + packetCaptureRuleIndex);
    var selectSrcNetworkData = ["any","local"];

    var inputTxtSrcPorts = document.createElement("input");
    inputTxtSrcPorts.type = "text";
    inputTxtSrcPorts.className = "span12";
    inputTxtSrcPorts.setAttribute("placeholder", "Source ports");
    var divRowFluidSrcPorts = document.createElement("div");
    divRowFluidSrcPorts.className = "span2";
    divRowFluidSrcPorts.appendChild(inputTxtSrcPorts);

    var selectDirection = document.createElement("div");
    selectDirection.className = "span1 pull-left selectDirection";
    $(selectDirection).attr('id','selectDirection-' + packetCaptureRuleIndex);
    var selectDirectionData = ['<>', '>'];

    var selectDestNetwork = document.createElement("div");
    selectDestNetwork.className = "span2 pull-left selectDestNetwork";
    $(selectDestNetwork).attr('id','selectDestNetwork-' + packetCaptureRuleIndex);
    selectDestNetworkData = ["any","local"];

    var inputTxtDestPorts = document.createElement("input");
    inputTxtDestPorts.type = "text";
    inputTxtDestPorts.className = "span12";
    inputTxtDestPorts.setAttribute("placeholder", "Destination ports");
    var divRowFluidDestPorts = document.createElement("div");
    divRowFluidDestPorts.className = "span2";
    divRowFluidDestPorts.appendChild(inputTxtDestPorts);
    var iBtnAddRule = document.createElement("i");
    iBtnAddRule.className = "icon-plus";
    iBtnAddRule.setAttribute("onclick", "appendRuleEntry(this);");
    iBtnAddRule.setAttribute("title", "Add rule below");

    var divPullLeftMargin5Plus = document.createElement("div");
    divPullLeftMargin5Plus.className = "pull-right margin-5";
    divPullLeftMargin5Plus.appendChild(iBtnAddRule);

    var iBtnDeleteRule = document.createElement("i");
    iBtnDeleteRule.className = "icon-minus";
    iBtnDeleteRule.setAttribute("onclick", "deleteRuleEntry(this);");
    iBtnDeleteRule.setAttribute("title", "Delete rule");

    var divPullLeftMargin5Minus = document.createElement("div");
    divPullLeftMargin5Minus.className = "pull-right margin-5";
    divPullLeftMargin5Minus.appendChild(iBtnDeleteRule);

    var divRowFluidMargin10 = document.createElement("div");
    divRowFluidMargin10.className = "row-fluid margin-0-0-5";
    divRowFluidMargin10.appendChild(selectProtocol);
    divRowFluidMargin10.appendChild(selectSrcNetwork);
    divRowFluidMargin10.appendChild(divRowFluidSrcPorts);
    divRowFluidMargin10.appendChild(selectDirection);
    divRowFluidMargin10.appendChild(selectDestNetwork);
    divRowFluidMargin10.appendChild(divRowFluidDestPorts);
    divRowFluidMargin10.appendChild(divPullLeftMargin5Plus);
    divRowFluidMargin10.appendChild(divPullLeftMargin5Minus);

    var rootDiv = document.createElement("div");
    rootDiv.className = 'rule-item';
    $(rootDiv).data('ruleIndex', packetCaptureRuleIndex);
    rootDiv.appendChild(divRowFluidMargin10);

    var vns = msAssociatedNetworks.data("contrailMultiselect").getAllData();
    for (var i = 0; i < vns.length; i++) {
        var vn = vns[i];
        selectSrcNetworkData.push(vn.id);
        selectDestNetworkData.push(vn.id);
    }
    $(selectProtocol).contrailDropdown({
    	placeholder: 'Select Protocol',
    	data: selectProtocolData
    });

    $(selectSrcNetwork).contrailDropdown({
    	placeholder: 'Source network (any)',
    	data: selectSrcNetworkData
    });

    $(selectDirection).contrailDropdown({
    	placeholder: 'Direction (<>)',
    	data: selectDirectionData
    });

    $(selectDestNetwork).contrailDropdown({
    	placeholder: 'Destination network (any)',
    	data: selectDestNetworkData
    });

    var sts = jsonPath(configObj, "$.service_templates[*].service-template");
    var nonAnalyzerInsts = [];
    var serviceInsts = [];
    if (null !== sts && sts.length > 0) {
        for (var i = 0; i < sts.length; i++) {
            if (sts[i].service_template_properties.service_type !== "analyzer") {
                if (typeof sts[i].service_instance_back_refs !== "undefined" && sts[i].service_instance_back_refs.length > 0) {
                    for (var j = 0; j < sts[i].service_instance_back_refs.length; j++) {
                        nonAnalyzerInsts[nonAnalyzerInsts.length] = sts[i].service_instance_back_refs[j].to[2];
                        serviceInsts[serviceInsts.length] = sts[i].service_instance_back_refs[j].to[2];
                    }
                }
            } else {
                if (typeof sts[i].service_instance_back_refs !== "undefined" && typeof sts[i].service_instance_back_refs[j] !== "undefined"
                    && typeof sts[i].service_instance_back_refs[j].to !== "undefined" && typeof sts[i].service_instance_back_refs[j].to[2] !== "undefined") {
                    serviceInsts[serviceInsts.length] = sts[i].service_instance_back_refs[j].to[2];
                }
            }
        }
    }

    if (null !== rule && typeof rule !== "undefined") {

        var protocol = rule["protocol"];
        if (null !== protocol && typeof protocol !== "undefined") {
            protocol = protocol.toUpperCase();
            $(selectProtocol).data("contrailDropdown").value(protocol);
        }
        var direction = rule["direction"];
        if (null !== direction && typeof direction !== "undefined") {
            direction = direction.toUpperCase();
            $(selectDirection).data("contrailDropdown").value(direction);
        }

        if (null !== rule["src_addresses"] && typeof rule["src_addresses"] !== "undefined" &&
            rule["src_addresses"].length > 0) {
            var srcNetwork = [];
            for (var i = 0; i < rule["src_addresses"].length; i++) {
                if (null !== rule["src_addresses"][i]["virtual_network"] &&
                    typeof rule["src_addresses"][i]["virtual_network"] !== "undefined") {
                    srcNetwork[i] = getVNName(rule["src_addresses"][i]["virtual_network"]);
                }
            }
            var srcNw = srcNetwork.join();
            $(selectSrcNetwork).data("contrailDropdown").value(srcNw);
        }
        if (null !== rule["dst_addresses"] && typeof rule["dst_addresses"] !== "undefined" &&
            rule["dst_addresses"].length > 0) {
            var destNetwork = [];
            for (var i = 0; i < rule["dst_addresses"].length; i++) {
                if (null !== rule["dst_addresses"][i]["virtual_network"] &&
                    typeof rule["dst_addresses"][i]["virtual_network"] !== "undefined") {
                    destNetwork[i] = getVNName(rule["dst_addresses"][i]["virtual_network"]);
                }
            }
            var destNw = destNetwork.join();
            $(selectDestNetwork).data("contrailDropdown").value(destNw);
        }

        if (null !== rule["src_ports"] && typeof rule["src_ports"] !== "undefined" &&
            rule["src_ports"].length > 0) {
            var portDesc = [];
            if (rule["src_ports"].length === 1 && rule["src_ports"][0]["start_port"] === -1) {
                $(inputTxtSrcPorts).val("Any");
            } else {
                for (var i = 0; i < rule["src_ports"].length; i++) {
                    if (rule["src_ports"][i]["end_port"] !== -1)
                        portDesc[i] = rule["src_ports"][i]["start_port"] + " - " + rule["src_ports"][i]["end_port"];
                    else
                        portDesc[i] = rule["src_ports"][i]["start_port"];
                }
                $(inputTxtSrcPorts).val(portDesc.join(","));
            }
        }

        if (null !== rule["dst_ports"] && typeof rule["dst_ports"] !== "undefined" &&
            rule["dst_ports"].length > 0) {
            var portDesc = [];
            if (rule["dst_ports"].length === 1 && rule["dst_ports"][0]["start_port"] === -1) {
                $(inputTxtDestPorts).val("Any");
            } else {
                for (var i = 0; i < rule["dst_ports"].length; i++) {
                    if (rule["dst_ports"][i]["end_port"] !== -1)
                        portDesc[i] = rule["dst_ports"][i]["start_port"] + " - " + rule["dst_ports"][i]["end_port"];
                    else
                        portDesc[i] = rule["dst_ports"][i]["start_port"];
                }
                $(inputTxtDestPorts).val(portDesc.join(","));
            }
        }
    }
    return rootDiv;
};

function deleteRuleEntry(who) {
    var templateDiv = who.parentNode.parentNode.parentNode;
    $(templateDiv).remove();
    templateDiv = $();
};

function populateDomains(result) {
    var domainsJSON, domainsDS = [];
    if (result && result.domains && result.domains.length > 0) {
        domainsJSON = result.domains;
        for (var i = 0; i < domainsJSON.length; i++) {
            domainsDS.push({text:domainsJSON[i]['fq_name'][0], value:domainsJSON[i]['uuid']});
        }
        ddDomain.setData(domainsDS);
        var sel_domain = getSelectedDomainProjectObjNew("ddDomainSwitcher", "contrailDropdown", 'domain');
        ddDomain.value(sel_domain);
        fetchProjects("populateProjects");
    } else {
        $("#gridAnalyzer").data("contrailGrid")._dataView.setData([]);
        btnCreateAnalyzer.addClass('disabled-link');
        setDomainProjectEmptyMsg('ddDomainSwitcher', 'domain');
        setDomainProjectEmptyMsg('ddProjectSwitcher', 'project');
        gridAnalyzer.showGridMessage("empty");
        emptyCookie('domain');
        emptyCookie('project');
    }
};

function handleDomains(e) {
    var dName = e.added.text;
    setCookie("domain", dName);
    fetchProjects("populateProjects");
};

function populateProjects(result) {
    var projectJSON, projectDS = [];
    if (result && result.projects && result.projects.length > 0) {
        projectJSON = result.projects;
        for (var i = 0; i < projectJSON.length; i++) {
            //if(!checkSystemProject(projectJSON[i]['fq_name'][1])) {
                projectDS.push({"text":projectJSON[i]['fq_name'][1], "value":projectJSON[i]['uuid']});
            //}
        }
        btnCreateAnalyzer.removeClass('disabled-link');
        $("#ddProjectSwitcher").data("contrailDropdown").enable(true);
        ddProject.setData(projectDS);
        var selProjectObj = getSelectedDomainProjectObjNew("ddProjectSwitcher", "contrailDropdown", 'project');

        $("#ddProjectSwitcher").data("contrailDropdown").value(selProjectObj);
        check4AnalyzerImage();
        fetchDataForGridAnalyzer();
    } else {
        $("#gridAnalyzer").data("contrailGrid")._dataView.setData([]);
        btnCreateAnalyzer.addClass('disabled-link');
        setDomainProjectEmptyMsg('ddProjectSwitcher', 'project');
        gridAnalyzer.showGridMessage("empty");
        emptyCookie('project');
    }
};
function getNewSelectedProjectObj() {
    var cookiedProject = getCookie("project"),
        firstProjectName = $("#ddProjectSwitcher").data('contrailDropdown').getAllData()[0].text;
    if (cookiedProject === false) {
        setCookie("project", firstProjectName);
        return firstProjectName;
    } else {
        for (var i = 0; i < $("#ddProjectSwitcher").data('contrailDropdown').getAllData().length; i++) {
            var pname = $("#ddProjectSwitcher").data('contrailDropdown').getAllData()[i].text;
            if (pname === cookiedProject) {
                return $("#ddProjectSwitcher").data('contrailDropdown').getAllData()[i].value;
            }
        }
    }
    setCookie("project", firstProjectName);
    return firstProjectName;
}
function handleProjects(e) {
    var pname = $(e.target).data('contrailDropdown').text();
    setCookie("project", pname);
    fetchDataForGridAnalyzer();
};

function fetchDataForGridAnalyzer() {
    var selectedProjectUUID = $(ddProjectSwitcher).data('contrailDropdown').value();
    var url = "/api/tenants/config/service-instances/" + selectedProjectUUID + "?template=analyzer-template";
    gridAnalyzer._dataView.setData([]);
    gridAnalyzer.showGridMessage('loading');
    doAjaxCall(url, "GET", null, "successHandlerForGridAnalyzer", "failureHandlerForGridAnalyzer", null, null);
};

function successHandlerForGridAnalyzer(result) {
    var uuids = jsonPath(result, "$..policyuuid");
    var getAjaxs = [];
    for (var i = 0; i < uuids.length; i++) {
        getAjaxs[i] = $.ajax({
            url:"/api/tenants/config/policy/" + uuids[i],
            type:"GET"
        });
    }
    $.when.apply($, getAjaxs).then(
        function () {
            //all success
            var analyzerPolicy = arguments;
            successHandlerForGridAnalyzerRow(analyzerPolicy, result.service_instances);
        },
        function () {
            //If atleast one api fails
            var results = arguments;
            failureHandlerForGridAnalyzerRow(results);
        });
};

function failureHandlerForGridAnalyzer(result) {
	gridAnalyzer.showGridMessage('errorGettingData');
};

function successHandlerForGridAnalyzerRow(analyzerPolicy, analyzers) {
    var analyzerData = [];
    var policies = jsonPath(analyzerPolicy, "$..network-policy");
    configObj["network-policys"] = [];
    var reload = false;
    var virtualNetwork = "Automatic";
    for (var i = 0; i < policies.length; i++) {
        configObj["network-policys"][i] = policies[i];
        var policy = policies[i], vmUUId;
        var policyName = jsonPath(policy, "$.fq_name[2]");

        if (typeof policyName === "object" && policyName.length === 1)
            policyName = policyName[0];
        else
            policyName = "-";

        var uuid = jsonPath(policy, "$.uuid");
        if (typeof uuid === "object" && uuid.length === 1)
            uuid = uuid[0];

        var networks = jsonPath(policy, "$.virtual_network_back_refs[*].to[2]");
        if (networks === false) {
            networks = ["-"];
        }

        if (policy["network_policy_entries"] && policy["network_policy_entries"]["policy_rule"] &&
            policy["network_policy_entries"]["policy_rule"].length > 0) {
            var ruleDescriptions = [];
            var policyEntries = policy["network_policy_entries"]["policy_rule"];
            for (var j = 0; j < policyEntries.length; j++) {
                var rule = policyEntries[j];
                ruleDescriptions[j] = formatPolicyRule(rule);
            }
        } else {
            ruleDescriptions = ["-"];
        }
        var vmBackRefs = analyzers[i]['ConfigData']['service-instance']['virtual_machine_back_refs'];
        if(vmBackRefs == null || vmBackRefs.length == 0) {
            vmUUId = null;
            reload = true;
        } else {
            vmUUId = vmBackRefs[0]["uuid"];
        }
        if(analyzers[i]['ConfigData']['service-instance']['service_instance_properties']['left_virtual_network'] != "") {
            virtualNetwork = getVNName(analyzers[i]['ConfigData']['service-instance']['service_instance_properties']['left_virtual_network']);
        } else {
            virtualNetwork = "Automatic";
        }

        analyzerData.push({
            "Id":i, "NetworkPolicy":policyName, "PolicyRules":ruleDescriptions, "PolicyUUID":uuid, "AnalyzerName":analyzers[i]['ConfigData']['service-instance']['fq_name'][2],
            "VirtualNetwork": virtualNetwork, "AnalyzerUUID":analyzers[i]['ConfigData']['service-instance']['uuid'],
            "AssociatedNetworks":networks, "VMUUID": vmUUId, vmStatus: analyzers[i].vmStatus
        });
    }
    if(analyzerData.length == 0){
    	gridAnalyzer.showGridMessage('empty');
    }
    else{
    	gridAnalyzer._dataView.setData(analyzerData);
    }

    if(reload) {
        setTimeout("fetchDataForGridAnalyzer()", 30000);
    }
};

function failureHandlerForGridAnalyzerRow(result, cbParam) {
	gridAnalyzer.showGridMessage('errorGettingData');
};

function initgridAnalyzerDetail(e) {
};

function gridAnalyzerRowChange(arg) {
};

function closeCreateAnalyzerWindow() {
    clearValuesFromDomElements();
};

function clearValuesFromDomElements() {
    mode = "";
    txtPolicyName.val("");
    txtAnalyzerName.val("");
    txtAnalyzerName[0].disabled = false;
    msAssociatedNetworks.data("contrailMultiselect").value("");
    dlVirtualNetwork.value("Automatic");
    dlVirtualNetwork.enable(true);
    clearRuleEntries();
};

function clearRuleEntries() {
    var tuples = $("#ruleTuples")[0].children;
    if (tuples && tuples.length > 0) {
        var tupleLength = tuples.length;
        for (var i = 0; i < tupleLength; i++) {
            $(tuples[0]).remove();
        }
    }
};

function launchAnalyzer(rowIndex) {
	var selectedProject = $("#ddProjectSwitcher").data('contrailDropdown').text();
	var selectedRow = gridAnalyzer._dataView.getItem(rowIndex);
    var vmUUID = selectedRow['VMUUID'];
    var analyzerName = selectedRow['AnalyzerName'];
    if(vmUUID == null) {
        showInfoWindow("Analyzer is not ready. Please try after few minutes.", "Launch Analyzer");
    } else {
        var url = "/api/tenants/config/service-instance-vm?project_id=" + selectedProject + "&vm_id=" + vmUUID;
        doAjaxCall(url, "GET", null, "launchAnayzerInstanceCB", "failureLaunchVNCcb", false, {"sameWindow": true, "title": "VNC Console: " + analyzerName});
    }
};

function launchAnayzerInstanceCB(result, cbParams){
    var href = jsonPath(result, "$.console.url")[0];
    document.getElementById("consoleText").innerHTML = "";
    document.getElementById("consoleText").innerHTML = "If console is not responding to keyboard input: click the grey status bar below.  Click here to show only console";
    launchVNCcb(result, cbParams);
    $("body").animate({scrollTop:$("body")[0].scrollHeight-$("#vnc-console-widget").height()-60}, 1500);

}

function showAnalyzerEditWindow(mode,rowIndex) {
    var selectedDomain = $("#ddDomainSwitcher").data('contrailDropdown').text();
    var selectedProject = $("#ddProjectSwitcher").data('contrailDropdown').text();
    var getAjaxs = [];
    getAjaxs[0] = $.ajax({
        url:"/api/tenants/config/virtual-networks?tenant_id=" + selectedDomain + ":" + selectedProject,
        type:"GET"
    });

    var selectedDomainUUID = $(ddDomainSwitcher).val();
    getAjaxs[1] = $.ajax({
        url:"/api/tenants/config/service-instance-templates/" + selectedDomainUUID,
        type:"GET"
    });

    $.when.apply($, getAjaxs).then(
        function () {
            //all success
            clearValuesFromDomElements();
            var results = arguments;
            var vns = jsonPath(results[0][0], "$.virtual-networks[*].fq_name[2]");
            var vnsWithAutomatic = ["Automatic"].concat(vns);
            var virtualNetworks = jsonPath(results[0][0], "$.virtual-networks[*]");
            configObj["virtual-networks"] = [];
            if (null !== virtualNetworks && typeof virtualNetworks === "object" && virtualNetworks.length > 0) {
                for (var i = 0; i < virtualNetworks.length; i++) {
                    configObj["virtual-networks"][i] = {};
                    configObj["virtual-networks"][i] = virtualNetworks[i];
                }
            }

            msAssociatedNetworks.data("contrailMultiselect").setData(vns);
            dlVirtualNetwork.setData(vnsWithAutomatic);

            var sts = jsonPath(results[1][0], "$.service_templates[*].service-template");
            configObj["service_templates"] = [];
            if (null !== sts && sts.length > 0) {
                for (var i = 0; i < sts.length; i++) {
                    configObj["service_templates"][i] = {};
                    configObj["service_templates"][i]["service-template"] = sts[i];
                }
            }

            if (mode === "add") {
                windowCreateAnalyzer.find('.modal-header-title').text('Create Analyzer');
            } else if (mode === "edit") {
                var selectedRow = gridAnalyzer._dataView.getItem(rowIndex);
                windowCreateAnalyzer.find('.modal-header-title').text('Edit Analyzer: ' + selectedRow.AnalyzerName);
                txtPolicyName.val(selectedRow.NetworkPolicy);
                txtAnalyzerName.val(selectedRow.AnalyzerName);
                txtAnalyzerName[0].disabled = true;

                dlVirtualNetwork.value(selectedRow.VirtualNetwork);
                dlVirtualNetwork.enable(false);

                var rowId = selectedRow["Id"];
                var selectedAnalyzer = configObj["network-policys"][rowId];

                var networks = jsonPath(selectedAnalyzer, "$.virtual_network_back_refs[*].to[2]");
                if (networks && networks.length > 0) {
                    msAssociatedNetworks.data("contrailMultiselect").value(networks);
                } else {
                    msAssociatedNetworks.data("contrailMultiselect").value("");
                }
                if (selectedAnalyzer["network_policy_entries"] && selectedAnalyzer["network_policy_entries"]["policy_rule"] &&
                    selectedAnalyzer["network_policy_entries"]["policy_rule"].length > 0) {
                    var policyEntries = selectedAnalyzer["network_policy_entries"]["policy_rule"];
                    for (var j = 0; j < policyEntries.length; j++) {
                        var rule = policyEntries[j];
                        var ruleEntry = createRuleEntry(rule);
                        $(ruleTuples).append(ruleEntry);
                    }
                }
            }
            windowCreateAnalyzer.modal("show");
        },
        function () {
            //If atleast one api fails
            var results = arguments;

        });
};

function createAnalyzerSuccessCB() {
    var analyzerPolicyName = getDefaultAnalyzerPolicyName(txtAnalyzerName.val());
    var analyzerPolicy = getAnalyzerPolicy(analyzerPolicyName);
    doAjaxCall("/api/tenants/config/policys", "POST", JSON.stringify(analyzerPolicy), "createPolicySuccessCB", "createPolicyFailureCB");
};

function createAnalyzerFailureCB(error) {
    windowCreateAnalyzer.modal("hide");
    showInfoWindow("Error in Analyzer creation: " + error.responseText, "Error");
};

function createPolicySuccessCB() {
    windowCreateAnalyzer.modal("hide");
    fetchDataForGridAnalyzer();
};

function createPolicyFailureCB() {
    windowCreateAnalyzer.modal("hide");
    fetchDataForGridAnalyzer();
};

function validate() {
    if (validateAnalyzer() && validatePolicy()) {
        return true;
    } else {
        return false;
    }
};

function validatePolicy() {
    return true;
};

function validateAnalyzer() {
    if ($(txtAnalyzerName).val().trim() == "") {
        showInfoWindow("Enter a valid instance name.", "Input Required.");
        return false;
    }
    return true;
};

function destroy() {
    windowCreateAnalyzer = $("#windowCreateAnalyzer");
    windowCreateAnalyzer.remove();
    windowCreateAnalyzer = $();

    confirmDelete = $("#confirmDelete");
    confirmDelete.remove();
    confirmDelete = $();
};

function getAnalyzerPolicy(analyzerPolicyName) {
    var selectedDomain = $("#ddDomainSwitcher").data('contrailDropdown').text();
    var selectedProject = $("#ddProjectSwitcher").data('contrailDropdown').text();

    var analyzerPolicy = {};
    analyzerPolicy["ui_analyzer_flag"] = true;
    analyzerPolicy["network-policy"] = {};
    analyzerPolicy["network-policy"]["parent_type"] = "project";

    analyzerPolicy["network-policy"]["fq_name"] = [];
    analyzerPolicy["network-policy"]["fq_name"][0] = selectedDomain;
    analyzerPolicy["network-policy"]["fq_name"][1] = selectedProject;
    analyzerPolicy["network-policy"]["fq_name"][2] = analyzerPolicyName ? analyzerPolicyName : txtPolicyName.val();

    var networks = msAssociatedNetworks.data("contrailMultiselect").value();

    if (networks && networks.length > 0) {
        analyzerPolicy["network-policy"]["virtual_network_back_refs"] = [];
        for (var i = 0; i < networks.length; i++) {
            analyzerPolicy["network-policy"]["virtual_network_back_refs"][i] = {};
            analyzerPolicy["network-policy"]["virtual_network_back_refs"][i]["attr"] = {};
            analyzerPolicy["network-policy"]["virtual_network_back_refs"][i]["attr"]["timer"] = {"start_time":""};
            analyzerPolicy["network-policy"]["virtual_network_back_refs"][i]["attr"]["sequence"] = null;
            analyzerPolicy["network-policy"]["virtual_network_back_refs"][i]["uuid"] = jsonPath(configObj, "$..virtual-networks[?(@.fq_name[2]=='" + networks[i] + "')]")[0]["uuid"];
            analyzerPolicy["network-policy"]["virtual_network_back_refs"][i]["to"] = [];
            analyzerPolicy["network-policy"]["virtual_network_back_refs"][i]["to"][0] = selectedDomain;
            analyzerPolicy["network-policy"]["virtual_network_back_refs"][i]["to"][1] = selectedProject;
            analyzerPolicy["network-policy"]["virtual_network_back_refs"][i]["to"][2] = networks[i];
        }
    }

    var ruleTuples = $("#ruleTuples")[0].children;
    if (ruleTuples && ruleTuples.length > 0) {
        analyzerPolicy["network-policy"]["network_policy_entries"] = {};
        analyzerPolicy["network-policy"]["network_policy_entries"]["policy_rule"] = [];
        for (var i = 0; i < ruleTuples.length; i++) {
            analyzerPolicy["network-policy"]["network_policy_entries"]["policy_rule"][i] = {};
            var rule = analyzerPolicy["network-policy"]["network_policy_entries"]["policy_rule"][i];

            var ruleTuple = $($(ruleTuples[i]).find("div")[0]).children();
            var action = null;
            var protocol = $('#selectProtocol-' + $(ruleTuples[i]).data('ruleIndex')).data("contrailDropdown").text();
            protocol = getProtocol(protocol);
            var srcVN = $('#selectSrcNetwork-' + $(ruleTuples[i]).data('ruleIndex')).data("contrailDropdown").text();
            srcVN = checkValidSourceNetwork(srcVN);
            srcVN = getFQNofVN(selectedDomain, selectedProject, srcVN);

            var srcPorts = $($(ruleTuple[2]).find("input")).val();

            var direction = $('#selectDirection-' + $(ruleTuples[i]).data('ruleIndex')).data("contrailDropdown").text();
            if (direction !== "<>" && direction !== ">") {
                direction = "<>";
            }

            var destVN = $('#selectDestNetwork-' + $(ruleTuples[i]).data('ruleIndex')).data("contrailDropdown").text();
            destVN = checkValidDestinationNetwork(destVN);
            destVN = getFQNofVN(selectedDomain, selectedProject, destVN);

            var destPorts = $($(ruleTuple[5]).find("input")).val();

            var applyServices = null;
            var mirrorTo = selectedDomain + ":" + selectedProject + ":" + txtAnalyzerName.val();

            rule["application"] = [];
            rule["rule_sequence"] = {};
            rule["rule_sequence"]["major"] = -1;
            rule["rule_sequence"]["minor"] = -1;

            rule["ui_rule_id"] = {};
            if (i == 0) {
                rule["ui_rule_id"]["first"] = null;
            } else if (i == ruleTuples.length - 1) {
                rule["ui_rule_id"]["last"] = null;
            } else {
                rule["ui_rule_id"]["after"] = i - 1 + ".0";
            }
            rule["direction"] = direction;
            rule["protocol"] = protocol.toLowerCase();

            rule["action_list"] = {};
            rule["action_list"]["simple_action"] = action;
            rule["action_list"]["gateway_name"] = null;

            if (applyServices && applyServices.length > 0) {
                rule["action_list"]["apply_service"] = getApplyServices(applyServices);
            } else {
                rule["action_list"]["apply_service"] = null;
            }

            if (mirrorTo && "" !== mirrorTo.trim()) {
                rule["action_list"]["mirror_to"] = {};
                rule["action_list"]["mirror_to"]["analyzer_name"] = mirrorTo;
            } else {
                rule["action_list"]["mirror_to"] = null;
            }
            populateAddressesInRule("src", rule, srcVN);
            populateAddressesInRule("dst", rule, destVN);
            populatePortsInRule("src", rule, srcPorts);
            populatePortsInRule("dst", rule, destPorts);
        }
    }
    return analyzerPolicy;
};

function getAnalyzer() {
    var analyzerInstance = {};
    analyzerInstance["ui_analyzer_flag"] = true;
    var selectedDomaindd = $("#ddDomainSwitcher").data("contrailDropdown");
    var selectedDomain = selectedDomaindd.text();
    var selectedProjectdd = $("#ddProjectSwitcher").data("contrailDropdown");
    var selectedProject = selectedProjectdd.text();
    var leftVN = $('#dlVirtualNetwork').data('contrailDropdown').value();

    leftVN = getFormatVNName(leftVN);
    leftVN = leftVN != "" ? getFQNofVN(selectedDomain, selectedProject, leftVN) : leftVN;

    analyzerInstance["service-instance"] = {};
    analyzerInstance["service-instance"]["parent_type"] = "project";
    analyzerInstance["service-instance"]["fq_name"] = [];
    analyzerInstance["service-instance"]["fq_name"] = [selectedDomain, selectedProject, $(txtAnalyzerName).val()];

    analyzerInstance["service-instance"]["service_template_refs"] = [];
    analyzerInstance["service-instance"]["service_template_refs"][0] = {};
    analyzerInstance["service-instance"]["service_template_refs"][0]["to"] = [];
    analyzerInstance["service-instance"]["service_template_refs"][0]["to"] = [selectedDomain, "analyzer-template"];

    analyzerInstance["service-instance"]["service_instance_properties"] = {};

    analyzerInstance["service-instance"]["service_instance_properties"]["scale_out"] = {};
    analyzerInstance["service-instance"]["service_instance_properties"]["scale_out"]["max_instances"] = 1;
    analyzerInstance["service-instance"]["service_instance_properties"]["scale_out"]["auto_scale"] = false;

    analyzerInstance["service-instance"]["service_instance_properties"]["right_virtual_network"] = "";
    analyzerInstance["service-instance"]["service_instance_properties"]["management_virtual_network"] = "";
    analyzerInstance["service-instance"]["service_instance_properties"]["left_virtual_network"] = leftVN;
    return analyzerInstance;
};

function getVNName(vnFullName) {
    var vnArray;
    if(vnFullName == "any" || vnFullName == "local") {
        return vnFullName;
    } else {
        vnArray = vnFullName.split(":");
        if (vnArray.length == 3) {
            return vnArray[2];
        } else {
            return null;
        }
    }
};

function check4AnalyzerImage() {
    var selectedDomain = $("#ddDomainSwitcher").data('contrailDropdown').text();
    var url = '/api/tenants/config/service-template-images/' + selectedDomain;
    doAjaxCall(url, "GET", null, "successHandler4AnalyzerImage", "failureHandler4AnalyzerImage");
};

function successHandler4AnalyzerImage(result) {
    var images = result.images;
    PacketCaptureObj.isAnalyzerImageCheckDone = true;
    if(images != null) {
        for(var i = 0; i < images.length; i++) {
            if(images[i].name == 'analyzer') {
                PacketCaptureObj.isAnalyzerImageAvailable = true;
                break;
            }
        }
    }
};

function failureHandler4AnalyzerImage(error) {
    showInfoWindow("Error in getting analyzer image.", "Error");
    PacketCaptureObj.isAnalyzerImageAvailable = false;
    PacketCaptureObj.isAnalyzerImageCheckDone = true;
};


text:
import React from 'react';
import Paper from 'material-ui/Paper';
import AutoComplete from 'material-ui/AutoComplete';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import {Tab, Tabs} from 'material-ui';
import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card';
import FullStarIcon from 'material-ui/svg-icons/toggle/star';
import EmptyStarIcon from 'material-ui/svg-icons/toggle/star-border';
import faker from 'faker';
import IconButton from 'material-ui/IconButton';
import InfoIcon from 'material-ui/svg-icons/action/info';
import DeleteIcon from 'material-ui/svg-icons/content/clear';
import LinkIcon from 'material-ui/svg-icons/action/launch';
import MoreIcon from 'material-ui/svg-icons/navigation/more-vert';
import Snackbar from 'material-ui/Snackbar';
import NextIcon from 'material-ui/svg-icons/navigation/chevron-right';
import PreviousIcon from 'material-ui/svg-icons/navigation/chevron-left';
import FirstIcon from 'material-ui/svg-icons/navigation/first-page';
import LastIcon from 'material-ui/svg-icons/navigation/last-page';
import TextField from 'material-ui/TextField';

import styles from './First.css';

class First extends React.Component {
  constructor() {
    super();
    this.state = {
      value: 1,
      dataSource: [],
      entries: [],
      snackbarOpen: false,
      snackbarMessage: '',
      projectValue: 'All',
      contactValue: 'All',
      sourceValue: 'All',
      categoryValue: 'All',
      languageValue: 'All',
      countryValue: 'All',
      regionValue: 'All',
      townValue: 'All',
      count: 0,
      maxPage: 0,
      currentPage: 0,
      regionsList: [],
      townsList: [],
      searchString: ''
    };
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData() {
    let phase = 0;
    let searchString = this.state.searchString;
    if (searchString.length === 0)
      searchString = '_';
    console.info('Fetching data...', '/api/getEntries/' + this.state.projectValue + '/' + this.state.categoryValue + '/' + this.state.contactValue + '/' + this.state.currentPage + '/' + this.state.countryValue + '/' + this.state.regionValue + '/' + this.state.townValue + '/' + searchString + '/');
    fetch('/api/getEntries/' + this.state.projectValue + '/' + this.state.categoryValue + '/' + this.state.contactValue + '/' + this.state.currentPage + '/' + this.state.countryValue + '/' + this.state.regionValue + '/' + this.state.townValue + '/' + searchString + '/').then((res) => {
      return res.json().then((json) => {
        let result = json.entries;
        console.info(json);
        this.setState({
          entries: json.entries,
          regionsList: json.regionsList,
          townsList: json.townsList
        }, () => {
          this.setState({
            count: json.count,
            maxPage: json.maxPage
          }, () => {
            let msg = 'Found ' + this.state.count + ' result';
            if (json.count !== 1) {
              msg += '';
            }
            this.setState({
              snackbarMessage: msg
            }, () => {
              this.setState({
                snackbarOpen: true
              }, () => {
                console.info('state', this.state);
              });
            });
          });
        });
      });
    });
  }
  handleChange(event) {
    this.setState({searchString: event.target.value});
  }
  handleSubmit(event) {
    event.preventDefault();
    this.fetchData();
  }
  handleChangeProject = (event, index, value) => this.setState({
    projectValue: value,
    currentPage: 0
  }, () => {
    this.fetchData();
  });
  handleChangeContact = (event, index, value) => this.setState({
    contactValue: value,
    currentPage: 0
  }, () => {
    this.fetchData();
  });
  handleChangeSource = (event, index, value) => this.setState({
    sourceValue: value,
    currentPage: 0
  }, () => {
    this.fetchData();
  });
  handleChangeCategory = (event, index, value) => this.setState({
    categoryValue: value,
    currentPage: 0
  }, () => {
    this.fetchData();
  });
  handleChangeLanguage = (event, index, value) => this.setState({
    languageValue: value,
    currentPage: 0
  }, () => {
    this.fetchData();
  });
  handleChangeCountry = (event, index, value) => this.setState({
    countryValue: value,
    regionsList: [],
    townsList: [],
    regionValue: 'All',
    townValue: 'All',
    currentPage: 0
  }, () => {
    this.fetchData();
  });
  handleChangeRegion = (event, index, value) => this.setState({
    regionValue: value,
    townsList: [],
    townValue: 'All',
    currentPage: 0
  }, () => {
    this.fetchData();
  });
  handleChangeTown = (event, index, value) => this.setState({
    townValue: value,
    currentPage: 0
  }, () => {
    this.fetchData();
  });
  fakeCard(entry, i) {
    let title = entry.date.toString().substring(0, 10);
    // let title = entry.project + ' ' + entry.category;
    let subtitle = entry.town + ', ' + entry.address;
    if (this.state.contactValue === 'Phone_Only')
      title = entry.phone;
    else if (this.state.contactValue === 'Email_Only')
      subtitle = (

          {entry.email}
{entry.town + ', ' + entry.address}

      );
    else if (this.state.contactValue === 'Email_Phone') {
      title = entry.phone;
      subtitle = (

          {entry.email}
{entry.town + ', ' + entry.address}

      );
    }
    return (
      <Card key={i} expanded={true} className={styles.card}>
        <CardHeader
          className={styles.cardHeader}
          title={title}
          subtitle={subtitle}
          avatar={faker.image.image()}
          actAsExpander={true}
          showExpandableButton={false}/>
        <CardText className={styles.cardBody} expandable={true}>
          {entry.body}
        </CardText>
        <CardActions className={styles.cardActions}>
          <IconButton tooltip="Delete">
            <DeleteIcon/></IconButton>
          <IconButton target="_blank" href={entry.url} tooltip="See original page">
            <LinkIcon/></IconButton>
          <IconButton tooltip="More">
            <MoreIcon/></IconButton>
        </CardActions>
      </Card>
    );
  }
  generateCards() {
    return this.state.entries.map((entry, i) => {
      return this.fakeCard(entry, i);
    });
  }
  getFirstPage() {
    if (this.state.currentPage > 0) {
      this.setState({
        currentPage: 0
      }, () => {
        this.fetchData();
      });
    }
  }
  getPreviousPage() {
    if (this.state.currentPage > 0) {
      this.setState({
        currentPage: this.state.currentPage - 1
      }, () => {
        this.fetchData();
      });
    }
  }
  getNextPage() {
    if (this.state.currentPage < this.state.maxPage) {
      this.setState({
        currentPage: this.state.currentPage + 1
      }, () => {
        this.fetchData();
      });
    }
  }
  getLastPage() {
    if (this.state.currentPage < this.state.maxPage) {
      this.setState({
        currentPage: this.state.maxPage
      }, () => {
        this.fetchData();
      });
    }
  }
  generateRegions() {
    return this.state.regionsList.map((region, i) => {
      return <MenuItem key={i} value={region} primaryText={region}/>
    });
  }
  generateTowns() {
    return this.state.townsList.map((town, i) => {
      return <MenuItem className={styles.townsMenu} key={i} value={town} primaryText={town}/>
    });
  }
  handleRequestClose = () => {
    console.info('Closing snackbar...');
    this.setState({snackbarOpen: false});
  };
  render() {
    return (

        <Snackbar
          className={styles.snackbar}
          open={this.state.snackbarOpen}
          message={this.state.snackbarMessage}
          onRequestClose={this.handleRequestClose}
          autoHideDuration={4000}/>
        <Paper className={styles.firstPaper}>

            <form onSubmit={this.handleSubmit.bind(this)}>
              <TextField
                fullWidth
                onChange={this.handleChange.bind(this)}
                id='searchString'
                floatingLabelText='Type anything'
                value={this.state.searchString}/>
            </form>

            <SelectField
              floatingLabelText="Project"
              value={this.state.projectValue}
              onChange={this.handleChangeProject}>
              <MenuItem value='All' primaryText="All"/>
              <MenuItem value='Nanny' primaryText="Nanny"/>
              <MenuItem value='Cleaner' primaryText="Cleaner"/>
              <MenuItem value='Education' primaryText="Education"/>
              <MenuItem value='Music teacher' primaryText="Music teacher"/>
              <MenuItem value='Photography' primaryText="Photography"/>
              <MenuItem value='Music_Band' primaryText="Music band"/>
              <MenuItem value='Rides' primaryText="Rides"/>
              <MenuItem value='Miscellaneous' primaryText="Miscellaneous"/>
            </SelectField>
            <SelectField
              floatingLabelText="Contact info"
              value={this.state.contactValue}
              onChange={this.handleChangeContact}>
              <MenuItem value='All' primaryText="All"/>
              <MenuItem value='Phone_Only' primaryText="Phone only"/>
              <MenuItem value='Email_Only' primaryText="Email only"/>
              <MenuItem value='Email_Phone' primaryText="Phone & email"/>
              <MenuItem value='No_Info' primaryText="No contact info"/>
            </SelectField>
            <SelectField
              floatingLabelText="Source"
              value={this.state.sourceValue}
              onChange={this.handleChangeSource}>
              <MenuItem value='All' primaryText="All"/>
              <MenuItem value='Kijiji' primaryText="Kijiji"/>
              <MenuItem value='Gumtree_UK' primaryText="Gumtree UK"/>
              <MenuItem value='Locanto' primaryText="Locanto"/>
              <MenuItem value='LeBonCoin' primaryText="LeBonCoin"/>
              <MenuItem value='Gumtree_AU' primaryText="Gumtree AU"/>
              <MenuItem value='Classifiedads' primaryText="Classifiedads"/>
            </SelectField>
            <SelectField
              floatingLabelText="Category"
              value={this.state.categoryValue}
              onChange={this.handleChangeCategory}>
              <MenuItem value='All' primaryText="All"/>
              <MenuItem value='Offering' primaryText="Offering"/>
              <MenuItem value='Wanted' primaryText="Wanted"/>
            </SelectField>

            <SelectField
              floatingLabelText="Language"
              value={this.state.languageValue}
              onChange={this.handleChangeLanguage}>
              <MenuItem value='All' primaryText="All"/>
              <MenuItem value='English' primaryText="English"/>
              <MenuItem value='French' primaryText="French"/>
              <MenuItem value='Unknown' primaryText="Unknown"/>
            </SelectField>
            <SelectField
              floatingLabelText="Country"
              value={this.state.countryValue}
              onChange={this.handleChangeCountry}>
              <MenuItem value='All' primaryText="All"/>
              <MenuItem value="Canada" primaryText="Canada"/>
              <MenuItem value="United Kingdom" primaryText="United Kingdom"/>
              <MenuItem value="France" primaryText="France"/>
              <MenuItem value="Australia" primaryText="Australia"/>
            </SelectField>
            <SelectField
              floatingLabelText="Region"
              value={this.state.regionValue}
              onChange={this.handleChangeRegion}
              disabled={!this.state.regionsList || this.state.regionsList.length === 0}>
              {this.generateRegions()}
            </SelectField>
            <SelectField
              className={styles.townSelect}
              floatingLabelText="Town"
              value={this.state.townValue}
              onChange={this.handleChangeTown}
              disabled={!this.state.townsList || this.state.townsList.length === 0}>
              {this.generateTowns()}
            </SelectField>

        </Paper>
        <Tabs>
          <Tab label='Feed'>

              {this.generateCards()}

              <IconButton
                onTouchTap={() => this.getFirstPage()}
                disabled={this.state.currentPage <= 0}
                tooltip="First page">
                <FirstIcon/>
              </IconButton>
              <IconButton
                onTouchTap={() => this.getPreviousPage()}
                disabled={this.state.currentPage <= 0}
                tooltip="Previous page">
                <PreviousIcon/>
              </IconButton>
              {this.state.currentPage}
              <IconButton
                onTouchTap={() => this.getNextPage()}
                disabled={this.state.currentPage >= this.state.maxPage}
                tooltip="Next page">
                <NextIcon/>
              </IconButton>
              <IconButton
                onTouchTap={() => this.getLastPage()}
                disabled={this.state.currentPage >= this.state.maxPage}
                tooltip="Last page">
                <LastIcon/>
              </IconButton>

          </Tab>
          <Tab label='Trasmit'></Tab>
          <Tab label='Scrape'></Tab>
          <Tab label='Statistics'></Tab>
        </Tabs>

    );
  }
}

export default First;


text:
(function () {
    'use strict';

    /* Directives */

    var directives = angular.module('admin.directives', []);

    directives.directive('sidebar', function () {
       return function (scope, element, attrs) {
           $(element).sidebar({
               position:"right"
           });
       };
    });

    directives.directive('clearForm', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                $(element).on('hidden', function () {
                    $('#' + attrs.clearForm).clearForm();
                });
            }
        };
    });

    directives.directive('setLevelFilter', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var elm = angular.element(element), attribute = attrs;
                elm.click(function (e) {
                    if (elm.children().hasClass("fa-check-square-o")) {
                        $(this).children().removeClass('fa-check-square-o').addClass('fa-square-o');
                        $(this).removeClass('active');
                    }
                    else {
                        elm.children().addClass('fa-check-square-o').removeClass('fa-square-o');
                        elm.addClass('active');
                    }
                });
            }
        };
    });

    directives.directive('filereader', function () {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                element.bind('change', function(e){
                   scope.$apply(function(){
                       scope[attrs.filereader](e.target.files[0]);
                   });
                });
            }
        };
    });

}());