text:
package me.minidigger.voxelgameslib.api.signs;

import com.google.gson.annotations.Expose;

import java.util.Optional;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Transient;

import me.minidigger.voxelgameslib.api.block.Block;
import me.minidigger.voxelgameslib.api.block.metadata.SignMetaData;
import me.minidigger.voxelgameslib.api.event.VGLEventHandler;
import me.minidigger.voxelgameslib.api.event.events.sign.SignUpdateEvent;
import me.minidigger.voxelgameslib.api.exception.VoxelGameLibException;
import me.minidigger.voxelgameslib.api.map.Vector3D;
import me.minidigger.voxelgameslib.api.server.Server;
import me.minidigger.voxelgameslib.api.world.World;

import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;

/**
 * Stores the location of a traced sign into the db
 */
@Data
@Entity
public class SignLocation {
    @Id
    @GeneratedValue
    private Long id;

    @Expose
    @Column
    private Vector3D location;

    @Expose
    @Column
    private String world;

    @Transient
    private Block block;

    @Expose
    @Column
    @Setter(AccessLevel.PRIVATE)
    private String lines0;
    @Expose
    @Column
    @Setter(AccessLevel.PRIVATE)
    private String lines1;
    @Expose
    @Column
    @Setter(AccessLevel.PRIVATE)
    private String lines2;
    @Expose
    @Column
    @Setter(AccessLevel.PRIVATE)
    private String lines3;

    /**
     * Constructs a new sign location
     *
     * @param location the coordinates
     * @param world    the world
     * @param server   the server to get block information from
     * @param lines    the lines this sign currently has
     */
    public SignLocation(Vector3D location, String world, Server server, String[] lines) {
        this.location = location;
        this.world = world;

        Optional<World> w = server.getWorld(world);
        if (!w.isPresent()) {
            throw new VoxelGameLibException("Unknown world " + world);
        }

        block = w.get().getBlockAt(location);
        if (!(block.getMetaData() instanceof SignMetaData)) {
            throw new VoxelGameLibException("No sign at world " + world + " location " + location);
        }
        setLines(lines);
    }

    protected SignLocation() {
        //JPA
        setLines(new String[]{lines0, lines1, lines2, lines3});
    }

    public void setLines(String[] lines) {
        lines0 = lines[0];
        lines1 = lines[1];
        lines2 = lines[2];
        lines3 = lines[3];
        if (this.block != null) {
            ((SignMetaData) this.block.getMetaData()).setLines(lines);
        }
    }

    public String[] getLines() {
        return new String[]{lines0, lines1, lines2, lines3};
    }

    /**
     * Checks if the block on this location is still a sign
     *
     * @return if the block is still a sign
     */
    public boolean isStillValid(Server server) {
        if (block == null) {
            Optional<World> w = server.getWorld(world);
            if (!w.isPresent()) {
                throw new VoxelGameLibException("Unknown world " + world);
            }

            block = w.get().getBlockAt(location);
        }

        return block.getMetaData() instanceof SignMetaData;
    }

    /**
     * Fires a SignUpdateEvent for the sign at this location
     *
     * @param eventHandler the event handler that should handle the event
     */
    public void fireUpdateEvent(VGLEventHandler eventHandler) {
        SignMetaData metaData = (SignMetaData) block.getMetaData();
        String[] text = metaData.getLines();
        SignUpdateEvent event = new SignUpdateEvent(world, location, text);
        eventHandler.callEvent(event);
        if (!event.isCanceled()) {
            metaData.setLines(event.getText());
        }
    }
}


text:
require 'abstract_unit'
require 'active_support/core_ext/date'
require 'active_support/core_ext/numeric/time'

class TimeTravelTest < ActiveSupport::TestCase
  setup do
    Time.stubs now: Time.now
  end

  teardown do
    travel_back
  end

  def test_time_helper_travel
    expected_time = Time.now + 1.day
    travel 1.day

    assert_equal expected_time.to_s(:db), Time.now.to_s(:db)
    assert_equal expected_time.to_date, Date.today
  end

  def test_time_helper_travel_with_block
    expected_time = Time.now + 1.day

    travel 1.day do
      assert_equal expected_time.to_s(:db), Time.now.to_s(:db)
      assert_equal expected_time.to_date, Date.today
    end

    assert_not_equal expected_time.to_s(:db), Time.now.to_s(:db)
    assert_not_equal expected_time.to_date, Date.today
  end

  def test_time_helper_travel_to
    expected_time = Time.new(2004, 11, 24, 01, 04, 44)
    travel_to expected_time

    assert_equal expected_time, Time.now
    assert_equal Date.new(2004, 11, 24), Date.today
  end

  def test_time_helper_travel_to_with_block
    expected_time = Time.new(2004, 11, 24, 01, 04, 44)

    travel_to expected_time do
      assert_equal expected_time, Time.now
      assert_equal Date.new(2004, 11, 24), Date.today
    end

    assert_not_equal expected_time, Time.now
    assert_not_equal Date.new(2004, 11, 24), Date.today
  end

  def test_time_helper_travel_back
    expected_time = Time.new(2004, 11, 24, 01, 04, 44)

    travel_to expected_time
    assert_equal expected_time, Time.now
    assert_equal Date.new(2004, 11, 24), Date.today
    travel_back

    assert_not_equal expected_time, Time.now
    assert_not_equal Date.new(2004, 11, 24), Date.today
  end

  def test_travel_to_will_reset_the_usec_to_avoid_mysql_rouding
    travel_to Time.utc(2014, 10, 10, 10, 10, 50, 999999) do
      assert_equal 50, Time.now.sec
      assert_equal 0, Time.now.usec
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php
require_once("include.php");

$title = $str['title'];

$style = '';
$content = '';
$mode = 'home';
$include = '';
$script = '';

if (isset($_SESSION['info_id'])) {
	$id = mysql_real_escape_string($_SESSION['info_id']);
	if (isset($_GET['delete'])) {
		mysql_query("DELETE FROM members WHERE userid='$id'");
		unset($_SESSION['info_id']);
		header('Location: /');
		exit();
	}
	$password = $_POST['password'];
	//openssl_private_decrypt(base64_decode($_POST['password']), $password, $_SESSION['privkey']);
	if ($password != '') {
		$result = mysql_query("SELECT * FROM members WHERE userid='$id';");
		$data = mysql_fetch_row($result);
		$pw = explode('$', $data[2]);
		$newpw = $pw[0] . '$' . hash('sha512', $pw[0] . $password);
		mysql_query("UPDATE members SET password='$newpw' WHERE userid='$id';");
	}
	if ($_POST['addr'] !== '') {
		$addr = mysql_real_escape_string($_POST['addr']);
		if (mb_strlen($addr) > 10) {
			$content .= '
' . $str['err_addr_toolong'] . '
';
			goto error;
		} else if (!preg_match('/^[a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣ\-* ]+$/', $addr)) {
			$content .= '
' . $str['err_addr_character'] . '
';
			goto error;
		} else if (mb_strlen($addr) < 2) {
			$content .= '
' . $str['err_addr_tooshort'] . '
';
			goto error;
		} else {
			$result = mysql_query("SELECT * FROM members WHERE addr='$addr';");
			$data = mysql_fetch_row($result);
			if (count($data) >= 2) {
				$content .= '
' . $str['err_duplicate_addr'] . '
';
				goto error;
			} else {
				mysql_query("UPDATE members SET addr='$addr' WHERE userid='$id';");
			}
		}
	}
	if (!isset($_POST['enablelist'])) {
		mysql_query("UPDATE members SET enablelist='0' WHERE userid='$id';");
	} else {
		mysql_query("UPDATE members SET enablelist='1' WHERE userid='$id';");
	}

	$id = mysql_real_escape_string($_SESSION['info_id']);
	$result = mysql_query("SELECT * FROM members WHERE userid='$id';");
	$data = mysql_fetch_row($result);
	$others = unserialize($data[10]);
	if (mb_strlen($_POST['comment']) < 140) {
		$others['comment'] = htmlspecialchars($_POST['comment']);
	}
	$others = serialize($others);
	$others = mysql_real_escape_string($others);
	mysql_query("UPDATE members SET others='$others' WHERE userid='$id';");

	$content .= '
' . $str['myinfo_changed'] . '
';
	error:
} else {
	header('Location: ./_login');
}
require_once('template.php');
?>


text:
#include "stb/stb_image.h"
#include "stb/stb_image_write.h"
#include "stb/stb_image_resize.h"

namespace scpak
{
    int calcMipmapSize(int width, int height, int level = 0);
    int generateMipmap(int width, int height, int level, unsigned char *image);

    template<void old_packer(const std::string &inputDir, PakItem &output)>
    void packer_wrapper(const std::string &inputDir, PakItem &output, const std::string &meta)
    {
        old_packer(inputDir, output);
    }

    PakFile pack(const std::string &dirPath, const std::map<std::string, packer_type> &packers, const packer_type &default_packer)
    {
        PakFile pak;
        std::vector<PakItem> contents = pak.contents();
        std::string dirPathSafe = dirPath;
        if (*dirPathSafe.rbegin() != pathsep)
            dirPathSafe += pathsep;
        std::ifstream fPakInfo(dirPathSafe + PakInfoFileName);
        if (!fPakInfo)
            throw std::runtime_error("cannot open " + dirPathSafe + PakInfoFileName);
        std::string line;
        int lineNumber = 1;
        while (std::getline(fPakInfo, line))
        {
            std::size_t split1 = line.find(':');
            if (split1 == std::string::npos)
            {
                std::stringstream ss;
                ss << "cannot parse " << PakInfoFileName << ", line " << lineNumber;
                throw std::runtime_error(ss.str());
            }
            std::string name = line.substr(0, split1);
            std::size_t split2 = line.find(':', split1 + 1);
            std::string type = line.substr(split1 + 1, split2 - split1 - 1);
            std::string extraInfo;
            if (split2 != std::string::npos)
                extraInfo = line.substr(split2 + 1, std::string::npos);
            PakItem item;
            item.name = name;
            item.type = type;

            auto it = packers.find(item.type);
            if (it != packers.end())
                it->second(dirPathSafe, item, extraInfo);
            else
                default_packer(dirPathSafe, item, extraInfo);

            pak.addItem(std::move(item));
            ++lineNumber;
        }
        fPakInfo.close();
        return pak;
    }

    PakFile pack(const std::string &dirPath, bool packText, bool packTexture, bool packFont, bool packSound)
    {
        std::map<std::string, packer_type> packers;
        if (packText)
        {
            packers.insert(std::pair<std::string, packer_type>("System.String", packer_wrapper<pack_string>));
            packers.insert(std::pair<std::string, packer_type>("System.Xml.Linq.XElement", packer_wrapper<pack_string>));
        }
        if (packTexture)
            packers.insert(std::pair<std::string, packer_type>("Engine.Graphics.Texture2D", pack_texture));
        if (packFont)
            packers.insert(std::pair<std::string, packer_type>("Engine.Media.BitmapFont", packer_wrapper<pack_bitmapFont>));
        if (packSound)
            packers.insert(std::pair<std::string, packer_type>("Engine.Audio.SoundBuffer", packer_wrapper<pack_soundBuffer>));

        packer_type default_packer = packer_wrapper<pack_raw>;
        return pack(dirPath, packers, default_packer);
    }

    PakFile packAll(const std::string & dirPath)
    {
        return pack(dirPath, true, true, true, true);
    }

    void pack_raw(const std::string & inputDir, PakItem & item)
    {
        std::string filePath = inputDir + item.name;
        int fileSize = getFileSize(filePath.c_str());
        std::ifstream file(filePath, std::ios::binary);
        item.data.resize(fileSize);
        item.length = fileSize;
        file.read(reinterpret_cast<char*>(item.data.data()), fileSize);
    }

