text:
package org.apache.camel.component.jetty;

import java.util.Map;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;

/**
 * @version
 */
public class HttpProducerQueryParamTest extends BaseJettyTest {

    private String url = "http://0.0.0.0:" + getPort() + "/cheese";

    @Test
    public void testQueryParameters() throws Exception {
        Exchange exchange = template.request(url + "?quote=Camel%20rocks", null);
        assertNotNull(exchange);

        String body = exchange.getOut().getBody(String.class);
        Map<?, ?> headers = exchange.getOut().getHeaders();

        assertEquals("Bye World", body);
        assertEquals("Carlsberg", headers.get("beer"));
    }

    @Test
    public void testQueryParametersWithHeader() throws Exception {
        Exchange exchange = template.request(url, new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(Exchange.HTTP_QUERY, "quote=Camel rocks");
            }
        });
        assertNotNull(exchange);

        String body = exchange.getOut().getBody(String.class);
        Map<?, ?> headers = exchange.getOut().getHeaders();

        assertEquals("Bye World", body);
        assertEquals("Carlsberg", headers.get("beer"));
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("jetty:" + url).process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        String quote = exchange.getIn().getHeader("quote", String.class);
                        assertEquals("Camel rocks", quote);

                        exchange.getOut().setBody("Bye World");
                        exchange.getOut().setHeader("beer", "Carlsberg");
                    }
                });
            }
        };
    }
}


text:
class RemoveLogin < ActiveRecord::Migration
  def self.up
    remove_column :users, :login
  end

  def self.down
    add_column :users, :login, :string
  end
end

redpajama_set_name: RedPajamaGithub


text:
GIT ?= git
ZIP ?= zip

all: twitter-icon-notifier.zip

clean:
	rm -f twitter-icon-notifier.zip

twitter-icon-notifier.zip: background.js extension-icon-128.png manifest.json notify.js
	$(ZIP) $@ $^

# vim: set noet ts=8 sw=8:


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using GameEngine;

namespace Troma
{
    public class MainMenu : MenuScreen
    {
        private Button soloMenuEntry;
        private Button multiMenuEntry;
        private Button scoreMenuEntry;
        private Button optionsMenuEntry;
        private Button exitMenuEntry;

        private SpriteFont tromaFont;
        private Vector2 tromaPos;
        private Color tromaColor;

        private Texture2D bg;
        private Texture2D bgTrans;
        private Texture2D arrow;

        private Rectangle bgRect;
        private Rectangle bgTransRect;
        private Rectangle arrowRect;

        public MainMenu(Game game)
            : base(game)
        {
            Vector2 entryPos = new Vector2(143, 435);
            float space = 110;

            // Create menu entries.
            soloMenuEntry = new Button(string.Empty, 1, entryPos);
            entryPos.Y += space;
            multiMenuEntry = new Button(string.Empty, 1, entryPos);
            entryPos.Y += space;
            scoreMenuEntry = new Button(string.Empty, 1, entryPos);
            entryPos.Y += space;
            optionsMenuEntry = new Button(string.Empty, 1, entryPos);
            entryPos.Y += space;
            exitMenuEntry = new Button(string.Empty, 1, entryPos);

            // Hook up menu event handlers.
            soloMenuEntry.Selected += SoloMenuEntrySelected;
            multiMenuEntry.Selected += MultiMenuEntrySelected;
            scoreMenuEntry.Selected += ScoreMenuEntrySelected;
            optionsMenuEntry.Selected += OptionsMenuEntrySelected;
            exitMenuEntry.Selected += OnCancel;

            // Add entries to the menu.
            MenuEntries.Add(soloMenuEntry);
            MenuEntries.Add(multiMenuEntry);
            MenuEntries.Add(scoreMenuEntry);
            MenuEntries.Add(optionsMenuEntry);
            MenuEntries.Add(exitMenuEntry);

            SceneRenderer.InitializeMenu();
        }

        public override void LoadContent()
        {
            base.LoadContent();

            tromaFont = GameServices.Game.Content.Load<SpriteFont>("Fonts/LuckyTypewriter");
            tromaColor = new Color(112, 97, 63);

            bg = GameServices.Game.Content.Load<Texture2D>("Menus/background");
            bgTrans = GameServices.Game.Content.Load<Texture2D>("Menus/translucide");
            arrow = GameServices.Game.Content.Load<Texture2D>("Menus/arrow");

            bgRect = new Rectangle(0, 0, 1920, 1080);
            bgTransRect = new Rectangle(0, 0, 550, 1080);
            arrowRect = new Rectangle(0, 0, 64, 64);

            SoundManager.Play("Menu");

            if (Settings.Name == "")
                TimerManager.Add(300, EventLoadPopUp);
        }

        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
            SetMenuEntryText();
        }

        public override void Draw(GameTime gameTime)
        {
            int width = GameServices.GraphicsDevice.Viewport.Width;
            int height = GameServices.GraphicsDevice.Viewport.Height;

            float widthScale = (float)width / 1920;
            float heightScale = (float)height / 1080;

            bgRect.Height = height;
            bgRect.Width = (int)(height * 1.778f);
            bgRect.X = -(bgRect.Width - width) / 2;

            bgTransRect.Height = height;
            bgTransRect.Width = (int)(500 * widthScale);

            tromaPos = new Vector2(
                1380 * widthScale,
                50 * heightScale);

            GameServices.SpriteBatch.Begin();

            GameServices.SpriteBatch.Draw(bg, bgRect, Color.White * TransitionAlpha);
            GameServices.SpriteBatch.Draw(bgTrans, bgTransRect, Color.White * TransitionAlpha * 0.15f);
            GameServices.SpriteBatch.DrawString(tromaFont, "troma", tromaPos, tromaColor * TransitionAlpha, 0,
                Vector2.Zero, (widthScale + heightScale) / 2, SpriteEffects.None, 0);

            // Draw each menu entry in turn.
            for (int i = 0; i < MenuEntries.Count; i++)
            {
                bool isSelected = IsActive && (i == selectedEntry);
                MenuEntries[i].Draw(gameTime, this, isSelected);

                if (isSelected)
                {
                    arrowRect.Height = (int)(64 * ((widthScale + heightScale) / 2));
                    arrowRect.Width = arrowRect.Height;
                    arrowRect.X = (int)(MenuEntries[i].Position.X - 1.5f * arrowRect.Width);
                    arrowRect.Y = (int)MenuEntries[i].Position.Y;
                    GameServices.SpriteBatch.Draw(arrow, arrowRect, Color.White * TransitionAlpha);
                }
            }

            GameServices.SpriteBatch.End();
        }

        private void SoloMenuEntrySelected(object sender, EventArgs e)
        {
            SoundManager.Stop();
            LoadingScreen.Load(game, ScreenManager, true, new SoloScreen(game, Map.Town),
                new HistoryScreen(game));
        }

        private void MultiMenuEntrySelected(object sender, EventArgs e)
        {
            ScreenManager.AddScreen(new ConnectOrHost(game, ErrorType.None));
        }

        private void ScoreMenuEntrySelected(object sender, EventArgs e)
        {
            ScreenManager.AddScreen(new ScoreMenu(game));
        }

        private void OptionsMenuEntrySelected(object sender, EventArgs e)
        {
            ScreenManager.AddScreen(new OptionsMenu(game));
        }

        protected override void OnCancel(object sender, EventArgs e)
        {
            SoundManager.Stop();
            game.Exit();
        }

        private void SetMenuEntryText()
        {
            soloMenuEntry.Text = "Solo";
            multiMenuEntry.Text = Resource.Multiplayer;
            scoreMenuEntry.Text = "Score";
            optionsMenuEntry.Text = "Options";
            exitMenuEntry.Text = Resource.Exit;
        }

        public void EventLoadPopUp(object o, EventArgs e)
        {
            ScreenManager.AddScreen(new NameScreen(game));
        }
    }
}


text:
package org.incode.eurocommercial.contactapp.app.fixture.scenarios;

import java.net.URL;
import java.util.List;
import java.util.Map;

import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;

import org.apache.isis.applib.fixturescripts.FixtureScript;

import org.isisaddons.module.excel.dom.ExcelFixture;

import org.incode.eurocommercial.contactapp.module.contact.fixture.ContactTearDown;
import org.incode.eurocommercial.contactapp.module.contacts.dom.Contact;
import org.incode.eurocommercial.contactapp.module.country.fixture.CountryTearDown;
import org.incode.eurocommercial.contactapp.module.group.fixture.ContactGroupTearDown;
import org.incode.eurocommercial.contactapp.module.number.fixture.ContactNumberTearDown;
import org.incode.eurocommercial.contactapp.module.role.fixture.ContactRoleTearDown;

import lombok.Getter;

public class DemoFixture extends FixtureScript {

    public DemoFixture() {
        withDiscoverability(Discoverability.DISCOVERABLE);
    }

    @Getter
    private final List<Contact> contacts = Lists.newArrayList();

    @Override
    protected void execute(final ExecutionContext ec) {

        // zap everything
        ec.executeChild(this, new ContactRoleTearDown());
        ec.executeChild(this, new ContactNumberTearDown());
        ec.executeChild(this, new ContactTearDown());
        ec.executeChild(this, new ContactGroupTearDown());
        ec.executeChild(this, new CountryTearDown());

        // load data from spreadsheet
        final URL spreadsheet = Resources.getResource(DemoFixture.class, getSpreadsheetBasename() + ".xlsx");
        final ExcelFixture fs = new ExcelFixture(spreadsheet, getHandlers());
        ec.executeChild(this, fs);

        // make objects created by ExcelFixture available to our caller.
        final Map<Class, List<Object>> objectsByClass = fs.getObjectsByClass();

        getContacts().addAll(
                FluentIterable
                        .from((List) objectsByClass.get(ContactImport.class))
                        .filter(Predicates.notNull())
                        .toList());

    }

    protected String getSpreadsheetBasename() {
        return getClass().getSimpleName();
    }

    private Class[] getHandlers() {
        return new Class[]{
                ContactImport.class,
        };
    }
}


text:
package com.amebame.triton.service.elasticsearch.method;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

import javax.inject.Inject;

