text:
package com.eaw1805.battles.field.test;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.eaw1805.battles.BattleField;
import com.eaw1805.battles.field.FieldBattleProcessor;
import com.eaw1805.battles.field.morale.MoraleChecker;
import com.eaw1805.battles.field.orders.FieldBattleOrderProcessor;
import com.eaw1805.battles.field.processors.LongRangeProcessor;
import com.eaw1805.battles.field.processors.commander.CommanderProcessor;
import com.eaw1805.battles.field.processors.commander.CommanderType;
import com.eaw1805.battles.field.test.FieldBattleTestUtils.TerrainConstantsEnum;
import com.eaw1805.battles.field.utils.ArmyUtils;
import com.eaw1805.battles.field.utils.VisualisationUtils;
import com.eaw1805.data.HibernateUtil;
import com.eaw1805.data.model.army.ArmyType;
import com.eaw1805.data.model.army.Battalion;
import com.eaw1805.data.model.army.Brigade;
import com.eaw1805.data.model.battles.field.FieldBattleMap;
import com.eaw1805.data.model.battles.field.FieldBattlePosition;
import com.eaw1805.data.model.battles.field.FieldBattleSector;
import com.eaw1805.data.model.battles.field.Order;
import com.eaw1805.data.model.battles.field.enumerations.ArmEnum;
import com.eaw1805.data.model.battles.field.enumerations.FormationEnum;
import com.eaw1805.data.model.battles.field.enumerations.MoraleStatusEnum;
import com.eaw1805.data.model.battles.field.enumerations.OrdersEnum;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class LongRangeFireProcessorTest {

    private FieldBattleProcessor fieldBattleProcessor;
    private LongRangeProcessor longRangeProcessor;
    private Brigade brigade0;
    private BattleField bf;
    private Brigade brigade1;
    private Brigade brigade2;

    @Before
    @SuppressWarnings("unchecked")
    public void setup() {

        FieldBattleMap fbMap = new FieldBattleMap(45, 40);

        List<Brigade>[] sideBrigadesArray = (List<Brigade>[]) Array.newInstance(List.class, 2);

        List<Brigade> sideBrigades0 = new ArrayList<Brigade>();
        brigade0 = new Brigade();
        brigade0.setBattalions(new HashSet<Battalion>());
        sideBrigades0.add(brigade0);
        Order basicOrder0 = new Order();
        basicOrder0.setActivationRound(0);
        basicOrder0.setCheckpoint1(new FieldBattlePosition(20, 40));
        basicOrder0.setOrderTypeEnum(OrdersEnum.ENGAGE_IF_IN_RANGE);
        brigade0.setBasicOrder(basicOrder0);
        brigade0.setFormationEnum(FormationEnum.LINE);
        brigade0.setFieldBattlePosition(new FieldBattlePosition(20, 19));
        FieldBattleTestUtils.addBattalions(brigade0, 100, ArmEnum.INFANTRY, false);
        brigade0.setArmTypeEnum(ArmyUtils.findArm(brigade0));
        brigade0.setMoraleStatusEnum(MoraleStatusEnum.NORMAL);

        List<Brigade> sideBrigades1 = new ArrayList<Brigade>();
        brigade1 = new Brigade();
        brigade1.setBattalions(new HashSet<Battalion>());
        sideBrigades1.add(brigade1);
        Order basicOrder1 = new Order();
        basicOrder1.setActivationRound(0);
        basicOrder1.setCheckpoint1(new FieldBattlePosition(20, 0));
        basicOrder1.setOrderTypeEnum(OrdersEnum.ENGAGE_IF_IN_RANGE);
        brigade1.setBasicOrder(basicOrder1);
        brigade1.setFormationEnum(FormationEnum.LINE);
        brigade1.setFieldBattlePosition(new FieldBattlePosition(20, 21));
        FieldBattleTestUtils.addBattalions(brigade1, 100, ArmEnum.INFANTRY, false);
        brigade1.setArmTypeEnum(ArmyUtils.findArm(brigade1));
        brigade1.setMoraleStatusEnum(MoraleStatusEnum.NORMAL);

        brigade2 = new Brigade();
        brigade2.setBattalions(new HashSet<Battalion>());
        sideBrigades1.add(brigade2);
        Order basicOrder2 = new Order();
        basicOrder2.setActivationRound(0);
        basicOrder2.setCheckpoint1(new FieldBattlePosition(20, 0));
        basicOrder2.setOrderTypeEnum(OrdersEnum.ENGAGE_IF_IN_RANGE);
        brigade2.setBasicOrder(basicOrder2);
        brigade2.setFormationEnum(FormationEnum.LINE);
        brigade2.setFieldBattlePosition(new FieldBattlePosition(20, 22));
        FieldBattleTestUtils.addBattalions(brigade2, 100, ArmEnum.INFANTRY, false);
        brigade2.setArmTypeEnum(ArmyUtils.findArm(brigade2));
        brigade2.setMoraleStatusEnum(MoraleStatusEnum.NORMAL);

        sideBrigadesArray[0] = sideBrigades0;
        sideBrigadesArray[1] = sideBrigades1;

        bf = FieldBattleTestUtils.prepareBattleField(TerrainConstantsEnum.PLAINS.getId(), 9, 3, 2, 2);
        fieldBattleProcessor = new FieldBattleProcessor(false, HibernateUtil.DB_S1);
        fieldBattleProcessor.setBattleField(bf);
        fieldBattleProcessor.setFieldBattleOrderProcessor(new FieldBattleOrderProcessor(fieldBattleProcessor));
        fieldBattleProcessor.setFbMap(fbMap);
        fieldBattleProcessor.setSideBrigades(sideBrigadesArray);
        fieldBattleProcessor.setMoraleChecker(new MoraleChecker(fieldBattleProcessor));
        fieldBattleProcessor.getMoraleChecker().calculateInitialSideMoralesIfRequired();

        BiMap<FieldBattleSector, Brigade> sectorsToBrigades = HashBiMap.create();
        sectorsToBrigades.put(fbMap.getFieldBattleSector(brigade0.getFieldBattlePosition().getX(), brigade0.getFieldBattlePosition().getY()), brigade0);
        sectorsToBrigades.put(fbMap.getFieldBattleSector(brigade1.getFieldBattlePosition().getX(), brigade1.getFieldBattlePosition().getY()), brigade1);
        sectorsToBrigades.put(fbMap.getFieldBattleSector(brigade2.getFieldBattlePosition().getX(), brigade2.getFieldBattlePosition().getY()), brigade2);
        fieldBattleProcessor.setSectorsToBrigades(sectorsToBrigades);

        CommanderProcessor commanderProcessorMock = mock(CommanderProcessor.class);
        when(commanderProcessorMock.influencedByCommander(any(Brigade.class))).thenReturn(false);
        when(commanderProcessorMock.influencedByCommanderOfType(any(Brigade.class), any(CommanderType.class))).thenReturn(false);
        fieldBattleProcessor.setCommanderProcessor(commanderProcessorMock);

        longRangeProcessor = new LongRangeProcessor(fieldBattleProcessor);
    }

    @Test
    public void testProcess() throws IOException {

        System.out.println(VisualisationUtils.getHeadCountInformation(brigade0));
        System.out.println(VisualisationUtils.getHeadCountInformation(brigade1));
        System.out.println(VisualisationUtils.getHeadCountInformation(brigade2));

        for (int round = 1; round < 50; round++) {

            for (int side = 0; side <= 1; side++) {

                longRangeProcessor.process(side, round);
                System.out.println("Brigade 0\n");
                System.out.println(VisualisationUtils.getHeadCountInformation(brigade0));
                System.out.println("\n");
                System.out.println("Brigade 1\n");
                System.out.println(VisualisationUtils.getHeadCountInformation(brigade1));
                System.out.println("\n");
                System.out.println("Brigade 2\n");
                System.out.println(VisualisationUtils.getHeadCountInformation(brigade2));

            }

        }

    }

    @Test
    public void testProcess_1Inf_2Art() {
        brigade0.setFormationEnum(FormationEnum.COLUMN);
        brigade0.getBattalions().clear();

        ArmyType infantryArmyType = new ArmyType();
        infantryArmyType.setName("in");
        infantryArmyType.setType("in");
        infantryArmyType.setLongRange(8);
        infantryArmyType.setLongCombat(7);

        ArmyType artilleryArmyType = new ArmyType();
        artilleryArmyType.setName("Ar");
        artilleryArmyType.setType("Ar");
        artilleryArmyType.setLongRange(8);
        artilleryArmyType.setLongCombat(7);

        Battalion battalion1 = new Battalion();
        battalion1.setType(infantryArmyType);
        battalion1.setHeadcount(800);
        battalion1.setExperience(3);
        brigade0.getBattalions().add(battalion1);

        Battalion battalion2 = new Battalion();
        battalion2.setType(artilleryArmyType);
        battalion2.setHeadcount(800);
        battalion2.setExperience(3);
        brigade0.getBattalions().add(battalion2);

        Battalion battalion3 = new Battalion();
        battalion3.setType(artilleryArmyType);
        battalion3.setHeadcount(800);
        battalion3.setExperience(3);
        brigade0.getBattalions().add(battalion3);

        brigade0.setArmTypeEnum(ArmyUtils.findArm(brigade0));

        printBrigadesStatus();

        for (int round = 1; round < 50; round++) {

            for (int side = 0; side <= 1; side++) {

                longRangeProcessor.process(side, round);
                printBrigadesStatus();

            }

        }

    }

    @Test
    public void testProcess_1Inf_2Art_WithRicochet() {
        brigade0.setFormationEnum(FormationEnum.COLUMN);
        brigade0.getBattalions().clear();

        ArmyType infantryArmyType = new ArmyType();
        infantryArmyType.setName("in");
        infantryArmyType.setType("in");
        infantryArmyType.setLongRange(8);
        infantryArmyType.setLongCombat(7);

        ArmyType artilleryArmyType = new ArmyType();
        artilleryArmyType.setName("Ar");
        artilleryArmyType.setType("Ar");
        artilleryArmyType.setLongRange(8);
        artilleryArmyType.setLongCombat(7);

        Battalion battalion1 = new Battalion();
        battalion1.setType(infantryArmyType);
        battalion1.setHeadcount(800);
        battalion1.setExperience(3);
        brigade0.getBattalions().add(battalion1);

        Battalion battalion2 = new Battalion();
        battalion2.setType(artilleryArmyType);
        battalion2.setHeadcount(800);
        battalion2.setExperience(3);
        brigade0.getBattalions().add(battalion2);

        Battalion battalion3 = new Battalion();
        battalion3.setType(artilleryArmyType);
        battalion3.setHeadcount(800);
        battalion3.setExperience(3);
        brigade0.getBattalions().add(battalion3);

        brigade0.setArmTypeEnum(ArmyUtils.findArm(brigade0));

        printBrigadesStatus();

        for (int round = 1; round < 50; round++) {

            for (int side = 0; side <= 1; side++) {

                longRangeProcessor.process(side, round);
                printBrigadesStatus();

            }

        }

    }

    private void printBrigadesStatus() {
        System.out.println("Brigade 0\n");
        System.out.println(VisualisationUtils.getHeadCountInformation(brigade0));
        System.out.println("\n");
        System.out.println("Brigade 1\n");
        System.out.println(VisualisationUtils.getHeadCountInformation(brigade1));
        System.out.println("\n");
        System.out.println("Brigade 2\n");
        System.out.println(VisualisationUtils.getHeadCountInformation(brigade2));
    }

}