    void pack_string(const std::string &inputDir, PakItem &item)
    {
        std::string fileName = inputDir + item.name;
        if (item.type == "System.String")
            fileName += ".txt";
        else if (item.type == "System.Xml.Linq.XElement")
            fileName += ".xml";
        else
            throw std::runtime_error("wrong item type");

        std::ifstream fin;
        fin.open(fileName, std::ios::binary);
        fin.seekg(0, std::ios::beg);
        int offsetBeg = fin.tellg();
        fin.seekg(0, std::ios::end);
        int offsetEnd = fin.tellg();
        int fileSize = offsetEnd - offsetBeg;
        fin.seekg(0, std::ios::beg);

        item.data.resize(fileSize + 5);
        MemoryBinaryWriter writer(item.data.data());
        writer.write7BitEncodedInt(fileSize);
        item.length = fileSize + writer.position;
        fin.read(reinterpret_cast<char*>(item.data.data() + writer.position), fileSize);
        fin.close();
    }

    void pack_bitmapFont(const std::string &inputDir, PakItem &item)
    {
        std::string listFileName = inputDir + item.name + ".lst";
        std::string textureFileName = inputDir + item.name + ".tga";

        std::ifstream fList;
        fList.open(listFileName);
        int glyphCount;
        fList >> glyphCount;

        int width, height, comp;
        unsigned char *data = stbi_load(textureFileName.c_str(), &width, &height, &comp, 4);
        item.data.resize(sizeof(GlyphInfo) * glyphCount + 50 + width*height * 4);

        MemoryBinaryWriter writer(item.data.data());
        writer.writeInt(glyphCount);
        for (int i = 0; i < glyphCount; ++i)
        {
            GlyphInfo glyph;
            fList >> glyph.unicode
                >> glyph.texCoord1.x >> glyph.texCoord1.y
                >> glyph.texCoord2.x >> glyph.texCoord2.y
                >> glyph.offset.x >> glyph.offset.y
                >> glyph.width;
            writer.writeUtf8Char(glyph.unicode);
            writer.writeFloat(glyph.texCoord1.x);
            writer.writeFloat(glyph.texCoord1.y);
            writer.writeFloat(glyph.texCoord2.x);
            writer.writeFloat(glyph.texCoord2.y);
            writer.writeFloat(glyph.offset.x);
            writer.writeFloat(glyph.offset.y);
            writer.writeFloat(glyph.width);
        }
        float glyphHeight; fList >> glyphHeight;
        Vector2f spacing; fList >> spacing.x >> spacing.y;
        float scale; fList >> scale;
        int fallbackCode; fList >> fallbackCode;
        writer.writeFloat(glyphHeight);
        writer.writeFloat(spacing.x);
        writer.writeFloat(spacing.y);
        writer.writeFloat(scale);
        writer.writeUtf8Char(fallbackCode);
        fList.close();

        writer.writeBoolean(0);
        writer.writeInt(width);
        writer.writeInt(height);
        writer.writeInt(1);
        std::memcpy(item.data.data() + writer.position, data, width*height * 4);
        item.length = writer.position + width*height * 4;

        stbi_image_free(data);
    }

    void pack_texture(const std::string & inputDir, PakItem & item, const std::string &meta)
    {
        std::string filePathRaw = inputDir + item.name;
        std::string fileName = filePathRaw;
        if (pathExists((filePathRaw + ".tga").c_str()))
            fileName += ".tga";
        else if (pathExists((filePathRaw + ".png").c_str()))
            fileName += ".png";
        else if (pathExists((filePathRaw + ".bmp").c_str()))
            fileName += ".bmp";
        else if (pathExists(filePathRaw.c_str()))
        {
            pack_raw(inputDir, item);
            return;
        }
        else
            throw std::runtime_error("cannot find image file: " + item.name);
        int width, height, comp;
        unsigned char *data = stbi_load(fileName.c_str(), &width, &height, &comp, 0);
        if (data == nullptr)
            throw std::runtime_error("cannot load image file: " + item.name);
        if (comp != 4)
            throw std::runtime_error("image must have 4 components in every pixel: " + item.name);

        bool keepSourceImageInTag = std::stoi(meta);
        int mipmapLevel = std::stoi(meta.substr(meta.find(' ')));

        item.length = 1 + sizeof(int) * 3 + calcMipmapSize(width, height, mipmapLevel) * comp;
        item.data.resize(item.length);
        MemoryBinaryWriter writer(item.data.data());
        writer.writeBoolean(keepSourceImageInTag);
        writer.writeInt(width);
        writer.writeInt(height);
        writer.writeInt(mipmapLevel);
        std::copy(data, data + width*height*comp, item.data.begin() + writer.position);
        stbi_image_free(data);
        int offset = generateMipmap(width, height, mipmapLevel, item.data.data() + sizeof(int) * 3);
    }

    void pack_soundBuffer(const std::string &inputDir, PakItem &item)
    {
        std::string inputFilePathBase = inputDir + item.name;
        if (pathExists(inputFilePathBase.c_str()))
        {
            int fileSize = getFileSize(inputFilePathBase.c_str());
            std::ifstream file(inputFilePathBase, std::ios::binary);
            item.data.resize(fileSize);
            item.length = fileSize;
            file.read(reinterpret_cast<char*>(item.data.data()), fileSize);
            file.close();
        }
        else if (pathExists((inputFilePathBase + ".wav").c_str()))
        {
            static const int bitsPerSample = 16;

            std::string fileName = inputFilePathBase + ".wav";
            std::ifstream fin(fileName, std::ios::binary);
            WavHeader header;
            fin.read(reinterpret_cast<char*>(&header), sizeof(header));
            item.data.resize(header.subchunk2Size + 13);
            MemoryBinaryWriter writer(item.data.data());
            writer.writeBoolean(false);
            writer.writeInt(header.channelCount);
            writer.writeInt(header.sampleRate);
            writer.writeInt(header.subchunk2Size);

            if (header.bitsPerSample != 16)
            {
                throw std::runtime_error("WAV-" + fileName + ": bitsPerSample must be 16.");
            }

            fin.read(reinterpret_cast<char*>(item.data.data() + writer.position), header.subchunk2Size);
            fin.close();
            item.length = item.data.size();
        }
    }

    int calcMipmapSize(int width, int height, int level)
    {
        if (level == 1)
            return width * height;
        if (!isPowerOfTwo(width) || !isPowerOfTwo(height))
            throw std::runtime_error("generating mipmaps for non-power of 2 images not supported");

        int size = width * height;
        while (width != 1 && height != 1 && level > 1)
        {
            width /= 2;
            height /= 2;
            --level;
            size += width * height;
        }
        if (width == 1 && height != 1)
            while (height != 1 && level > 1)
            {
                height /= 2;
                --level;
                size += width * height;
            }
        else if (height == 1 && width != 1)
            while (width != 1 && level > 1)
            {
                width /= 2;
                --level;
                size += width*height;
            }
        return size;
    }

    int generateMipmap(int width, int height, int level, unsigned char *image)
    {
        const int comp = 4;

        if (level == 1)
            return width * height * comp;
        if (!isPowerOfTwo(width) || !isPowerOfTwo(height))
            throw std::runtime_error("generating mipmaps for non-power of 2 images not supported");

        int offset = width * height * comp;
        int w = width, h = height;
        while (w != 1 && h % 2 != 1 && level > 1)
        {
            w /= 2;
            h /= 2;
            --level;
            stbir_resize_uint8(image, width, height, 0,
                image + offset, w, h, 0,
                comp);
            offset += w * h * comp;
        }
        if (w == 1 && h != 1)
            while (h != 1 && level > 1)
            {
                h /= 2;
                --level;
                stbir_resize_uint8(image, width, height, 0,
                    image + offset, w, h, 0,
                    comp);
                offset += w * h * comp;
            }
        else if (h == 1 && w != 1)
            while (w != 1 && level > 1)
            {
                w /= 2;
                --level;
                stbir_resize_uint8(image, width, height, 0,
                    image + offset, w, h, 0,
                    comp);
                offset += w * h * comp;
            }
        return offset;
    }
}


text:
using System.Collections.Generic;
using UnityEngine;

namespace Sparrow
{
	/// <summary>
	/// Handles generation of the room
	/// </summary>
	public class RoomGenerator : SingletonBehaviour<RoomGenerator>
	{
		/// <summary>
		/// Pieces of the room/map
		/// </summary>
		public List<RoomPiece> Pieces;

		/// <summary>
		/// The room piece to start with
		/// </summary>
		public RoomPiece StartingRoomPiece;

		/// <summary>
		/// Finds room pieces with paths of a certain direction
		/// </summary>
		/// <returns>The pieces with appropriate paths</returns>
		/// <param name="pathPosition">The needed path</param>
		public List<RoomPiece> PiecesWithPaths(RoomPath.PathPosition pathPosition)
		{
			return Pieces.FindAll((obj) => obj.HasPathDirection(pathPosition));
		}

		/// <summary>
		/// Generates the room!!
		/// </summary>
		void GenerateRoom()
		{
			// Start with the initial piece
			var start = Instantiate(StartingRoomPiece);
			start.transform.SetParent(transform);

			// Keep building out room pieces
			var pathQueue = new Queue<RoomPath>();
			var paths = start.GetPaths();
			foreach (var path in paths)
			{
				pathQueue.Enqueue(path);
			}

			int maxRooms = 10;
			int currentRooms = 1;
			while (pathQueue.Count > 0)
			{
				var path = pathQueue.Dequeue();
				if (null == path || currentRooms >= maxRooms)
				{
					continue;
				}

				var newPaths = CreateConnectedRoomPiece(path);
				++currentRooms;
				foreach (var nextPath in newPaths)
				{
					pathQueue.Enqueue(nextPath);
				}
			}
		}

		/// <summary>
		/// Start of the game!
		/// </summary>
		void Start()
		{
			GenerateRoom();
		}

		/// <summary>
		/// Creates the connected room piece.
		/// </summary>
		/// <returns>The connected room piece.</returns>
		/// <param name="path">New path connectors</param>
		List<RoomPath> CreateConnectedRoomPiece(RoomPath path)
		{
			switch (path.Position)
			{
				case RoomPath.PathPosition.Top:
					{
						// Find another piece that has a top path and spawn it
						var piece = PiecesWithPaths(RoomPath.PathPosition.Bottom);
						if (piece.Count == 0)
						{
							break;
						}
						var index = Random.Range(0, piece.Count);
						var bounds = piece[index].GetBounds();
						var posDelta = (bounds.size.y / 2f) - 1f;
						var newPiece = Instantiate(piece[index],
							(path.transform.position + new Vector3(0f, posDelta, 0f)),
							Quaternion.identity);
						newPiece.transform.SetParent(transform);
						return newPiece.GetPaths().FindAll(
							pathEntry => pathEntry.Position != RoomPath.PathPosition.Bottom);
					}
				case RoomPath.PathPosition.Right:
					{
						// Find another piece that has a left path and spawn it
						var piece = PiecesWithPaths(RoomPath.PathPosition.Left);
						if (piece.Count == 0)
						{
							break;
						}
						var index = Random.Range(0, piece.Count);
						var bounds = piece[index].GetBounds();
						var posDelta = (bounds.size.x / 2f) - 1f;
						var newPiece = Instantiate(piece[index],
							(path.transform.position + new Vector3(posDelta, 0f, 0f)),
							Quaternion.identity);
						newPiece.transform.SetParent(transform);
						return newPiece.GetPaths().FindAll(
							pathEntry => pathEntry.Position != RoomPath.PathPosition.Left);
					}
				case RoomPath.PathPosition.Bottom:
					{
						// Find another piece that has a top path and spawn it
						var piece = PiecesWithPaths(RoomPath.PathPosition.Top);
						if (piece.Count == 0)
						{
							break;
						}
						var index = Random.Range(0, piece.Count);
						var bounds = piece[index].GetBounds();
						var posDelta = (bounds.size.y / 2f) + 1f;
						var newPiece = Instantiate(piece[index],
							(path.transform.position - new Vector3(0f, posDelta, 0f)),
							Quaternion.identity);
						newPiece.transform.SetParent(transform);
						return newPiece.GetPaths().FindAll(
							pathEntry => pathEntry.Position != RoomPath.PathPosition.Top);
					}
				case RoomPath.PathPosition.Left:
					{
						// Find another piece that has a right path and spawn it
						var piece = PiecesWithPaths(RoomPath.PathPosition.Right);
						if (piece.Count == 0)
						{
							break;
						}
						var index = Random.Range(0, piece.Count);
						var bounds = piece[index].GetBounds();
						var posDelta = (bounds.size.x / 2f) + 1f;
						var newPiece = Instantiate(piece[index],
							(path.transform.position - new Vector3(posDelta, 0f, 0f)),
							Quaternion.identity);
						newPiece.transform.SetParent(transform);
						return newPiece.GetPaths().FindAll(
							pathEntry => pathEntry.Position != RoomPath.PathPosition.Right);
					}
				case RoomPath.PathPosition.Ignored:
					// Ignored
					break;
				default:
					Debug.LogWarning("Invalid path position.");
					break;
			}

			// Return null if we weren't able to find or perform anything
			return null;
		}
	}
}