import org.elasticsearch.action.WriteConsistencyLevel;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.get.GetResult;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.facet.Facet;
import org.elasticsearch.search.facet.Facets;

import com.amebame.triton.client.elasticsearch.method.DeleteDocument;
import com.amebame.triton.client.elasticsearch.method.GetDocument;
import com.amebame.triton.client.elasticsearch.method.GetDocumentResult;
import com.amebame.triton.client.elasticsearch.method.IndexDocument;
import com.amebame.triton.client.elasticsearch.method.IndexDocumentResult;
import com.amebame.triton.client.elasticsearch.method.MultiGetDocument;
import com.amebame.triton.client.elasticsearch.method.MultiGetDocumentResult;
import com.amebame.triton.client.elasticsearch.method.SearchDocument;
import com.amebame.triton.client.elasticsearch.method.SearchDocumentHit;
import com.amebame.triton.client.elasticsearch.method.SearchDocumentResult;
import com.amebame.triton.client.elasticsearch.method.UpdateDocument;
import com.amebame.triton.client.elasticsearch.method.UpdateDocumentResult;
import com.amebame.triton.config.TritonElasticSearchConfiguration;
import com.amebame.triton.exception.TritonErrors;
import com.amebame.triton.json.Json;
import com.amebame.triton.server.TritonMethod;
import com.amebame.triton.service.elasticsearch.TritonElasticSearchClient;
import com.amebame.triton.service.elasticsearch.TritonElasticSearchException;
import com.fasterxml.jackson.databind.JsonNode;

public class TritonElasticSearchMethods {

	private TritonElasticSearchClient clients;

	private TritonElasticSearchConfiguration config;

	@Inject
	public TritonElasticSearchMethods(
			TritonElasticSearchClient clients,
			TritonElasticSearchConfiguration config) {
		this.clients = clients;
		this.config = config;
	}

	private TimeValue timeout() {
		return TimeValue.timeValueMillis(config.getTimeout());
	}

	/**
	 * Index the document.
	 * @param index
	 * @return
	 */
	@TritonMethod("elasticsearch.index")
	public IndexDocumentResult index(IndexDocument index) {

		Client client = clients.getClient(index.getCluster());
		IndexRequestBuilder builder = client.prepareIndex(index.getIndex(), index.getType(), index.getId());

		// set TTL if exists
		if (index.getTtl() > 0L) {
			builder.setTTL(index.getTtl());
		}

		builder
		.setSource(Json.bytes(index.getSource()))
		.setRefresh(index.isRefresh())
		.setRouting(index.getRouting())
		;

		IndexResponse response = builder.get(timeout());
		return new IndexDocumentResult(response.getId(), response.getVersion());

	}

	/**
	 * Get the document by id
	 * @param get
	 * @return
	 */
	@TritonMethod("elasticsearch.get")
	public GetDocumentResult get(GetDocument get) {

		Client client = clients.getClient(get.getCluster());
		GetResponse response = client
				.prepareGet(get.getIndex(), get.getType(), get.getId())
				.setRouting(get.getRouting())
				.get(timeout());

		if (response.isExists()) {

			GetDocumentResult result = new GetDocumentResult();
			result.setId(response.getId());
			result.setVersion(response.getVersion());
			result.setSource(response.getSource());
			return result;

		} else {

			// return null if not exist
			return null;
		}
	}

	/**
	 * Get multiple documents by ids.
	 * @param multiGet
	 * @return
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	@TritonMethod("elasticsearch.multiget")
	public MultiGetDocumentResult multiget(MultiGetDocument multiGet) {

		Client client = clients.getClient(multiGet.getCluster());
		MultiGetResponse response = client.prepareMultiGet()
				.add(multiGet.getIndex(), multiGet.getType(), multiGet.getIds())
				.get(timeout());

		MultiGetDocumentResult result = new MultiGetDocumentResult();

		for (MultiGetItemResponse item : response.getResponses()) {
			if (item.isFailed()) {
				result.addFail(item.getId(), item.getFailure().getMessage());
			} else {
				GetDocumentResult itemResult = new GetDocumentResult();
				GetResponse itemResponse = item.getResponse();
				itemResult.setId(item.getId());
				itemResult.setVersion(itemResponse.getVersion());
				itemResult.setSource(itemResponse.getSource());
				result.addItem(itemResult);
			}
		}
		return result;

	}

	/**
	 * Search documents by query.
	 * @param search
	 */
	@TritonMethod("elasticsearch.search")
	public SearchDocumentResult search(SearchDocument search) {

		Client client = clients.getClient(search.getCluster());

		SearchResponse response = null;

		if (search.hasScrollId()) {
			response = searchScroll(client, search.getScrollId());
		} else {
			response = searchQuery(client, search);
		}

		SearchHits hits = response.getHits();
		String scrollId = response.getScrollId();
		Facets facets = response.getFacets();

		SearchDocumentResult result = new SearchDocumentResult();

		// Convert facets field.
		if (facets != null) {
			try {
				XContent content = XContentFactory.xContent(XContentType.JSON);
				XContentBuilder builder = XContentBuilder.builder(content);
				for (Facet facet : facets) {
					if (facet instanceof ToXContent) {
						((ToXContent) facet).toXContent(builder, ToXContent.EMPTY_PARAMS);
					}
				}
				BytesReference bytesRef = builder.bytes();
				JsonNode facetNode = Json.tree(bytesRef.toBytes());
				result.setFacets(facetNode);

			} catch (IOException e) {
				throw new TritonElasticSearchException(TritonErrors.elasticsearch_error, e.getMessage(), e);
			}
		}

		// Convert hit field
		if (hits != null) {
			result.setTotal(hits.totalHits());

			for (SearchHit hit : hits) {
				SearchDocumentHit hitItem = new SearchDocumentHit();
				hitItem.setId(hit.getId());
				hitItem.setIndex(hit.getIndex());
				hitItem.setType(hit.getType());
				hitItem.setScore(hit.getScore());
				JsonNode source = Json.tree(hit.getSourceRef().toBytes());
				hitItem.setSource(source);
				result.addHit(hitItem);
			}
		}

		result.setScrollId(scrollId);
		result.setTook(response.getTookInMillis());

		return result;
	}

	/**
	 * Search by scroll ID
	 * @param client
	 * @param scrollId
	 * @return
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	private SearchResponse searchScroll(Client client, String scrollId) {
		return client.prepareSearchScroll(scrollId).get(timeout());
	}

	/**
	 * Search by document
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	private SearchResponse searchQuery(Client client, SearchDocument search) {

		SearchRequestBuilder builder = client.prepareSearch(search.getIndices());

		builder
		.setTypes(search.getTypes())
		.setFrom(search.getFrom())
		.setSize(search.getSize())
		;

		if (search.hasRoutings()) {
			builder.setRouting(search.getRoutings());
		}

		if (search.hasSearchType()) {
			builder.setSearchType(search.getSearchType());
		}

		if (search.hasQuery()) {
			builder.setQuery(Json.bytes(search.getQuery()));
		}

		if (search.hasFilter()) {
			builder.setFilter(Json.bytes(search.getFilter()));
		}

		if (search.hasFacets()) {
			builder.setFacets(Json.bytes(search.getFacets()));
		}

		return builder.get(timeout());
	}

	@TritonMethod("elasticsearch.update")
	public UpdateDocumentResult update(UpdateDocument update) {

		Client client = clients.getClient(update.getCluster());

		UpdateRequestBuilder builder = client.prepareUpdate(update.getIndex(), update.getType(), update.getId());

		if (update.hasDoc()) {
			builder.setDoc(Json.stringify(update.getDoc()));
		}
		if (update.hasUpsert()) {
			builder.setUpsert(Json.stringify(update.getUpsert()));
		}
		if (update.hasScript()) {
			builder.setScript(update.getScript());
		}
		if (update.hasParams()) {
			builder.setScriptParams(update.getParams());
		}

		builder
		.setConsistencyLevel(WriteConsistencyLevel.QUORUM)
		.setRouting(update.getRouting())
		.setRefresh(update.isRefresh())
		.setDocAsUpsert(update.isDocAsUpsert())
		;

		UpdateResponse response = builder.get(timeout());
		GetResult getResult = response.getGetResult();

		UpdateDocumentResult result = new UpdateDocumentResult();
		result.setId(response.getId());
		result.setVersion(response.getVersion());

		if (getResult != null && getResult.source() != null) {
			result.setSource(Json.tree(getResult.source()));
		}
		return result;
	}

	@TritonMethod("elasticsearch.delete")
	public boolean delete(DeleteDocument delete) {

		Client client = clients.getClient(delete.getCluster());

		client
		.prepareDelete()
		.setIndex(delete.getIndex())
		.setType(delete.getType())
		.setId(delete.getId())
		.setRefresh(delete.isRefresh())
		.get(timeout())
		;

		return true;
	}

}


text:
<?php

class ModernNavalBattle extends LandBattle
{
    public $specialHexesMap = ['SpecialHexA'=>1, 'SpecialHexB'=>2, 'SpecialHexC'=>2];

    public $specialHexA;
    public $specialHexB;
    public $specialHexC;

    /* @var MapData $mapData */
    public $mapData;
    public $mapViewer;
    public $force;
    public $terrain;
    public $moveRules;
    public $combatRules;
    public $gameRules;
    public $victory;
    public $arg;
    public $scenario;

    public $players;