text:
using System.Linq;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using NUnit.Framework;

namespace MongoDB.Driver.Tests.Jira
{
    [TestFixture]
    public class CSharp718
    {
        public class C
        {
            public int Id;
            public int[] Foo;
        }

        private MongoServer _server;
        private MongoDatabase _database;
        private MongoCollection<C> _collection;

        [TestFixtureSetUp]
        public void Setup()
        {
            _server = Configuration.TestServer;
            _database = Configuration.TestDatabase;
            _collection = Configuration.GetTestCollection<C>();
            TestSetup();
        }

        [Test]
        public void TestLinqNullEquality()
        {
            var postsWithFoo = (from d in _collection.AsQueryable<C>()
                where d.Foo == null
                select d).Count();
            Assert.AreEqual(2, postsWithFoo);
        }

        [Test]
        public void TestLinqNullInequality()
        {
            var postsWithFoo = (from d in _collection.AsQueryable<C>()
                where d.Foo != null
                select d).Count();
            Assert.AreEqual(3, postsWithFoo);
        }

        private void TestSetup()
        {
            _collection.RemoveAll();
            _collection.Insert(new C() { Id = 1});
            _collection.Insert(new C() { Id = 2, Foo = null});
            _collection.Insert(new C() { Id = 3, Foo = new int[] {1}});
            _collection.Insert(new C() { Id = 4, Foo = new int[] { 1, 2 } });
            _collection.Insert(new C() { Id = 5, Foo = new int[] { 1, 2, 3 } });
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
const chalk = require('chalk');
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const exec = require('child-process-promise').exec;

class Deployr {

    constructor(config = {}) {
        const { key = null, port = 4000, memoryLimit = '10mb', branch, checkCommits = true } = config;

        this.key = key;
        this.port = port;
        this.memoryLimit = memoryLimit;
        this.branch = branch;
        this.checkCommits = checkCommits;
    }

    listen = callback => {
        // Create express server
        const app = express();

        // parse JSON
        // (Github web hooks send JSON)
        app.use(bodyParser.urlencoded({ limit: this.memoryLimit, extended: true }));
        app.use(bodyParser.json({ limit: this.memoryLimit }));

        // handle POST requests
        app.post('*', (req, res) => {
            const action = req.body;

            if (this.branch && action.ref !== `refs/heads/${this.branch}`) return; // check branch
            if (this.checkCommits && (!action.commits || !action.commits.length)) return; // check if commits made

            if (this.key) {
                // Verify SHA1 encrypted secret key
                // This is to make sure no one can send a bogus requests
                const hmac = crypto.createHmac('sha1', this.key);
                hmac.update(JSON.stringify(req.body));
                const sig = 'sha1=' + hmac.digest('hex');

                // Key mismatch
                // Likely bogus request. stop executing
                if (req.headers['x-hub-signature'] !== sig) {
                    this.log(chalk.red.bold('Github secret key verificiation failed!'));
                    return;
                }
            }

            // We're good to go
            console.log(chalk.gray('-----------------------------------'));
            this.log(chalk.yellow.bold('✨  Starting deployment...'));

            callback(req.body, this.pull);

            res.send('deploying');
        });

        app.listen(this.port, err => {
            if (err) {
                console.error(err);
                return;
            }

            this.log(`🌐  Listening on port ${this.port}`);
        });
    }

    // Get latest from github
    // This also runs `git reset --hard`
    // to make sure we're identical to github repo
    pull = () =>
        new Promise((resolve, reject) => {
            this.log('Git: start');

            exec('git reset --hard')
                .then(() => exec('git pull'))
                .then(() => {
                    this.log('Git: finished');
                    resolve();
                })
                .catch(err => {
                    console.log(err.stdout);
                    reject(err);
                });
        })

    log = message => {
        console.log(chalk.gray('[deployr] ') + message);
    }
}

module.exports = Deployr;


text:
<?php get_header(); ?>

<?php // Get Theme Options from Database
	$theme_options = leeway_theme_options();

	// Display Featured Post Slideshow if activated
	if ( isset($theme_options['slider_active_blog']) and $theme_options['slider_active_blog'] == true ) :

		get_template_part( 'featured-content-slider' );

	endif;
?>

		<?php if ( function_exists( 'themezee_breadcrumbs' ) ) themezee_breadcrumbs(); ?>

		<?php if (have_posts()) : while (have_posts()) : the_post();

			get_template_part( 'content', $theme_options['posts_length'] );

			endwhile;

		leeway_display_pagination();

		endif; ?>

		<?php get_sidebar(); ?>

<?php get_footer(); ?>


text:
exports.data = {
	name: 'Source',
	command: 'source',
	description: 'Provides a link to the bot\'s source code',
	group: 'system',
	syntax: 'wt source',
	author: 'Matt C: matt@artemisbot.uk',
	permissions: 0
};

const log = require('../lib/log.js')(exports.data.name);

exports.func = async (msg, args, bot) => {
	try {
		log.verbose(`${msg.member.displayName} (${msg.author.username}#${msg.author.discriminator}) has requested the bot's source in #${msg.channel.name} on ${msg.guild.name}.`);
		await msg.reply(`The bot's source can be found at https://github.com/artemisbot/wakingtitan`);
	} catch (e) {
		log.error(`Something went wrong: ${e}`);
	}
};


text:
  {{$parent.vm.modalTitle}}

      Practical Startpage

{{item.title}}

{{item.text}}

      {{vm.data.languages}}

English(default)

Deutsch/German

Jeremy Clarke

                    Linked

                    profile

Robert Priebs

                     Xing profile

Español/Spanish

                @albertva

Mattias Bengtsson

                    Linked

                    profile

Français/French

Emma Songeur

                    Hallo and Bonjour

Português(Brasil)/Portuguese(Brazil)

Rafael Ferreira

Svenska/Swedish

Paul Dhillon

                    Linked

                    profile

Türkçe/Turkish

Çağdaş Şeniş

                    Linked

                    profile

      {{vm.data.libraries}}

ngJsTree

angular-drag-and-drop-lists


text:
package opensesim.gui.orderbook;

/**
 *
 * @author tobias
 */
public class QutoesHorizontal extends javax.swing.JPanel {

    /**
     * Creates new form QutoesHorizontal
     */
    public QutoesHorizontal() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Price: 200.123");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(110, 110, 110)
                .addComponent(jLabel1)
                .addContainerGap(175, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:id="@+id/draw_layout"
    android:layout_height="match_parent">

    <android.support.design.widget.CoordinatorLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/toolbar_my_patients"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            android:theme="?attr/actionBarTheme" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:orientation="horizontal"
                android:weightSum="2">

                <ImageButton
                    android:id="@+id/imageButton_my_patients_options"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:background="@drawable/menu"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="5dp"
                    />

                <android.support.v7.widget.SearchView
                    android:id="@+id/search_bar_my_patients_search"
                    android:layout_width="wrap_content"
                    android:layout_height="50dp"
                    android:layout_marginStart="5dp" />

                <TextView
                    android:id="@+id/textView_my_patients_patients"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Patients"
                    android:textColor="#ffffff"
                    android:textAlignment="center"
                    android:clickable="false"
                    android:textSize="20dp"
                    android:padding="2dp"
                    android:gravity="center"
                    android:layout_marginTop="10dp"
                    android:layout_weight="2" />

                <ImageButton
                    android:id="@+id/imageButton_my_patients_add_patient"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_marginStart="10dp"
                    android:layout_marginEnd="14dp"
                    android:background="@drawable/add_user_2"
                    android:layout_marginTop="10dp"/>

            </LinearLayout>

        </android.support.design.widget.AppBarLayout>

        <ListView
            android:id="@+id/listView_my_patients"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

        <com.wang.avi.AVLoadingIndicatorView
            android:id="@+id/avi"
            android:layout_width="75dp"
            android:layout_height="75dp"
            style="@style/AVLoadingIndicatorView"
            android:visibility="visible"
            app:indicatorName="BallClipRotateMultipleIndicator" android:layout_gravity="center"
            app:indicatorColor= "@color/colorAccent"
            />

    </android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:orientation="vertical"
            android:background="#3498db"
            android:weightSum="2">

            <ImageView
                android:layout_width="150dp"
                android:layout_height="150dp"
                android:background="@drawable/logo"
                android:layout_gravity="center"
                />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginStart="20dp"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp">

                <TextView
                    android:id="@+id/textView_navigation_dr"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="#ffffff"
                    android:textSize="20dp"
                    android:text="Dr. "/>

                <TextView
                    android:id="@+id/textView_navigation_fullname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Full name"
                    android:textColor="#ffffff"
                    android:textSize="20dp"/>

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:background="#ffffff">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp">

                <ImageView
                    android:id="@+id/imageView_navigation_view_profile"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    app:srcCompat="@drawable/view_profile"
                    android:layout_marginStart="20dp"
                    android:clickable="true"/>

                <TextView
                    android:id="@+id/pro_btn"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="View Profile"
                    android:textSize="24dp"
                    android:textColor="#000000"
                    android:layout_marginStart="20dp"
                    android:clickable="true"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp">

                <ImageView
                    android:id="@+id/imageView_navigation_delete_account"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    app:srcCompat="@drawable/delete_account"
                    android:layout_marginStart="20dp"/>

                <TextView
                    android:id="@+id/delete_account_btn"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Delete Account"
                    android:textColor="#000000"
                    android:textSize="24dp"
                    android:layout_marginStart="20dp"
                    android:clickable="true"
                    />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp">

                <ImageView
                    android:id="@+id/imageView_navigation_logout"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    app:srcCompat="@drawable/logout"
                    android:layout_marginStart="20dp"/>

                <TextView
                    android:id="@+id/logout_btn"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Logout"
                    android:textColor="#000000"
                    android:textSize="24dp"
                    android:layout_marginStart="20dp"
                    android:clickable="true"
                    />

            </LinearLayout>

            </LinearLayout>
        </LinearLayout>

    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>


text:
<?php
/**
 * Created by PhpStorm.
 * User: jeen
 * Date: 2017/10/19
 * Time: 21:56
 */

namespace common\core;

use common\model\Module;

class ModuleInfo extends PackageInfo
{
    public $type = Module::TYPE_EXTEND;

    public function getModuleClass()
    {
        return $this->getNamespace() . '\\' . 'Module';
    }

    public function getIsCore()
    {
        return $this->type == Module::TYPE_CORE;
    }

    protected function addMenu($name, $route)
    {
        $id = \Yii::$app->db->createCommand('SELECT `id` FROM {{%menu}} WHERE `name`="插件" AND `parent` IS NULL')->queryScalar();
        $model = new Menu();
        $model->name = $name;
        $model->route = $route;
        $model->parent = $id;
        return $model->save(false);
    }

    protected function deleteMenu($name)
    {
        $id = \Yii::$app->db->createCommand('SELECT `id` FROM {{%menu}} WHERE `name`="插件" AND `parent` IS NULL')->queryScalar();
        $menu = Menu::find()->where(['parent' => $id])->andWhere(['name' => $name])->one();
        if ($menu === null) {
            return true;
        }
        return $menu->delete();
    }
}


text:
<?php

/**
 * @namespace
 */
namespace Solarium\Core\Query;
use Solarium\Core\Query\QueryInterface;
use Solarium\Core\Client\Request;

/**
 * Interface for requestbuilders
 */
interface RequestBuilderInterface
{

    /**
     * Build request for a select query
     *
     * @param  QueryInterface $query
     * @return Request
     */
    public function build(QueryInterface $query);

}


text:
<?php
namespace sbnc\modules;

use sbnc\Sbnc;
use sbnc\core\Module;

/**
 * Class Content
 *
 * Can count links, spam words and block mail injections by keywords
 *
 * @package sbnc\modules
 */
class Content extends Module
{

    ######################################################################################
    #########################           CONFIGURATION            #########################
    ######################################################################################

    /**
     * May be disabled if any inconsistencies occur
     *
     * @var bool Enable or disable module
     */
    protected $enabled = true;

    /**
     * Module options
     *
     * - maxlinks
     *      check how often you allow the http:// or <a in your form
     *
     * - mailwords
     *      gives an error if these string are used in the form:
     *      bcc: cc: multipart [url Content-Type:
     *
     * - spam_words
     *      allow a maximum of words from the spam_words list in your form
     *      multiple words count as one match e.g. "buy viagra today at viagrastore.com"
     *      gets a score of 1
     *
     * @var array Options
     */
    private $use = ['max_links', 'mail_words', 'spam_words'];

    /**
     * Set options the used checks
     *
     * @var array
     */
    private $options = [
        'max_links' => [
            'max' => 2
        ],
        'spam_words' => [
            'max' => 2,
            'count_duplicates' => false
        ]
    ];

    /**
     * Set your custom error messages
     *
     * @var array Error messages
     */
    private $errors = [
        'max_links' => 'A maximum of %max% urls are allowed on the entire form.',
        'mail_words' => 'Mail injection detected. Do not use these words: bcc:, cc:, multipart, [url, Content-Type',
        'spam_words' => 'A maximum of %max% blacklisted matches are allowed, %matches% used: %words%'
    ];

    /**
     * List of spam words
     *
     * @var array Collection of spam words
     */
    private $spam_words = [
        'д', 'и', 'ж', 'Ч', 'Б', '\. ,', '\? ,',
        '-online', '4u', 'aceteminophen', 'adderall', 'adipex', 'advicer', 'ambien', 'anime', 'ass', 'augmentation',
        'baccarat', 'baccarrat', 'bdsm', 'bitch', 'blackjack', 'bllogspot', 'booker', 'breast', 'byob',
        'car-rental-e-site', 'car-rentals-e-site', 'carisoprodol', 'casino', 'casinos', 'cephalaxin', 'chatroom',
        'cialis', 'citalopram', 'clomid', 'cock', 'coolcoolhu', 'coolhu', 'credit card', 'credit-card-debt',
        'credit-report-4u', 'cwas', 'cyclen', 'cyclobenzaprine', 'cymbalta', 'dating', 'dating-e-site', 'day-trading',
        'debt', 'debt-consolidation', 'debt-consolidation-consultant', 'dick', 'discreetordering', 'doxycycline',
        'duty-free', 'dutyfree', 'enhancement', 'ephedra', 'equityloans', 'facial', 'femdom', 'fetish', 'finance',
        'fioricet', 'flowers', 'flowers-leading-site', 'freenet', 'freenet-shopping', 'fuck', 'fucking', 'gambling',
        'gambling-', 'gay', 'gdf', 'gds', 'hair-loss', 'health-insurancedeals-4u', 'holdem', 'holdempoker',
        'holdemsoftware', 'holdemtexasturbowilson', 'homeequityloans', 'homefinance', 'hotel', 'hotel-dealse-site',
        'hotele-site', 'hotelse-site', 'hqtube', 'hydrocodone', 'incest', 'insurance', 'insurance-quotesdeals-4u',
        'insurancedeals-4u', 'jrcreations', 'lesbian', 'levitra', 'lexapro', 'lipitor', 'loan', 'lorazepam',
        'lunestra', 'macinstruct', 'male', 'mortgage', 'mortgage-4-u', 'mortgagequotes', 'meridia', 'myspace',
        'naked', 'nude', 'online-gambling', 'onlinegambling-4u', 'ottawavalleyag', 'ownsthis', 'oxycodone', 'oxycontin',
        'palm-texas-holdem-game', 'paxil', 'payday', 'penis', 'percocet', 'pharmacy', 'phentermine', 'pills', 'poker',
        'poker-chip', 'porn', 'porno', 'poze', 'propecia', 'pussy', 'rental', 'rental-car-e-site', 'ringtone',
        'ringtones', 'roulette', 'sex', 'shemale', 'shit', 'shoes', 'slot-machine', 'soma', 'texas holdem',
        'texas-holdem', 'thorcarlson', 'thx', 'tits', 'titties', 'top-e-site', 'top-site', 'tramadol', 'trading',
        'trim-spa', 'ultram', 'valeofglamorganconservatives', 'valium', 'valtrex', 'viagra', 'vicodin', 'vicoprofen',
        'vioxx', 'visa', 'xanax', 'xenical', 'youtube', 'zolus'
    ];

    ######################################################################################
    ######################################################################################

    public function init()
    {
        if (isset($this->options['max_links']['max'])) {
            $this->options['max_links']['max']++;
        }
    }

    public function check()
    {
        $request = implode(Sbnc::request());

        if (in_array('max_links', $this->use)) {
            if (preg_match_all("#http:#i", $request, $out) > $this->options['max_links']['max']) {
                $err = str_replace('%max%', $this->options['max_links']['max'], $this->errors['max_links']);
                Sbnc::addError($err);

                $log = 'Maximum of ' . $this->options['max_links']['max'] . ' links reached.';
                Sbnc::log('spam-content', $log);
            }
        }

        if (in_array('mail_words', $this->use)) {
            if (preg_match("/bcc:|cc:|multipart|Content-Type:/i", $request)) {
                $err = $this->errors['mail_words'];
                Sbnc::addError($err);
                Sbnc::log('spam-content', 'Mail injection detected');
            }
        }
        if (in_array('spam_words', $this->use)) {

            $names = implode('|', $this->spam_words);
            $regex = '#[-+]?(' . $names . ')#';
            preg_match_all($regex, $request, $all_matches);

            if (!$this->options['spam_words']['count_duplicates']) {
                $matches = isset($all_matches[0]) ? array_unique($all_matches[0]) : [];
            } else {
                $matches = isset($all_matches[0]) ? $all_matches[0] : [];
            }

            $num_matches = count($matches);

            if ($num_matches > $this->options['spam_words']['max']) {
                $words = implode(', ', $matches);
                $err = str_replace(
                    ['%max%', '%words%', '%matches%'],
                    [$this->options['spam_words']['max'], $words, $num_matches],
                    $this->errors['spam_words']
                );
                Sbnc::addError($err);
                $log = 'More than ' . $this->options['spam_words']['max'] . ' spam words found: ' . $words;
                Sbnc::log('spam-content', $log);
            }
        }
    }

}


text:
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{ .Params.Title }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="{{ .Site.Params.theme_color }}">
<meta name="description" content="{{ .Description }}">
<meta property="og:description" content="{{ .Description }}">
<meta name="twitter:description" content="{{ .Description }}">
<meta property="og:image" content="{{ .Params.Thumbnail }}">
<meta name="twitter:image" content="{{ .Params.Thumbnail }}">
<link rel="icon" href="{{ .Site.BaseURL }}img/{{ .Site.Params.Favicon }}" type="image/x-icon">
<link rel="shortcut icon" href="{{ .Site.BaseURL }}img/{{ .Site.Params.Favicon }}" type="image/x-icon">
<link rel="stylesheet" href="{{ .Site.BaseURL }}css/final.css">
<link rel="stylesheet" href="{{ .Site.BaseURL }}css/normalize.css">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet">


text:
package jp77.utillib.interfaces;

public interface IInputBuffer {
	public int fill(byte[] buffer, int offset, int length);
}


text:
<?xml version="1.0"?>
<package>
  <name>infinisoleil</name>
  <version>1.1.0</version>
  <description>
    This package provides a ROS driver for Infinisoleil sensors.
  </description>

  <maintainer email="3d-sensing@nippon-control-system.co.jp">
    NCS 3D Sensing Team
  </maintainer>
  <author email="3d-sensing@nippon-control-system.co.jp">
    NCS 3D Sensing Team
  </author>

  <license>BSD</license>
  <url type="website">http://ros.org/wiki/infinisoleil</url>
  <url type="repository">
    https://github.com/ncs-3d-sensing/infinisoleil
  </url>
  <url type="bugtracker">
    https://github.com/ncs-3d-sensing/infinisoleil/issues
  </url>

  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>diagnostic_updater</build_depend>
  <build_depend>dynamic_reconfigure</build_depend>
  <build_depend>nodelet</build_depend>
  <build_depend>roscpp</build_depend>
  <build_depend>sensor_msgs</build_depend>
  <build_depend>roslaunch</build_depend>
  <build_depend>rostest</build_depend>

  <run_depend>diagnostic_updater</run_depend>
  <run_depend>dynamic_reconfigure</run_depend>
  <run_depend>nodelet</run_depend>
  <run_depend>roscpp</run_depend>
  <run_depend>sensor_msgs</run_depend>

  <export>
    <nodelet plugin="${prefix}/infinisoleil_nodelets.xml"/>
  </export>
</package>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Peniophora rufa f. subpileata

### Remarks
null


text:
package ala

import akka.actor.{ActorRef, Actor}
import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.StrictLogging
import spray.http.HttpHeaders.RawHeader
import spray.http.StatusCodes._
import spray.routing.{RequestContext, HttpService}

trait DeployService extends HttpService with StrictLogging {

  val apiKey: String

  val deployActor: ActorRef

  def customDeployHeader = (ctx: RequestContext) => {
    ctx.request.headers.exists {
      case RawHeader(DeployService.DEPLOY_KEY_HEADER, `apiKey`) => true
      case _ => false
    }
  }

  val deployRoute =
    path( "deploy" / Segment ) { version ⇒
      post {
        authorize(customDeployHeader) {
          complete {
            logger.debug(s"Authorized")
            deployActor ! DeployActor.DeployVersionMessage(version)
            Accepted
          }
        }
      }
    }

}

object DeployService {

  val DEPLOY_KEY_HEADER = "X-DEPLOY-KEY"

}

class DeployServiceActor(val deployActorPropsFactory: DeployActorPropsFactory) extends Actor with DeployService with StrictLogging {

  val config = ConfigFactory.load()
  logger.debug(s"Config loaded from ${config.origin().description()}")

  val deployActor = context.system.actorOf( deployActorPropsFactory(config) )

  val apiKey = config.getString("deploy.api.key")

  def receive = runRoute(sealRoute(deployRoute))

  def actorRefFactory = context

}


text:
void report();
void report ( const char* msg );

void simpleQueryTest();
void queryFlowTest();
void restAPITest();
void crossValidate();


text:
#include "tensorflow/compiler/tf2xla/shape_util.h"

#include <numeric>

#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/core/lib/core/status.h"

namespace tensorflow {
namespace {

Status PopulateInfeedLayoutVector(const xla::Shape& shape,
                                  std::vector<int>* layouts) {
  if (shape.IsTuple()) {
    int64 tuple_elements = xla::ShapeUtil::TupleElementCount(shape);
    for (int64 i = 0; i < tuple_elements; ++i) {
      const xla::Shape& subshape =
          xla::ShapeUtil::GetTupleElementShape(shape, i);
      TF_RETURN_IF_ERROR(PopulateInfeedLayoutVector(subshape, layouts));
    }
  } else if (xla::LayoutUtil::HasLayout(shape)) {
    for (auto dim : xla::LayoutUtil::MinorToMajor(shape)) {
      layouts->push_back(dim);
    }
  } else {
    layouts->insert(layouts->end(), shape.rank(), -1);
  }
  return Status::OK();
}

// Populate the output layout unless the minor_to_major array contains all -1
// value, in which case the layout is considered missing and the API returns
// false.
xla::StatusOr<bool> MakeLayout(absl::Span<const int64> minor_to_major,
                               xla::Layout* layout) {
  if (std::all_of(minor_to_major.begin(), minor_to_major.end(),
                  [](int64 dim) { return dim == -1; })) {
    return false;
  }
  std::vector<bool> dim_present(minor_to_major.size(), false);
  for (auto dim : minor_to_major) {
    const int minor_to_major_size = minor_to_major.size();
    if (dim < 0 || dim >= minor_to_major_size) {
      return errors::InvalidArgument("Layout dimension out of range: dim=", dim,
                                     " rank=", minor_to_major.size());
    }
    if (dim_present[dim]) {
      return errors::InvalidArgument("Repeated layout dimension: dim=", dim);
    }
    dim_present[dim] = true;
  }
  *layout = xla::LayoutUtil::MakeLayout(minor_to_major);
  return true;
}

Status AssignLayout(
    absl::Span<const int64> minor_to_major,
    const std::function<xla::Layout(const xla::Shape&)>& layout_func,
    xla::Shape* shape) {
  xla::Layout layout;
  TF_ASSIGN_OR_RETURN(bool has_layout, MakeLayout(minor_to_major, &layout));
  if (!has_layout && layout_func) {
    layout = layout_func(*shape);
  }
  *shape->mutable_layout() = layout;
  return Status::OK();
}

}  // namespace

// Convert an XLA Shape into the equivalent TensorFlow shape.
Status XLAShapeToTensorShape(const xla::Shape& shape,
                             TensorShape* tensor_shape) {
  if (shape.IsTuple()) {
    return errors::InvalidArgument("XLA shape ",
                                   xla::ShapeUtil::HumanString(shape),
                                   " cannot be converted to a TensorShape");
  }
  *tensor_shape = TensorShape();
  for (int i = 0; i < shape.rank(); ++i) {
    tensor_shape->AddDim(shape.dimensions(i));
  }
  return Status::OK();
}

// Convert a TensorShape into the equivalent XLA Shape proto.
Status TensorShapeToXLAShape(DataType dtype,
                             const PartialTensorShape& tensor_shape,
                             xla::Shape* shape) {
  xla::PrimitiveType type;
  TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(dtype, &type));
  *shape = TensorShapeToXLAShape(type, tensor_shape);
  return Status::OK();
}

xla::Shape TensorShapeToXLAShape(xla::PrimitiveType type,
                                 const PartialTensorShape& tensor_shape) {
  if (tensor_shape.unknown_rank()) {
    // For unknown shape, create a rank 1 size 0 tensor.
    return xla::ShapeUtil::MakeShapeWithLayout(type, {0}, {0});
  }
  int rank = tensor_shape.dims();
  std::vector<int64> dimensions(rank);
  std::vector<bool> dynamic_dimensions(rank, false);
  std::vector<int64> layout(rank);
  for (int d = 0; d < rank; ++d) {
    dimensions[d] = tensor_shape.dim_size(d);
    if (dimensions[d] < 0) {
      dynamic_dimensions[d] = true;
    }
  }
  // XLA uses minor-to-major; Tensorflow uses major-to-minor.
  std::iota(layout.rbegin(), layout.rend(), 0);
  xla::Shape result =
      xla::ShapeUtil::MakeShapeWithLayout(type, dimensions, layout);

  for (int64 d = 0; d < rank; ++d) {
    result.set_dynamic_dimension(d, dynamic_dimensions[d]);
  }
  return result;
}

// Convert a TensorShape into the equivalent XLA Shape proto.
Status TensorShapeToXLAShape(DataType dtype, const TensorShape& tensor_shape,
                             xla::Shape* shape) {
  xla::PrimitiveType type;
  TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(dtype, &type));
  *shape = TensorShapeToXLAShape(type, tensor_shape);
  return Status::OK();
}

xla::Shape TensorShapeToXLAShape(xla::PrimitiveType type,
                                 const TensorShape& tensor_shape) {
  int rank = tensor_shape.dims();
  std::vector<int64> dimensions(rank);
  std::vector<int64> layout(rank);
  for (int d = 0; d < rank; ++d) {
    dimensions[d] = tensor_shape.dim_size(d);
  }
  // XLA uses minor-to-major; Tensorflow uses major-to-minor.
  std::iota(layout.rbegin(), layout.rend(), 0);

  return xla::ShapeUtil::MakeShapeWithLayout(type, dimensions, layout);
}

xla::StatusOr<std::vector<int>> GetShapeLayoutVector(const xla::Shape& shape) {
  std::vector<int> layouts;
  TF_RETURN_IF_ERROR(PopulateInfeedLayoutVector(shape, &layouts));
  return layouts;
}

Status GetShapeWithLayout(
    const xla::Shape& input_shape, absl::Span<const int64> minor_to_major,
    const std::function<xla::Layout(const xla::Shape&)>& layout_func,
    xla::Shape* output_shape) {
  if (input_shape.IsTuple()) {
    int64 tuple_elements = xla::ShapeUtil::TupleElementCount(input_shape);
    std::vector<xla::Shape> shapes;
    shapes.reserve(tuple_elements);
    size_t position = 0;
    for (int64 i = 0; i < tuple_elements; ++i) {
      const xla::Shape& shape =
          xla::ShapeUtil::GetTupleElementShape(input_shape, i);
      if (shape.IsTuple()) {
        return errors::InvalidArgument(
            "Nested tuples not supported: ",
            xla::ShapeUtil::HumanString(input_shape));
      }
      int64 rank = shape.rank();
      if (position + rank > minor_to_major.size()) {
        return errors::InvalidArgument(
            "Not enough layout attribute elements: position=", position,
            " rank=", rank, " elements=", minor_to_major.size());
      }
      shapes.push_back(shape);
      TF_RETURN_IF_ERROR(AssignLayout(
          absl::Span<const int64>(minor_to_major).subspan(position, rank),
          layout_func, &shapes.back()));
      position += rank;

      VLOG(4) << "Shape[" << i
              << "] = " << xla::ShapeUtil::HumanStringWithLayout(shapes.back());
    }
    if (position != minor_to_major.size()) {
      return errors::InvalidArgument(
          "Too many elements passed in the layout attribute: position=",
          position, " size=", minor_to_major.size());
    }
    *output_shape = xla::ShapeUtil::MakeTupleShape(shapes);
  } else {
    int64 rank = input_shape.rank();
    const int64 minor_to_major_size = minor_to_major.size();
    if (rank != minor_to_major_size) {
      return errors::InvalidArgument(
          "Wrong number of layout attribute elements: rank=", rank,
          " elements=", minor_to_major.size());
    }
    *output_shape = input_shape;
    TF_RETURN_IF_ERROR(AssignLayout(minor_to_major, layout_func, output_shape));

    VLOG(4) << "Shape[] = "
            << xla::ShapeUtil::HumanStringWithLayout(*output_shape);
  }
  return Status::OK();
}

}  // namespace tensorflow


text:
[![Build Status](https://travis-ci.org/tether/manner.svg?branch=master)](https://travis-ci.org/tether/manner)
[![NPM](https://img.shields.io/npm/v/manner.svg)](https://www.npmjs.com/package/manner)
[![Downloads](https://img.shields.io/npm/dm/manner.svg)](http://npm-stat.com/charts.html?package=manner)
[![guidelines](https://tether.github.io/contribution-guide/badge-guidelines.svg)](https://github.com/tether/contribution-guide)

Quickly create HTTP services from an object. Manner is framework agnostic and can be plugged to any HTTP server.

  * **know the response type**: Return buffers, streams, promises, objects or any type of primitives. Manner knows your data type and send its content as fast as possible down the HTTP response.
  * **chunk the response content**: Response are encoded using the chunk transfer protocol. Manner is memory efficient and can manage a large amount of concurrent request.
  * **decode the request data**: Manner intelligently decode the data sent through the request and supports any kind of encoding (application/x-www-form-urlencoded, multipart/form-data, json, etc).
  * **manage your service status**: Manner knows what's going on with your response and send the appropriate status code whenever a method has not been implemented, a media type is not supported, etc.
  * **expose methods**: Access your service methods independently from any HTTP request. Perfect to decouple your API from its implementation.
  * **schema**: Apply schema to annotate and validate your service(s) (see [test suite](https://github.com/tether/manner/blob/master/test/manner.js))

## Usage

Create a web service from an object:

```javascript
const http = require('http')
const service= require('manner')

const db = []

const api = service({
  'get': {
    '/': () => 'hello you',
    '/earth': '/world',
    '/:name': (query) => `hello ${query.name}!`
  },
  'post': (query, data) => {
    return db.push(data)
  }
})

// HTTP service
http.createServer((req, res) => {
  api(req, res).pipe(res)
})

// Programmatic service
api.get('/')
// => hello you

api.get('/bob')
// => hello bob!

api.get('/earth')
// => hello world!
```

and programmaticaly add or call routes

```js

const api = service({
  'get': () => 'hello world'
})

api.get('/:name', query => {
  return `hello ${query.name}!`
})

api.get('/bob')
// => hello bob!
```

## Installation

```shell
npm install manner --save
```

[![NPM](https://nodei.co/npm/manner.png)](https://nodei.co/npm/manner/)

## Question

For support, bug reports and or feature requests please make sure to read our
community guidelines and use the issue list of this repo and make sure it's not present yet in our reporting checklist.

## Contribution

The open source community is very important to us. If you want to participate to this repository, please make sure to read our guidelines before making any pull request. If you have any related project, please let everyone know in our wiki.

## License

The MIT License (MIT)

Copyright (c) 2017 Tether Inc

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />

    <title>React+Redux+WinJS v0.0.0</title>

    <link rel="stylesheet" href="index.css"/>
  </head>

  <body>
    <script src="index.js"></script>
  </body>
</html>


text:
//  Estimote Fleet Management SDK
//  Copyright © 2015 Estimote. All rights reserved.

#import <Foundation/Foundation.h>
#import "ESTTelemetryInfo.h"
#import "ESTGPIOPortsData.h"

NS_ASSUME_NONNULL_BEGIN

/**
 *  ESTTelemetryInfoGPIO contains information about GPIO ports value
 *  delivered from telemetry packet.

 *  Instance of this class is created automatically by `ESTUtilityManager`
 *  when new telemetry packet containing GPIO information is ranged. Object
 *  is delivered in `ESTTelemetryNotificationGPIONotificationBlock`
 *  provided using `ESTTelemetryNotificationGPIO` class.
 */
DEPRECATED_MSG_ATTRIBUTE("Deprecated since 4.31.0.")
@interface ESTTelemetryInfoGPIO : ESTTelemetryInfo

/**
 *  Object containing values for all available GPIO ports.
 */
@property (nonatomic, strong, readonly) ESTGPIOPortsData *portsData;

/**
 *  Method allows to initialize object with GPIO ports data.
 *
 *  @param portsData GPIO ports data taken from telemetry packet.
 *
 *  @return Initialized object.
 */
- (instancetype)initWithGPIOPortsData:(ESTGPIOPortsData *)portsData
                      shortIdentifier:(NSString *)shortIdentifier;

@end

NS_ASSUME_NONNULL_END


text:
#ifndef __PCIE_KERNEL_API_H__
#define __PCIE_KERNEL_API_H__

#define PCIE_HOST_BRIDGE_NUM            (1)
#define PCIE_MAX_PORT_NUM               (4)
#define PCIE_MAX_OUTBOUND               (6)
#define PCIE_MAX_INBOUND               (4)
#define PCIE3_MAX_OUTBOUND               (16)
#define PCIE3_MAX_INBOUND                (16)

#define PCIE_LINK_LOOP_CNT          (0x1000)
#define PCIE_IATU_ADDR_MASK         (0xFFFFF000)
#define PCIE_1M_ALIGN_SHIRFT        (20)
#define PCIE_BDF_MASK               (0xF0000FFF)
#define PCIE_BUS_SHIRFT             (20)
#define PCIE_DEV_SHIRFT             (15)
#define PCIE_FUNC_SHIRFT            (12)

#define PCIE_DBI_CS2_ENABLE              (0x1)
#define PCIE_DBI_CS2_DISABLE             (0x0)

#define PCIE_DMA_CHANLE_READ             (0x1)
#define PCIE_DMA_CHANLE_WRITE             (0x0)

#define PCIE_ERR_IATU_TABLE_NULL            EFIERR (1)
#define PCIE_ERR_LINK_OVER_TIME             EFIERR (2)
#define PCIE_ERR_UNIMPLEMENT_PCIE_TYPE      EFIERR (3)
#define PCIE_ERR_ALREADY_INIT               EFIERR (4)
#define PCIE_ERR_PARAM_INVALID              EFIERR (5)
#define PCIE_ERR_MEM_OPT_OVER               EFIERR (6)
#define PCIE_ERR_NOT_INIT                   EFIERR (7)
#define PCIE_ERR_CFG_OPT_OVER               EFIERR (8)
#define PCIE_ERR_DMA_READ_CHANLE_BUSY       EFIERR (9)
#define PCIE_ERR_DMA_WRITE_CHANLE_BUSY      EFIERR (10)
#define PCIE_ERR_DMAR_NO_RESORCE            EFIERR (11)
#define PCIE_ERR_DMAW_NO_RESORCE            EFIERR (12)
#define PCIE_ERR_DMA_OVER_MAX_RESORCE       EFIERR (13)
#define PCIE_ERR_NO_IATU_WINDOW             EFIERR (14)
#define PCIE_ERR_DMA_TRANSPORT_OVER_TIME    EFIERR (15)
#define PCIE_ERR_DMA_MEM_ALLOC_ERROR        EFIERR (16)
#define PCIE_ERR_DMA_ABORT                  EFIERR (17)
#define PCIE_ERR_UNSUPPORT_BAR_TYPE         EFIERR (18)

typedef enum {
    PCIE_ROOT_COMPLEX,
    PCIE_END_POINT,
    PCIE_NTB_TO_NTB,
    PCIE_NTB_TO_RP,
} PCIE_PORT_TYPE;

typedef enum {
    PCIE_GEN1_0 = 1,    //PCIE 1.0
    PCIE_GEN2_0 = 2,    //PCIE 2.0
    PCIE_GEN3_0 = 4     //PCIE 3.0
} PCIE_PORT_GEN;

typedef enum {
    PCIE_WITDH_X1 = 0x1,
    PCIE_WITDH_X2 = 0x3,
    PCIE_WITDH_X4 = 0x7,
    PCIE_WITDH_X8 = 0xf,
    PCIE_WITDH_INVALID
} PCIE_PORT_WIDTH;

typedef struct {
    PCIE_PORT_TYPE      PortType;
    PCIE_PORT_WIDTH     PortWidth;
    PCIE_PORT_GEN       PortGen;
    UINT8               PcieLinkUp;
} PCIE_PORT_INFO;

typedef struct tagPciecfg_params
{
    UINT32 preemphasis;
    UINT32 deemphasis;
    UINT32 swing;
    UINT32 balance;
}pcie_cfg_params_s;

typedef enum {
    PCIE_CORRECTABLE_ERROR = 0,
    PCIE_NON_FATAL_ERROR,
    PCIE_FATAL_ERROR,
    PCIE_UNSUPPORTED_REQUEST_ERROR,
    PCIE_ALL_ERROR
} PCIE_ERROR_TYPE;

typedef union tagPcieDeviceStatus
{
       struct
        {
            UINT16 correctable_error : 1;
            UINT16 non_fatal_error : 1;
            UINT16 fatal_error : 1;
            UINT16 unsupported_error : 1;
            UINT16 aux_power : 1;
            UINT16 transaction_pending : 1;
            UINT16 reserved_6_15 : 10;
       }Bits;

    UINT16 Value;
}pcie_device_status_u;

typedef union tagPcieUcAerStatus
{
      struct
        {
            UINT32    undefined   : 1   ; /* [0] undefined  */
            UINT32    reserved_1_3   : 3   ; /* reserved */
            UINT32    data_link_proto_error   : 1   ; /* Data Link Protocol Error Status */
            UINT32    reserved_5_11   : 7   ; /* reserved */
            UINT32    poisoned_tlp_status   : 1   ; /* Poisoned TLP Status */
            UINT32    flow_control_proto_error   : 1   ; /* Flow Control Protocol Error Status */
            UINT32    completion_time_out   : 1   ; /* Completion Timeout Status */
            UINT32    compler_abort_status   : 1   ; /* Completer Abort Status */
            UINT32    unexpect_completion_status   : 1   ; /* Unexpected Completion Status */
            UINT32    receiver_overflow_status   : 1   ; /*Receiver Overflow Status */
            UINT32    malformed_tlp_status   : 1   ; /* Malformed TLP Status*/
            UINT32    ecrc_error_status   : 1   ; /* ECRC Error Status */
            UINT32    unsupport_request_error_status   : 1   ; /* Unsupported Request Error Status */
            UINT32    reserved_21   : 1   ; /*  reserved */
            UINT32    uncorrectable_interal_error   : 1   ; /* Uncorrectable Internal Error Status */
            UINT32    reserved_23   : 1   ; /* reserved*/
            UINT32    atomicop_egress_blocked_status   : 1   ; /* AtomicOp Egress Blocked Status */
            UINT32    tlp_prefix_blocked_error_status   : 1   ; /* TLP Prefix Blocked Error Status */
            UINT32    reserved_26_31   : 1   ; /* reserved */
       }Bits;

       UINT32 Value;
}pcie_uc_aer_status_u;

typedef union tagPcieCoAerStatus
{
       struct
        {
            UINT32    receiver_error_status   : 1   ; /* Receiver Error Status  */
            UINT32    reserved_1_5   : 5   ; /* Reserved */
            UINT32    bad_tlp_status   : 1   ; /* Bad TLP Status */
            UINT32    bad_dllp_status   : 1   ; /* Bad DLLP Status */
            UINT32    reply_num_rollover_status   : 1   ; /* REPLAY_NUM Rollover Status*/
            UINT32    reserved_9_11   : 3   ; /* Reserved */
            UINT32    reply_timer_timeout   : 1   ; /* Replay Timer Timeout Status */
            UINT32    advisory_nonfatal_error   : 1   ; /* Advisory Non-Fatal Error Status*/
            UINT32    corrected_internal_error   : 1   ; /*Corrected Internal Error Status*/
            UINT32    reserved_15_31   : 1   ; /* Reserved */
       }Bits;
       UINT32 Value;
}pcie_co_aer_status_u;

typedef struct tagPcieAerStatus
{
    pcie_uc_aer_status_u uc_aer_status;
    pcie_co_aer_status_u co_aer_status;
}pcie_aer_status_s;

typedef struct tagPcieLoopTestResult
{
   UINT32 tx_pkts_cnt;
   UINT32 rx_pkts_cnt;
   UINT32 error_pkts_cnt;
   UINT32 droped_pkts_cnt;
   UINT32 push_cnt;
   pcie_device_status_u device_status;
   pcie_aer_status_s    pcie_aer_status;
} pcie_loop_test_result_s;

typedef struct tagPcieDmaChannelAttrs {
    UINT32 dma_chan_en;
    UINT32 dma_mode;
    UINT32 channel_status;
}pcie_dma_channel_attrs_s;

typedef enum tagPcieDmaChannelStatus
{
    PCIE_DMA_CS_RESERVED = 0,
    PCIE_DMA_CS_RUNNING = 1,
    PCIE_DMA_CS_HALTED = 2,
    PCIE_DMA_CS_STOPPED = 3
}pcie_dma_channel_status_e;

typedef enum tagPcieDmaIntType{
    PCIE_DMA_INT_TYPE_DONE=0,
    PCIE_DMA_INT_TYPE_ABORT,
    PCIE_DMA_INT_ALL,
    PCIE_DMA_INT_NONE
}pcie_dma_int_type_e;

typedef enum tagPcieMulWinSize
{
    WIN_SIZE_4K = 0xc,
    WIN_SIZE_8K,
    WIN_SIZE_16K,
    WIN_SIZE_32K,
    WIN_SIZE_64K,
    WIN_SIZE_128K,
    WIN_SIZE_256K,
    WIN_SIZE_512K,
    WIN_SIZE_1M,
    WIN_SIZE_2M,
    WIN_SIZE_4M,
    WIN_SIZE_8M,
    WIN_SIZE_16M,
    WIN_SIZE_32M,
    WIN_SIZE_64M,
    WIN_SIZE_128M,
    WIN_SIZE_256M,
    WIN_SIZE_512M,
    WIN_SIZE_1G,
    WIN_SIZE_2G,
    WIN_SIZE_4G,
    WIN_SIZE_8G,
    WIN_SIZE_16G,
    WIN_SIZE_32G,
    WIN_SIZE_64G,
    WIN_SIZE_128G,
    WIN_SIZE_256G,
    WIN_SIZE_512G = 0x27,
}pcie_mul_win_size_e;

typedef struct tagPcieMultiCastCfg
{
    UINT64 multicast_base_addr;
    pcie_mul_win_size_e base_addr_size;
    UINT64 base_translate_addr;
}pcie_multicast_cfg_s;

typedef enum tagPcieMode
{
    PCIE_EP_DEVICE = 0x0,
    LEGACY_PCIE_EP_DEVICE = 0x1,
    RP_OF_PCIE_RC = 0x4,
    PCIE_INVALID = 0x100
}pcie_mode_e;

typedef struct{
    UINT32              PortIndex;
    PCIE_PORT_INFO      PortInfo;
    UINT64              iep_bar01; /*iep bar 01*/
    UINT64              iep_bar23;
    UINT64              iep_bar45;
    UINT64              iep_bar01_xlat;
    UINT64              iep_bar23_xlat;
    UINT64              iep_bar45_xlat;
    UINT64              iep_bar_lmt23;
    UINT64              iep_bar_lmt45; /*bar limit*/
    UINT64              eep_bar01;
    UINT64              eep_bar23;
    UINT64              eep_bar45;
    UINT64              eep_bar23_xlat;
    UINT64              eep_bar45_xlat;
    UINT64              eep_bar_lmt23; /*bar limit*/
    UINT64              eep_bar_lmt45; /*bar limit*/
} PCIE_NTB_CFG;

extern int pcie_mode_get(UINT32 Port, PCIE_PORT_INFO *port_info);

extern int pcie_port_ctrl(UINT32 Port, UINT32 port_ctrl);

extern int pcie_link_speed_set(UINT32 Port, PCIE_PORT_GEN speed);

extern int pcie_port_cfg_set(UINT32 Port, pcie_cfg_params_s *cfg_params);

extern int pcie_port_cfg_get(UINT32 Port, pcie_cfg_params_s *cfg_params);

extern int pcie_dma_chan_ctl(UINT32 Port,UINT32 channel,UINT32 control);

extern int pcie_dma_chan_attribu_set(UINT32 Port,UINT32 channel, pcie_dma_channel_attrs_s *dma_attribute);

extern int pcie_dma_cur_status_get(UINT32 Port, UINT32 channel, pcie_dma_channel_status_e *dma_channel_status);

extern int pcie_dma_int_enable(UINT32 Port, UINT32 channel, pcie_dma_int_type_e int_type);

extern int pcie_dma_int_mask(UINT32 Port, UINT32 channel, pcie_dma_int_type_e int_type);

extern int pcie_dma_tranfer_stop(UINT32 Port, UINT32 channel);

extern int pcie_dma_int_status_get(UINT32 Port, UINT32 channel, int *dma_int_status);

extern int pcie_dma_int_clear(UINT32 Port, UINT32 channel, pcie_dma_int_type_e dma_int_type);

extern int pcie_dma_read(UINT32 Port,void *source, void *dest,UINT32 transfer_size, UINT32 burst_size);

extern int pcie_dma_write(UINT32 Port,void *source, void *dest,UINT32 transfer_size, UINT32 burst_size);

extern int pcie_multicast_cfg_set(UINT32 Port,pcie_multicast_cfg_s *multicast_cfg,UINT32 win_num);

extern int pcie_setup_ntb(UINT32 Port, PCIE_NTB_CFG *ntb_cfg);

extern int pcie_ntb_doorbell_send(UINT32 Port,UINT32 doorbell);

extern int pcie_loop_test_start(UINT32 Port, UINT32 loop_type);

extern int pcie_loop_test_stop(UINT32 Port, UINT32 loop_type);

extern int pcie_loop_test_get(UINT32 Port, UINT32 loop_type, pcie_loop_test_result_s *test_result);
extern int pcie_port_reset(UINT32 Port);

extern int pcie_port_error_report_enable(UINT32 Port, UINT32 bus, UINT32 dev, UINT32 func, PCIE_ERROR_TYPE pcie_error);

extern int pcie_port_error_report_disable(UINT32 Port, UINT32 bus, UINT32 dev, UINT32 func, PCIE_ERROR_TYPE pcie_error);

extern int pcie_device_error_status_get(UINT32 Port, UINT32 bus, UINT32 dev, UINT32 func,UINT32 clear, \
pcie_device_status_u *pcie_stat);
extern int pcie_port_aer_cap_get(UINT32 Port, UINT32 bus, UINT32 dev, UINT32 func,UINT32 *aer_cap);

extern int pcie_port_aer_status_get(UINT32 Port, UINT32 bus, UINT32 dev, UINT32 func,pcie_uc_aer_status_u *pcie_aer_status);
extern int pcie_port_aer_status_clr(UINT32 Port, UINT32 bus, UINT32 dev, UINT32 func);

extern int pcie_port_aer_report_enable(UINT32 Port, PCIE_ERROR_TYPE pcie_aer_type);

extern int pcie_port_aer_report_disable(UINT32 Port, PCIE_ERROR_TYPE pcie_aer_type);

extern int pcie_cfg_read(UINT32 Port, UINT32 bus, UINT32 dev, UINT32 func, UINT32 reg_offset, UINT32 * value, UINT32 length);

extern int pcie_cfg_write(UINT32 Port, UINT32 bus, UINT32 dev, UINT32 func, UINT32 reg_offset, UINT8 * data, UINT32 length);

extern int pcie_mem_read(UINT32 Port,void * local_addr, void *pcie_mem_addr,UINT32 length);

extern int pcie_mem_write(UINT32 Port,void *local_addr , void *pcie_mem_addr,UINT32 length);

#endif


text:
Login to OpenAM (e.g. https://openam.example.com/openam) with the user 'amadmin' and the password chosen during the installation.

![](https://github.com/icclab/cyclops-support/blob/master/dashboard/doc/images/openam_tabs.png)

Most configuration will be done in the "Access Control" tab. A lot of additional configuration will be possible, but only the necessary steps are listed here. In the "Access Control" tab, choose the default realm to get started.

## Services

First, we have to set up the required services. To add a new service, click on the "add" button and select the service name:

* **User Self Service**: Users should be able to register, therefore we have to select "Self-Registration for Users". If users should be able to reset a forgotten password, check "Forgot Password for Users"

* **E-Mail Service**: The registration sends automated E-Mail. For this, a mail server needs to be configured. Gmail, for instance, uses hostname=smtp.gmail.com and port=465. Authentication username and password are the credentials for the GMail account to be used.

* **OAuth2 Provider**: Most default settings can be used. Only in the "Supported Claims" list you need to add 3 additional values: _keystoneid_, _isMemberOf_, _memberOf_

Save the changes at the top

## Agents

Choose the sub-tab **OAuth 2.0/OpenID Connect Client**. Add a new agent. You can choose any desired name and password (Note: These credentials later need to be configured in the **/WEB-INF/configuration.txt** file as OAUTH_CLIENT_NAME and OAUTH_CLIENT_PASS). After saving, you will be redirected back to the Agent overview.

Click on the newly created Agent name to access the configuration page. In the "Scope(s)" list, add the following entries: _openid_, _profile_, _keystoneid_, _memberOf_, _isMemberOf_

![](https://github.com/icclab/cyclops-support/blob/master/dashboard/doc/images/openam_agent_scopes.png)

Save your settings at the top

## Subjects

Choose the sub-tab _Group_ and create a new group called _CyclopsAdmin_.

## Privileges

Choose the _CyclopsAdmin_ group to change its privileges as follows:

![](https://github.com/icclab/cyclops-support/blob/master/dashboard/doc/images/openam_group_privileges.png)

## Custom Profile Attribute

Additionally to the in-OpenAM configuration, a new profile attribute needs to be added. Following the [official guide](http://docs.forgerock.org/en/openam/12.0.0/dev-guide/index/chap-custom-attr.html), an **optional** attribute called **keystoneid** needs to be added for the dashboard to store an OpenStack Keystone User ID. Note that later versions of the installation script will automate this step.

Note: **Do not restart Tomcat until you have finished all three steps**


text:
package server

import (
	"google.golang.org/grpc"
	sdkgrpc "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/containeranalysis/containeranalysis_go_proto"
)

// RegisterServers registers each resource with the gRPC server.
func RegisterServers(s *grpc.Server) {
	sdkgrpc.RegisterContaineranalysisNoteServiceServer(s, &NoteServer{})
}


text:
<?php

App::uses('AppController', 'Controller');

class UsersController extends AppController {

    public $name = 'Users';
	public $components = array('Crypt');

    public function beforeFilter() {
        parent::beforeFilter();

        $this->Auth->authenticate['Form'] = array(
            'userModel' => 'User',
            'scope' => array(
                'OR' => array(
                    'User.vacation IS NULL',
                    "DATE_ADD(User.vacation, INTERVAL '".Configure::read('vacation')."' DAY) < '".date('Y-m-d H:i:s')."'"
                )
            )
        );

        $this->Auth->allow('login', 'autoLogin', 'logout');
		$this->Auth->allow('initDB'); // Nous pouvons supprimer cette ligne après avoir fini
	}

	public function initDB() {
		$group = $this->User->Group;
		//Allow admins to everything
		$group->id = 1;
		$this->Acl->allow($group, 'controllers');
		$this->Acl->allow($group, 'controllers/Users');
		$this->Acl->allow($group, 'controllers/Posts');
		$this->Acl->allow($group, 'controllers/Comments');
		$this->Acl->deny($group, 'controllers/Abouts');
		$this->Acl->deny($group, 'controllers/Abouts/index');
		var_dump($this->Acl->check($group, 'controllers/Abouts'));
		var_dump($this->Acl->check($group, 'controllers/Abouts/index'));

		//allow managers to posts and widgets
		$group->id = 2;
		$this->Acl->allow($group, 'controllers');
		$this->Acl->allow($group, 'controllers/Posts');
		$this->Acl->allow($group, 'controllers/Widgets');

		//allow users to only add and edit on posts and widgets
		$group->id = 3;
		$this->Acl->allow($group, 'controllers');
		$this->Acl->allow($group, 'controllers/Posts/add');
		$this->Acl->allow($group, 'controllers/Posts/edit');
		$this->Acl->allow($group, 'controllers/Widgets/add');
		$this->Acl->allow($group, 'controllers/Widgets/edit');

		$user = $this->User;
		$user->id = 5; # xxx
		$this->Acl->deny($user, 'controllers/Abouts');
		$this->Acl->deny($user, 'controllers/Abouts/index');
		$this->Acl->allow($user, 'controllers/Abouts/home');
		var_dump($this->Acl->check($user, 'controllers/Abouts'));
		var_dump($this->Acl->check($user, 'controllers/Abouts/index'));
		var_dump($this->Acl->check($user, 'controllers/Abouts/home'));
		//nous ajoutons un exit pour éviter d'avoir un message d'erreur affreux "missing views" (manque une vue)
		echo "tout est ok";
		exit;
	}

    public function login($id = null) {
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {

                $this->User->afterLogin();
                $this->Logs->afterLogin();

				$prefix = !empty($this->request->data['User']['prefix']) ? '/'.$this->request->data['User']['prefix'] : '';
                $this->redirect($prefix.$this->Auth->redirect());
            } else {
                $this->Session->setFlash(__('Votre Nom d\'utilisateur ou mot de passe invalide, réessayer'));
            }
        } else {
            if(!empty($id)) {
                $user = $this->User->find('first', array(
                    'fields' => array(
                        'User.username'
                    ),
                    'conditions' => array(
                        'User.id' => $id
                    ),
                    'recursive' => -1
                ));
                $this->request->data = $user;
            }
        }
    }

    public function admin_login() {
        $this->render('login');
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {

                $this->User->afterLogin();
                $this->Logs->afterLogin();

                $this->redirect($this->Auth->redirect());
            } else {
                $this->Session->setFlash(__('Votre Nom d\'utilisateur ou mot de passe invalide, réessayer'));
            }
        }
    }

    public function logout() {
		$this->User->afterLogout();
		$this->Logs->afterLogout();
        $this->redirect($this->Auth->logout());
    }

    public function admin_logout() {
		$this->User->afterLogout();
		$this->Logs->afterLogout();
        $this->redirect($this->Auth->logout());
    }

    public function register() {
        if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $id = $this->User->id;
                $this->request->data['User'] = array_merge($this->request->data['User'], array('id' => $id));
                if ($this->Auth->login($this->request->data['User'])) {

                    $this->User->afterLogin();
                    $this->Log->afterLogin();

                    $this->redirect($this->Auth->redirect());
                }
            }
        }
    }

	public function autoLogin($id = null) {
 		if($this->request->is('get')) {
			//debug($this->request);
			$this->User->id = $id;
			if (!$this->User->exists()) {
				throw new NotFoundException(__('Invalid User'));
				$this->redirect(array('action' => 'login'));
			}

			if(!empty($this->request->query)) {
				$query = $this->request->query;

				$this->User->recursive = 0;
				$user = $this->User->findById($id);

				$q = array(
					'uid' => $this->Crypt->fnEncrypt($user['User']['id']),
					'upd' => md5($user['User']['password'].'#'.crc32($user['User']['password'])),
					'utoken' => md5($user['User']['email'].'#'.$user['User']['created']),
					'upw' => md5($user['User']['password2'].'#'.$user['User']['created'])
				);

				if($query['uid'] == $q['uid'] && $query['upd'] == $q['upd'] && $query['utoken'] == $q['utoken'] && $query['upw'] == $q['upw']) {
					$user['User']['Group'] = $user['Group'];
					$user['User']['Role'] = $user['Role'];
					unset($user['Group'], $user['Role']);
					if ($this->Auth->login($user['User'])) {

						$this->User->afterLogin();
						$this->Logs->afterLogin();

						$this->redirect($this->Auth->redirect());
					} else {
						$this->Session->setFlash(__('Votre Nom d\'utilisateur ou mot de passe invalide, réessayer'));
					}
				}
			}
		}

		$users = $this->User->find('all', array(
			'recursive' => -1
		));

		#$this->Crypt->fnDecrypt();
		foreach($users as $key => $val) {
			$users[$key]['User']['autoLink'] = array(
				'controller' => 'users',
				'action' => 'autoLogin',
				'u'.$val['User']['id'],
				'?' => array(
					'uid' => $this->Crypt->fnEncrypt($val['User']['id']),
					'upd' => md5($val['User']['password'].'#'.crc32($val['User']['password'])),
					'utoken' => md5($val['User']['email'].'#'.$val['User']['created']),
					'upw' => md5($val['User']['password2'].'#'.$val['User']['created'])
				)
			);
		}

		$this->set(compact('users'));
	}

    public function changePassword($id = null) {
        if ($this->request->is('post') || $this->request->is('put')) {
            $data = $this->request->data;

            if (!empty($data['User']['old_password']) && !empty($data['User']['password']) && !empty($data['User']['password2'])) {
                $user = $this->User->find('first', array(
                    'fields' => array(
                        'User.password'
                    ),
                    'conditions' => array(
                        'User.id' => $id
                    ),
                    'recursive' => -1
                ));

                if (AuthComponent::password($data['User']['old_password']) == $user['User']['password']) {

                    if ($data['User']['password'] == $data['User']['password2']) {
                        //$data['User']['password'] = $data['User']['password'];

                        $this->User->id = $id;
                        if ($this->User->saveField('password', $data['User']['password'])) {
                            $this->Session->setFlash("Votre mot de passe a bien été modifier");
                        } else {
                            $this->Session->setFlash("Impossible de sauvegarder");
                        }
                    } else {
                        $this->User->validationErrors['password2'] = array('Les mots de passe ne correspondent pas');
                    }
                } else {
                    $this->User->validationErrors['old_password'] = array('La mot de passe actuel est incorrect !');
                }
            }
        }

        $user = $this->User->find('first', array(
            'fields' => array(
                'User.username'
            ),
            'conditions' => array(
                'User.id' => $id
            ),
            'recursive' => -1
        ));

        $this->request->data = array(
            'User' => array(
                'id' => $id,
                'username' => $user['User']['username'],
                'old_password' => '',
                'password' => '',
                'password2' => ''
            )
        );
    }

    public function vacation($id = null) {
        $query = $this->request->query;
        if(!empty($query['confirm']) && $query['confirm'] == 'true') {
            $this->User->id = $id;
            $this->User->saveField('vacation', date('Y-m-d H:i:s'));
            $this->Session->setFlash('Vous etes maintenant en mode Vacance');
            $this->redirect(array('action' => 'logout'));
        }
        $this->set(compact('id'));
    }

    public function move($id = null) {

        if ($this->request->is('post') || $this->request->is('put')) {
            $this->User->id = $id;
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash('Group and Role for user changed');
                $this->redirect(array('action' => 'index'));
            }
        }
        $user = $this->User->findById($id);

        $roles = $this->User->Role->find('list', array(
            'fields' => array(
                'Role.name'
            ),
            'recursive' => -1
        ));
		$groups = $this->User->Group->find('list', array(
            'fields' => array(
                'Group.name'
            ),
            'recursive' => -1
        ));

        $this->request->data = array(
            'User' => array(
                'id' => $user['User']['id'],
                'group_id' => $user['User']['group_id'],
				'role_id' => $user['User']['role_id']
            )
        );

        $this->set(compact('user', 'roles', 'groups'));
    }

    public function index() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    public function view($id = null) {
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        }
        $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
        $this->set('user', $this->User->find('first', $options));
    }

    public function show($id = null, $slug = null) {
        $user = $this->User->find('first', array(
			'conditions' => array(
				'User.id' => $id,
				'User.username' => $slug
			),
			'recursive' => 1
        ));
		$users = $this->User->find('all', array(
			'recursive' => -1
        ));
		$this->set(compact('user', 'users'));

        /* ***** *** ***** */
        #invocation d'un web service REST
        $link = Router::url("/chat/messages/show/{$id}", true);
        $postfields = array(
            'username' => $user['User']['username'],
            'password' => $user['User']['username'],
        );
		$header = array(
			"Accept: text/xml,application/xml,application/xhtml+xml,",
			"Accept-Charset: utf-8"
		);

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $link);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		curl_setopt($curl, CURLOPT_ENCODING, 'UTF-8');
        curl_setopt($curl, CURLOPT_COOKIESESSION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);

        $return = curl_exec($curl);
        if($return === false) {
			debug(curl_errno($curl));
            debug(curl_error($curl));
            debug(curl_getinfo($curl));
        }

        curl_close($curl);

        $this->set('messages', $return);
        /* ***** *** ***** */
    }

    public function add() {
        if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        }
        $groups = $this->User->Group->find('list');
        $roles = $this->User->Role->find('list');
        $this->set(compact('groups', 'roles'));
    }

    public function edit($id = null) {
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
            $this->request->data = $this->User->find('first', $options);
        }
        $groups = $this->User->Group->find('list');
        $roles = $this->User->Role->find('list');
        $this->set(compact('groups', 'roles'));
    }

    public function delete($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->User->delete()) {
            $this->Session->setFlash(__('User deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted'));
        $this->redirect(array('action' => 'index'));
    }

}