text:
package org.apache.poi.poifs.storage;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Random;

import junit.framework.TestCase;

import org.apache.poi.util.DummyPOILogger;

/**
 * Class to test RawDataBlock functionality
 *
 * @author Marc Johnson
 */
public final class TestRawDataBlock extends TestCase {
	static {
		// We always want to use our own
		//  logger
		System.setProperty(
				"org.apache.poi.util.POILogger",
				"org.apache.poi.util.DummyPOILogger"
		);
	}

	/**
	 * Test creating a normal RawDataBlock
	 */
	public void testNormalConstructor() throws IOException {
		byte[] data = new byte[ 512 ];

		for (int j = 0; j < 512; j++)
		{
			data[ j ] = ( byte ) j;
		}
		RawDataBlock block = new RawDataBlock(new ByteArrayInputStream(data));

		assertTrue("Should not be at EOF", !block.eof());
		byte[] out_data = block.getData();

		assertEquals("Should be same length", data.length, out_data.length);
		for (int j = 0; j < 512; j++)
		{
			assertEquals("Should be same value at offset " + j, data[ j ],
						 out_data[ j ]);
		}
	}

	/**
	 * Test creating an empty RawDataBlock
	 */
	public void testEmptyConstructor() throws IOException {
		byte[]	   data  = new byte[ 0 ];
		RawDataBlock block = new RawDataBlock(new ByteArrayInputStream(data));

		assertTrue("Should be at EOF", block.eof());
		try
		{
			block.getData();
		}
		catch (IOException ignored)
		{

			// as expected
		}
	}

	/**
	 * Test creating a short RawDataBlock
	 * Will trigger a warning, but no longer an IOException,
	 *  as people seem to have "valid" truncated files
	 */
	public void testShortConstructor() throws Exception {
		// Get the logger to be used
		DummyPOILogger logger = new DummyPOILogger();
		Field fld = RawDataBlock.class.getDeclaredField("log");
		fld.setAccessible(true);
		fld.set(null, logger);
		assertEquals(0, logger.logged.size());

		// Test for various data sizes
		for (int k = 1; k <= 512; k++)
		{
			byte[] data = new byte[ k ];

			for (int j = 0; j < k; j++)
			{
				data[ j ] = ( byte ) j;
			}
			RawDataBlock block = null;

			logger.reset();
			assertEquals(0, logger.logged.size());

			// Have it created
			block = new RawDataBlock(new ByteArrayInputStream(data));
			assertNotNull(block);

			// Check for the warning is there for <512
			if(k < 512) {
				assertEquals(
						"Warning on " + k + " byte short block",
						1, logger.logged.size()
				);

				// Build the expected warning message, and check
				String bts = k + " byte";
				if(k > 1) {
					bts += "s";
				}

				assertEquals(
						"7 - Unable to read entire block; "+bts+" read before EOF; expected 512 bytes. Your document was either written by software that ignores the spec, or has been truncated!",
						(String)(logger.logged.get(0))
				);
			} else {
				assertEquals(0, logger.logged.size());
			}
		}
	}

	/**
	 * Tests that when using a slow input stream, which
	 *  won't return a full block at a time, we don't
	 *  incorrectly think that there's not enough data
	 */
	public void testSlowInputStream() throws Exception {
		// Get the logger to be used
		DummyPOILogger logger = new DummyPOILogger();
		Field fld = RawDataBlock.class.getDeclaredField("log");
		fld.setAccessible(true);
		fld.set(null, logger);
		assertEquals(0, logger.logged.size());

		// Test for various ok data sizes
		for (int k = 1; k < 512; k++) {
			byte[] data = new byte[ 512 ];
			for (int j = 0; j < data.length; j++) {
				data[j] = (byte) j;
			}

			// Shouldn't complain, as there is enough data,
			//  even if it dribbles through
			RawDataBlock block =
				new RawDataBlock(new SlowInputStream(data, k));
			assertFalse(block.eof());
		}

		// But if there wasn't enough data available, will
		//  complain
		for (int k = 1; k < 512; k++) {
			byte[] data = new byte[ 511 ];
			for (int j = 0; j < data.length; j++) {
				data[j] = (byte) j;
			}

			logger.reset();
			assertEquals(0, logger.logged.size());

			// Should complain, as there isn't enough data
			RawDataBlock block =
				new RawDataBlock(new SlowInputStream(data, k));
			assertNotNull(block);
			assertEquals(
					"Warning on " + k + " byte short block",
					1, logger.logged.size()
			);
		}
	}

	/**
	 * An input stream which will return a maximum of
	 *  a given number of bytes to read, and often claims
	 *  not to have any data
	 */
	public static class SlowInputStream extends InputStream {
		private Random rnd = new Random();
		private byte[] data;
		private int chunkSize;
		private int pos = 0;

		public SlowInputStream(byte[] data, int chunkSize) {
			this.chunkSize = chunkSize;
			this.data = data;
		}

		/**
		 * 75% of the time, claim there's no data available
		 */
		private boolean claimNoData() {
			if(rnd.nextFloat() < 0.25f) {
				return false;
			}
			return true;
		}

		public int read() {
			if(pos >= data.length) {
				return -1;
			}
			int ret = data[pos];
			pos++;

			if(ret < 0) ret += 256;
			return ret;
		}

		/**
		 * Reads the requested number of bytes, or the chunk
		 *  size, whichever is lower.
		 * Quite often will simply claim to have no data
		 */
		public int read(byte[] b, int off, int len) {
			// Keep the length within the chunk size
			if(len > chunkSize) {
				len = chunkSize;
			}
			// Don't read off the end of the data
			if(pos + len > data.length) {
				len = data.length - pos;

				// Spot when we're out of data
				if(len == 0) {
					return -1;
				}
			}

			// 75% of the time, claim there's no data
			if(claimNoData()) {
				return 0;
			}

			// Copy, and return what we read
			System.arraycopy(data, pos, b, off, len);
			pos += len;
			return len;
		}

		public int read(byte[] b) {
			return read(b, 0, b.length);
		}
	}
}


text:
const CACHE_VERSION = 1;

const BASE_CACHE_FILES = [
  "/assets/main.css",
  "/assets/molokai.css",
  "/manifest.json",
  "/favicon.ico",
];

const OFFLINE_CACHE_FILES = [
  "/assets/main.css",
  "/assets/molokai.css",
  "/index.html",
];

const NOT_FOUND_CACHE_FILES = [
  "/assets/main.css",
  "/assets/molokai.css",
  "/404.html",
];

const OFFLINE_PAGE = "/index.html";
const NOT_FOUND_PAGE = "/404.html";

const CACHE_VERSIONS = {
  assets: "assets-v" + CACHE_VERSION,
  content: "content-v" + CACHE_VERSION,
  offline: "offline-v" + CACHE_VERSION,
  notFound: "404-v" + CACHE_VERSION,
};

// Define MAX_TTL's in SECONDS for specific file extensions
const MAX_TTL = {
  "/": 3600,
  html: 3600,
  json: 86400,
  js: 86400,
  css: 86400,
};

const CACHE_BLACKLIST = [
  //(str) => {
  //    return !str.startsWith('http://localhost') && !str.startsWith('https://gohugohq.com');
  //},
];

const SUPPORTED_METHODS = ["GET"];

/**
 * isBlackListed
 * @param {string} url
 * @returns {boolean}
 */
function isBlacklisted(url) {
  return CACHE_BLACKLIST.length > 0
    ? !CACHE_BLACKLIST.filter((rule) => {
        if (typeof rule === "function") {
          return !rule(url);
        } else {
          return false;
        }
      }).length
    : false;
}

/**
 * getFileExtension
 * @param {string} url
 * @returns {string}
 */
function getFileExtension(url) {
  let extension = url.split(".").reverse()[0].split("?")[0];
  return extension.endsWith("/") ? "/" : extension;
}

/**
 * getTTL
 * @param {string} url
 */
function getTTL(url) {
  if (typeof url === "string") {
    let extension = getFileExtension(url);
    if (typeof MAX_TTL[extension] === "number") {
      return MAX_TTL[extension];
    } else {
      return null;
    }
  } else {
    return null;
  }
}

/**
 * installServiceWorker
 * @returns {Promise}
 */
function installServiceWorker() {
  return Promise.all([
    caches.open(CACHE_VERSIONS.assets).then((cache) => {
      return cache.addAll(BASE_CACHE_FILES);
    }),
    caches.open(CACHE_VERSIONS.offline).then((cache) => {
      return cache.addAll(OFFLINE_CACHE_FILES);
    }),
    caches.open(CACHE_VERSIONS.notFound).then((cache) => {
      return cache.addAll(NOT_FOUND_CACHE_FILES);
    }),
  ]).then(() => {
    return self.skipWaiting();
  });
}

/**
 * cleanupLegacyCache
 * @returns {Promise}
 */
function cleanupLegacyCache() {
  let currentCaches = Object.keys(CACHE_VERSIONS).map((key) => {
    return CACHE_VERSIONS[key];
  });

  return new Promise((resolve, reject) => {
    caches
      .keys()
      .then((keys) => {
        return (legacyKeys = keys.filter((key) => {
          return !~currentCaches.indexOf(key);
        }));
      })
      .then((legacy) => {
        if (legacy.length) {
          Promise.all(
            legacy.map((legacyKey) => {
              return caches.delete(legacyKey);
            })
          )
            .then(() => {
              resolve();
            })
            .catch((err) => {
              reject(err);
            });
        } else {
          resolve();
        }
      })
      .catch(() => {
        reject();
      });
  });
}

function precacheUrl(url) {
  if (!isBlacklisted(url)) {
    caches.open(CACHE_VERSIONS.content).then((cache) => {
      cache
        .match(url)
        .then((response) => {
          if (!response) {
            return fetch(url);
          } else {
            // already in cache, nothing to do.
            return null;
          }
        })
        .then((response) => {
          if (response) {
            return cache.put(url, response.clone());
          } else {
            return null;
          }
        });
    });
  }
}