    function __construct($data = null, $arg = false, $scenario = false, $game = false){
        $this->mapData = MapData::getInstance();
        if ($data) {
            $this->arg = $data->arg;
            $this->scenario = $data->scenario;
            $this->terrainName = $data->terrainName;
            $this->game = $data->game;
            $this->mapData->init($data->mapData);
            $this->mapViewer = array(new MapViewer($data->mapViewer[0]), new MapViewer($data->mapViewer[1]), new MapViewer($data->mapViewer[2]));

            $units = $data->force->units;
            unset($data->force->units);
            $this->force = new NavalForce($data->force);
            foreach($units as $unit){
                $this->force->injectUnit(static::buildUnit($unit));
            }

            $this->terrain = new Terrain($data->terrain);
            $this->moveRules = new NavalMoveRules($this->force, $this->terrain, $data->moveRules);
            $this->combatRules = new NavalCombatRules($this->force, $this->terrain, $data->combatRules);
            $this->gameRules = new GameRules($this->moveRules, $this->combatRules, $this->force,  $data->gameRules);
            $this->victory = new Victory($data);

            $this->players = $data->players;
        } else {
            $this->arg = $arg;
            $this->scenario = $scenario;
            $this->game = $game;

            $this->mapViewer = array(new MapViewer(), new MapViewer(), new MapViewer());
            $this->force = new NavalForce();
            $this->terrain = new Terrain();
            $this->moveRules = new NavalMoveRules($this->force, $this->terrain);

            $this->combatRules = new NavalCombatRules($this->force, $this->terrain);
            $this->gameRules = new GameRules($this->moveRules, $this->combatRules, $this->force);
        }
    }
    /*
     * terrainInit() gets called during game init, from unitInit(). It happens as a new game gets started.
     */
    function terrainInit($terrainDoc)
    {
        $terrainInfo = $terrainDoc->terrain;

        $specialHexes = $terrainInfo->specialHexes ? $terrainInfo->specialHexes : [];
        $mapHexes = new stdClass();
        foreach ($specialHexes as $hexName => $specialHex) {
            $mapHexes->$hexName = $this->specialHexesMap[$specialHex];
            $this->{lcfirst($specialHex)}[] = $hexName;
        }
        $this->mapData->setSpecialHexes($mapHexes);

        $this->players = array("", "", "");
        for ($player = 0; $player <= 2; $player++) {
            $this->mapViewer[$player]->setData($terrainInfo->originX, $terrainInfo->originY, // originX, originY
                $terrainInfo->b, $terrainInfo->b, // top hexagon height, bottom hexagon height
                $terrainInfo->a, $terrainInfo->c,// hexagon edge width, hexagon center width
            $terrainInfo->mapWidth);
        }

        $oldMapUrl = $this->mapData->mapUrl;
        if (!$oldMapUrl) {
            $maxCol = $terrainInfo->maxCol;
            $maxRow = $terrainInfo->maxRow;
            $mapUrl = $terrainInfo->mapUrl;
            $this->mapData->setData($maxCol, $maxRow, $mapUrl);

            Hexagon::setMinMax();
            $this->terrain->setMaxHex();
        }
        return;
    }

    /*
     * terrainGen() gets called when a map is "published" from the map editor. It's not
     * related to a game start or a game file. It just generates the terrain info that gets saved to the
     * file terrain-Gamename
     *
     * TerrainFeatures that aren't declared here MUST be declared in the subclass BEFORE it calls it's parent::
     * TerrainFeatures that DO exist here but need to be modified MUST be declared AFTER the subclass calls it's parent::
     */
    function terrainGen($mapDoc, $terrainDoc)
    {
        // code, name, displayName, letter, entranceCost, traverseCost, combatEffect, is Exclusive

        $this->terrain->addTerrainFeature("clear", "clear", "c", 1, 0, 0, true);
        $this->terrain->addTerrainFeature("offmap", "offmap", "o", 1, 0, 0, true);
        $this->terrain->addTerrainFeature("blocked", "blocked", "b", "blocked", 0, 0, true, true);

        $terrainArr = json_decode($terrainDoc->hexStr->hexEncodedStr);

        $mapId = $terrainDoc->hexStr->map;
        $map = $mapDoc->map;
        $this->terrain->mapUrl = $mapUrl = $map->mapUrl;
        $this->terrain->maxCol = $maxCol = $map->numX;
        $this->terrain->maxRow = $maxRow = $map->numY;
        $this->terrain->mapWidth = $map->mapWidth;
        $this->mapData->setData($maxCol, $maxRow, $mapUrl);

        Hexagon::setMinMax();
        $this->terrain->setMaxHex();
        $a = $map->a;
        $b = $map->b;
        $c = $map->c;
        $this->terrain->a = $a;
        $this->terrain->b = $b;
        $this->terrain->c = $c;
        $this->terrain->originY = $b * 3 - $map->y;
        $xOff = ($a + $c) * 2 - ($c / 2 + $a);
        $this->terrain->originX = $xOff - $map->x;

        for ($col = 100; $col <= $maxCol * 100; $col += 100) {
            for ($row = 1; $row <= $maxRow; $row++) {
                $this->terrain->addTerrain($row + $col, LOWER_LEFT_HEXSIDE, "clear");
                $this->terrain->addTerrain($row + $col, UPPER_LEFT_HEXSIDE, "clear");
                $this->terrain->addTerrain($row + $col, BOTTOM_HEXSIDE, "clear");
                $this->terrain->addTerrain($row + $col, HEXAGON_CENTER, "clear");

            }
        }
        foreach ($terrainArr as $terrain) {
            foreach ($terrain->type as $terrainType) {
                $name = $terrainType->name;
                $matches = [];
                if (preg_match("/SpecialHex/", $name)) {
                    $this->terrain->addSpecialHex($terrain->number, $name);
                } else if (preg_match("/^ReinforceZone(.*)$/", $name, $matches)) {
                    $this->terrain->addReinforceZone($terrain->number, $matches[1]);
                } else {
                    $tNum = sprintf("%04d", $terrain->number);
                    $this->terrain->addTerrain($tNum, $terrain->hexpartType, strtolower($name));
                }
            }
        }
    }
}


text:
 /*
  *
  * Sensational Wallpapers Pack 1
  *
  * Wallpaper Designed by AZ2ENVY
  *
  */

package com.death2all110.SensationalWallpapers1;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.widget.Button;
import android.content.DialogInterface;
import android.content.Intent;

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

import com.death2all110.SensationalWallpapers1.R;