self.addEventListener("install", (event) => {
  event.waitUntil(Promise.all([installServiceWorker(), self.skipWaiting()]));
});

// The activate handler takes care of cleaning up old caches.
self.addEventListener("activate", (event) => {
  event.waitUntil(
    Promise.all([
      cleanupLegacyCache(),
      self.clients.claim(),
      self.skipWaiting(),
    ]).catch((err) => {
      event.skipWaiting();
    })
  );
});

self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.open(CACHE_VERSIONS.content).then((cache) => {
      return cache
        .match(event.request)
        .then((response) => {
          if (response) {
            let headers = response.headers.entries();
            let date = null;

            for (let pair of headers) {
              if (pair[0] === "date") {
                date = new Date(pair[1]);
              }
            }

            if (date) {
              let age = parseInt(
                (new Date().getTime() - date.getTime()) / 1000
              );
              let ttl = getTTL(event.request.url);

              if (ttl && age > ttl) {
                return new Promise((resolve) => {
                  return fetch(event.request.clone())
                    .then((updatedResponse) => {
                      if (updatedResponse) {
                        cache.put(event.request, updatedResponse.clone());
                        resolve(updatedResponse);
                      } else {
                        resolve(response);
                      }
                    })
                    .catch(() => {
                      resolve(response);
                    });
                }).catch((err) => {
                  return response;
                });
              } else {
                return response;
              }
            } else {
              return response;
            }
          } else {
            return null;
          }
        })
        .then((response) => {
          if (response) {
            return response;
          } else {
            return fetch(event.request.clone())
              .then((response) => {
                if (response.status < 400) {
                  if (
                    ~SUPPORTED_METHODS.indexOf(event.request.method) &&
                    !isBlacklisted(event.request.url)
                  ) {
                    cache.put(event.request, response.clone());
                  }
                  return response;
                } else {
                  return caches.open(CACHE_VERSIONS.notFound).then((cache) => {
                    return cache.match(NOT_FOUND_PAGE);
                  });
                }
              })
              .then((response) => {
                if (response) {
                  return response;
                }
              })
              .catch(() => {
                return caches
                  .open(CACHE_VERSIONS.offline)
                  .then((offlineCache) => {
                    return offlineCache.match(OFFLINE_PAGE);
                  });
              });
          }
        })
        .catch((error) => {
          console.error("  Error in fetch handler:", error);
          throw error;
        });
    })
  );
});

self.addEventListener("message", (event) => {
  if (typeof event.data === "object" && typeof event.data.action === "string") {
    switch (event.data.action) {
      case "cache":
        precacheUrl(event.data.url);
        break;
      default:
        console.log("Unknown action: " + event.data.action);
        break;
    }
  }
});


text:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  helper_method :current_user

  def sat_through_wed
    Time.now.saturday? || Time.now.sunday? || Time.now.monday? || Time.now.tuesday? || Time.now.wednesday?
  end
  helper_method :sat_through_wed

  def thurs_through_sat
    Time.now.thursday? || Time.now.friday? || Time.now.saturday?
  end
  helper_method :thurs_through_sat

  def authorize
    redirect_to '/login' unless current_user
  end
end


text:
package com.thoughtworks.go.server.service;

import com.thoughtworks.go.config.ConfigTag;
import com.thoughtworks.go.config.PluginProfile;
import com.thoughtworks.go.config.PluginProfiles;
import com.thoughtworks.go.config.commands.EntityConfigUpdateCommand;
import com.thoughtworks.go.config.exceptions.GoConfigInvalidException;
import com.thoughtworks.go.i18n.LocalizedMessage;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.service.result.LocalizedOperationResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedHashMap;
import java.util.Map;

public abstract class PluginProfilesService<M extends PluginProfile> {
    protected final GoConfigService goConfigService;
    protected final EntityHashingService hashingService;
    protected Logger LOGGER = LoggerFactory.getLogger(getClass());

    public PluginProfilesService(GoConfigService goConfigService, EntityHashingService hashingService) {
        this.goConfigService = goConfigService;
        this.hashingService = hashingService;
    }

    protected abstract PluginProfiles<M> getPluginProfiles();

    public M findProfile(String id) {
        return getPluginProfiles().find(id);
    }

    public Map<String, M> listAll() {
        Map<String, M> result = new LinkedHashMap<>();
        for (M profile : getPluginProfiles()) {
            result.put(profile.getId(), profile);
        }
        return result;
    }

    protected void update(Username currentUser, M pluginProfile, LocalizedOperationResult result, EntityConfigUpdateCommand<M> command) {
        try {
            goConfigService.updateConfig(command, currentUser);
        } catch (Exception e) {
            if (e instanceof GoConfigInvalidException) {
                result.unprocessableEntity(LocalizedMessage.string("ENTITY_CONFIG_VALIDATION_FAILED", pluginProfile.getClass().getAnnotation(ConfigTag.class).value(), pluginProfile.getId(), e.getMessage()));
            } else {
                if (!result.hasMessage()) {
                    LOGGER.error(e.getMessage(), e);
                    result.internalServerError(LocalizedMessage.string("SAVE_FAILED_WITH_REASON", "An error occurred while saving the profile config. Please check the logs for more information."));
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// 80/100
/// </summary>
namespace _04._Roli_The_Coder
{
    class RoliTheCoder
    {
        static void Main()
        {
            string input = string.Empty;
            Dictionary<int, HashSet<string>> eventsParticipants = new Dictionary<int, HashSet<string>>();
            Dictionary<int, string> eventsName = new Dictionary<int, string>();

            while ((input = Console.ReadLine()) != "Time for Code")
            {
                string[] args = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                if (args.Length < 2)
                {
                    continue;
                }

                int id = 0; //possible exeption if it's not a num!
                if (!int.TryParse(args[0], out id))
                {
                    continue;
                }
                string name = args[1];//event name
                if (!name.StartsWith("#"))
                {
                    //validate event name.
                    continue;
                }
                name=name.Trim('#');

                //validating participants.
                bool IsValid = true;

                if (args.Length > 2)
                {

                    for (int i = 2; i < args.Length; i++)
                    {
                        //validating participants
                        if (!args[i].StartsWith("@"))
                        {
                            IsValid = false;
                            break;
                        }
                    }

                    if (!IsValid)
                    {
                        continue;
                    }
                }

                if (eventsName.ContainsKey(id))
                {
                    var existName = eventsName[id];
                    if (existName == name)
                    {
                        for (int i = 2; i < args.Length; i++)
                        {
                            //if all are valid.
                            eventsParticipants[id].Add(args[i]);
                        }
                    }
                }
                else
                {
                    eventsName[id] = name.Trim('#');
                    eventsParticipants[id] = new HashSet<string>();

                    for (int i = 2; i < args.Length; i++)
                    {
                        //if all are valid.
                        eventsParticipants[id].Add(args[i]);
                    }
                }
            }

            //Possible mistake with the order....
            foreach (var ev in eventsParticipants.OrderByDescending(x=>x.Value.Count))
            {
                Console.WriteLine($"{eventsName[ev.Key]} - {ev.Value.Count()}");
                foreach (var ppl in ev.Value.OrderBy(x=>x))
                {
                    Console.WriteLine(ppl);
                }
            }
        }

    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('songwriter', '0006_auto_20170902_0723'),
    ]

    operations = [
        migrations.AlterField(
            model_name='song',
            name='author',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='songwriter.Author'),
        ),
        migrations.AlterField(
            model_name='song',
            name='comments',
            field=models.TextField(blank=True, verbose_name='Comments'),
        ),
        migrations.AlterField(
            model_name='song',
            name='editor',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='songwriter.Editor'),
        ),
    ]


text:
// Copyright (c) Umbraco.
// See LICENSE for more details.

using NUnit.Framework;
using Umbraco.Cms.Infrastructure.Persistence.Mappers;
using Umbraco.Cms.Tests.UnitTests.TestHelpers;

namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.Persistence.Mappers
{
    [TestFixture]
    public class DictionaryTranslationMapperTest
    {
        [Test]
        public void Can_Map_Key_Property()
        {
            // Act
            string column = new DictionaryTranslationMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Key");

            // Assert
            Assert.That(column, Is.EqualTo("[cmsLanguageText].[UniqueId]"));
        }

        [Test]
        public void Can_Map_Language_Property()
        {
            // Act
            string column = new DictionaryTranslationMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Language");

            // Assert
            Assert.That(column, Is.EqualTo("[cmsLanguageText].[languageId]"));
        }

        [Test]
        public void Can_Map_Value_Property()
        {
            // Act
            string column = new DictionaryTranslationMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Value");

            // Assert
            Assert.That(column, Is.EqualTo("[cmsLanguageText].[value]"));
        }
    }
}


text:
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.AmazonSimpleDBClient;
import com.amazonaws.services.simpledb.model.DomainMetadataRequest;
import com.amazonaws.services.simpledb.model.DomainMetadataResult;
import com.amazonaws.services.simpledb.model.ListDomainsRequest;
import com.amazonaws.services.simpledb.model.ListDomainsResult;

/**
 * Welcome to your new AWS Java SDK based project!
 *
 * This class is meant as a starting point for your console-based application that
 * makes one or more calls to the AWS services supported by the Java SDK, such as EC2,
 * SimpleDB, and S3.
 *
 * In order to use the services in this sample, you need:
 *
 *  - A valid Amazon Web Services account. You can register for AWS at:
 *       https://aws-portal.amazon.com/gp/aws/developer/registration/index.html
 *
 *  - Your account's Access Key ID and Secret Access Key:
 *       http://aws.amazon.com/security-credentials
 *
 *  - A subscription to Amazon EC2. You can sign up for EC2 at:
 *       http://aws.amazon.com/ec2/
 *
 *  - A subscription to Amazon SimpleDB. You can sign up for Simple DB at:
 *       http://aws.amazon.com/simpledb/
 *
 *  - A subscription to Amazon S3. You can sign up for S3 at:
 *       http://aws.amazon.com/s3/
 */
public class AwsConsoleApp {

    /*
     * Important: Be sure to fill in your AWS access credentials in the
     *            AwsCredentials.properties file before you try to run this
     *            sample.
     * http://aws.amazon.com/security-credentials
     */

    static AmazonEC2      ec2;
    static AmazonS3       s3;
    static AmazonSimpleDB sdb;

    /**
     * The only information needed to create a client are security credentials
     * consisting of the AWS Access Key ID and Secret Access Key. All other
     * configuration, such as the service endpoints, are performed
     * automatically. Client parameters, such as proxies, can be specified in an
     * optional ClientConfiguration object when constructing a client.
     *
     * @see com.amazonaws.auth.BasicAWSCredentials
     * @see com.amazonaws.auth.PropertiesCredentials
     * @see com.amazonaws.ClientConfiguration
     */
    private static void init() throws Exception {
        AWSCredentials credentials = new PropertiesCredentials(
                AwsConsoleApp.class.getResourceAsStream("AwsCredentials.properties"));

        ec2 = new AmazonEC2Client(credentials);
        s3  = new AmazonS3Client(credentials);
        sdb = new AmazonSimpleDBClient(credentials);
    }

    public static void main(String[] args) throws Exception {

        System.out.println("===========================================");
        System.out.println("Welcome to the AWS Java SDK!");
        System.out.println("===========================================");

        init();

        /*
         * Amazon EC2
         *
         * The AWS EC2 client allows you to create, delete, and administer
         * instances programmatically.
         *
         * In this sample, we use an EC2 client to get a list of all the
         * availability zones, and all instances sorted by reservation id.
         */
        try {
            DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
            System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() +
                    " Availability Zones.");

            DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
            List<Reservation> reservations = describeInstancesRequest.getReservations();
            Set<Instance> instances = new HashSet<Instance>();

            for (Reservation reservation : reservations) {
                instances.addAll(reservation.getInstances());
            }

            System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
        } catch (AmazonServiceException ase) {
                System.out.println("Caught Exception: " + ase.getMessage());
                System.out.println("Reponse Status Code: " + ase.getStatusCode());
                System.out.println("Error Code: " + ase.getErrorCode());
                System.out.println("Request ID: " + ase.getRequestId());
        }

        /*
         * Amazon SimpleDB
         *
         * The AWS SimpleDB client allows you to query and manage your data
         * stored in SimpleDB domains (similar to tables in a relational DB).
         *
         * In this sample, we use a SimpleDB client to iterate over all the
         * domains owned by the current user, and add up the number of items
         * (similar to rows of data in a relational DB) in each domain.
         */
        try {
            ListDomainsRequest sdbRequest = new ListDomainsRequest().withMaxNumberOfDomains(100);
            ListDomainsResult sdbResult = sdb.listDomains(sdbRequest);

            int totalItems = 0;
            for (String domainName : sdbResult.getDomainNames()) {
                DomainMetadataRequest metadataRequest = new DomainMetadataRequest().withDomainName(domainName);
                DomainMetadataResult domainMetadata = sdb.domainMetadata(metadataRequest);
                totalItems += domainMetadata.getItemCount();
            }

            System.out.println("You have " + sdbResult.getDomainNames().size() + " Amazon SimpleDB domain(s)" +
                    "containing a total of " + totalItems + " items.");
        } catch (AmazonServiceException ase) {
                System.out.println("Caught Exception: " + ase.getMessage());
                System.out.println("Reponse Status Code: " + ase.getStatusCode());
                System.out.println("Error Code: " + ase.getErrorCode());
                System.out.println("Request ID: " + ase.getRequestId());
        }

        /*
         * Amazon S3
         *
         * The AWS S3 client allows you to manage buckets and programmatically
         * put and get objects to those buckets.
         *
         * In this sample, we use an S3 client to iterate over all the buckets
         * owned by the current user, and all the object metadata in each
         * bucket, to obtain a total object and space usage count. This is done
         * without ever actually downloading a single object -- the requests
         * work with object metadata only.
         */
        try {
            List<Bucket> buckets = s3.listBuckets();

            long totalSize  = 0;
            int  totalItems = 0;
            for (Bucket bucket : buckets) {
                /*
                 * In order to save bandwidth, an S3 object listing does not
                 * contain every object in the bucket; after a certain point the
                 * S3ObjectListing is truncated, and further pages must be
                 * obtained with the AmazonS3Client.listNextBatchOfObjects()
                 * method.
                 */
                ObjectListing objects = s3.listObjects(bucket.getName());
                do {
                    for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                        totalSize += objectSummary.getSize();
                        totalItems++;
                    }
                    objects = s3.listNextBatchOfObjects(objects);
                } while (objects.isTruncated());
            }

            System.out.println("You have " + buckets.size() + " Amazon S3 bucket(s), " +
                    "containing " + totalItems + " objects with a total size of " + totalSize + " bytes.");
        } catch (AmazonServiceException ase) {
            /*
             * AmazonServiceExceptions represent an error response from an AWS
             * services, i.e. your request made it to AWS, but the AWS service
             * either found it invalid or encountered an error trying to execute
             * it.
             */
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            /*
             * AmazonClientExceptions represent an error that occurred inside
             * the client on the local host, either while trying to send the
             * request to AWS or interpret the response. For example, if no
             * network connection is available, the client won't be able to
             * connect to AWS to execute a request and will throw an
             * AmazonClientException.
             */
            System.out.println("Error Message: " + ace.getMessage());
        }
    }
}


text:
package org.apache.olingo.odata2.janos.processor.core.data.source;

import org.apache.olingo.odata2.api.annotation.edm.EdmFunctionImport;
import org.apache.olingo.odata2.api.annotation.edm.EdmFunctionImportParameter;
import org.apache.olingo.odata2.api.edm.EdmException;
import org.apache.olingo.odata2.api.exception.ODataApplicationException;
import org.apache.olingo.odata2.api.exception.ODataNotFoundException;
import org.apache.olingo.odata2.api.exception.ODataNotImplementedException;
import org.apache.olingo.odata2.janos.processor.api.data.source.FunctionExecutor;
import org.apache.olingo.odata2.janos.processor.api.data.source.FunctionSource;
import org.apache.olingo.odata2.janos.processor.api.data.store.DataStoreManager;
import org.apache.olingo.odata2.janos.processor.core.util.AnnotationHelper;
import org.apache.olingo.odata2.janos.processor.core.util.AnnotationRuntimeException;
import org.apache.olingo.odata2.janos.processor.core.util.ClassHelper;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

/**
 */
public class AnnotationFunctionSource implements FunctionSource {

  private AnnotationHelper annotationHelper = new AnnotationHelper();
  private Map<String, FunctionHolder> functionHolders = new HashMap<>();
  private DataStoreManager dataStoreManager;

  private AnnotationFunctionSource() { /* private ctor because of builder */ }

  private void init(Collection<Class<?>> annotatedClasses) {
    for (Class<?> annotatedClass : annotatedClasses) {
      List<Method> methods = annotationHelper.getAnnotatedMethods(annotatedClass, EdmFunctionImport.class, false);

      for (Method method : methods) {
        initFunctionHolder(annotatedClass, method);
      }
    }
  }

  private void initFunctionHolder(Class<?> annotatedClass, Method method) {
    try {
      EdmFunctionImport efi = method.getAnnotation(EdmFunctionImport.class);
      String name = efi.name();
      if(name.isEmpty()) {
        name = method.getName();
      }

      LinkedHashMap<String, EdmFunctionImportParameter> parameters = extractParameters(method.getParameters());

      FunctionHolder holder = new FunctionHolder();
      holder.method = method;
      holder.executor = annotatedClass.newInstance();
      holder.functionImport = efi;
      holder.functionParameters = parameters;
      //
      callInitMethods(holder.executor);

      functionHolders.put(name, holder);
    } catch (InstantiationException | IllegalAccessException e) {
      e.printStackTrace();
    }

  }

  private void callInitMethods(Object functionInstance) {
    if(functionInstance instanceof FunctionExecutor) {
      ((FunctionExecutor) functionInstance).init(dataStoreManager);
    }
  }

  private LinkedHashMap<String, EdmFunctionImportParameter> extractParameters(Parameter[] parameters) {
    LinkedHashMap<String, EdmFunctionImportParameter> result = new LinkedHashMap<>();
    for (Parameter parameter : parameters) {
      EdmFunctionImportParameter efip = parameter.getAnnotation(EdmFunctionImportParameter.class);
      result.put(efip.name(), efip);
    }
    return result;
  }

//  @Override
//  public FunctionExecutor getFunctionExecutor(String functionName) {
//    FunctionHolder holder = functionHolders.get(functionName);
//    if(holder == null) {
//      return null;
//    }
//    return holder.executor;
//  }

  @Override
  public Object executeFunction(org.apache.olingo.odata2.api.edm.EdmFunctionImport function,
                                Map<String, Object> parameters, Map<String, Object> keys)
      throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {

    return executeFunction(function.getName(), parameters);
  }

  public Object executeFunction(String functionName, Map<String, Object> parameters) {
    FunctionHolder holder = functionHolders.get(functionName);
    if(holder != null) {
      Object[] exParameters = mapParameters(holder, parameters);
      return holder.execute(exParameters);
    }
    return null;
  }

  private Object[] mapParameters(FunctionHolder holder, Map<String, Object> parameters) {
    List<Object> resParameters = new ArrayList<>();
    for (Map.Entry<String, EdmFunctionImportParameter> s : holder.functionParameters.entrySet()) {
      Object paraInstance = parameters.get(s.getKey());
      resParameters.add(paraInstance);
    }

    return resParameters.toArray(new Object[resParameters.size()]);
  }

  static class FunctionHolder {
    Object executor;
    Method method;
    EdmFunctionImport functionImport;
    LinkedHashMap<String, EdmFunctionImportParameter> functionParameters;

    public Object execute(Object... parameters) {
      try {
        return method.invoke(executor, parameters);
      } catch (IllegalAccessException | InvocationTargetException e) {
        throw new AnnotationRuntimeException("Exception in methods access.", e);
      }
    }
  }

  /*
   * Builder below
   */

  public static AnnotationFunctionSourceBuilder with(Collection<Class<?>> annotatedClasses) {
    return new AnnotationFunctionSourceBuilder(annotatedClasses);
  }

  public static AnnotationFunctionSourceBuilder with(final String packageToScan) {
    return new AnnotationFunctionSourceBuilder(packageToScan);
  }

  public static class AnnotationFunctionSourceBuilder {
    private final String packageToScan;
    private final Collection<Class<?>> annotatedClasses;

    private AnnotationFunctionSource afs = new AnnotationFunctionSource();

    public AnnotationFunctionSourceBuilder(Collection<Class<?>> annotatedClasses) {
      this(null, annotatedClasses);
    }

    public AnnotationFunctionSourceBuilder(String packageToScan) {
      this(packageToScan, null);
    }

    private AnnotationFunctionSourceBuilder(String packageToScan, Collection<Class<?>> annotatedClasses) {
      this.packageToScan = packageToScan;
      this.annotatedClasses = annotatedClasses;
    }

    public AnnotationFunctionSourceBuilder with(AnnotationHelper helper) {
      afs.annotationHelper = helper;
      return this;
    }

    public AnnotationFunctionSourceBuilder with(DataStoreManager dataStoreManager) {
      afs.dataStoreManager = dataStoreManager;
      return this;
    }

    public AnnotationFunctionSource build() {
      if(annotatedClasses != null) {
        afs.init(annotatedClasses);
      } else if(packageToScan != null) {
        List<Class<?>> foundClasses = ClassHelper.loadClasses(packageToScan,
            afs.annotationHelper::hasEdmFunction);

        afs.init(foundClasses);
      } else {
        throw new IllegalArgumentException("No annotated classes defined in builder.");
      }
      return afs;
    }
  }
}


text: set SWAK_HOME=C:\Users\Administrator\works\swak\devhome


text:
function openintab(url) {
    var togo = window.location.protocol + "//" + window.location.host + "/designer/editor?uuid=" + url + "&profile=jbpm&pp=";
    window.open(togo, '_blank');
}


text:
class UpdateConfigColumns < ActiveRecord::Migration[5.1]
  safety_assured
  def change
    # arduino_debug_messages
    add_column    :fbos_configs, :api_migrated,           :boolean, default: false
    remove_column :fbos_configs, :os_auto_update,         :number,  default: 0
    add_column    :fbos_configs, :os_auto_update,         :boolean, default: false
    remove_column :fbos_configs, :arduino_debug_messages, :number, default: 0
    add_column    :fbos_configs, :arduino_debug_messages, :boolean, default: false
  end
end


text:
using System;
using System.Net.NetworkInformation;

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

using AppStudio.Services;
using AppStudio.ViewModels;

namespace AppStudio.Views
{
    public sealed partial class GoProTipsPage : Page
    {
        private NavigationHelper _navigationHelper;

        public GoProTipsPage()
        {
            this.InitializeComponent();
            _navigationHelper = new NavigationHelper(this);
            GoProTipsModel = new GoProTipsViewModel();

            SizeChanged += OnSizeChanged;
        }

        public GoProTipsViewModel GoProTipsModel { get; private set; }

        public NavigationHelper NavigationHelper
        {
            get { return _navigationHelper; }
        }

        private void OnSizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (e.NewSize.Width < 500)
            {
                VisualStateManager.GoToState(this, "SnappedView", true);
            }
            else
            {
                VisualStateManager.GoToState(this, "FullscreenView", true);
            }
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            _navigationHelper.OnNavigatedTo(e);
            NavigationServices.CurrentViewModel = null;
            await GoProTipsModel.LoadItems(NetworkInterface.GetIsNetworkAvailable());
            DataContext = this;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            _navigationHelper.OnNavigatedFrom(e);
        }
    }
}


text: Simpleapp::Application.config.session_store :cookie_store, key: '_simpleapp_session'


text:
package delete

import (
	"fmt"

	"github.com/Telmate/proxmox-api-go/cli"
	"github.com/spf13/cobra"
)

var deleteCmd = &cobra.Command{
	Use:   "delete",
	Short: "With this command you can delete existing items from proxmox",
}

func init() {
	cli.RootCmd.AddCommand(deleteCmd)
}

func deleteID(args []string, IDtype string) (err error) {
	var exitStatus string
	id := cli.RequiredIDset(args, 0, IDtype+"ID")
	c := cli.NewClient()
	switch IDtype {
	case "AcmeAccount":
		exitStatus, err = c.DeleteAcmeAccount(id)
	case "MetricServer":
		err = c.DeleteMetricServer(id)
	case "Pool":
		err = c.DeletePool(id)
	case "Storage":
		err = c.DeleteStorage(id)
	case "User":
		err = c.DeleteUser(id)
	}
	if err != nil {
		if exitStatus != "" {
			err = fmt.Errorf("error deleting %s (%s): %v, error status: %s ", IDtype, id, err, exitStatus)
		}
		return
	}
	cli.PrintItemDeleted(deleteCmd.OutOrStdout(), id, IDtype)
	return
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Asterinema glabratae var. roupalae Bat. & M.L. Farr

### Remarks
null


text:
package org.literacybridge.dashboard.processors;

import org.literacybridge.dashboard.aggregation.AggregationOf;
import org.literacybridge.dashboard.aggregation.StatAggregator;
import org.literacybridge.stats.formats.logFile.LogLineContext;

/**
 * Creates aggregations similiar to the ones found in the flashdata.bin files from the logs.
 *
 * This aggregates content + survey information.
 *
 * For the content, the main metric is a histogram of how long the content was played for.  It is broken into:
 *

 *
Played for more than 10 seconds

 *
Played for more than 1/4 of the total length

 *
Played for more than 1/2 of the total length

 *
Played for more than 3/4 of the total length

 *
Played to completion

 *

 *
 *    It is important to note that this is a histogram, NOT an aggregation.  So a content play that goes for 1/2 of the
 *    length, will NOT register as a 1/4 play in addition to a 1/2 play.
 */
public class LogAggregationProcessor extends AbstractLogProcessor {

  final public StatAggregator aggregator = new StatAggregator();

  // Play times of less than this are considered to be just flipping through the messages, not an
  // actual playback.
  static final int minSecondsPlayedToConsiderPlaying = 10;
  // Playing within this much of the end is considered finishing the message.
  static final int maxSecondsRemainingToConsiderFinished = 2;

  public LogAggregationProcessor() {
  }

  public void clear() {
    aggregator.clear();
  }

  @Override
  public void onPlayed(LogLineContext context, String contentId, short secondsPlayed, short secondsSomething,
                       int volume, double voltage, boolean ended) {

    //There are a number of aggregations, and unfortunately different stats from both stats files (which log 10 second plays)
    //and FlashData files, which have it set up in quarter play, half play, three quarters play, etc.

    // FlashData stats are FIRST match of:
    // finished: position > total_length - 2000 (milliseconds)
    // 3/4:      position > .75 * total_length
    // 1/2:      position > total_length / 2
    // 1/4:      position > total_length / 4
    // started:  position >= 10 seconds
    // else no stat recorded
    //
    // applied:  count of # times user indicated they would apply a message
    // useless:  count of # times user indicated a message is useless
    // totalSeconds: cumulative # seconds message was played (in each rotation), to a max of 65,535 seconds
    //                 (per TB, so up to 18 hours per tb (per rotation) is recorded).

    // Stats files are ALL of:
    // finished: position all bytes in file
    // started:  position > 10 seconds

    // Log stats record the elapsed time playing less any time spent paused.
    // Log stats log '-Ended' if playback ended by itself (ie, ran out of bytes to play).

    // Log stats do NOT account for skipping forward or backward, nor do they account for playing faster
    // or slower.

    // Not only are the stats apples, oranges, and peaches, but none of them are reliable,
    // so it is not even possible to prefer one over another as "more accurate".

    double fractionPlayed = ((double)secondsPlayed)/((double)secondsSomething);
    boolean nearlyFinished = (secondsSomething - secondsPlayed) <= maxSecondsRemainingToConsiderFinished;
    if (ended || nearlyFinished) {
      aggregator.add(context.context.deploymentId, AggregationOf.finishedPlays, contentId, context.context.village,
                     context.context.talkingBookId, 1);
    } else if (fractionPlayed >= .75) {
      aggregator.add(context.context.deploymentId, AggregationOf.threeQuartersPlays, contentId, context.context.village,
                     context.context.talkingBookId, 1);
    } else if (fractionPlayed >= .50) {
      aggregator.add(context.context.deploymentId, AggregationOf.halfPlays, contentId, context.context.village,
                     context.context.talkingBookId, 1);
    } else if (fractionPlayed >= .25) {
      aggregator.add(context.context.deploymentId, AggregationOf.quarterPlays, contentId, context.context.village,
                     context.context.talkingBookId, 1);
    } else if (secondsPlayed >= minSecondsPlayedToConsiderPlaying) {
      aggregator.add(context.context.deploymentId, AggregationOf.tenSecondPlays, contentId, context.context.village,
                     context.context.talkingBookId, 1);
    }

    if (secondsPlayed >= minSecondsPlayedToConsiderPlaying) {
      aggregator.add(context.context.deploymentId, AggregationOf.totalTimePlayed, contentId, context.context.village,
                     context.context.talkingBookId, secondsPlayed);
    }
  }

  @Override
  public void onSurvey(LogLineContext context, String contentId) {
    aggregator.add(context.context.deploymentId, AggregationOf.surveyTaken, contentId, context.context.village,
                   context.context.talkingBookId, 1);
  }

  @Override
  public void onSurveyCompleted(LogLineContext context, String contentId, boolean useful) {

    if (useful) {
      aggregator.add(context.context.deploymentId, AggregationOf.surveyApplied, contentId, context.context.village,
                     context.context.talkingBookId, 1);
    } else {
      aggregator.add(context.context.deploymentId, AggregationOf.surveyUseless, contentId, context.context.village,
                     context.context.talkingBookId, 1);
    }
  }

}


text:
function initTextlinkWrite() {
  callClick("dateless", function() {
    $E("publish_end").disabled = this.checked ? true : false;
  });
  var _stylesChanged = function() {
    $E("template").disabled = this.value != "custom";
    send(
      "index.php/Widgets/Textlink/Models/Action/get",
      "action=styles&val=" + this.value + "&id=" + $E("id").value,
      function(xhr) {
        $E("template").value = xhr.responseText;
        doTextlinkDemo();
      },
      $E("prefix")
    );
  };
  var doTextlinkDemo = function() {
    var v = $E("name").value;
    $E("name_demo").innerHTML =
      "{WIDGET_TEXTLINK" + (v == "" ? "" : "_" + v) + "}";
  };
  $G("name").addEvent("keyup", doTextlinkDemo);
  $G("name").addEvent("change", doTextlinkDemo);
  $G("type").addEvent("change", _stylesChanged);
  _stylesChanged.call($E("type"));
}


text:
using RtmpSharp.IO;
using System;

namespace PoroLib.Structures
{
    [Serializable]
    [SerializedName("com.riotgames.platform.summoner.masterybook.TalentEntry")]
    public class TalentEntry
    {
        [SerializedName("rank")]
        public Int32 Rank { get; set; }
        [SerializedName("talentId")]
        public Int32 TalentId { get; set; }
        [SerializedName("talent")]
        public Talent Talent { get; set; }
        [SerializedName("summonerId")]
        public Double SummonerId { get; set; }
    }
}


text:
module.exports.command = "startup";
module.exports.run = function(remainder, parts, reply, command, from, to, text, raw) {

  var services = [
    'Pandora', 'Foursquare', 'Facebook', 'Netflix', 'Gmail', 'LinkedIn', 'NASA',
    'Eclipse', 'Spotify', 'Paypal', 'Twitter', 'AI', 'SB', 'GitHub', 'Google Glass',
    'Maps', 'Quora', 'Groupon', 'RSS', 'Redis', 'MapReduce', 'the iPhone',
    'Weedmaps', 'SnapChat', 'drones', 'WordPress', 'Napster', 'Tumblr', 'AirBnB',
    'cloud storage', 'a jQuery plugin', 'Reddit', 'Cash4Gold', 'Flickr', 'dongs',
    'Wikipedia', 'eHarmony', 'Amazon', 'Adult Friend Finder', 'EC2', 'S3',
    '4chan', 'Blogger', 'Pinterest', 'the PS3', 'the XBOX', 'Craigslist', 'XHamster',
    'CNN', 'a new programming language', 'a webbrowser', 'ads', 'The Pirate Bay', 'Ebay',
    'Deviant Art', 'mail order bombs', 'crowdsourced retirement funding', 'Siri',
    'a personal assistant', 'robot replacements', 'fingerboxes', 'concealed weaponry',
    'an iPhone app', 'complaint management', 'easy blogging', 'a pyramid scheme', 'fleshlights',
    'Farmlogs', 'Red Nova Labs', 'Threat Stack', 'graduate school', 'suscd\'s birthday',
    'Google Keep', 'Hangouts', 'Oculus Rift', 'virtual reality', 'VR', 'augmented reality', 'AR',
    '2 monitors', '5 monitors', 'UPS', 'FedEx', 'the USPS', 'Docker', 'Go', 'Lisp', 'Slack'
  ];
  var markets = [
    'finance', 'music', 'movies', 'pictures', 'gifs', 'pirated content', 'education',
    'hairstyling', 'red wine', 'literature', 'adult dancers', 'food', 'math',
    'hard engineering problems', 'botany', 'drugs', 'network administration',
    'shopping', 'cougars', 'MILFs', 'good looking people', 'the army', 'interns',
    'whiskey', 'retirement planning', 'beer', 'traveling', 'funerals', 'dongs',
    'presentations', 'online food delivery', 'the homeless', 'managing exes',
    'small businesses', 'coffee', 'textbooks', 'politics', 'your mom', 'slacklining',
    'gay people', 'cats', 'dogs', 'Germans', 'Christians', 'Athiests',
    'redditors', 'guns', 'ladies', 'men', 'programmers', 'ninjas', 'pirates',
    'criminals', 'prisoners', 'autists', 'artists', 'emo teens', 'babies',
    'republicans', 'people like ek', 'Amazon employees', 'B movies', 'pornstars',
    'hipsters', 'barbarians', 'native americans', 'hackers', 'retired strippers',
    'people like reed', 'snipers', 'devoted Christians', 'atheists', 'cats',
    'the unemployed', 'the 1%', 'business purposes', 'amputees', 'panda lovers',
    'recipes', 'writers', 'dogs', 'birds', 'anime', 'the POTUS', 'sick horses',
    'girls that look like brigid', "people who can't read good", 'family photos',
    'suscd\'s birthday', 'academia', 'mail delivery', 'secure storage', 'security',
    'privacy', 'high frequency trading', 'investing', 'an awful idea', 'a better idea',
    'peer reviewed', 'penetration testing', '3D printing', 'smart housing', 'eggs'
  ];

  var startup_pitches = [
    '-service- for -market-',
    '-service- for -market-',
    '-service- for -market-',
    '-service- for -market-',
    '-service- for -market-',
    '-market- as a -service-',
    '-service- but -service-',
    '-market- but -market-',
    '-service- for -market-, but like -service-',
    '-service- for -market-, in the style of -service-',
    '-service- for -market-, marketed at -market-',
    '-service- to combine -market- with -market-',
    '-service- as a service',
    'a method for performing -service- using a computer',
    'an invention in which -service- is used for -market-'
  ];

  var pitch = startup_pitches[Math.floor(Math.random() * startup_pitches.length)];

  while (pitch.indexOf('-service-') > -1) {
  	var random_service = services[Math.floor(Math.random() * services.length)];
  	pitch = pitch.replace('-service-', random_service);
  }

  while (pitch.indexOf('-market-') > -1) {
  	var random_market = markets[Math.floor(Math.random() * markets.length)];
  	pitch = pitch.replace('-market-', random_market);
  }

  reply('Random startup idea: ' + pitch);
};


text:
#include "modules/skottie/src/SkottieAdapter.h"

#include "include/core/SkFont.h"
#include "include/core/SkMatrix.h"
#include "include/core/SkMatrix44.h"
#include "include/core/SkPath.h"
#include "include/core/SkRRect.h"
#include "include/private/SkTo.h"
#include "include/utils/Sk3D.h"
#include "modules/skottie/src/SkottieValue.h"
#include "modules/sksg/include/SkSGDraw.h"
#include "modules/sksg/include/SkSGGradient.h"
#include "modules/sksg/include/SkSGGroup.h"
#include "modules/sksg/include/SkSGPaint.h"
#include "modules/sksg/include/SkSGPath.h"
#include "modules/sksg/include/SkSGRect.h"
#include "modules/sksg/include/SkSGTransform.h"
#include "modules/sksg/include/SkSGTrimEffect.h"

#include <cmath>
#include <utility>

namespace skottie {

namespace internal {

DiscardableAdaptorBase::DiscardableAdaptorBase() = default;

void DiscardableAdaptorBase::setAnimators(sksg::AnimatorList&& animators) {
    fAnimators = std::move(animators);
}

void DiscardableAdaptorBase::onTick(float t) {
    for (auto& animator : fAnimators) {
        animator->tick(t);
    }

    this->onSync();
}

} // namespace internal

RRectAdapter::RRectAdapter(sk_sp<sksg::RRect> wrapped_node)
    : fRRectNode(std::move(wrapped_node)) {}

RRectAdapter::~RRectAdapter() = default;

void RRectAdapter::apply() {
    // BM "position" == "center position"
    auto rr = SkRRect::MakeRectXY(SkRect::MakeXYWH(fPosition.x() - fSize.width() / 2,
                                                   fPosition.y() - fSize.height() / 2,
                                                   fSize.width(), fSize.height()),
                                  fRadius.width(),
                                  fRadius.height());
   fRRectNode->setRRect(rr);
}

TransformAdapter2D::TransformAdapter2D(sk_sp<sksg::Matrix<SkMatrix>> matrix)
    : fMatrixNode(std::move(matrix)) {}

TransformAdapter2D::~TransformAdapter2D() = default;

SkMatrix TransformAdapter2D::totalMatrix() const {
    SkMatrix t = SkMatrix::MakeTrans(-fAnchorPoint.x(), -fAnchorPoint.y());

    t.postScale(fScale.x() / 100, fScale.y() / 100); // 100% based
    t.postRotate(fRotation);
    t.postTranslate(fPosition.x(), fPosition.y());
    // TODO: skew

    return t;
}

void TransformAdapter2D::apply() {
    fMatrixNode->setMatrix(this->totalMatrix());
}

TransformAdapter3D::Vec3::Vec3(const VectorValue& v) {
    fX = v.size() > 0 ? v[0] : 0;
    fY = v.size() > 1 ? v[1] : 0;
    fZ = v.size() > 2 ? v[2] : 0;
}

TransformAdapter3D::TransformAdapter3D()
    : fMatrixNode(sksg::Matrix<SkMatrix44>::Make(SkMatrix::I())) {}

TransformAdapter3D::~TransformAdapter3D() = default;

sk_sp<sksg::Transform> TransformAdapter3D::refTransform() const {
    return fMatrixNode;
}

SkMatrix44 TransformAdapter3D::totalMatrix() const {
    SkMatrix44 t;

    t.setTranslate(-fAnchorPoint.fX, -fAnchorPoint.fY, -fAnchorPoint.fZ);
    t.postScale(fScale.fX / 100, fScale.fY / 100, fScale.fZ / 100);

    SkMatrix44 r;
    r.setRotateDegreesAbout(0, 0, 1, fRotation.fZ);
    t.postConcat(r);
    r.setRotateDegreesAbout(0, 1, 0, fRotation.fY);
    t.postConcat(r);
    r.setRotateDegreesAbout(1, 0, 0, fRotation.fX);
    t.postConcat(r);

    t.postTranslate(fPosition.fX, fPosition.fY, fPosition.fZ);

    return t;
}

void TransformAdapter3D::apply() {
    fMatrixNode->setMatrix(this->totalMatrix());
}

CameraAdapter:: CameraAdapter(const SkSize& viewport_size)
    : fViewportSize(viewport_size) {}

CameraAdapter::~CameraAdapter() = default;

SkMatrix44 CameraAdapter::totalMatrix() const {
    // Camera parameters:
    //
    //   * location          -> position attribute
    //   * point of interest -> anchor point attribute
    //   * orientation       -> rotation attribute
    //
    SkPoint3 pos = { this->getPosition().fX,
                     this->getPosition().fY,
                    -this->getPosition().fZ },
             poi = { this->getAnchorPoint().fX,
                     this->getAnchorPoint().fY,
                    -this->getAnchorPoint().fZ },
              up = { 0, 1, 0 };

    // Initial camera vector.
    SkMatrix44 cam_t;
    Sk3LookAt(&cam_t, pos, poi, up);

    // Rotation origin is camera position.
    {
        SkMatrix44 rot;
        rot.setRotateDegreesAbout(1, 0, 0,  this->getRotation().fX);
        cam_t.postConcat(rot);
        rot.setRotateDegreesAbout(0, 1, 0,  this->getRotation().fY);
        cam_t.postConcat(rot);
        rot.setRotateDegreesAbout(0, 0, 1, -this->getRotation().fZ);
        cam_t.postConcat(rot);
    }

    // Flip world Z, as it is opposite of what Sk3D expects.
    cam_t.preScale(1, 1, -1);

    // View parameters:
    //
    //   * size     -> composition size (TODO: AE seems to base it on width only?)
    //   * distance -> "zoom" camera attribute
    //
    const auto view_size     = SkTMax(fViewportSize.width(), fViewportSize.height()),
               view_distance = this->getZoom(),
               view_angle    = std::atan(sk_ieee_float_divide(view_size * 0.5f, view_distance));

    SkMatrix44 persp_t;
    Sk3Perspective(&persp_t, 0, view_distance, 2 * view_angle);
    persp_t.postScale(view_size * 0.5f, view_size * 0.5f, 1);

    SkMatrix44 t;
    t.setTranslate(fViewportSize.width() * 0.5f, fViewportSize.height() * 0.5f, 0);
    t.preConcat(persp_t);
    t.preConcat(cam_t);

    return t;
}

RepeaterAdapter::RepeaterAdapter(sk_sp<sksg::RenderNode> repeater_node, Composite composite)
    : fRepeaterNode(repeater_node)
    , fComposite(composite)
    , fRoot(sksg::Group::Make()) {}

RepeaterAdapter::~RepeaterAdapter() = default;

void RepeaterAdapter::apply() {
    static constexpr SkScalar kMaxCount = 512;
    const auto count = static_cast<size_t>(SkTPin(fCount, 0.0f, kMaxCount) + 0.5f);

    const auto& compute_transform = [this] (size_t index) {
        const auto t = fOffset + index;

        // Position, scale & rotation are "scaled" by index/offset.
        SkMatrix m = SkMatrix::MakeTrans(-fAnchorPoint.x(),
                                         -fAnchorPoint.y());
        m.postScale(std::pow(fScale.x() * .01f, fOffset),
                    std::pow(fScale.y() * .01f, fOffset));
        m.postRotate(t * fRotation);
        m.postTranslate(t * fPosition.x() + fAnchorPoint.x(),
                        t * fPosition.y() + fAnchorPoint.y());

        return m;
    };

    // TODO: start/end opacity support.

    // TODO: we can avoid rebuilding all the fragments in most cases.
    fRoot->clear();
    for (size_t i = 0; i < count; ++i) {
        const auto insert_index = (fComposite == Composite::kAbove) ? i : count - i - 1;
        fRoot->addChild(sksg::TransformEffect::Make(fRepeaterNode,
                                                    compute_transform(insert_index)));
    }
}

PolyStarAdapter::PolyStarAdapter(sk_sp<sksg::Path> wrapped_node, Type t)
    : fPathNode(std::move(wrapped_node))
    , fType(t) {}

PolyStarAdapter::~PolyStarAdapter() = default;

void PolyStarAdapter::apply() {
    static constexpr int kMaxPointCount = 100000;
    const auto count = SkToUInt(SkTPin(SkScalarRoundToInt(fPointCount), 0, kMaxPointCount));
    const auto arc   = sk_ieee_float_divide(SK_ScalarPI * 2, count);

    const auto pt_on_circle = [](const SkPoint& c, SkScalar r, SkScalar a) {
        return SkPoint::Make(c.x() + r * std::cos(a),
                             c.y() + r * std::sin(a));
    };

    // TODO: inner/outer "roundness"?

    SkPath poly;

    auto angle = SkDegreesToRadians(fRotation - 90);
    poly.moveTo(pt_on_circle(fPosition, fOuterRadius, angle));
    poly.incReserve(fType == Type::kStar ? count * 2 : count);

    for (unsigned i = 0; i < count; ++i) {
        if (fType == Type::kStar) {
            poly.lineTo(pt_on_circle(fPosition, fInnerRadius, angle + arc * 0.5f));
        }
        angle += arc;
        poly.lineTo(pt_on_circle(fPosition, fOuterRadius, angle));
    }

    poly.close();
    fPathNode->setPath(poly);
}

GradientAdapter::GradientAdapter(sk_sp<sksg::Gradient> grad, size_t colorStopCount)
        : fGradient(std::move(grad)), fColorStopCount(colorStopCount) {}

void GradientAdapter::apply() {
    this->onApply();

    // Gradient color stops are specified as a consolidated float vector holding:
    //
    //   a) an (optional) array of color/RGB stop records (t, r, g, b)
    //
    // followed by
    //
    //   b) an (optional) array of opacity/alpha stop records (t, a)
    //
    struct ColorRec {
        float t, r, g, b;
    };
    struct OpacityRec {
        float t, a;
    };

    // The number of color records is explicit (fColorStopCount),
    // while the number of opacity stops is implicit (based on the size of fStops).
    //
    // |fStops| holds ColorRec x |fColorStopCount| + OpacityRec x N
    const auto c_count = fColorStopCount, c_size = c_count * 4,
               o_count = (fStops.size() - c_size) / 2;
    if (fStops.size() < c_size || fStops.size() != (c_count * 4 + o_count * 2)) {
        // apply() may get called before the stops are set, so only log when we have some stops.
        if (!fStops.empty()) {
            SkDebugf("!! Invalid gradient stop array size: %zu\n", fStops.size());
        }
        return;
    }

    const auto* current_c = reinterpret_cast<const ColorRec*>(fStops.data());
    const auto* end_c = current_c + c_count;
    const auto* current_o = reinterpret_cast<const OpacityRec*>(end_c);
    const auto* end_o = current_o + o_count;

    // TODO: Gradient/ColorStop should use 4f.
    sksg::Gradient::ColorStop prev_stop = {0.0f, SK_ColorBLACK};
    if (current_c < end_c) {
        prev_stop.fColor = SkColor4f{current_c->r, current_c->g, current_c->b, 1.0}.toSkColor();
    }
    if (current_o < end_o) {
        prev_stop.fColor = SkColorSetA(prev_stop.fColor, SkScalarRoundToInt(current_o->a * 255));
    }

    auto lerp = [](float a, float b, float t) { return a + t * (b - a); };

    auto next_stop = [&]() -> sksg::Gradient::ColorStop {
        const auto prev_c = SkColor4f::FromColor(prev_stop.fColor);

        const uint8_t has_color_stop = SkToU8(current_c < end_c),
                      has_opacity_stop = SkToU8(current_o < end_o);

        switch (has_color_stop | (has_opacity_stop << 1)) {
            case 0x01: {
                // Color-only stop.
                sksg::Gradient::ColorStop cs{
                        current_c->t,
                        SkColor4f{current_c->r, current_c->g, current_c->b, prev_c.fA}.toSkColor()};

                current_c++;
                return cs;
            }
            case 0x02: {
                // Opacity-only stop.
                sksg::Gradient::ColorStop cs{
                        current_o->t,
                        SkColor4f{prev_c.fR, prev_c.fG, prev_c.fB, current_o->a}.toSkColor()};

                current_o++;
                return cs;
            }
            case 0x03: {
                // Separate color and opacity stops.
                // Merge-sort the two arrays, LERP-ing intermediate channel values as needed.

                auto c = SkColor4f{current_c->r, current_c->g, current_c->b, current_o->a};
                auto t_rgb = current_c->t, t_a = current_o->t;

                if (SkScalarNearlyEqual(t_rgb, t_a)) {
                    // Coincident color and opacity stops: no LERP needed, consume both.
                    current_c++;
                    current_o++;

                    return {t_rgb, c.toSkColor()};
                }

                if (t_rgb < t_a) {
                    // Color stop followed by opacity stop: LERP alpha, consume the color stop.
                    const auto rel_t = SkTPin(sk_ieee_float_divide(t_rgb - prev_stop.fPosition,
                                                                   t_a - prev_stop.fPosition),
                                              0.0f, 1.0f);
                    c.fA = lerp(prev_c.fA, c.fA, rel_t);

                    current_c++;

                    return {t_rgb, c.toSkColor()};
                } else {
                    // Opacity stop followed by color stop: LERP r/g/b, consume the opacity stop.
                    const auto rel_t = SkTPin(sk_ieee_float_divide(t_a - prev_stop.fPosition,
                                                                   t_rgb - prev_stop.fPosition),
                                              0.0f, 1.0f);
                    c.fR = lerp(prev_c.fR, c.fR, rel_t);
                    c.fG = lerp(prev_c.fG, c.fG, rel_t);
                    c.fB = lerp(prev_c.fB, c.fB, rel_t);

                    current_o++;

                    return {t_a, c.toSkColor()};
                }
            }

            default:
                SkUNREACHABLE;
        }
    };

    std::vector<sksg::Gradient::ColorStop> stops;
    stops.reserve(c_count);

    while (current_c < end_c || current_o < end_o) {
        prev_stop = next_stop();
        stops.push_back(prev_stop);
    }

    stops.shrink_to_fit();
    fGradient->setColorStops(std::move(stops));
}

LinearGradientAdapter::LinearGradientAdapter(sk_sp<sksg::LinearGradient> grad, size_t stopCount)
    : INHERITED(std::move(grad), stopCount) {}

void LinearGradientAdapter::onApply() {
    auto* grad = static_cast<sksg::LinearGradient*>(fGradient.get());
    grad->setStartPoint(this->startPoint());
    grad->setEndPoint(this->endPoint());
}

RadialGradientAdapter::RadialGradientAdapter(sk_sp<sksg::RadialGradient> grad, size_t stopCount)
    : INHERITED(std::move(grad), stopCount) {}

void RadialGradientAdapter::onApply() {
    auto* grad = static_cast<sksg::RadialGradient*>(fGradient.get());
    grad->setStartCenter(this->startPoint());
    grad->setEndCenter(this->startPoint());
    grad->setStartRadius(0);
    grad->setEndRadius(SkPoint::Distance(this->startPoint(), this->endPoint()));
}

TrimEffectAdapter::TrimEffectAdapter(sk_sp<sksg::TrimEffect> trimEffect)
    : fTrimEffect(std::move(trimEffect)) {
    SkASSERT(fTrimEffect);
}

TrimEffectAdapter::~TrimEffectAdapter() = default;

void TrimEffectAdapter::apply() {
    // BM semantics: start/end are percentages, offset is "degrees" (?!).
    const auto  start = fStart  / 100,
                  end = fEnd    / 100,
               offset = fOffset / 360;

    auto startT = SkTMin(start, end) + offset,
          stopT = SkTMax(start, end) + offset;
    auto   mode = SkTrimPathEffect::Mode::kNormal;

    if (stopT - startT < 1) {
        startT -= SkScalarFloorToScalar(startT);
        stopT  -= SkScalarFloorToScalar(stopT);

        if (startT > stopT) {
            using std::swap;
            swap(startT, stopT);
            mode = SkTrimPathEffect::Mode::kInverted;
        }
    } else {
        startT = 0;
        stopT  = 1;
    }

    fTrimEffect->setStart(startT);
    fTrimEffect->setStop(stopT);
    fTrimEffect->setMode(mode);
}

} // namespace skottie


text:
#include <sys/mman.h>
#include <runtime_reqs.h>

int munmap(void *start, size_t length)
{
  runtime_free(start, length);
  return 0;
}


text:
package edu.ucsb.jpregel.system;

import java.awt.geom.Point2D;

/**
 *
 * @author Pete Cappello
 */
public class CombinerMinDouble extends Combiner<Point2D.Float, Double>
{
    @Override
    protected Message<Point2D.Float, Double> combine( Message<Point2D.Float, Double> currentMessage, Message<Point2D.Float, Double> newMessage )
    {
        return ( currentMessage.getMessageValue() <= newMessage.getMessageValue() ) ? currentMessage : newMessage;
    }
}


text:
return {
	name = "doh.cleanbrowsing.org-doh-family-filter",
	label = _("CleanBrowsing (Family Filter)"),
	resolver_url = "https://doh.cleanbrowsing.org/doh/family-filter/",
	bootstrap_dns = "185.228.168.168,1.1.1.1",
	help_link = "https://cleanbrowsing.org/guides/dnsoverhttps",
	help_link_text = "CleanBrowsing.org"
}


text:
Picker

        {% with img=current %}

            ${img.title}

        {% end-with %}

        {% for img in images %}

                ${img.title}

        {% end-for %}


text:
package org.oskari.service.wfs3;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.Arrays;

import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.json.JSONArray;
import org.junit.Ignore;
import org.junit.Test;
import org.opengis.referencing.crs.CoordinateReferenceSystem;

import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;

import fi.nls.oskari.domain.map.OskariLayer;
import fi.nls.oskari.service.ServiceException;
import fi.nls.oskari.util.JSONHelper;

public class OskariWFS3ClientTest {

    @Ignore("Depends on outside service, results might vary")
    @Test
    public void testGetFeaturesHardLimit() throws ServiceException, IOException {
        OskariLayer layer = new OskariLayer();
        layer.setUrl("https://beta-paikkatieto.maanmittauslaitos.fi/geographic-names/wfs3/v1/");
        layer.setName("places");
        CoordinateReferenceSystem crs = OskariWFS3Client.getCRS84();
        Envelope envelope = new Envelope(21.35, 21.40, 61.35, 61.40);
        ReferencedEnvelope bbox = new ReferencedEnvelope(envelope, crs);

        int limit = 10;
        SimpleFeatureCollection sfc = OskariWFS3Client.getFeatures(layer, bbox, crs);
        assertEquals(limit, sfc.size());
        int i = 0;
        try (SimpleFeatureIterator it = sfc.features()) {
            while (it.hasNext()) {
                i++;
                it.next();
            }
        }
        assertEquals(limit, i);

        limit = 1000;
        sfc = OskariWFS3Client.getFeatures(layer, bbox, crs);
        assertEquals(29, sfc.size());
        i = 0;
        try (SimpleFeatureIterator it = sfc.features()) {
            while (it.hasNext()) {
                i++;
                it.next();
            }
        }
        assertEquals(29, i);
    }

    @Ignore("Depends on outside service, results might vary")
    @Test
    public void testGetFeaturesHardLimitPaging() throws ServiceException, IOException {
        OskariLayer layer = new OskariLayer();
        layer.setUrl("https://beta-paikkatieto.maanmittauslaitos.fi/geographic-names/wfs3/v1/");
        layer.setName("places");
        CoordinateReferenceSystem crs = OskariWFS3Client.getCRS84();
        int limit = OskariWFS3Client.PAGE_SIZE + 10;
        SimpleFeatureCollection sfc = OskariWFS3Client.getFeatures(layer, null, crs);
        assertEquals(limit, sfc.size());
        int i = 0;
        try (SimpleFeatureIterator it = sfc.features()) {
            while (it.hasNext()) {
                i++;
                it.next();
            }
        }
        assertEquals(limit, i);
    }

    @Ignore("Depends on outside service, results might vary")
    @Test
    public void testGetFeaturesServiceSupportingCRS_EPSG3067() throws Exception {
        OskariLayer layer = new OskariLayer();
        layer.setUrl("https://beta-paikkatieto.maanmittauslaitos.fi/maastotiedot/wfs3/v1/");
        layer.setName("rakennus");
        layer.setCapabilities(JSONHelper.createJSONObject("crs-uri", new JSONArray(Arrays.asList("http://www.opengis.net/def/crs/EPSG/0/3067"))));
        CoordinateReferenceSystem epsg3067 = CRS.decode("EPSG:3067");
        ReferencedEnvelope bbox = new ReferencedEnvelope(500000, 501000, 6822000, 6823000, epsg3067);
        SimpleFeatureCollection sfc = OskariWFS3Client.getFeatures(layer, bbox, epsg3067);
        assertFalse(sfc.isEmpty());
        try (SimpleFeatureIterator it = sfc.features()) {
            while (it.hasNext()) {
                Geometry geometryEnvelope = ((Geometry) it.next().getDefaultGeometry()).getEnvelope();
                assertTrue(geometryEnvelope.within(JTS.toGeometry(bbox)));
            }
        }
    }

}


text:
from __future__ import unicode_literals
from ..surface import ProbeVolumeWithModel

def test_ProbeVolumeWithModel_inputs():
    input_map = dict(InputModel=dict(argstr='%s',
    position=-2,
    ),
    InputVolume=dict(argstr='%s',
    position=-3,
    ),
    OutputModel=dict(argstr='%s',
    hash_files=False,
    position=-1,
    ),
    args=dict(argstr='%s',
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    terminal_output=dict(deprecated='1.0.0',
    nohash=True,
    ),
    )
    inputs = ProbeVolumeWithModel.input_spec()

    for key, metadata in list(input_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(inputs.traits()[key], metakey) == value

def test_ProbeVolumeWithModel_outputs():
    output_map = dict(OutputModel=dict(position=-1,
    ),
    )
    outputs = ProbeVolumeWithModel.output_spec()

    for key, metadata in list(output_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(outputs.traits()[key], metakey) == value