public class wallpaper extends Activity implements AdapterView.OnItemSelectedListener,
        OnClickListener {

    private Gallery mGallery;
    private ImageView mImageView;
    private boolean mIsWallpaperSet;

    private Bitmap mBitmap;

    private ArrayList<Integer> mThumbs;
    private ArrayList<Integer> mImages;
    private WallpaperLoader mLoader;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

        findWallpapers();

        setContentView(R.layout.wallpaper_chooser);

        mGallery = (Gallery) findViewById(R.id.gallery);
        mGallery.setAdapter(new ImageAdapter(this));
        mGallery.setOnItemSelectedListener(this);
        mGallery.setCallbackDuringFling(false);

        findViewById(R.id.set).setOnClickListener(this);

        mImageView = (ImageView) findViewById(R.id.wallpaper);

		Button alert = (Button) findViewById(R.id.about_page);
		alert.setOnClickListener(new View.OnClickListener() {
			public void onClick(View about) {
				// If "About was clicked.....
				if (about == findViewById(R.id.about_page)) {
					// Prepare the alert box!!
					AlertDialog.Builder alertbox = new AlertDialog.Builder(wallpaper.this);

					// Set title of box....
					alertbox.setTitle("About This App");

					// Set message to display...
					alertbox.setMessage("This is a simple 'about' page." + "\n" + "\n" + "lorem ipsum" + "\n" "lorem ipsum");

					// Add a neutral button to the alert box AND assign a listener for said button...
					alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener(){

						// click listener for box
						public void onClick(DialogInterface arg0, int arg1){
							// Button was clicked!!
							Toast.makeText(getApplicationContext(), "Dialog closed successfully!", Toast.LENGTH_LONG).show();
						}
					});

					//Positive button that goes to link...
					alertbox.setPositiveButton("Positive!", new DialogInterface.OnClickListener(){
						//listener with link info even a toast
						public void onClick(DialogInterface arg2, int arg3){
							//Button Pressed
							Intent linkMe = new Intent ();
							linkMe.setAction(Intent.ACTION_VIEW);
							linkMe.addCategory(Intent.CATEGORY_BROWSABLE);
							linkMe.setData(Uri.parse("http://yourlinkhere.net"));
							startActivity(linkMe);
							Toast.makeText(getApplicationContext(), "Launching Link!", Toast.LENGTH_LONG).show();
						}
					});
					// show it!!!
					alertbox.show();
		    }
			}
		});

    }

    private void findWallpapers() {
        mThumbs = new ArrayList<Integer>(24);
        mImages = new ArrayList<Integer>(24);

        final Resources resources = getResources();
        final String packageName = getApplication().getPackageName();

        addWallpapers(resources, packageName, R.array.wallpapers);
        addWallpapers(resources, packageName, R.array.extra_wallpapers);
    }

    private void addWallpapers(Resources resources, String packageName, int list) {
        final String[] extras = resources.getStringArray(list);
        for (String extra : extras) {
            int res = resources.getIdentifier(extra, "drawable", packageName);
            if (res != 0) {
                final int thumbRes = resources.getIdentifier(extra + "_small",
                        "drawable", packageName);

                if (thumbRes != 0) {
                    mThumbs.add(thumbRes);
                    mImages.add(res);
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsWallpaperSet = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
            mLoader.cancel(true);
            mLoader = null;
        }
    }

    public void onItemSelected(AdapterView parent, View v, int position, long id) {
        if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
            mLoader.cancel();
        }
        mLoader = (WallpaperLoader) new WallpaperLoader().execute(position);
    }

    /*
     * When using touch if you tap an image it triggers both the onItemClick and
     * the onTouchEvent causing the wallpaper to be set twice. Ensure we only
     * set the wallpaper once.
     */
    private void selectWallpaper(int position) {
        if (mIsWallpaperSet) {
            return;
        }

        mIsWallpaperSet = true;
        try {
            InputStream stream = getResources().openRawResource(mImages.get(position));
            setWallpaper(stream);
            setResult(RESULT_OK);
            finish();
        } catch (IOException e) {
            Log.e("Paperless System", "Failed to set wallpaper: " + e);
        }
    }

    public void onNothingSelected(AdapterView parent) {
    }

    private class ImageAdapter extends BaseAdapter {
        private LayoutInflater mLayoutInflater;

        ImageAdapter(wallpaper context) {
            mLayoutInflater = context.getLayoutInflater();
        }

        public int getCount() {
            return mThumbs.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView image;

            if (convertView == null) {
                image = (ImageView) mLayoutInflater.inflate(R.layout.wallpaper_item, parent, false);
            } else {
                image = (ImageView) convertView;
            }

            int thumbRes = mThumbs.get(position);
            image.setImageResource(thumbRes);
            Drawable thumbDrawable = image.getDrawable();
            if (thumbDrawable != null) {
                thumbDrawable.setDither(true);
            } else {
                Log.e("Paperless System", String.format(
                    "Error decoding thumbnail resId=%d for wallpaper #%d",
                    thumbRes, position));
            }
            return image;
        }
    }

    public void onClick(View v) {
        selectWallpaper(mGallery.getSelectedItemPosition());

		}

    class WallpaperLoader extends AsyncTask<Integer, Void, Bitmap> {
        BitmapFactory.Options mOptions;

        WallpaperLoader() {
            mOptions = new BitmapFactory.Options();
            mOptions.inDither = false;
            mOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
        }

        protected Bitmap doInBackground(Integer... params) {
            if (isCancelled()) return null;
            try {
                return BitmapFactory.decodeResource(getResources(),
                        mImages.get(params[0]), mOptions);
            } catch (OutOfMemoryError e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap b) {
            if (b == null) return;

            if (!isCancelled() && !mOptions.mCancel) {
                // Help the GC
                if (mBitmap != null) {
                    mBitmap.recycle();
                }

                final ImageView view = mImageView;
                view.setImageBitmap(b);

                mBitmap = b;

                final Drawable drawable = view.getDrawable();
                drawable.setFilterBitmap(true);
                drawable.setDither(true);

                view.postInvalidate();

                mLoader = null;
            } else {
               b.recycle();
            }
        }

        void cancel() {
            mOptions.requestCancelDecode();
            super.cancel(true);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_dark"
    >

    <TextView
        android:id="@+id/textViewClaimNameInExpense"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:textColor="@color/text"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/holder" />

</RelativeLayout>


text:
Article 1200
----
Il y a solidarité de la part des débiteurs, lorsqu'ils sont obligés à une même
chose, de manière que chacun puisse être contraint pour la totalité, et que le
paiement fait par un seul libère les autres envers le créancier.


text:
> Creating a verbfile

A basic `verbfile.js`:

```js
'use strict';

var verb = require('verb4');
verb.data('package.json');

verb.task('default', function() {
  verb.src('.verbrc.md')
    .pipe(verb.dest(__dirname));
});
```


text:
<!doctype html>

<title>Agendor Quiz</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../doc/docs.css">

<link rel="stylesheet" href="../lib/codemirror.css">
<link rel="stylesheet" href="../addon/fold/foldgutter.css">
<link rel="stylesheet" href="../addon/dialog/dialog.css">
<link rel="stylesheet" href="../theme/monokai.css">

Agendor Front-end Engineer Quiz

Create a function that receives an array that has numbers and arrays (like [1, [2, [3, 4, [5]]], 6]) and returns just numbers ([1, 2, 3, 4, 5, 6]).

The code editor below has a similar behaviour to Sublime Text.

  <button class="js-exam-runSolution">Run</button>
  <button class="js-exam-testSolution">Test</button>
  <button class="js-exam-submitSolution">Submit</button>


text:
from __future__ import absolute_import, division, print_function

__metaclass__ = type

ANSIBLE_METADATA = {
    'metadata_version': '1.1',
    'status': ['preview'],
    'supported_by': 'community'
}

DOCUMENTATION = '''
---
module: vmware_vspan_session
short_description: Create or remove a Port Mirroring session.
description:
   - This module can be used to create, delete or edit different kind of port mirroring sessions.
version_added: '2.8'
author:
- Peter Gyorgy (@gyorgypeter)
notes:
    - Tested on vSphere 6.7
requirements:
    - "python > =  2.6"
    - PyVmomi
options:
    switch:
        description:
            - The name of the distributed vSwitch on which to add or remove the mirroring session.
        required: True
        aliases: [ 'switch_name' ]
        type: str
    name:
        description:
            - Name of the session.
        required: True
        type: str
    state:
        choices:
            - 'present'
            - 'absent'
        description:
            - Create or remove the session.
        required: True
        type: str
    session_type:
        default: 'dvPortMirror'
        choices:
            - 'encapsulatedRemoteMirrorSource'
            - 'remoteMirrorDest'
            - 'remoteMirrorSource'
            - 'dvPortMirror'
        description:
            - Select the mirroring type.
            - '- C(encapsulatedRemoteMirrorSource) (str): In encapsulatedRemoteMirrorSource session, Distributed Ports
            can be used as source entities, and Ip address can be used as destination entities.'
            - '- C(remoteMirrorDest) (str): In remoteMirrorDest session, vlan Ids can be used as source entities, and
            Distributed Ports can be used as destination entities.'
            - '- C(remoteMirrorSource) (str): In remoteMirrorSource session, Distributed Ports can be used as source
            entities, and uplink ports name can be used as destination entities.'
            - '- C(dvPortMirror) (str): In dvPortMirror session, Distributed Ports can be used as both source and
            destination entities.'
        required: False
        type: str
    enabled:
        type: bool
        default: True
        description:
            - Whether the session is enabled.
    description:
        description:
            - The description for the session.
        required: False
        type: str
    source_port_transmitted:
        description:
            - Source port for which transmitted packets are mirrored.
        required: False
        type: str
    source_port_received:
        description:
            - Source port for which received packets are mirrored.
        required: False
        type: str
    destination_port:
        description:
            - Destination port that received the mirrored packets. Also any port designated in the value of this
             property can not match the source port in any of the Distributed Port Mirroring session.
        required: False
        type: str
    encapsulation_vlan_id:
        description:
            - VLAN ID used to encapsulate the mirrored traffic.
        required: False
        type: int
    strip_original_vlan:
        description:
            - Whether to strip the original VLAN tag. if false, the original VLAN tag will be preserved on the mirrored
             traffic. If encapsulationVlanId has been set and this property is false, the frames will be double tagged
             with the original VLAN ID as the inner tag.
        type: bool
        required: False
    mirrored_packet_length:
        description:
            - An integer that describes how much of each frame to mirror. If unset, all of the frame would be mirrored.
             Setting this property to a smaller value is useful when the consumer will look only at the headers.
             The value cannot be less than 60.
        required: False
        type: int
    normal_traffic_allowed:
        description:
            - Whether or not destination ports can send and receive "normal" traffic. Setting this to false will make
             mirror ports be used solely for mirroring and not double as normal access ports.
        type: bool
        required: False
    sampling_rate:
        description:
            - Sampling rate of the session. If its value is n, one of every n packets is mirrored.
             Valid values are between 1 to 65535, and default value is 1.
        type: int
        required: False
    source_vm_transmitted:
        description:
            - With this parameter it is possible, to add a NIC of a VM to a port mirroring session.
            - 'Valid attributes are:'
            - '- C(name) (str): Name of the VM'
            - '- C(nic_label) (bool): Label of the Network Interface Card to use.'
        type: dict
    source_vm_received:
        description:
            - With this parameter it is possible, to add a NIC of a VM to a port mirroring session.
            - 'Valid attributes are:'
            - '- C(name) (str): Name of the VM'
            - '- C(nic_label) (bool): Label of the Network Interface Card to use.'
        type: dict
    destination_vm:
        description:
            - With this parameter it is possible, to add a NIC of a VM to a port mirroring session.
            - 'Valid attributes are:'
            - '- C(name) (str): Name of the VM'
            - '- C(nic_label) (bool): Label of the Network Interface Card to use.'
        required: False
        type: dict
extends_documentation_fragment: vmware.documentation
'''

EXAMPLES = '''
- name: Create distributed mirroring session.
  vmware_vspan_session:
    hostname: '{{ vcenter_hostname }}'
    username: '{{ vcenter_username }}'
    password: '{{ vcenter_password }}'
    switch_name: dvSwitch
    state: present
    name: Basic Session
    enabled: True
    description: "Example description"
    source_port_transmitted: 817
    source_port_received: 817
    destination_port: 815
  delegate_to: localhost

- name: Create remote destination mirroring session.
  vmware_vspan_session:
    hostname: '{{ vcenter_hostname }}'
    username: '{{ vcenter_username }}'
    password: '{{ vcenter_password }}'
    switch_name: dvSwitch
    state: present
    name: Remote Session
    enabled: True
    description: "Example description"
    source_port_received: 105
    destination_port: 815
    session_type: "remoteMirrorDest"
  delegate_to: localhost

- name: Create remote destination mirroring session.
  vmware_vspan_session:
    hostname: '{{ vcenter_hostname }}'
    username: '{{ vcenter_username }}'
    password: '{{ vcenter_password }}'
    switch_name: dvSwitch
    state: absent
    name: Remote Session
  delegate_to: localhost
'''

RETURN = """#
"""

try:
    from pyVmomi import vim, vmodl
except ImportError as e:
    pass

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import (vmware_argument_spec, PyVmomi, find_dvs_by_name,
                                         find_vm_by_name, wait_for_task)

class VMwareVspanSession(PyVmomi):
    def __init__(self, module):
        super(VMwareVspanSession, self).__init__(module)
        self.switch = module.params['switch']
        self.name = module.params['name']
        self.session_type = module.params['session_type']
        self.enabled = module.params['enabled']
        self.state = module.params['state']
        self.description = module.params['description']
        self.source_port_transmitted = module.params['source_port_transmitted']
        self.source_port_received = module.params['source_port_received']
        self.destination_port = module.params['destination_port']
        self.encapsulation_vlan_id = module.params['encapsulation_vlan_id']
        self.strip_original_vlan = module.params['strip_original_vlan']
        self.mirrored_packet_length = module.params['mirrored_packet_length']
        self.normal_traffic_allowed = module.params['normal_traffic_allowed']
        self.sampling_rate = module.params['sampling_rate']
        self.dv_switch = find_dvs_by_name(self.content, self.switch)
        if self.dv_switch is None:
            self.module.fail_json(msg="There is no dvSwitch with the name: {0:s}.".format(self.switch))
        self.operation = None
        self.modified_ports = dict()
        self.deleted_session = None
        if module.params['source_vm_transmitted'] is not None:
            if (module.params['source_vm_transmitted']['name'] is None or
                    module.params['source_vm_transmitted']['nic_label'] is None):
                self.module.fail_json(msg="Please provide both VM name and NIC Label")
            self.source_vm_transmitted_name = module.params['source_vm_transmitted']['name']
            self.source_vm_transmitted_nic_label = module.params['source_vm_transmitted']['nic_label']
        if module.params['source_vm_received'] is not None:
            if (module.params['source_vm_received']['name'] is None or
                    module.params['source_vm_received']['nic_label'] is None):
                self.module.fail_json(msg="Please provide both VM name and NIC Label")
            self.source_vm_received_name = module.params['source_vm_received']['name']
            self.source_vm_received_nic_label = module.params['source_vm_received']['nic_label']
        if module.params['destination_vm'] is not None:
            if (module.params['destination_vm']['name'] is None or
                    module.params['destination_vm']['nic_label'] is None):
                self.module.fail_json(msg="Please provide both VM name and NIC Label")
            self.destination_vm_name = module.params['destination_vm']['name']
            self.destination_vm_nic_label = module.params['destination_vm']['nic_label']

    def set_operation(self):
        """Sets the operation according to state"""
        if self.state == 'absent':
            self.operation = 'remove'
        elif self.state == 'present' and self.find_session_by_name() is None:
            self.operation = 'add'
        else:
            self.operation = 'edit'

    def find_session_by_name(self):
        """Finds a session by name
        Returns
        -------
        vim.dvs.VmwareDistributedVirtualSwitch.VspanSession
            The session if there was a session by the given name, else returns None
        """
        for vspan_session in self.dv_switch.config.vspanSession:
            if vspan_session.name == self.name:
                return vspan_session
        return None

    def get_vm_port(self, vm_name, nic_label):
        """Finds the port of the VM
        Returns
        -------
        str
            the port number as a string, or None if the NIC couldnt be found
        """
        vm = find_vm_by_name(self.content, vm_name)
        if vm is None:
            self.module.fail_json(msg="There is no VM with the name: {0:s}.".format(vm_name))
        for hardware in vm.config.hardware.device:
            if isinstance(hardware, vim.vm.device.VirtualVmxnet3):
                if hardware.deviceInfo.label == nic_label:
                    return hardware.backing.port.portKey
        return None

    def set_port_for_vm(self):
        """Sets the ports, to the VM's specified port."""
        if hasattr(self, 'source_vm_transmitted_name') and hasattr(self, 'source_vm_transmitted_nic_label'):
            port = self.get_vm_port(self.source_vm_transmitted_name, self.source_vm_transmitted_nic_label)
            if port is not None:
                self.source_port_transmitted = port
            else:
                self.module.fail_json(
                    msg="No port could be found for VM: {0:s} NIC: {1:s}".format(self.source_vm_transmitted_name,
                                                                                self.source_vm_transmitted_nic_label))
        if hasattr(self, 'source_vm_received_name') and hasattr(self, 'source_vm_received_nic_label'):
            port = self.get_vm_port(self.source_vm_received_name, self.source_vm_received_nic_label)
            if port is not None:
                self.source_port_received = port
            else:
                self.module.fail_json(
                    msg="No port could be found for VM: {0:s} NIC: {1:s}".format(self.source_vm_received_name,
                                                                                self.source_vm_received_nic_label))
        if hasattr(self, 'destination_vm_name') and hasattr(self, 'destination_vm_nic_label'):
            port = self.get_vm_port(self.destination_vm_name, self.destination_vm_nic_label)
            if port is not None:
                self.destination_port = port
            else:
                self.module.fail_json(
                    msg="No port could be found for VM: {0:s} NIC: {1:s}".format(self.destination_vm_name,
                                                                                self.destination_vm_nic_label))

    def process_operation(self):
        """Calls the create or delete function based on the operation"""
        self.set_operation()
        if self.operation == 'remove':
            results = self.remove_vspan_session()
            self.module.exit_json(**results)
        if self.operation == 'add':
            self.set_port_for_vm()
            results = self.add_vspan_session()
            self.module.exit_json(**results)
        if self.operation == 'edit':
            self.remove_vspan_session()
            self.set_port_for_vm()
            results = self.add_vspan_session()
            self.module.exit_json(**results)

    def set_port_security_promiscuous(self, ports, state):
        """Set the given port to the given promiscuous state.
        Parameters
        ----------
        port : str[]
            PortKey
        state: bool
            State of the promiscuous mode, if true its allowed, else not.
        """
        # Creating the new port policy
        port_spec = []
        vim_bool = vim.BoolPolicy(value=state)
        port_policy = vim.dvs.VmwareDistributedVirtualSwitch.SecurityPolicy(allowPromiscuous=vim_bool)
        port_settings = vim.dvs.VmwareDistributedVirtualSwitch.VmwarePortConfigPolicy(securityPolicy=port_policy)
        for port in ports:
            temp_port_spec = vim.dvs.DistributedVirtualPort.ConfigSpec(
                operation="edit",
                key=port,
                setting=port_settings
            )
            port_spec.append(temp_port_spec)

        task = self.dv_switch.ReconfigureDVPort_Task(port_spec)
        try:
            wait_for_task(task)
        except Exception:
            self.restore_original_state()
            self.module.fail_json(msg=task.info.error.msg)

    def turn_off_promiscuous(self):
        """Disable all promiscuous mode ports, and give them back in a list.
        Returns
        -------
        list
            Contains every port, where promiscuous mode has been turned off
        """
        # Ports that are in mirror sessions
        ports = []
        ports_of_selected_session = []
        for vspan_session in self.dv_switch.config.vspanSession:
            if vspan_session.sourcePortReceived is not None:
                session_ports = vspan_session.sourcePortReceived.portKey
                for port in session_ports:
                    if vspan_session.name == self.name:
                        ports_of_selected_session.append(port)
                    elif not(port in ports):
                        ports.append(port)
            if vspan_session.sourcePortTransmitted is not None:
                session_ports = vspan_session.sourcePortTransmitted.portKey
                for port in session_ports:
                    if vspan_session.name == self.name:
                        ports_of_selected_session.append(port)
                    elif not(port in ports):
                        ports.append(port)
            if vspan_session.destinationPort is not None:
                session_ports = vspan_session.destinationPort.portKey
                for port in session_ports:
                    if vspan_session.name == self.name:
                        ports_of_selected_session.append(port)
                    elif not(port in ports):
                        ports.append(port)
        promiscuous_ports = []
        if ports:
            dv_ports = self.dv_switch.FetchDVPorts(vim.dvs.PortCriteria(portKey=ports))
            # If a port is promiscuous set disable it, and add it to the array to enable it after the changes are made.
            for dv_port in dv_ports:
                if dv_port.config.setting.securityPolicy.allowPromiscuous.value:
                    self.set_port_security_promiscuous([dv_port.key], False)
                    self.modified_ports.update({dv_port.key: True})
                    promiscuous_ports.append(dv_port.key)
        if ports_of_selected_session:
            current_dv_ports = self.dv_switch.FetchDVPorts(vim.dvs.PortCriteria(portKey=ports_of_selected_session))
            for dv_port in current_dv_ports:
                if dv_port.config.setting.securityPolicy.allowPromiscuous.value:
                    self.set_port_security_promiscuous([dv_port.key], False)
                    self.modified_ports.update({dv_port.key: True})
        # Return the promiscuous ports array, to set them back after the config is finished.
        return promiscuous_ports

    def delete_mirroring_session(self, key):
        """Deletes the mirroring session.
        Parameters
        ----------
        key : str
            Key of the Session
        """
        session = vim.dvs.VmwareDistributedVirtualSwitch.VspanSession(
            key=key
        )
        config_version = self.dv_switch.config.configVersion
        s_spec = vim.dvs.VmwareDistributedVirtualSwitch.VspanConfigSpec(vspanSession=session, operation="remove")
        c_spec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec(vspanConfigSpec=[s_spec], configVersion=config_version)
        task = self.dv_switch.ReconfigureDvs_Task(c_spec)
        try:
            wait_for_task(task)
        except Exception:
            self.restore_original_state()
            self.module.fail_json(msg=task.info.error.msg)

    def restore_original_state(self):
        """In case of failure restore, the changes we made."""
        for port, state in self.modified_ports.items():
            self.set_port_security_promiscuous([port], state)
        if self.deleted_session is not None:
            session = self.deleted_session
            config_version = self.dv_switch.config.configVersion
            s_spec = vim.dvs.VmwareDistributedVirtualSwitch.VspanConfigSpec(vspanSession=session, operation="add")
            c_spec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec(vspanConfigSpec=[s_spec], configVersion=config_version)
            # Revert the delete
            task = self.dv_switch.ReconfigureDvs_Task(c_spec)
            try:
                wait_for_task(task)
            except Exception:
                self.restore_original_state()
                self.module.fail_json(msg=task.info.error.msg)

    def remove_vspan_session(self):
        """Calls the necessary functions to delete a VSpanSession."""
        results = dict(changed=False, result="")
        mirror_session = self.find_session_by_name()
        if mirror_session is None:
            results['result'] = "There is no VSpanSession with the name: {0:s}.".format(self.name)
            return results
        promiscuous_ports = self.turn_off_promiscuous()
        session_key = mirror_session.key
        # Delete Mirroring Session
        self.delete_mirroring_session(session_key)
        # Session
        self.deleted_session = mirror_session
        # Set back the promiscuous ports
        if promiscuous_ports:
            self.set_port_security_promiscuous(promiscuous_ports, True)
        results['changed'] = True
        results['result'] = 'VSpan Session has been deleted'
        return results

    def check_if_session_name_is_free(self):
        """Checks whether the name is used or not
        Returns
        -------
        bool
            True if the name is free and False if it is used.
        """
        for vspan_session in self.dv_switch.config.vspanSession:
            if vspan_session.name == self.name:
                return False
        return True

    def create_vspan_session(self):
        """Builds up the session, adds the parameters that we specified, then creates it on the vSwitch"""

        session = vim.dvs.VmwareDistributedVirtualSwitch.VspanSession(
            name=self.name,
            enabled=True
        )
        if self.session_type is not None:
            session.sessionType = self.session_type
            if self.session_type == 'encapsulatedRemoteMirrorSource':
                if self.source_port_received is not None:
                    port = vim.dvs.VmwareDistributedVirtualSwitch.VspanPorts(portKey=str(self.source_port_received))
                    if not self.dv_switch.FetchDVPorts(vim.dvs.PortCriteria(portKey=port.portKey)):
                        self.module.fail_json(msg="Couldn't find port: {0:s}".format(self.source_port_received))
                    session.sourcePortReceived = port
                if self.source_port_transmitted is not None:
                    port = vim.dvs.VmwareDistributedVirtualSwitch.VspanPorts(portKey=str(self.source_port_transmitted))
                    if not self.dv_switch.FetchDVPorts(vim.dvs.PortCriteria(portKey=port.portKey)):
                        self.module.fail_json(msg="Couldn't find port: {0:s}".format(self.source_port_transmitted))
                    session.sourcePortTransmitted = port
                if self.destination_port is not None:
                    port = vim.dvs.VmwareDistributedVirtualSwitch.VspanPorts(ipAddress=str(self.destination_port))
                    session.destinationPort = port
            if self.session_type == 'remoteMirrorSource':
                if self.source_port_received is not None:
                    port = vim.dvs.VmwareDistributedVirtualSwitch.VspanPorts(portKey=str(self.source_port_received))
                    if not self.dv_switch.FetchDVPorts(vim.dvs.PortCriteria(portKey=port.portKey)):
                        self.module.fail_json(msg="Couldn't find port: {0:s}".format(self.source_port_received))
                    session.sourcePortReceived = port
                if self.source_port_transmitted is not None:
                    port = vim.dvs.VmwareDistributedVirtualSwitch.VspanPorts(portKey=str(self.source_port_transmitted))
                    if not self.dv_switch.FetchDVPorts(vim.dvs.PortCriteria(portKey=port.portKey)):
                        self.module.fail_json(msg="Couldn't find port: {0:s}".format(self.source_port_transmitted))
                    session.sourcePortTransmitted = port
                if self.destination_port is not None:
                    port = vim.dvs.VmwareDistributedVirtualSwitch.VspanPorts(uplinkPortName=str(self.destination_port))
                    session.destinationPort = port
            if self.session_type == 'remoteMirrorDest':
                if self.source_port_received is not None:
                    port = vim.dvs.VmwareDistributedVirtualSwitch.VspanPorts(vlans=[int(self.source_port_received)])
                    if int(self.source_port_received) not in self.dv_switch.QueryUsedVlanIdInDvs():
                        self.module.fail_json(msg="Couldn't find vlan: {0:s}".format(self.source_port_received))
                    session.sourcePortReceived = port
                if self.destination_port is not None:
                    port = vim.dvs.VmwareDistributedVirtualSwitch.VspanPorts(portKey=str(self.destination_port))
                    if not self.dv_switch.FetchDVPorts(vim.dvs.PortCriteria(portKey=port.portKey)):
                        self.module.fail_json(msg="Couldn't find port: {0:s}".format(self.destination_port))
                    session.destinationPort = port
            if self.session_type == 'dvPortMirror':
                if self.source_port_received is not None:
                    port = vim.dvs.VmwareDistributedVirtualSwitch.VspanPorts(portKey=str(self.source_port_received))
                    if not self.dv_switch.FetchDVPorts(vim.dvs.PortCriteria(portKey=port.portKey)):
                        self.module.fail_json(msg="Couldn't find port: {0:s}".format(self.source_port_received))
                    session.sourcePortReceived = port
                if self.source_port_transmitted is not None:
                    port = vim.dvs.VmwareDistributedVirtualSwitch.VspanPorts(portKey=str(self.source_port_transmitted))
                    if not self.dv_switch.FetchDVPorts(vim.dvs.PortCriteria(portKey=port.portKey)):
                        self.module.fail_json(msg="Couldn't find port: {0:s}".format(self.source_port_transmitted))
                    session.sourcePortTransmitted = port
                if self.destination_port is not None:
                    port = vim.dvs.VmwareDistributedVirtualSwitch.VspanPorts(portKey=str(self.destination_port))
                    if not self.dv_switch.FetchDVPorts(vim.dvs.PortCriteria(portKey=port.portKey)):
                        self.module.fail_json(msg="Couldn't find port: {0:s}".format(self.destination_port))
                    session.destinationPort = port
        if self.description is not None:
            session.description = self.description
        if self.encapsulation_vlan_id is not None:
            session.encapsulationVlanId = self.encapsulation_vlan_id
        if self.strip_original_vlan is not None:
            session.stripOriginalVlan = self.strip_original_vlan
        if self.mirrored_packet_length is not None:
            session.mirroredPacketLength = self.mirrored_packet_length
        if self.normal_traffic_allowed is not None:
            session.normalTrafficAllowed = self.normal_traffic_allowed
        if self.sampling_rate is not None:
            session.samplingRate = self.sampling_rate
        config_version = self.dv_switch.config.configVersion
        s_spec = vim.dvs.VmwareDistributedVirtualSwitch.VspanConfigSpec(vspanSession=session, operation="add")
        c_spec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec(vspanConfigSpec=[s_spec], configVersion=config_version)
        task = self.dv_switch.ReconfigureDvs_Task(c_spec)
        try:
            wait_for_task(task)
        except Exception:
            self.restore_original_state()
            self.module.fail_json(msg=task.info.error.msg)

    def add_vspan_session(self):
        """Calls the necessary functions to create a VSpanSession"""
        results = dict(changed=False, result="")
        promiscous_ports = self.turn_off_promiscuous()
        if not self.check_if_session_name_is_free():
            self.module.fail_json(msg="There is another VSpan Session with the name: {0:s}.".format(self.name))
        # Locate the ports, we want to use
        dv_ports = None
        ports = [str(self.source_port_received), str(self.source_port_transmitted), str(self.destination_port)]
        if ports:
            dv_ports = self.dv_switch.FetchDVPorts(vim.dvs.PortCriteria(portKey=ports))
        for dv_port in dv_ports:
            if dv_port.config.setting.securityPolicy.allowPromiscuous.value:
                self.set_port_security_promiscuous([dv_port.key], False)
                self.modified_ports.update({dv_port.key: True})
        # Now we can create the VspanSession
        self.create_vspan_session()
        # Finally we can set the destination port to promiscuous mode
        if self.session_type == 'dvPortMirror' or self.session_type == 'remoteMirrorDest':
            self.set_port_security_promiscuous([str(self.destination_port)], True)
        # Set Back the Promiscuous ports
        if promiscous_ports:
            self.set_port_security_promiscuous(promiscous_ports, True)
        results['changed'] = True
        results['result'] = 'Mirroring session has been created.'
        return results

def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(dict(
        switch=dict(type='str', required=True, aliases=['switch_name']),
        name=dict(type='str', required=True),
        state=dict(type='str', required=True, choices=['present', 'absent']),
        session_type=dict(type='str', default='dvPortMirror', choices=['dvPortMirror',
                                                                       'encapsulatedRemoteMirrorSource',
                                                                       'remoteMirrorDest',
                                                                       'remoteMirrorSource']),
        enabled=dict(type='bool', default=True),
        description=dict(type='str'),
        source_port_transmitted=dict(type='str'),
        source_port_received=dict(type='str'),
        destination_port=dict(type='str'),
        encapsulation_vlan_id=dict(type='int'),
        strip_original_vlan=dict(type='bool'),
        mirrored_packet_length=dict(type='int'),
        normal_traffic_allowed=dict(type='bool'),
        sampling_rate=dict(type='int'),
        source_vm_transmitted=dict(type='dict',
                                   options=dict(
                                       name=dict(type='str'),
                                       nic_label=dict(type='str'))),
        source_vm_received=dict(type='dict',
                                options=dict(
                                    name=dict(type='str'),
                                    nic_label=dict(type='str'))),
        destination_vm=dict(type='dict',
                            options=dict(
                                name=dict(type='str'),
                                nic_label=dict(type='str'))),
    ))
    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False)
    session = VMwareVspanSession(module)
    session.process_operation()

if __name__ == '__main__':
    main()


text:
package com.banckle.crm.api;

import com.banckle.client.ApiException;
import com.banckle.client.ApiInvoker;

import com.sun.jersey.multipart.FormDataMultiPart;

import javax.ws.rs.core.MediaType;

import java.io.File;
import java.util.*;

public class AuthApi {
    public AuthApi AuthApi() {
        return this;
    }
  String basePath = "https://apps.banckle.com/api/v2";
  ApiInvoker apiInvoker = ApiInvoker.getInstance();

  public ApiInvoker getInvoker() {
    return apiInvoker;
  }

  public void setBasePath(String basePath) {
    this.basePath = basePath;
  }

  public String getBasePath() {
    return basePath;
  }

  //error info- code: 404 reason: "can't authenticate" model: ErrorModel
  public String getToken (Map<String, String> body) throws ApiException {
    Object postBody = body;
    // verify required params are set
    if(body == null ) {
       throw new ApiException(400, "missing required params");
    }
    // create path and map variables
    String path = "/auth/token".replaceAll("\\{format\\}","json");

    // query params
    Map<String, String> queryParams = new HashMap<String, String>();
    Map<String, String> headerParams = new HashMap<String, String>();
    Map<String, String> formParams = new HashMap<String, String>();

    String[] contentTypes = {
      "application/json"};

    String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

    if(contentType.startsWith("multipart/form-data")) {
      boolean hasFields = false;
      FormDataMultiPart mp = new FormDataMultiPart();
      if(hasFields)
        postBody = mp;
    }
    else {
      }

    try {
      String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType);
      if(response != null){
        return (String) ApiInvoker.deserialize(response, "", String.class);
      }
      else {
        return null;
      }
    } catch (ApiException ex) {
      if(ex.getCode() == 404) {
      	return null;
      }
      else {
        throw ex;
      }
    }
  }

  }


text:
package com.amazonaws.services.ecr.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.ecr.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * RepositoryMarshaller
 */
public class RepositoryJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a JSONWriter
     */
    public void marshall(Repository repository, JSONWriter jsonWriter) {
        if (repository == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonWriter.object();

            if (repository.getRepositoryArn() != null) {
                jsonWriter.key("repositoryArn").value(
                        repository.getRepositoryArn());
            }

            if (repository.getRegistryId() != null) {
                jsonWriter.key("registryId").value(repository.getRegistryId());
            }

            if (repository.getRepositoryName() != null) {
                jsonWriter.key("repositoryName").value(
                        repository.getRepositoryName());
            }

            jsonWriter.endObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static RepositoryJsonMarshaller instance;

    public static RepositoryJsonMarshaller getInstance() {
        if (instance == null)
            instance = new RepositoryJsonMarshaller();
        return instance;
    }

}


text:
module Lumos
  module Formatters
    module BaseHorizontal
      def horizontal_pattern
        delimiter * chopped_message_length
      end

      def horizontal_line
        paragraph      = content_paragraph(chopped_message[0])
        paragraph_size = paragraph.size
        draft_size     = horizontal_pattern.size

        draft_size > paragraph_size ? horizontal_pattern[0...paragraph_size] : horizontal_pattern
      end

      def horizontal_padding
        "\n" * padding if padding > 0
      end

      def horizontal_result
        "#{horizontal_line}\n"\
        "#{horizontal_padding}"\
        "#{iterate_chopped_lines{ |line| "#{content_paragraph(line)}\n" }}"\
        "#{horizontal_padding}"\
        "#{horizontal_line}"
      end
    end
  end
end


text:
======================
Structuring Your Tasks
======================
Tips & Tricks
-------------

These are some general guidelines for programming with jug.

What can be a task?
-------------------

Almost any named function can be a task.

What should be a task?
----------------------

The trade-off is between tasks that are too small (you have too many of them
and the overhead of ``jug`` will overwhelm your process) or too big (and then
you have too few tasks per processor.

As a rule of thumb, each task should take at least a few seconds, but you
should have enough tasks that your processors are not idle.

Task size control
-----------------

Certain mechanisms in jug, for example, ``jug.mapreduce.map`` and
``jug.mapreduce.mapreduce`` allow the user to tweak the task breakup with a
couple of parameters

In ``map`` for example, ``jug`` does, by default, issue a task for each element
in the sequence. It rather issues one for each 4 elements. This expects tasks
to not take that long so that grouping them gives you a better trade-off
between the throughput and latency. You might quibble with the default, but the
principle is sound and it is only a default: the setting is there to give you
more control.

Identifying tasks
-----------------

In the module ``jug.hash``, jug attempts to construct a unique identifier, called
a hash, for each of your tasks. For doing that, the name of the function involved
invoked in the task together with  the parameters that it receives are used. This
makes jug easy to use but has some drawbacks:

- If your functions take long/big arguments, the hash process will potentially be
  costly. That's a common situation when you are processing arrays for example, or
  if you are using sets/dictionaries, in which case the default handling needs
  to get a sorted list from the elements of the set/dictionary.

- Jug might not know how to handle the types of your arguments,

- Arguments might be equivalent, and thus the tasks should be identified in the
  same way, without jug knowing. As a very contrived example, suppose that a task uses
  an argument which is an angle and for the purpose of your program all the values
  are equivalent modulo 2*pi.

If you control the types of your arguments, you can add a ``__jug_hash__``
method to your type directly. This method should return a string::

    class MySpecialThing:
        def __jug_hash__(self):
            return some_string

Alternatively, you can use ``jug.utils.CustomHash`` in the case where you
cannot (or rather, would not) change the types::

    from jug.utils import CustomHash
    def my_hash_function(x):
        return some_string_based_on_x

    complex = ...
    value = CustomHash(complex, my_hash_function)

Now, ``value`` behaves exactly like ``complex``, but its hash is computed by
calling ``my_hash_function``.


text: default_app_config = 'map.apps.MapConfig'


text:
/**
 * @file
 *   This file implements the Joiner Router role.
 */

#include "joiner_router.hpp"

#if OPENTHREAD_FTD

#include <stdio.h>

#include "common/as_core_type.hpp"
#include "common/code_utils.hpp"
#include "common/encoding.hpp"
#include "common/instance.hpp"
#include "common/locator_getters.hpp"
#include "common/log.hpp"
#include "meshcop/meshcop.hpp"
#include "meshcop/meshcop_tlvs.hpp"
#include "thread/mle.hpp"
#include "thread/thread_netif.hpp"
#include "thread/uri_paths.hpp"

namespace ot {
namespace MeshCoP {

RegisterLogModule("JoinerRouter");

JoinerRouter::JoinerRouter(Instance &aInstance)
    : InstanceLocator(aInstance)
    , mSocket(aInstance)
    , mRelayTransmit(UriPath::kRelayTx, &JoinerRouter::HandleRelayTransmit, this)
    , mTimer(aInstance, JoinerRouter::HandleTimer)
    , mJoinerUdpPort(0)
    , mIsJoinerPortConfigured(false)
{
    Get<Tmf::Agent>().AddResource(mRelayTransmit);
}

void JoinerRouter::HandleNotifierEvents(Events aEvents)
{
    if (aEvents.Contains(kEventThreadNetdataChanged))
    {
        Start();
    }
}

void JoinerRouter::Start(void)
{
    VerifyOrExit(Get<Mle::MleRouter>().IsFullThreadDevice());

    if (Get<NetworkData::Leader>().IsJoiningEnabled())
    {
        uint16_t port = GetJoinerUdpPort();

        VerifyOrExit(!mSocket.IsBound());

        IgnoreError(mSocket.Open(&JoinerRouter::HandleUdpReceive, this));
        IgnoreError(mSocket.Bind(port));
        IgnoreError(Get<Ip6::Filter>().AddUnsecurePort(port));
        LogInfo("Joiner Router: start");
    }
    else
    {
        VerifyOrExit(mSocket.IsBound());

        IgnoreError(Get<Ip6::Filter>().RemoveUnsecurePort(mSocket.GetSockName().mPort));

        IgnoreError(mSocket.Close());
    }

exit:
    return;
}

uint16_t JoinerRouter::GetJoinerUdpPort(void)
{
    uint16_t                rval = OPENTHREAD_CONFIG_JOINER_UDP_PORT;
    const JoinerUdpPortTlv *joinerUdpPort;

    VerifyOrExit(!mIsJoinerPortConfigured, rval = mJoinerUdpPort);

    joinerUdpPort = As<JoinerUdpPortTlv>(Get<NetworkData::Leader>().GetCommissioningDataSubTlv(Tlv::kJoinerUdpPort));
    VerifyOrExit(joinerUdpPort != nullptr);

    rval = joinerUdpPort->GetUdpPort();

exit:
    return rval;
}

void JoinerRouter::SetJoinerUdpPort(uint16_t aJoinerUdpPort)
{
    mJoinerUdpPort          = aJoinerUdpPort;
    mIsJoinerPortConfigured = true;
    Start();
}

void JoinerRouter::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo)
{
    static_cast<JoinerRouter *>(aContext)->HandleUdpReceive(AsCoreType(aMessage), AsCoreType(aMessageInfo));
}

void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
{
    Error            error;
    Coap::Message *  message = nullptr;
    Tmf::MessageInfo messageInfo(GetInstance());
    ExtendedTlv      tlv;
    uint16_t         borderAgentRloc;
    uint16_t         offset;

    LogInfo("JoinerRouter::HandleUdpReceive");

    SuccessOrExit(error = GetBorderAgentRloc(Get<ThreadNetif>(), borderAgentRloc));

    message = Get<Tmf::Agent>().NewPriorityNonConfirmablePostMessage(UriPath::kRelayRx);
    VerifyOrExit(message != nullptr, error = kErrorNoBufs);

    SuccessOrExit(error = Tlv::Append<JoinerUdpPortTlv>(*message, aMessageInfo.GetPeerPort()));
    SuccessOrExit(error = Tlv::Append<JoinerIidTlv>(*message, aMessageInfo.GetPeerAddr().GetIid()));
    SuccessOrExit(error = Tlv::Append<JoinerRouterLocatorTlv>(*message, Get<Mle::MleRouter>().GetRloc16()));

    tlv.SetType(Tlv::kJoinerDtlsEncapsulation);
    tlv.SetLength(aMessage.GetLength() - aMessage.GetOffset());
    SuccessOrExit(error = message->Append(tlv));
    offset = message->GetLength();
    SuccessOrExit(error = message->SetLength(offset + tlv.GetLength()));
    aMessage.CopyTo(aMessage.GetOffset(), offset, tlv.GetLength(), *message);

    messageInfo.SetSockAddrToRlocPeerAddrTo(borderAgentRloc);

    SuccessOrExit(error = Get<Tmf::Agent>().SendMessage(*message, messageInfo));

    LogInfo("Sent relay rx");

exit:
    FreeMessageOnError(message, error);
}

void JoinerRouter::HandleRelayTransmit(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo)
{
    static_cast<JoinerRouter *>(aContext)->HandleRelayTransmit(AsCoapMessage(aMessage), AsCoreType(aMessageInfo));
}

void JoinerRouter::HandleRelayTransmit(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
{
    OT_UNUSED_VARIABLE(aMessageInfo);

    Error                    error;
    uint16_t                 joinerPort;
    Ip6::InterfaceIdentifier joinerIid;
    Kek                      kek;
    uint16_t                 offset;
    uint16_t                 length;
    Message *                message = nullptr;
    Message::Settings        settings(Message::kNoLinkSecurity, Message::kPriorityNet);
    Ip6::MessageInfo         messageInfo;

    VerifyOrExit(aMessage.IsNonConfirmablePostRequest(), error = kErrorDrop);

    LogInfo("Received relay transmit");

    SuccessOrExit(error = Tlv::Find<JoinerUdpPortTlv>(aMessage, joinerPort));
    SuccessOrExit(error = Tlv::Find<JoinerIidTlv>(aMessage, joinerIid));

    SuccessOrExit(error = Tlv::FindTlvValueOffset(aMessage, Tlv::kJoinerDtlsEncapsulation, offset, length));

    VerifyOrExit((message = mSocket.NewMessage(0, settings)) != nullptr, error = kErrorNoBufs);

    SuccessOrExit(error = message->SetLength(length));
    aMessage.CopyTo(offset, 0, length, *message);

    messageInfo.GetPeerAddr().SetToLinkLocalAddress(joinerIid);
    messageInfo.SetPeerPort(joinerPort);

    SuccessOrExit(error = mSocket.SendTo(*message, messageInfo));

    if (Tlv::Find<JoinerRouterKekTlv>(aMessage, kek) == kErrorNone)
    {
        LogInfo("Received kek");

        DelaySendingJoinerEntrust(messageInfo, kek);
    }

exit:
    FreeMessageOnError(message, error);
}

void JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessageInfo, const Kek &aKek)
{
    Error                 error   = kErrorNone;
    Message *             message = Get<MessagePool>().Allocate(Message::kTypeOther);
    JoinerEntrustMetadata metadata;

    VerifyOrExit(message != nullptr, error = kErrorNoBufs);

    metadata.mMessageInfo = aMessageInfo;
    metadata.mMessageInfo.SetPeerPort(Tmf::kUdpPort);
    metadata.mSendTime = TimerMilli::GetNow() + kJoinerEntrustTxDelay;
    metadata.mKek      = aKek;

    SuccessOrExit(error = metadata.AppendTo(*message));

    mDelayedJoinEnts.Enqueue(*message);

    if (!mTimer.IsRunning())
    {
        mTimer.FireAt(metadata.mSendTime);
    }

exit:
    FreeMessageOnError(message, error);
    LogError("schedule joiner entrust", error);
}

void JoinerRouter::HandleTimer(Timer &aTimer)
{
    aTimer.Get<JoinerRouter>().HandleTimer();
}

void JoinerRouter::HandleTimer(void)
{
    SendDelayedJoinerEntrust();
}

void JoinerRouter::SendDelayedJoinerEntrust(void)
{
    JoinerEntrustMetadata metadata;
    Message *             message = mDelayedJoinEnts.GetHead();

    VerifyOrExit(message != nullptr);
    VerifyOrExit(!mTimer.IsRunning());

    metadata.ReadFrom(*message);

    if (TimerMilli::GetNow() < metadata.mSendTime)
    {
        mTimer.FireAt(metadata.mSendTime);
    }
    else
    {
        mDelayedJoinEnts.DequeueAndFree(*message);

        Get<KeyManager>().SetKek(metadata.mKek);

        if (SendJoinerEntrust(metadata.mMessageInfo) != kErrorNone)
        {
            mTimer.Start(0);
        }
    }

exit:
    return;
}

Error JoinerRouter::SendJoinerEntrust(const Ip6::MessageInfo &aMessageInfo)
{
    Error          error = kErrorNone;
    Coap::Message *message;

    message = PrepareJoinerEntrustMessage();
    VerifyOrExit(message != nullptr, error = kErrorNoBufs);

    IgnoreError(Get<Tmf::Agent>().AbortTransaction(&JoinerRouter::HandleJoinerEntrustResponse, this));

    LogInfo("Sending JOIN_ENT.ntf");
    SuccessOrExit(error = Get<Tmf::Agent>().SendMessage(*message, aMessageInfo,
                                                        &JoinerRouter::HandleJoinerEntrustResponse, this));

    LogInfo("Sent joiner entrust length = %d", message->GetLength());
    LogCert("[THCI] direction=send | type=JOIN_ENT.ntf");

exit:
    FreeMessageOnError(message, error);
    return error;
}

Coap::Message *JoinerRouter::PrepareJoinerEntrustMessage(void)
{
    Error          error;
    Coap::Message *message = nullptr;
    Dataset        dataset;
    NetworkNameTlv networkName;
    const Tlv *    tlv;
    NetworkKey     networkKey;

    message = Get<Tmf::Agent>().NewPriorityConfirmablePostMessage(UriPath::kJoinerEntrust);
    VerifyOrExit(message != nullptr, error = kErrorNoBufs);

    message->SetSubType(Message::kSubTypeJoinerEntrust);

    Get<KeyManager>().GetNetworkKey(networkKey);
    SuccessOrExit(error = Tlv::Append<NetworkKeyTlv>(*message, networkKey));
    SuccessOrExit(error = Tlv::Append<MeshLocalPrefixTlv>(*message, Get<Mle::MleRouter>().GetMeshLocalPrefix()));
    SuccessOrExit(error = Tlv::Append<ExtendedPanIdTlv>(*message, Get<ExtendedPanIdManager>().GetExtPanId()));

    networkName.Init();
    networkName.SetNetworkName(Get<NetworkNameManager>().GetNetworkName().GetAsData());
    SuccessOrExit(error = networkName.AppendTo(*message));

    IgnoreError(Get<ActiveDatasetManager>().Read(dataset));

    if ((tlv = dataset.GetTlv<ActiveTimestampTlv>()) != nullptr)
    {
        SuccessOrExit(error = tlv->AppendTo(*message));
    }
    else
    {
        ActiveTimestampTlv activeTimestamp;
        activeTimestamp.Init();
        SuccessOrExit(error = activeTimestamp.AppendTo(*message));
    }

    if ((tlv = dataset.GetTlv<ChannelMaskTlv>()) != nullptr)
    {
        SuccessOrExit(error = tlv->AppendTo(*message));
    }
    else
    {
        ChannelMaskBaseTlv channelMask;
        channelMask.Init();
        SuccessOrExit(error = channelMask.AppendTo(*message));
    }

    if ((tlv = dataset.GetTlv<PskcTlv>()) != nullptr)
    {
        SuccessOrExit(error = tlv->AppendTo(*message));
    }
    else
    {
        PskcTlv pskc;
        pskc.Init();
        SuccessOrExit(error = pskc.AppendTo(*message));
    }

    if ((tlv = dataset.GetTlv<SecurityPolicyTlv>()) != nullptr)
    {
        SuccessOrExit(error = tlv->AppendTo(*message));
    }
    else
    {
        SecurityPolicyTlv securityPolicy;
        securityPolicy.Init();
        SuccessOrExit(error = securityPolicy.AppendTo(*message));
    }

    SuccessOrExit(error = Tlv::Append<NetworkKeySequenceTlv>(*message, Get<KeyManager>().GetCurrentKeySequence()));

exit:
    FreeAndNullMessageOnError(message, error);
    return message;
}

void JoinerRouter::HandleJoinerEntrustResponse(void *               aContext,
                                               otMessage *          aMessage,
                                               const otMessageInfo *aMessageInfo,
                                               Error                aResult)
{
    static_cast<JoinerRouter *>(aContext)->HandleJoinerEntrustResponse(AsCoapMessagePtr(aMessage),
                                                                       AsCoreTypePtr(aMessageInfo), aResult);
}

void JoinerRouter::HandleJoinerEntrustResponse(Coap::Message *         aMessage,
                                               const Ip6::MessageInfo *aMessageInfo,
                                               Error                   aResult)
{
    OT_UNUSED_VARIABLE(aMessageInfo);

    SendDelayedJoinerEntrust();

    VerifyOrExit(aResult == kErrorNone && aMessage != nullptr);

    VerifyOrExit(aMessage->GetCode() == Coap::kCodeChanged);

    LogInfo("Receive joiner entrust response");
    LogCert("[THCI] direction=recv | type=JOIN_ENT.rsp");

exit:
    return;
}

void JoinerRouter::JoinerEntrustMetadata::ReadFrom(const Message &aMessage)
{
    uint16_t length = aMessage.GetLength();

    OT_ASSERT(length >= sizeof(*this));
    IgnoreError(aMessage.Read(length - sizeof(*this), *this));
}

} // namespace MeshCoP
} // namespace ot

#endif // OPENTHREAD_FTD


text:
This sample demonstrates receiving passive data updates in the background using the
`PassiveMonitoringClient` API.

### Running the sample

You will need a Wear device or emulator with Health Services installed. Open the sample project in
Android Studio and launch the app on your device or emulator.

On startup, the app checks whether heart rate data is available. If it is, you will see a screen
like this:

![heart rate available screenshot](screenshots/whs_passive_data_available.png)

Use the switch to enable or disable passive data updates. The most recent measurement received is
shown below that.

Note that on some devices, it may take several minutes for a value to be returned and displayed.

On devices where heart rate data is not available, you will see a screen like this:

![heart rate unavailable screenshot](screenshots/whs_passive_data_not_available.png)

### Try it with synthetic data

With the sample running, you can turn on the sythetic data tracker by running the below command from
a shell. This will mimic the user performing an activity and generating heart rate data. Check the
app UI or logcat messages to see these data updates.

```shell
adb shell am broadcast \
-a "whs.USE_SYNTHETIC_PROVIDERS" \
com.google.android.wearable.healthservices
```

To see different heart rate values, try simulating different exercises:
```shell
# walking
adb shell am broadcast \
-a "whs.synthetic.user.START_WALKING" \
com.google.android.wearable.healthservices

# running
adb shell am broadcast \
-a "whs.synthetic.user.START_RUNNING" \
com.google.android.wearable.healthservices
```

To stop using the synthetic tracker, run this command:
```shell
adb shell am broadcast -a \
"whs.USE_SENSOR_PROVIDERS" \
com.google.android.wearable.healthservices
```


text:
/*
 * sched_clock.h: support for extending counters to full 64-bit ns counter
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */
#ifndef LINUX_SCHED_CLOCK
#define LINUX_SCHED_CLOCK

#ifdef CONFIG_GENERIC_SCHED_CLOCK
extern void sched_clock_postinit(void);
#else
static inline void sched_clock_postinit(void) { }
#endif

extern void sched_clock_register(u64 (*read)(void), int bits,
				 unsigned long rate);

#endif


text:
require 'rails/generators'
require 'rails/generators/migration'

module Chimpy
  class MigrationGenerator < Rails::Generators::Base
    include Rails::Generators::Migration
    source_root File.expand_path('../templates', __FILE__)

    def copy_files
      @sync_class = Chimpy.configuration.sync_class.to_s
      migration_template('add_column_to_sync_class.rb.erb', "db/migrate/add_chimpy_to_#{@sync_class.underscore.pluralize}.rb")
    end

    def self.next_migration_number(dirname) #:nodoc:
      if ActiveRecord::Base.timestamped_migrations
        Time.now.utc.strftime("%Y%m%d%H%M%S")
      else
        "%.3d" % (current_migration_number(dirname) + 1)
      end
    end
  end
end