text:
<?php

namespace Application\Block\Mapas;
use Loader;
use Page;
use Core;
use Concrete\Core\Block\BlockController;

class Controller extends BlockController
{
    protected $btTable = 'btMapas';
    protected $btExportTables = array('btMapas', 'btMapasEntries');
    protected $btInterfaceWidth = "1050";
    protected $btInterfaceHeight = "500";
    protected $btCacheBlockRecord = true;
    protected $btCacheBlockOutput = true;
    protected $btCacheBlockOutputOnPost = true;
    protected $btCacheBlockOutputForRegisteredUsers = false;

    public $titulo_mapa = "";
    public $titulo = "";
    public $width = "";
    public $height = "";
    public $location = "";
    public $descripcion = "";
    public $latitud = "";
    public $longitud = "";
    public $scrollwheel = true;
    public $icono = 3;
    public $zoom = 14;

    /**
     * Used for localization. If we want to localize the name/description we have to include this.
     */
    public function getBlockTypeDescription()
    {
        return t("Introduzca una dirección y un mapa de Google de la ubicación Que se colocará en su página.");
    }

    public function getBlockTypeName()
    {
        return t("Mapas Senatics");
    }

    public function __construct($obj = null)
    {
        parent::__construct($obj);
        if (!$this->titulo_mapa) {
            $this->titulo_mapa = t("");
        }
        if (!$this->zoom) {
            $this->zoom = t("14");
        }
    }

    public function validate($args)
    {
        $error = Core::make('helper/validation/error');

        if ($args['latitud'] === '' || $args['longtitud'] === '') {
            $error->add(t('You must select a valid location.'));
        }

        if (!is_numeric($args['zoom'])) {
            $error->add(t('Please enter a zoom number from 0 to 21.'));
        }
        if ($args['zoom']==0) {
            $error->add(t('Por favor ingrese un Número entre 0 y 21 para el ZOOM.'));
        }

        if ($error->has()) {
            return $error;
        }
    }

    public function registerViewAssets($outputContent = '')
    {
        $this->requireAsset('javascript', 'jquery');
        $this->addFooterItem(
            '<script defer src="https://maps.googleapis.com/maps/api/js"></script>
            <script type="text/javascript" src="'.BASE_URL.'/application/blocks/mapas/markerclusterer.js"></script>
            '
        );
    }

    public function add() {
        $this->requireAsset('core/file-manager');
        $this->requireAsset('redactor');

    }

    public function view()
    {
        $this->set('unique_identifier', Core::make('helper/validation/identifier')->getString(18));
        /*$this->set('bID', $this->bID);
        $this->set('title', $this->title);
        $this->set('location', $this->location);
        $this->set('latitude', $this->latitude);
        $this->set('longitude', $this->longitude);
        $this->set('zoom', $this->zoom);
        $this->set('scrollwheel', $this->scrollwheel);*/

        $this->set('bID', $this->bID);
        $this->set('zoom', $this->zoom);
        $this->set('height', $this->height);
        $this->set('width', $this->width);
        $this->set('scrollwheel', $this->scrollwheel);
        $this->set('titulo_mapa', $this->titulo_mapa);

        $db = Loader::db();
        $query = $db->GetAll("SELECT * FROM btMapasEntries WHERE bID=? ORDER BY orden", array($this->bID));
        $this->set('items', $query);

        //$this->set('paragraph', LinkAbstractor::translateFrom($this->paragraph));

    }

    public function save($data)
    {
        /*$data += array(
           'titulo' => '',
           'location' => '',
           'zoom' => -1,
           'latitud' => 0,
           'longitud' => 0,
           'width' => null,
           'width' => null,
           'scrollwheel' => 0,
        );
        $args['titulo'] = trim($data['titulo']);
        $args['location'] = trim($data['location']);
        $args['zoom'] = (intval($data['zoom']) >= 0 && intval($data['zoom']) <= 21) ? intval($data['zoom']) : 14;
        $args['latitud'] = is_numeric($data['latitud']) ? $data['latitud'] : 0;
        $args['longitud'] = is_numeric($data['longitud']) ? $data['longitud'] : 0;
        $args['width'] = $data['width'];
        $args['height'] = $data['height'];
        $args['scrollwheel'] = $data['scrollwheel'] ? 1 : 0;
        parent::save($args);*/

        $args['titulo_mapa'] = isset($data['titulo_mapa']) ? addslashes(trim($data['titulo_mapa'])) : '';
        $args['zoom'] = isset($data['zoom']) ? addslashes(intval($data['zoom'])) : 14;
        $args['scrollwheel'] = isset($data['scrollwheel']) ? addslashes(trim($data['scrollwheel'])) : 0;
        $args['width'] = isset($data['width']) ? addslashes(trim($data['width'])) : '';
        $args['height'] = isset($data['height']) ? addslashes(trim($data['height'])) : '';
        $db = Loader::db();
        $db->execute('DELETE FROM btMapasEntries WHERE bID = ?', array($this->bID));

        $count = count($data['orden']);
        $i = 0;
        parent::save($args);
        $idsNuevos = array();

        while( $i < $count) {
                $db->execute('INSERT INTO btMapasEntries (bID, titulo, descripcion, latitud, longitud, orden, icono) VALUES (?, ?, ?, ?, ?, ?, ?)',
                array(
                    $this->bID,
                    htmlentities($data['titulo'][$i]),
                    htmlentities($data['descripcion'][$i]),
                    addslashes(is_numeric($data['latitud'][$i]) ? $data['latitud'][$i] : 0),
                    addslashes(is_numeric($data['longitud'][$i]) ? $data['longitud'][$i] : 0),
                    intval($data['orden'][$i]),
                    intval($data['icono'][$i])
                ));
                $i++;
        }
    }

    public function edit() {
        $this->requireAsset('core/file-manager');
        $this->requireAsset('redactor');
        $this->set('titulo_mapa', $this->titulo_mapa);
        $this->set('zoom', $this->zoom);
        $this->set('height', $this->height);
        $this->set('width', $this->width);
        $this->set('scrollwheel', $this->scrollwheel);

        $db = Loader::db();
        $query = $db->GetAll("SELECT * FROM btMapasEntries WHERE bID=?", array($this->bID));
        $this->set('items', $query);
    }

    public function duplicate($newBID) {
        parent::duplicate($newBID);
        $db = Loader::db();
        $v = array($this->bID);
        $q = 'SELECT * FROM btMapasEntries where bID = ?';
        $r = $db->query($q, $v);

        while($item = $r->FetchRow()) {
            $db->execute('INSERT INTO btMapasEntries (bID, titulo, descripcion, latitud, longitud, orden, icono) VALUES (?, ?, ?, ?, ?, ?, ?)',
                array(
                    $newBID,
                    htmlentities($data['titulo'][$i]),
                    htmlentities($data['descripcion'][$i]),
                    addslashes(is_numeric($data['latitud'][$i]) ? $data['latitud'][$i] : 0),
                    addslashes(is_numeric($data['longitud'][$i]) ? $data['longitud'][$i] : 0),
                    intval($data['orden'][$i]),
                    intval($data['icono'][$i])
                )
            );
        }
        //Elimina registros anteriores sin uso del bID anterior
        $db->execute('DELETE FROM btMapasEntries WHERE bID=?', array($this->bID));
    }

}


text:
package com.github.tomakehurst.wiremock.matching;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.tomakehurst.wiremock.extension.Parameters;

public class CustomMatcherDefinition {

    private final String name;
    private final Parameters parameters;

    public CustomMatcherDefinition(@JsonProperty("name") String name,
                                   @JsonProperty("parameters") Parameters parameters) {
        this.name = name;
        this.parameters = parameters;
    }

    public String getName() {
        return name;
    }

    public Parameters getParameters() {
        return parameters;
    }

}

redpajama_set_name: RedPajamaGithub


text:
namespace GoogleARCoreInternal
{
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using UnityEditor;
    using UnityEditor.Build;
    using UnityEngine;

    internal class RequiredOptionalPreprocessBuild : PreprocessBuildBase
    {
        public override void OnPreprocessBuild(BuildTarget target, string path)
        {
            var isARCoreRequired = ARCoreProjectSettings.Instance.IsARCoreRequired;

            Debug.LogFormat(
                "Building \"{0}\" app. Use 'Edit > Project Settings > ARCore' to adjust ARCore settings.\n" +
                "See {1} for more information.",
                isARCoreRequired ? "AR Required" : "AR Optional",
                "https://developers.google.com/ar/develop/unity/enable-arcore");

            AssetHelper.GetPluginImporterByName("google_ar_required.aar")
                .SetCompatibleWithPlatform(BuildTarget.Android, isARCoreRequired);
            AssetHelper.GetPluginImporterByName("google_ar_optional.aar")
                .SetCompatibleWithPlatform(BuildTarget.Android, !isARCoreRequired);
        }
    }
}


text:
#include "stdafx.h"
#include "hex_grid.h"
#include "data/hex_util.h"
#include "ui/hex_map.h"

//#include "to_from_json.h"

using namespace std;
using namespace glm;

namespace asdf
{
namespace hexmap
{
namespace data
{
    hex_grid_chunk_t::hex_grid_chunk_t(glm::uvec2 _size, hex_grid_cell_t const& default_cell_style)
    : size(_size)
    , allocated_size(_size)
    {
        cells.resize(size.x);

        for(auto& grid_y : cells)
        {
            grid_y.resize(size.y, default_cell_style);
        }
    }

    bool hex_grid_chunk_t::operator==(hex_grid_chunk_t const& rhs) const
    {

        return position       == rhs.position
            && size           == rhs.size
            && allocated_size == rhs.allocated_size
            && contents_equal(rhs);
    }

    bool hex_grid_chunk_t::contents_equal(hex_grid_chunk_t const& rhs) const
    {
        if(size != rhs.size)
            return false;

        for(size_t y = 0; y < size.y; ++y)
        {
            for(size_t x = 0; x < size.x; ++x)
            {
                if(cells[x][y] != rhs.cells[x][y])
                    return false;
            }
        }

        return true;
    }

    /* --Save Format--
        For each chunk
            write the size of the chunk (two unsigned 32-bit integers)
            for each column in the chunk
                write the cells of this column
    */
    void hex_grid_t::save_to_file(SDL_RWops* io)
    {
        ASSERT(io, "can't save a hex_grid to a null SDL_RWops");
        WARN_IF(chunks.empty(), "Saving an empty hex_grid");

        size_t total_bytes = 0;

        for_each_chunk([&](hex_grid_chunk_t const& chunk)
        {
            SDL_RWwrite(io, reinterpret_cast<const void*>(&chunk.size), sizeof(glm::uvec2), 1);
            for(auto column : chunk.cells)
            {
                size_t num_w = SDL_RWwrite(io, column.data(), sizeof(hex_grid_cell_t), column.size());
                ASSERT(num_w == column.size(), "chunk save error");
                LOG("wrote %zu cells", num_w);

                total_bytes += num_w * sizeof(hex_grid_cell_t);
            }
        });

        LOG("total hex_grid bytes written: %zu", total_bytes);
    }

    void hex_grid_t::load_from_file(SDL_RWops* io, hxm_header_t const& header)
    {
        chunks.clear();
        init(header.map_size, header.chunk_size);

        size_t total_bytes = 0;

        for_each_chunk([&](hex_grid_chunk_t& chunk)
        {
            SDL_RWread(io, &(chunk.size), sizeof(glm::uvec2), 1);

            for(auto& column : chunk.cells)
            {
                size_t num_r = SDL_RWread(io, column.data(), sizeof(hex_grid_cell_t), column.size());
                ASSERT(num_r == column.size(), "");
                LOG("read %zu cells", num_r);

                total_bytes += num_r * sizeof(hex_grid_cell_t);
            }
        });

        LOG("total hex_grid bytes read: %zu", total_bytes);
    }

    hex_grid_t::hex_grid_t(glm::uvec2 _size, hex_grid_cell_t const& default_cell_style)
    : size(_size)
    {
        init(size, default_cell_style);
    }

    void hex_grid_t::init(glm::uvec2 _size, glm::uvec2 chunk_size, hex_grid_cell_t const& default_cell_style)
    {
        size = _size;

        auto dv_x = div(long(_size.x), chunk_size.x); //cast to long since there's no overload of div that takes a unsigned int
        auto dv_y = div(long(_size.y), chunk_size.y); //

        size_t num_chunks_x = dv_x.quot + (dv_x.rem > 0);
        size_t num_chunks_y = dv_y.quot + (dv_y.rem > 0);

        chunks.resize(num_chunks_x); //create the top row

        //cycle through top row and add columns
        for(size_t x = 0; x < num_chunks_x; ++x)
        {
            chunks[x].resize(num_chunks_y); //add chunks for this column

            //for each chunk, set position and handle odd edges
            for(size_t y = 0; y < num_chunks_y; ++y)
            {
                auto& chunk = chunks[x][y];

                //init cells
                for(auto& column : chunk.cells)
                    for(auto& cell : column)
                        cell = default_cell_style;

                //set position to be used when rendering (acts like an {x,y} offset)
                chunk.position = ivec2(x,y);

                // adjust the size of the furthest chunks in this **column** if necessary
                // allows for map sizes that aren't multiples of chunk_size
                if(dv_x.rem > 0 && x == num_chunks_x - 1)
                    chunk.size.x = dv_x.rem;
            }

            // adjust the size of the furthest chunks in this **row** if necessary
            // allows for map sizes that aren't multiples of chunk_size
            if(dv_y.rem > 0)
                chunks[x][chunks[x].size() - 1].size.y = dv_y.rem;
        }
    }

    void hex_grid_t::init(glm::uvec2 size, hex_grid_cell_t const& default_cell_style)
    {
        init(size, glm::uvec2(new_chunk_width, new_chunk_height), default_cell_style);
    }

    /// Resize by allocating an entirely new hex-grid and copying the data over
    void resize_by_copy(glm::ivec2 new_size, resize_x_direction_e, resize_y_direction_e)
    {
        //TODO: create new array of chunks with new size and copy data
        // sounds expensive as hell
    }

    void hex_grid_t::resize(glm::uvec2 new_size, resize_x_direction_e xdir, resize_y_direction_e ydir)
    {
        using lvec2 = glm::detail::tvec2<int64_t>;

        lvec2 l_size(size.x, size.y);
        lvec2 l_newsize(new_size.x, new_size.y);

        lvec2 diff = l_newsize - l_size;
        bool grow_x = diff.x > 0;
        bool grow_y = diff.y > 0;
        bool shrink_x = diff.x < 0;
        bool shrink_y = diff.y < 0;

        // if(grow_x && grow_y)  //grow both
        // {
        //     grow(new_size - size, xdir, ydir);
        // }
        // else if(shrink_x && shrink_y)  //shrink both
        // {
        //     shrink(new_size - size, xdir, ydir);
        // }

        //shrink before grow to minimize data storage needed to undo such an action
        if(shrink_x)
        {
            shrink( uvec2(abs(diff.x), 0), xdir, ydir );
        }
        if(shrink_y)
        {
            shrink( uvec2(0, abs(diff.y)), xdir, ydir );
        }
        if(grow_x)
        {
            grow( uvec2(diff.x, 0), xdir, ydir );
        }
        if(grow_y)
        {
            grow( uvec2(0, diff.y), xdir, ydir );
        }
    }

    void hex_grid_t::grow(glm::uvec2 grow_amount, resize_x_direction_e xdir, resize_y_direction_e ydir)
    {
        ASSERT(grow_amount.x >=0 && grow_amount.y >= 0, "");

        //     add_columns(grow_amount.x, xdir);
        //     add_rows(grow_amount.y, ydir);
    }

    void hex_grid_t::shrink(glm::uvec2 shrink_amount, resize_x_direction_e, resize_y_direction_e)
    {
        ASSERT(shrink_amount.x >=0 && shrink_amount.y >= 0, "");
        EXPLODE("todo: hex_grid_t::shrink()");
    }

/*
    // WIP
    void add_columns(size_t num_cols, resize_x_direction_e dir)
    {
        if(num_cols == 0)
            return;

        auto dv_x = div(num_cols, max_chunk_width);
        auto num_new_chunks_x = dv_x.quot;// + (dv_x.rem > 0)

        //create chunks if they didn't already exist
        if(chunks.size() == 0)
        {
            chunks.resize(std::min(num_new_chunks_x, 1));
        }

        // if new column will fit in existing chunks
        if(num_new_chunks_x == 0 && num_cols)
        {
            auto end_chunk = chunks[std::max(chunks.size() - 1), 0)];
            auto available_space = end_chunk.allocated_size - end_chunk.size;

            if(resize_x_direction_e == resize_rightwards
                && grow_amount.x <= available_space)
            {
                end_chunk.allocated_size.x += grow_amount.x;
            }
        }
        else //else add new chunks
        {
            auto prev_size = chunks.size();
            chunks.resize(chunks.size() + num_new_chunks_x); //add new col

            //add chunks in that col
            for(size_t x = prev_size; x < prev_size + num_new_chunks_x; ++x)
            {
                auto& col = chunks[i];

                // use same number of chunks as 0th column
                // if this is the 0th column, no rows will be added yet
                col.resize(chunks[0].size());

                //FIXME does not handle awkward sizes
                for(size_t y = 0; y < col.size(); ++y)
                {
                    chunk.position = ivec2(x, y);
                }
            }
        }
    }

    // WIP
    void add_rows(size_t num_rows, resize_y_direction_e)
    {
        if(num_rows == 0)
            return;

        //if no chunks exist, create a column to start

    }
    */

    //FIXME handle cases where columns or rows have been added below 0,0
    bool hex_grid_t::is_in_bounds(ivec2 hx) const
    {
        return hx.x >= 0 && hx.y >= 0 && hx.x < size.x && hx.y < size.y;
    }

    bbox_units_t hex_grid_t::bounding_box_units() const
    {
        if(chunks.empty())
            return bbox_units_t{vec2(0), vec2(0)};

        //start with the bounds of cell positions
        bbox_units_t bb;
        bb.lower = chunks[0][0].position * ivec2(chunk_size());
        bb.upper = chunks.back().back().position * ivec2(chunk_size());
        bb.upper.x += chunks.back().front().size.x;
        bb.upper.y += chunks.back().back().size.y;

        //scale vertically since hexes aren't one unit tall
        bb.lower.y *= hex_height;
        bb.upper.y *= hex_height;

        //padding to account for column height offset and overlap (if applicable)
        if(chunks.size() > 1) ///FIXME handle vertical hexes
        {
            glm::vec2 size = bb.upper - bb.lower;
            bb.upper.x -= size.x * hex_width_d4;  //horizontal overlap
            bb.lower.y -= hex_height_d2; //vertical offset
        }

        //add padding to account for the fact that cell positions are at their centers
        bb.lower -= vec2(hex_width_d2, hex_height_d2);
        bb.upper += vec2(hex_width_d2, hex_height_d2);

        return bb;

    }

    glm::vec2 hex_grid_t::size_units() const
    {
        auto bbox = bounding_box_units();
        return vec2(bbox.upper - bbox.lower);
    }

    glm::uvec2 hex_grid_t::size_chunks() const
    {
        if(chunks.empty())
            return glm::uvec2(0);

        glm::uvec2 size;
        size.x = chunks.size();
        size.y = chunks[0].size();

        return size;
    }

    glm::uvec2 hex_grid_t::chunk_size() const
    {
        if(chunks.empty())
        {
            return glm::uvec2(new_chunk_width, new_chunk_height);
        }
        else
        {
            return chunks[0][0].allocated_size;
        }
    }

    hex_grid_cell_t& hex_grid_t::cell_at(ivec2 hex_coord)
    {
        ASSERT(is_in_bounds(hex_coord), "Asking for a cell that is out of bounds");

        auto chunk_coord = chunk_coord_from_hex_coord(hex_coord);
        hex_grid_chunk_t& chunk = chunks[chunk_coord.x][chunk_coord.y];

        ivec2 local_hex_coord = hex_coord - (chunk_coord * ivec2(new_chunk_width, new_chunk_height));
        return chunk.cell_at_local_coord(local_hex_coord);
    }

    // hex_grid_cell_t& hex_grid_t::cell_at(glm::vec2 world_pos)
    // {
    // }

    glm::ivec2 hex_grid_t::chunk_coord_from_hex_coord(ivec2 hex_coord) const
    {
        return hex_coord / ivec2(new_chunk_width, new_chunk_height);  //truncates
    }

    hex_grid_chunk_t& hex_grid_t::chunk_from_hex_coord(ivec2 hex_coord)
    {
        auto chunk_coord = chunk_coord_from_hex_coord(hex_coord);
        return chunks[chunk_coord.x][chunk_coord.y];
    }

}
}
}


text:
package com.siyeh.ig.migration;

import com.intellij.codeInspection.InspectionProfileEntry;
import com.siyeh.ig.LightJavaInspectionTestCase;
import org.jetbrains.annotations.Nullable;

/**
 * @author Bas Leijdekkers
 */
public class CollectionsFieldAccessReplaceableByMethodCallInspectionTest extends LightJavaInspectionTestCase {

  public void testCollectionsFieldAccessReplaceableByMethodCall() {
    doTest();
  }

  @Nullable
  @Override
  protected InspectionProfileEntry getInspection() {
    return new CollectionsFieldAccessReplaceableByMethodCallInspection();
  }
}


text:
import DS from 'ember-data';

export default DS.RESTSerializer.extend({
  isNewSerializerAPI: true,
  serialize: function(snapshot, options) {
    var json = this._super(snapshot, options);
    //don't persist this, it is handled by the server
    delete json.createdAt;

    return json;
  }
});


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
class AttributeSet extends Object {

	public static function getByID($asID) {
		$db = Loader::db();
		$row = $db->GetRow('select asID, asHandle, pkgID, asName, akCategoryID from AttributeSets where asID = ?', array($asID));
		if (isset($row['asID'])) {
			$akc = new AttributeSet();
			$akc->setPropertiesFromArray($row);
			return $akc;
		}
	}

	public static function getByHandle($asHandle) {
		$db = Loader::db();
		$row = $db->GetRow('select asID, asHandle, pkgID, asName, akCategoryID from AttributeSets where asHandle = ?', array($asHandle));
		if (isset($row['asID'])) {
			$akc = new AttributeSet();
			$akc->setPropertiesFromArray($row);
			return $akc;
		}
	}

	public static function getListByPackage($pkg) {
		$db = Loader::db();
		$list = array();
		$r = $db->Execute('select asID from AttributeSets where pkgID = ? order by asID asc', array($pkg->getPackageID()));
		while ($row = $r->FetchRow()) {
			$list[] = AttributeSet::getByID($row['asID']);
		}
		$r->Close();
		return $list;
	}

	public function getAttributeSetID() {return $this->asID;}
	public function getAttributeSetHandle() {return $this->asHandle;}
	public function getAttributeSetName() {return $this->asName;}
	public function getPackageID() {return $this->pkgID;}
	public function getPackageHandle() {return PackageList::getHandle($this->pkgID);}
	public function getAttributeSetKeyCategoryID() {return $this->akCategoryID;}

	public function addKey($ak) {
		$db = Loader::db();
		$no = $db->GetOne("select count(akID) from AttributeSetKeys where akID = ? and asID = ?", array($ak->getAttributeKeyID(), $this->getAttributeSetID()));
		if ($no < 1) {
			$do = $db->GetOne('select max(displayOrder) from AttributeSetKeys where asID = ?', $this->getAttributeSetID());
			$do++;
			$db->Execute('insert into AttributeSetKeys (asID, akID, displayOrder) values (?, ?, ?)', array($this->getAttributeSetID(), $ak->getAttributeKeyID(), $do));
		}
	}

	public function getAttributeKeys() {
		$db = Loader::db();
		$r = $db->Execute('select akID from AttributeSetKeys where asID = ? order by displayOrder asc', $this->getAttributeSetID());
		$keys = array();
		$cat = AttributeKeyCategory::getByID($this->akCategoryID);
		while ($row = $r->FetchRow()) {
			$ak = $cat->getAttributeKeyByID($row['akID']);
			if (is_object($ak)) {
				$keys[] = $ak;
			}
		}
		return $keys;
	}

	public function contains($ak) {
		$db = Loader::db();
		$r = $db->GetOne('select count(akID) from AttributeSetKeys where asID = ? and akID = ?', array($this->getAttributeSetID(), $ak->getAttributeKeyID()));
		return $r > 0;
	}

	/**
	 * Removes an attribute set and sets all keys within to have a set ID of 0.
	 */
	public function delete() {
		$db = Loader::db();
		$db->Execute('delete from AttributeSets where asID = ?', array($this->getAttributeSetID()));
		$db->Execute('delete from AttributeSetKeys where asID = ?', array($this->getAttributeSetID()));
	}

	public function deleteKey($ak) {
		$db = Loader::db();
		$db->Execute('delete from AttributeSetKeys where asID = ? and akID = ?', array($this->getAttributeSetID(), $ak->getAttributeKeyID()));
		$this->rescanDisplayOrder();
	}

	protected function rescanDisplayOrder() {
		$db = Loader::db();
		$do = 1;
		$r = $db->Execute('select akID from AttributeSetKeys where asID = ? order by displayOrder asc', $this->getAttributeSetID());
		while ($row = $r->FetchRow()) {
			$db->Execute('update AttributeSetKeys set displayOrder = ? where akID = ? and asID = ?', array($do, $row['akID'], $this->getAttributeSetID()));
			$do++;
		}
	}

	public function updateAttributesDisplayOrder($uats) {
		$db = Loader::db();
		for ($i = 0; $i < count($uats); $i++) {
			$v = array($this->getAttributeSetID(), $uats[$i]);
			$db->query("update AttributeSetKeys set displayOrder = {$i} where asID = ? and akID = ?", $v);
		}
	}

}


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of SidebarGrabber
 *
 * @author kottkedp
 */
class SidebarGrabber {

    public static function getInternalSidebarWidgets()
    {
        return self::getSidebarWidgets('internal');

    }

    public static function getExternalSidebarWidgets()
    {
        return self::getSidebarWidgets('external');
    }

    public static function getSidebarWidgets( $folder )
    {
        if(!is_string($folder))
        {
            throw new Exception('folder for sideboard not a valid folder');
        }
        //user id currently not used
        $returnMe = array();

        $path = MODEL_PATH.'sidebarwidgets'.DS.$folder;//getcwd();
        $supported_ext = array('class.php');
        $dir = @opendir($path);

        while($file = @readdir($dir))
        {
            if(!is_dir($path.$file))
            {
                $splitted = explode('.', $file);
                if(count($splitted) >2)
                {
                    $ext = strtolower($splitted[count($splitted)-2].".".$splitted[count($splitted)-1]);

                    if(in_array($ext, $supported_ext))
                    {

                            $filename = '';
                            for($i=0; $i<count($splitted)-2; $i++)
                            {
                                $filename .= $splitted[$i];
                            }

                            $returnMe[] = new $filename();
                    }
                }
            }
        }

        @closedir($dir);
        //sort($files);

        unset($path);
        unset($filename);
        unset($dir);
        unset($ext);
        unset($supported_ext);
        unset($splitted);

        return self::arrangeSideboardWidgets($returnMe);

    }

    public static function arrangeSideboardWidgets($widgets)
    {
        if(!is_array($widgets))
        {
            throw new Exception('Error in arranging sideboard widgets');
        }

        usort($widgets, 'self::sideboardWidgetCompare');

        return $widgets;

    }

    public static function sideboardWidgetCompare($a, $b)
    {
        if(!$a instanceof TC_SB_SidebarWidget || !$b instanceof TC_SB_SidebarWidget)
        {
            throw new Exception('comparison only accepts sidebar widgets');
        }

        if($a->get_priority() > $b->get_priority())
        {return 1;}
        if($a->get_priority() == $b->get_priority())
        {return 0;}
        if($a->get_priority() < $b->get_priority())
        {return -1;}

    }

}

?>


text:
//
//  MBProgressHUD+CMKit.m
//  CMKit
//
//  Created by yons on 16/11/1.
//  Copyright © 2016年 yons. All rights reserved.
//

#import "MBProgressHUD+CMKit.h"
#import "UIImageView+WebCache.h"

@implementation MBProgressHUD (CMKit)

#pragma mark 信息显示
+ (void)show:(NSString *)text icon:(NSString *)icon view:(UIView *)view {
    if (view == nil) {
        view = [[UIApplication sharedApplication].windows lastObject];
    }

    // 快速显示一个提示信息
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.labelText = text;
    // 设置图片
    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed: icon]];

//        FLAnimatedImageView *customView = [[FLAnimatedImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
//        UIImage *image = [UIImage imageWithContentsOfFile:[NSFileManager getBundlePathForFile:@"请检查网络2.gif"]];
////        CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
////        FLAnimatedImageView *customView = [[FLAnimatedImageView alloc] initWithFrame:rect];
//        customView.backgroundColor = [UIColor redColor];
//        NSURL *bundleUrl = [[NSBundle mainBundle] URLForResource:@"请检查网络2" withExtension:@"gif"];
//        [customView sd_setImageWithURL:bundleUrl];
//        hud.customView = customView;

    // 再设置模式
    hud.mode = MBProgressHUDModeCustomView;

    // 隐藏时候从父控件中移除
    hud.removeFromSuperViewOnHide = YES;

    // 1秒之后再消失
    [hud hide:YES afterDelay:1.5];
}

#pragma mark 显示错误或正确信息
+ (void)showError:(NSString *)error toView:(UIView *)view {
    [self show:error icon:@"MBProgressHUD+CMKit.bundle/error" view:view];
}

+ (void)showSuccess:(NSString *)success toView:(UIView *)view {
    [self show:success icon:@"MBProgressHUD+CMKit.bundle/success" view:view];
}

#pragma mark 显示一些信息
+ (MBProgressHUD *)showMessage:(NSString *)message toView:(UIView *)view {
    if (view == nil) {
        view = [[UIApplication sharedApplication].windows lastObject];
    }
    // 快速显示一个提示信息
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.labelText = message;
    // 隐藏时候从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.color = [UIColor blackColor];
    // YES代表需要蒙版效果
    hud.dimBackground = NO;
    return hud;
}

+ (void)showSuccess:(NSString *)success {
    [self showSuccess:success toView:nil];
}

+ (void)showError:(NSString *)error {
    [self showError:error toView:nil];
}

+ (MBProgressHUD *)showMessage:(NSString *)message {
    return [self showMessage:message toView:nil];
}

+ (void)hideHUDForView:(UIView *)view {
    if (view == nil) {
        view = [[UIApplication sharedApplication].windows lastObject];
    }
    [self hideHUDForView:view animated:YES];
}

+ (void)hideHUD {
    [self hideHUDForView:nil];
}

/**
 *  显示信息
 *  @param text 信息内容
 *  @param view 显示的视图
 */
+ (void)show:(NSString *)text toView:(UIView *)view
{
    if (view == nil) view = [[UIApplication sharedApplication].windows lastObject];
    // 快速显示一个提示信息
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.labelText = text;
    // 再设置模式
    hud.mode = MBProgressHUDModeText;
    // 隐藏时候从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.color = [UIColor blackColor];
    // 1秒之后再消失
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:view animated:YES];
    });
    // [hud hide:YES afterDelay:1.0];
}

/**
 显示信息

 @param text 信息内容
 @param view 显示的视图
 @param block 回调
 */
+ (void)show:(NSString *)text toView:(UIView *)view completionBlock:(void(^)())block
{
    if (view == nil) view = [[UIApplication sharedApplication].windows lastObject];
    // 快速显示一个提示信息
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.labelText = text;
    // 再设置模式
    hud.mode = MBProgressHUDModeText;
    // 隐藏时候从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.color = [UIColor blackColor];
    // 1秒之后再消失
    [hud hide:YES afterDelay:1.0];
    hud.completionBlock = ^{
        if (block) {
            block();
        }
    };
}

@end


text:
/* $Id$ */

/*! \file */

#include <config.h>

#include <time.h>

#include <isc/app.h>
#include <isc/buffer.h>
#include <isc/entropy.h>
#include <isc/hash.h>
#include <isc/mem.h>
#include <isc/os.h>
#include <isc/socket.h>
#include <isc/string.h>
#include <isc/task.h>
#include <isc/timer.h>
#include <isc/util.h>

#include "isctest.h"

isc_mem_t *mctx = NULL;
isc_entropy_t *ectx = NULL;
isc_log_t *lctx = NULL;
isc_taskmgr_t *taskmgr = NULL;
isc_timermgr_t *timermgr = NULL;
isc_socketmgr_t *socketmgr = NULL;
isc_task_t *maintask = NULL;
int ncpus;

static isc_boolean_t hash_active = ISC_FALSE;

/*
 * Logging categories: this needs to match the list in bin/named/log.c.
 */
static isc_logcategory_t categories[] = {
		{ "",                0 },
		{ "client",          0 },
		{ "network",         0 },
		{ "update",          0 },
		{ "queries",         0 },
		{ "unmatched",       0 },
		{ "update-security", 0 },
		{ "query-errors",    0 },
		{ NULL,              0 }
};

static void
cleanup_managers() {
	if (maintask != NULL)
		isc_task_destroy(&maintask);
	if (socketmgr != NULL)
		isc_socketmgr_destroy(&socketmgr);
	if (taskmgr != NULL)
		isc_taskmgr_destroy(&taskmgr);
	if (timermgr != NULL)
		isc_timermgr_destroy(&timermgr);
}

static isc_result_t
create_managers() {
	isc_result_t result;
#ifdef ISC_PLATFORM_USETHREADS
	ncpus = isc_os_ncpus();
#else
	ncpus = 1;
#endif

	CHECK(isc_taskmgr_create(mctx, ncpus, 0, &taskmgr));
	CHECK(isc_task_create(taskmgr, 0, &maintask));
	isc_taskmgr_setexcltask(taskmgr, maintask);

	CHECK(isc_timermgr_create(mctx, &timermgr));
	CHECK(isc_socketmgr_create(mctx, &socketmgr));
	return (ISC_R_SUCCESS);

  cleanup:
	cleanup_managers();
	return (result);
}

isc_result_t
isc_test_begin(FILE *logfile, isc_boolean_t start_managers) {
	isc_result_t result;

	isc_mem_debugging |= ISC_MEM_DEBUGRECORD;
	CHECK(isc_mem_create(0, 0, &mctx));
	CHECK(isc_entropy_create(mctx, &ectx));

	CHECK(isc_hash_create(mctx, ectx, 255));
	hash_active = ISC_TRUE;

	if (logfile != NULL) {
		isc_logdestination_t destination;
		isc_logconfig_t *logconfig = NULL;

		CHECK(isc_log_create(mctx, &lctx, &logconfig));
		isc_log_registercategories(lctx, categories);
		isc_log_setcontext(lctx);

		destination.file.stream = logfile;
		destination.file.name = NULL;
		destination.file.versions = ISC_LOG_ROLLNEVER;
		destination.file.maximum_size = 0;
		CHECK(isc_log_createchannel(logconfig, "stderr",
					    ISC_LOG_TOFILEDESC,
					    ISC_LOG_DYNAMIC,
					    &destination, 0));
		CHECK(isc_log_usechannel(logconfig, "stderr", NULL, NULL));
	}

#ifdef ISC_PLATFORM_USETHREADS
	ncpus = isc_os_ncpus();
#else
	ncpus = 1;
#endif

	if (start_managers)
		CHECK(create_managers());

	return (ISC_R_SUCCESS);

  cleanup:
	isc_test_end();
	return (result);
}

void
isc_test_end() {
	if (maintask != NULL)
		isc_task_detach(&maintask);
	if (taskmgr != NULL)
		isc_taskmgr_destroy(&taskmgr);
	if (lctx != NULL)
		isc_log_destroy(&lctx);
	if (hash_active) {
		isc_hash_destroy();
		hash_active = ISC_FALSE;
	}
	if (ectx != NULL)
		isc_entropy_detach(&ectx);

	cleanup_managers();

	if (mctx != NULL)
		isc_mem_destroy(&mctx);
}

/*
 * Sleep for 'usec' microseconds.
 */
void
isc_test_nap(isc_uint32_t usec) {
#ifdef HAVE_NANOSLEEP
	struct timespec ts;

	ts.tv_sec = usec / 1000000;
	ts.tv_nsec = (usec % 1000000) * 1000;
	nanosleep(&ts, NULL);
#elif HAVE_USLEEP
	usleep(usec);
#else
	/*
	 * No fractional-second sleep function is available, so we
	 * round up to the nearest second and sleep instead
	 */
	sleep((usec / 1000000) + 1);
#endif
}


text:
using Microsoft.Azure.WebJobs.Host.Listeners;
using Redis.WebJobs.Extensions.Listeners;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;

namespace Redis.WebJobs.Extensions.Framework
{
    internal abstract class ListenerBase : IListener
    {
        protected readonly CancellationTokenSource CancellationTokenSource;
        protected bool Disposed;

        public ListenerBase()
        {
            CancellationTokenSource = new CancellationTokenSource();
        }

        protected virtual void OnDisposing()
        {

        }

        [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_cancellationTokenSource")]
        public void Dispose()
        {
            if (!Disposed)
            {
                CancellationTokenSource.Cancel();

                OnDisposing();

                Disposed = true;
            }
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            ThrowIfDisposed();

            OnStarting();

            return StartAsyncCore(cancellationToken);
        }

        protected abstract Task StartAsyncCore(CancellationToken cancellationToken);

        protected virtual void OnStarting()
        {
            // override if needed
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            ThrowIfDisposed();

            OnStopping();

            CancellationTokenSource.Cancel();

            return StopAsyncCore(cancellationToken);
        }

        protected abstract Task StopAsyncCore(CancellationToken cancellationToken);

        protected virtual void OnStopping()
        {
            // override if needed
        }

        public void Cancel()
        {
            ThrowIfDisposed();
            CancellationTokenSource.Cancel();
        }

        protected void ThrowIfDisposed()
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(null);
            }
        }

        protected RedisProcessor CreateProcessor(string channelName)
        {
            var context = new RedisProcessorContext(channelName);
            return new RedisProcessor(context);
        }
    }
}


text:
.soria .dijitDialog {
	background: #eee;
	border: 1px solid #cbcbcb;
	-webkit-box-shadow: 0px 5px 10px #adadad;
	padding: 0px;
}
.soria .dijitDialog .dijitDialogTitle {

	font-weight: bold;
	padding: 0px 4px;
	font-size: 0.9em;
	color: #3243C5F;
}
.soria .dijitDialog .dijitDialogPaneContent {
	background: #ffffff;
	border:none;
	border-top: 1px solid #b1badf;
	padding:10px;
}
.soria .dijitDialogTitleBar {

	background: #fafafa url("images/titleBar.png") repeat-x top left;
	padding: 5px 6px 3px 6px;
	cursor: move;
	outline:0;
}
.soria .dijitDialogCloseIcon {

	background-image: url("images/spriteRoundedIconsSmallBl.png");
	background-repeat: no-repeat;
	background-position: -60px 0px;
	position: absolute;
	vertical-align: middle;
	right: 6px;
	top: 4px;
	height: 15px;
	width: 15px;
	cursor: pointer;
}
.dj_ie6 .soria .dijitDialogCloseIcon {
	background-image: url("images/spriteRoundedIconsSmallBl.gif");
}
.soria .dijitDialogCloseIcon-hover {
	background-position: -60px -15px;
}
.soria .dijitTooltip,
.soria .dijitTooltipDialog {

	background: transparent;
}
.dijitTooltipBelow {

	padding-top: 10px;
}
.dijitTooltipAbove {

	padding-bottom: 10px;
}
.soria .dijitTooltipContainer {

	background-color: #fff;
	border:1px solid #cbcbcb;
	padding:0.45em;
}
.soria .dijitTooltipConnector {

	border:0px;
	z-index: 2;
}
.soria .dijitTooltipABRight .dijitTooltipConnector {

	left: auto !important;
	right: 6px;
}
.soria .dijitTooltipBelow .dijitTooltipConnector {

	top: 0px;
	left: 6px;
	background:url("images/tooltipConnectorUp.png") no-repeat top left;
	width:17px;
	height:11px;
}
.dj_ie .soria .dijitTooltipBelow .dijitTooltipConnector {
	background-image: url("images/tooltipConnectorUp.gif");
}
.soria .dijitTooltipAbove .dijitTooltipConnector {

	bottom: 0px;
	left: 6px;
	background:url("images/tooltipConnectorDown.png") no-repeat top left;
	width:17px;
	height:11px;
}
.dj_ie .soria .dijitTooltipAbove .dijitTooltipConnector {
	background-image: url("images/tooltipConnectorDown.gif");
}
.dj_ie .soria .dijitTooltipAbove .dijitTooltipConnector {
	background-image: url("images/tooltipConnectorDown.gif");
}
.dj_ie6 .soria .dijitTooltipAbove .dijitTooltipConnector {
	bottom: -5px;
}
.soria .dijitTooltipLeft {
	padding-right: 10px;
}
.dj_ie6 .soria .dijitTooltipLeft {
	padding-left: 11px;
}
.soria .dijitTooltipLeft .dijitTooltipConnector {

	right: 0px;
	bottom: 3px;
	background:url("images/tooltipConnectorRight.png") no-repeat top left;
	width:11px;
	height:17px;
}
.dj_ie .soria .dijitTooltipLeft .dijitTooltipConnector {
	background-image: url("images/tooltipConnectorRight.gif");
}
.soria .dijitTooltipRight {
	padding-left: 10px;
}
.soria .dijitTooltipRight .dijitTooltipConnector {

	left: 0px;
	bottom: 3px;
	background:url("images/tooltipConnectorLeft.png") no-repeat top left;
	width:11px;
	height:17px;
}
.dj_ie .soria .dijitTooltipRight .dijitTooltipConnector {
	background-image: url("images/tooltipConnectorLeft.gif");
}


text: Converts stuff to BIN and HEX!


text:
this repo is for basic code that start learning react js

need to install webpack and webpack-dev-server

npm install -S webpack //install locally
npm install -g webpack //install globally
npm install -g webpack-dev-server

add to package.json

"scripts": {
    "dev": "webpack-dev-server --content-base src --inline --hot",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

so you can run

npm run dev

for short which is equivalent

webpack-dev-server --content-base src --inline --hot

## Instruction to run
1. Navigation to reactjs-basic
2. *npm install*
3. *npm run dev*
4. navigate to location:8080


text:
from django.core.management.base import BaseCommand, CommandError
from javanlp.models import Sentence
from javanlp.util import annotate_document

import os, stat, csv

class Command(BaseCommand):
    'Takes documents from [source], sends them through JavaNLP for annotations and then populates the sentences table.'
    help = 'Takes documents from [source], sends them through JavaNLP for annotations and then populates the sentences table.'

    def add_arguments(self, parser):
        parser.add_argument('--directory', type=str, help="Path to a directory from which to read each document sequentially")
        parser.add_argument('--csv', type=str, help="Path to a CSV file with format 'docid,gloss'")
        parser.add_argument('--server', type=str, default='localhost:9000', help="A JavaNLP annotation server endpoint")

    def get_docstream(self, **options):
        """
        Obtain a stream of documents from the arguments
        """
        if options['directory'] is not None:
            top = options['directory']
            for fname in os.listdir(top):
                path = os.path.join(top, fname)

                # For each file.
                if stat.S_ISREG(os.stat(path).st_mode):
                    with open(path) as f:
                        doc_id = fname.split('.', 1)[0]
                        gloss = f.read()
                    yield doc_id, gloss
        elif options['csv'] is not None:
            with open(options['csv']) as f:
                for doc_id, gloss in csv.reader(f):
                    yield doc_id, gloss

    def handle(self, *args, **options):
        if (not options['directory'] is None and not options['csv'] is None) or (options['directory'] is None and options['csv'] is None):
            raise CommandError("Must set exactly one of directory or csv")

        stream = self.get_docstream(**options)
        for doc_id, gloss in stream:
            print(doc_id)
            # Get annotations from the javanlp server.
            for sentence in annotate_document(doc_id, gloss, server=options['server']):
                sentence.save()


text:
SELECT mdata.periode_month AS periode_month,
       sum(mdata.Total) AS Total,
       sum(mdata.Total_n1) AS Total_n1,
       sum(mdata.Total_n2) AS Total_n2,
       sum(mdata.Total_n3) AS Total_n3,
       sum(mdata.Total_n4) AS Total_n4,
       strftime('%Y', date('now', 'start of year', 'localtime') ) AS name_n0,
       strftime('%Y', date('now', 'start of year', '-1 year', 'localtime') ) AS name_n1,
       strftime('%Y', date('now', 'start of year', '-2 year', 'localtime') ) AS name_n2,
       strftime('%Y', date('now', 'start of year', '-3 year', 'localtime') ) AS name_n3,
       strftime('%Y', date('now', 'start of year', '-4 year', 'localtime') ) AS name_n4
  FROM (
           SELECT txd.periode_month,
                  CASE WHEN txd.periode_year = strftime('%Y', date('now', 'start of year', 'localtime') ) THEN txd.Deposit + txd.Withdrawal ELSE 0 END AS Total,
                  CASE WHEN txd.periode_year = strftime('%Y', date('now', 'start of year', '-1 year', 'localtime') ) THEN txd.Deposit + txd.Withdrawal ELSE 0 END AS Total_n1,
                  CASE WHEN txd.periode_year = strftime('%Y', date('now', 'start of year', '-2 year', 'localtime') ) THEN txd.Deposit + txd.Withdrawal ELSE 0 END AS Total_n2,
                  CASE WHEN txd.periode_year = strftime('%Y', date('now', 'start of year', '-3 year', 'localtime') ) THEN txd.Deposit + txd.Withdrawal ELSE 0 END AS Total_n3,
                  CASE WHEN txd.periode_year = strftime('%Y', date('now', 'start of year', '-4 year', 'localtime') ) THEN txd.Deposit + txd.Withdrawal ELSE 0 END AS Total_n4
             FROM (
                      SELECT strftime('%Y', ca.TRANSDATE) AS periode_year,
                             strftime('%m', ca.TRANSDATE) AS periode_month,
                             CASE WHEN ca.transcode = 'Deposit' THEN (ca.transamount * IFNULL(CH.CURRVALUE, CF.BASECONVRATE) * 1.0) ELSE 0 END AS Deposit,
                             CASE WHEN ca.transcode = 'Withdrawal' THEN - (ca.transamount * IFNULL(CH.CURRVALUE, CF.BASECONVRATE) * 1.0) ELSE 0 END AS Withdrawal
                        FROM CHECKINGACCOUNT_V1 AS ca
                             LEFT JOIN
                             ACCOUNTLIST_V1 AC ON AC.ACCOUNTID = ca.ACCOUNTID
                             LEFT JOIN
                             CURRENCYFORMATS_V1 cf ON cf.currencyid = AC.currencyid
                             LEFT JOIN
                             CURRENCYHISTORY_V1 AS CH ON CH.CURRENCYID = CF.CURRENCYID AND
                                                         CH.CURRDATE = (
                                                                           SELECT MAX(CRHST.CURRDATE)
                                                                             FROM CURRENCYHISTORY_V1 AS CRHST
                                                                            WHERE CRHST.CURRENCYID = CF.CURRENCYID
                                                                       )
                       WHERE ca.TRANSDATE >= date('now', 'start of year', '-4 year', 'localtime') AND
                             ca.STATUS NOT IN ('V', 'D') AND
                             ca.TRANSCODE <> 'Transfer'
                  )
                  AS txd
       )
       AS mdata
 GROUP BY mdata.periode_month
 ORDER BY mdata.periode_month ASC;


text:
FROM gcr.io/distroless/static:latest

COPY build/monitor /

# nobody:nobody
USER 65534:65534
ENTRYPOINT ["/monitor"]


text:
namespace ppapi {

class TrackedCallback;

namespace proxy {

class PPAPI_PROXY_EXPORT FileSystemResource : public PluginResource,
                                              public thunk::PPB_FileSystem_API {
 public:
  // Creates a new FileSystemResource. The resource must be subsequently opened
  // via Open() before use.
  FileSystemResource(Connection connection,
                     PP_Instance instance,
                     PP_FileSystemType type);
  // Creates a FileSystemResource, attached to an existing pending host
  // resource. The |pending_renderer_id| and |pending_browser_id| must be
  // already-opened file systems.
  FileSystemResource(Connection connection,
                     PP_Instance instance,
                     int pending_renderer_id,
                     int pending_browser_id,
                     PP_FileSystemType type);

  FileSystemResource(const FileSystemResource&) = delete;
  FileSystemResource& operator=(const FileSystemResource&) = delete;

  ~FileSystemResource() override;

  // Resource overrides.
  thunk::PPB_FileSystem_API* AsPPB_FileSystem_API() override;

  // PPB_FileSystem_API implementation.
  int32_t Open(int64_t expected_size,
               scoped_refptr<TrackedCallback> callback) override;
  PP_FileSystemType GetType() override;
  void OpenQuotaFile(PP_Resource file_io) override;
  void CloseQuotaFile(PP_Resource file_io) override;
  int64_t RequestQuota(
      int64_t amount,
      thunk::PPB_FileSystem_API::RequestQuotaCallback callback) override;

  int32_t InitIsolatedFileSystem(const std::string& fsid,
                                 PP_IsolatedFileSystemType_Private type,
                                 base::OnceCallback<void(int32_t)> callback);

 private:
  struct QuotaRequest {
    QuotaRequest(int64_t amount,
                 thunk::PPB_FileSystem_API::RequestQuotaCallback callback);
    QuotaRequest(QuotaRequest&& other);
    QuotaRequest& operator=(QuotaRequest&& other);
    ~QuotaRequest();

    int64_t amount;
    thunk::PPB_FileSystem_API::RequestQuotaCallback callback;
  };

  // Called when the host has responded to our open request.
  void OpenComplete(scoped_refptr<TrackedCallback> callback,
                    const ResourceMessageReplyParams& params);

  // Called when the host has responded to our InitIsolatedFileSystem request.
  void InitIsolatedFileSystemReply(base::OnceClosure callback,
                                   const ResourceMessageReplyParams& params);
  void InitIsolatedFileSystemComplete(
      base::OnceCallback<void(int32_t)> callback);

  void ReserveQuota(int64_t amount);
  typedef std::map<int32_t, int64_t> OffsetMap;
  void ReserveQuotaComplete(const ResourceMessageReplyParams& params,
                            int64_t amount,
                            const OffsetMap& max_written_offsets);

  PP_FileSystemType type_;
  bool called_open_;
  uint32_t callback_count_;
  int32_t callback_result_;

  std::set<PP_Resource> files_;
  base::queue<QuotaRequest> pending_quota_requests_;
  int64_t reserved_quota_;
  bool reserving_quota_;
};

}  // namespace proxy
}  // namespace ppapi

#endif  // PPAPI_PROXY_FILE_SYSTEM_RESOURCE_H_


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Florence</title>

    <link rel="manifest" href="/florence/dist/manifest.json">

    <link href="https://cdn.ons.gov.uk/assets/florence/jquery-tag-it/jquery.tagit.css" rel="stylesheet" type="text/css">
    <link href="https://cdn.ons.gov.uk/assets/florence/jquery-tag-it/tagit.ui-florence.css" rel="stylesheet" type="text/css">
    <link href="https://cdn.ons.gov.uk/assets/florence/pagedown/pagedown.css" rel="stylesheet" type="text/css">
    <link href="https://cdn.ons.gov.uk/vendor/sweetalert/1.0.0/sweetalert.css" rel="stylesheet" type="text/css">
    <link href="https://cdn.ons.gov.uk/vendor/select2/select2.min.css" rel="stylesheet" />
    <link href="/florence/dist/legacy-assets/css/main.min.css" rel="stylesheet" type="text/css">
    <link href="/florence/dist/css/tablebuilder.css" rel="stylesheet" type="text/css">

Enable Javascript to use Florence


text:
NS_FS_BEGIN

JavaVM* JniUtil::getJavaVM()
{
	return Sys::getJavaVM();
}
void JniUtil::setJavaVM(JavaVM* jvm)
{
	Sys::setJavaVM(jvm);
}

JNIEnv* JniUtil::getEnv(bool attach)
{
	JNIEnv* env=0;
	JavaVM* jvm=Sys::getJavaVM();
	if(jvm->GetEnv((void**)&env,JNI_VERSION_1_4)!=JNI_OK)
	{
		FS_TRACE_WARN("Failed To get JNI Environment");
		return NULL;
	}
	if(attach)
	{
		if(jvm->AttachCurrentThread(&env,NULL)<0)
		{
			FS_TRACE_WARN("Failed to Attach Current Thread");
		}
	}

	return env;
}

void JniUtil::attachCurrentThread()
{
	JavaVM* jvm=Sys::getJavaVM();
	JNIEnv* env=getEnv(false);
	if(jvm->AttachCurrentThread(&env,0)<0)
	{
		FS_TRACE_WARN("Failed to Attach Current Thread");
	}
}

jclass JniUtil::getClass(const char* cls_name)
{
	JNIEnv* env=JniUtil::getEnv();
	jclass ret=0;
	ret=env->FindClass(cls_name);
	FS_TRACE_WARN_ON(ret==0,"Can't Find Class(cls_name)");
	return ret;
}

jmethodID JniUtil::getStaticMethodID(jclass cls,const char* method_name,const char* sig)
{
	JNIEnv* env=JniUtil::getEnv();
	jmethodID method_id=env->GetStaticMethodID(cls,method_name,sig);
	FS_TRACE_WARN_ON(method_id==0,"Can't Find Method(%s) Sig(%s)",method_name,sig);
	return method_id;
}

jmethodID JniUtil::getMethodID(jclass cls,const char* method_name,const char* sig)
{
	JNIEnv* env=JniUtil::getEnv();
	jmethodID method_id=env->GetMethodID(cls,method_name,sig);
	FS_TRACE_WARN_ON(method_id==0,"Can't Find Method(%s) Sig(%s)",method_name,sig);
	return method_id;
}

NS_FS_END


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

class core_user_renderer extends plugin_renderer_base {

    /**
     * Prints user files tree view
     * @return string
     */
    public function user_files_tree() {
        return $this->render(new user_files_tree);
    }

    public function render_user_files_tree(user_files_tree $tree) {
        if (empty($tree->dir['subdirs']) && empty($tree->dir['files'])) {
            $html = $this->output->box(get_string('nofilesavailable', 'repository'));
        } else {
            $htmlid = 'user_files_tree_'.uniqid();
            $module = array('name'=>'core_user', 'fullpath'=>'/user/module.js');
            $this->page->requires->js_init_call('M.core_user.init_tree', array(false, $htmlid), false, $module);
            $html = '
';
            $html .= $this->htmllize_tree($tree, $tree->dir);
            $html .= '
';
        }
        return $html;
    }

    /**
     * Internal function - creates htmls structure suitable for YUI tree.
     */
    protected function htmllize_tree($tree, $dir) {
        global $CFG;
        $yuiconfig = array();
        $yuiconfig['type'] = 'html';

        if (empty($dir['subdirs']) and empty($dir['files'])) {
            return '';
        }
        $result = '
';
        foreach ($dir['subdirs'] as $subdir) {
            $image = $this->output->pix_icon(file_folder_icon(), $subdir['dirname'], 'moodle', array('class'=>'icon'));
            $result .= '

'.$image.' '.s($subdir['dirname']).'
 '.$this->htmllize_tree($tree, $subdir).'
';
        }
        foreach ($dir['files'] as $file) {
            $url = file_encode_url("$CFG->wwwroot/pluginfile.php", '/'.$tree->context->id.'/user/private'.$file->get_filepath().$file->get_filename(), true);
            $filename = $file->get_filename();
            $image = $this->output->pix_icon(file_file_icon($file), $filename, 'moodle', array('class'=>'icon'));
            $result .= '

'.$image.' '.html_writer::link($url, $filename).'

';
        }
        $result .= '
';

        return $result;
    }
}

class user_files_tree implements renderable {
    public $context;
    public $dir;
    public function __construct() {
        global $USER;
        $this->context = context_user::instance($USER->id);
        $fs = get_file_storage();
        $this->dir = $fs->get_area_tree($this->context->id, 'user', 'private', 0);
    }
}


text:
/* eslint-disable no-use-before-define */

import * as instance from './instance';

function dump() {
  const hl = instance.get();
  const { cursor, stats, lastId, queries } = hl;
  console.log('[DUMP]', { cursor, stats, lastId, queries });
}

export { dump };


text:
import { ILogger, IShell, IShellRunOptions, ITaskChain } from '../definitions';
export declare const ERROR_SHELL_COMMAND_NOT_FOUND = "SHELL_COMMAND_NOT_FOUND";
export declare class Shell implements IShell {
    protected tasks: ITaskChain;
    protected log: ILogger;
    constructor(tasks: ITaskChain, log: ILogger);
    run(command: string, args: string[], {showCommand, showError, fatalOnNotFound, fatalOnError, showExecution, showSpinner, truncateErrorOutput, ...crossSpawnOptions}: IShellRunOptions): Promise<string>;
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using WII.HID.Lib;

namespace Testtool
{
    public partial class frmMain : Form
    {
        HIDDevice _device; //Wii controller object

        //Accelerometer rectangles
        System.Drawing.SolidBrush redBrush;
        System.Drawing.Graphics acceleroGraphics;

        //Drawing canvas
        private System.Drawing.Graphics graphics;

        int[] drawnPointsX = new int[0];
        int[] drawnPointsY = new int[0];

        public frmMain()
        {
            InitializeComponent();

            _device = HIDDevice.GetHIDDevice(0x57E, 0x306);

            //LED event handlers
            chkLed1.CheckedChanged += new System.EventHandler(chkLedHandler);
            chkLed2.CheckedChanged += new System.EventHandler(chkLedHandler);
            chkLed3.CheckedChanged += new System.EventHandler(chkLedHandler);
            chkLed4.CheckedChanged += new System.EventHandler(chkLedHandler);

            System.Timers.Timer statusUpdateTimer = new System.Timers.Timer();
            statusUpdateTimer.Elapsed += new ElapsedEventHandler(requestStatusUpdate);
            statusUpdateTimer.Interval = 1000;
            statusUpdateTimer.Enabled = true;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {

            enableIRCamera();
            createReport(0x12, new byte[2] { 0, 0x37 }); // start data stream via report 0x37
        }

        private void createReport(byte ReportID, byte[] data = null)
        {
            HIDReport report = _device.CreateReport();
            report.ReportID = ReportID;
            if(data != null)
            {
                for (int i = 0; i < data.Length; ++i)
                {
                    report.Data[i] = data[i];
                }
            }
            _device.WriteReport(report);
            _device.ReadReport(OnReadReport);
        }

        private void requestStatusUpdate(object source, ElapsedEventArgs e)
        {
            if (chkRumble.Checked) createReport(0x15, new byte[] { 1 });
            else createReport(0x15);
        }

        private void OnReadReport(HIDReport report)
        {
            if (this.InvokeRequired) { this.Invoke(new ReadReportCallback(OnReadReport), report); }
            else
            {
                switch (report.ReportID)
                {
                    case 0x20:
                        updateLeds(report);
                        pgbBattery.Value = Convert.ToInt32(report.Data[5]); // update battery
                        break;
                    case 0x37:
                        processButtonData(report);
                        processAccelerometerData(report);
                        processIRData(report);
                        break;
                }
                _device.ReadReport(OnReadReport);
            }
        }

        private void processIRData(HIDReport report)
        {
            int[,] IRPositions = getIRPositions(report);
            graphics = pcbDrawCanvas.CreateGraphics();

            lblIR1PosX.Text = IRPositions[0,0].ToString();
            lblIR2PosX.Text = IRPositions[1,0].ToString();
            lblIR3PosX.Text = IRPositions[2,0].ToString();
            lblIR4PosX.Text = IRPositions[3,0].ToString();

            lblIR1PosY.Text = IRPositions[0,1].ToString();
            lblIR2PosY.Text = IRPositions[1,1].ToString();
            lblIR3PosY.Text = IRPositions[2,1].ToString();
            lblIR4PosY.Text = IRPositions[3,1].ToString();

            if((report.Data[1] & 0x9F) == 0x4)
            {
                graphics.FillRectangle(new System.Drawing.SolidBrush(Color.Red), new Rectangle(1023-IRPositions[0, 0], IRPositions[0, 1], 10, 10));
                /*Array.Resize(ref drawnPointsX, drawnPointsX.Length + 1);
                Array.Resize(ref drawnPointsY, drawnPointsY.Length + 1);
                drawnPointsX[drawnPointsX.GetUpperBound(0)] = 1023 - IRPositions[0, 0];
                drawnPointsY[drawnPointsY.GetUpperBound(0)] = IRPositions[0, 1];*/

            }
            else
            {
                graphics.Clear(pcbDrawCanvas.BackColor);
                graphics.FillRectangle(new System.Drawing.SolidBrush(Color.Red), new Rectangle(1023 - IRPositions[0, 0], IRPositions[0, 1], 10, 10));

                /*for(int i=0;i<drawnPointsX.Length;++i)
                {
                    graphics.FillRectangle(new System.Drawing.SolidBrush(Color.Red), new Rectangle(drawnPointsX[i], drawnPointsY[i], 10, 10));
                }*/
            }

        }

        private void processButtonData(HIDReport report)
        {
                switch (report.Data[0] & 0x1F) //0x1F -> eerste 5 bits
                {
                    case 0x1: //Left
                        btnDirectionLeft.BackColor = Color.Red;
                        break;
                    case 0x2: // Right
                        btnDirectionRight.BackColor = Color.Red;
                        break;
                    case 0x4: //Down
                        btnDirectionDown.BackColor = Color.Red;
                        break;
                    case 0x5: //left-down
                        btnDirectionLeft.BackColor = Color.Red;
                        btnDirectionDown.BackColor = Color.Red;
                        break;
                    case 0x6: //right-down
                        btnDirectionRight.BackColor = Color.Red;
                        btnDirectionDown.BackColor = Color.Red;
                        break;
                    case 0x8: //Up
                        btnDiretionUp.BackColor = Color.Red;
                        break;
                    case 0x9: //left-up
                        btnDirectionLeft.BackColor = Color.Red;
                        btnDiretionUp.BackColor = Color.Red;
                        break;
                    case 0xA: //right-up
                        btnDirectionRight.BackColor = Color.Red;
                        btnDiretionUp.BackColor = Color.Red;
                        break;
                    case 0x10: // PLUS
                        btnPlus.BackColor = Color.Red;
                        break;
                    default:
                        foreach (Control ctrl in grpControllerFront.Controls) if(ctrl is Button) ctrl.BackColor = Color.White;
                        break;
                }

                switch(report.Data[1] & 0x9F) //0x9F -> eerste 5 bits + laatste bit
                {
                    case 0x1: //button 2
                        btn2.BackColor = Color.Red;
                        break;
                    case 0x2: //button 1
                        btn1.BackColor = Color.Red;
                        break;
                    case 0x4: //button B
                        btnB.BackColor = Color.Red;
                        break;
                    case 0x8: //button A
                        btnA.BackColor = Color.Red;
                        break;
                    case 0x10: //button -
                        btnMinus.BackColor = Color.Red;
                        break;
                    case 0x80: //button home
                        btnHome.BackColor = Color.Red;
                        break;
                    default:
                        foreach (Control ctrl in grpControllerRear.Controls) if (ctrl is Button) ctrl.BackColor = Color.White;
                        break;
                }
        }

        private void updateLeds(HIDReport report)
        {
            bool[] activeLeds = new bool[4];
            byte ledStatus = report.Data[2];
            byte mask = 1 << 4;

            for(int i=0;i<4;++i)
            {
                if((mask & ledStatus) > 0)
                {
                    switch (i)
                    {
                        case 0:
                            chkLed1.Checked = true;
                            break;
                        case 1:
                            chkLed2.Checked = true;
                            break;
                        case 2:
                            chkLed3.Checked = true;
                            break;
                        case 3:
                            chkLed4.Checked = true;
                            break;
                    }
                }
                else
                {
                    switch (i)
                    {
                        case 0:
                            chkLed1.Checked = false;
                            break;
                        case 1:
                            chkLed2.Checked = false;
                            break;
                        case 2:
                            chkLed3.Checked = false;
                            break;
                        case 3:
                            chkLed4.Checked = false;
                            break;
                    }
                }
                mask <<= 1;
            }
        }

        private void processAccelerometerData(HIDReport report)
        {
            float[] acceleroData = new float[3] { report.Data[2] / (float)255.0, report.Data[3] / (float)255.0, report.Data[4] / (float)255.0 }; //X,Y,Z

            drawAcceleroRectangles(acceleroData);
        }

        private void chkLedHandler(object sender, EventArgs e)
        {
            HIDReport report = _device.CreateReport();
            report.ReportID = 0x11;

            int i = 0;
            byte ledsHexSum = 0;
            foreach (Control ctrl in grpLeds.Controls)
            {
                if (ctrl is CheckBox)
                {
                    i++;
                    if (((CheckBox)ctrl).Checked)
                    {
                        switch (i)
                        {
                            case 1:
                                ledsHexSum |= 0x10;
                                break;
                            case 2:
                                ledsHexSum |= 0x20;
                                break;
                            case 3:
                                ledsHexSum |= 0x40;
                                break;
                            case 4:
                                ledsHexSum |= 0x80;
                                break;
                        }
                    }
                }
            }
            report.Data[0] = ledsHexSum;
            _device.WriteReport(report);
        }

        private void chkRumble_CheckedChanged(object sender, EventArgs e)
        {
            if(chkRumble.Checked) createReport(0x11, new byte[] { 1 });
            else createReport(0x11, new byte[] { 0 });
        }

        private void drawAcceleroRectangles(float[] acceleroData)
        {
            acceleroGraphics = grpControllerRear.CreateGraphics();
            acceleroGraphics.Clear(grpControllerRear.BackColor);

            redBrush = new System.Drawing.SolidBrush(Color.Red);

            float accelX, accelY, accelZ;
            if (acceleroData[0] >= .5) accelX = (acceleroData[0] - (float).5)*2;
            else accelX = (acceleroData[0] - (float).5)*2;
            if (acceleroData[1] >= .5) accelY = (acceleroData[1] - (float).5)*2;
            else accelY = (acceleroData[1] - (float).5)*2;
            if (acceleroData[2] >= .5) accelZ = (acceleroData[2] - (float).5)*2;
            else accelZ = (acceleroData[2] - (float).5)*2;

            if (accelX < 0) acceleroGraphics.FillRectangle(redBrush, new Rectangle(155 - Convert.ToInt16(-(accelX * 150)), 440, Convert.ToInt16(-(accelX * 150)), 50));//X-
            else acceleroGraphics.FillRectangle(redBrush, new Rectangle(155, 440, (Convert.ToInt16(accelX * 150)), 50));//X+

            if (accelZ < 0) acceleroGraphics.FillRectangle(redBrush, new Rectangle(125, 440 - Convert.ToInt16(-(accelZ * 150)), 50, Convert.ToInt16(-(accelZ * 150))));//Z-
            else acceleroGraphics.FillRectangle(redBrush, new Rectangle(125, 490, 50, Convert.ToInt16(accelZ * 150)));//Z+

            if (accelY < 0) acceleroGraphics.FillRectangle(redBrush, new Rectangle(155 - Convert.ToInt16(-(accelY * 150)), 650, Convert.ToInt16(-(accelY * 150)), 50));//Y-
            else acceleroGraphics.FillRectangle(redBrush, new Rectangle(155, 650, Convert.ToInt16(accelY * 150), 50));//Y+

            lblAccelerationX.Text = accelX.ToString();
            lblAccelerationY.Text = accelY.ToString();
            lblAccelerationZ.Text = accelZ.ToString();
        }

        private void enableIRCamera()
        {
            createReport(0x13, new byte[1] { 0x04 });
            createReport(0x1a, new byte[1] { 0x04 });
            writeDataToRegister(0xB00030, new byte[1] { 0x08 });

            //Gevoeligheid Wii level 3
            writeDataToRegister(0xB00000, new byte[9] { 0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xaa, 0x00, 0x64 });
            writeDataToRegister(0xb0001a, new byte[2] { 0x63, 0x03 });

            writeDataToRegister(0xB00033, new byte[1] { 0x1 });
            writeDataToRegister(0xB00030, new byte[1] { 0x8 });

        }
        private void writeDataToRegister(int address, byte[] data)
        {
            if ((_device != null))
            {
                int index = 0;
                while (index < data.Length)
                {
                    // Bepaal hoeveel bytes er nog moeten verzonden worden
                    int leftOver = data.Length - index;

                    // We kunnen maximaal 16 bytes per keer verzenden dus moeten we het aantal te verzenden bytes daarop limiteren
                    int count = (leftOver > 16 ? 16 : leftOver);
                    int tempAddress = address + index;
                    HIDReport report = _device.CreateReport();
                    report.ReportID = 0x16;
                    report.Data[0] = (byte)((tempAddress & 0x4000000) >> 0x18);
                    report.Data[1] = (byte)((tempAddress & 0xff0000) >> 0x10);
                    report.Data[2] = (byte)((tempAddress & 0xff00) >> 0x8);
                    report.Data[3] = (byte)((tempAddress & 0xff));
                    report.Data[4] = (byte)count;
                    Buffer.BlockCopy(data, index, report.Data, 5, count);
                    _device.WriteReport(report);
                    index += 16;
                }
            }
        }

        private int[,] getIRPositions(HIDReport report)
        {
            //5 - 9 / 10- 14
            int x1 = report.Data[5] | (report.Data[7] & 3 << 4) << 4;
            int x2 = report.Data[8] | (report.Data[7] & 3) << 8;
            int x3 = report.Data[10] | (report.Data[12] & 3 << 4) << 4;
            int x4 = report.Data[13] | (report.Data[12] & 3) << 8;

            int y1 = report.Data[6] | (report.Data[7] & 3 << 6) << 2;
            int y2 = report.Data[9] | (report.Data[7] & 3 << 2) << 6;
            int y3 = report.Data[11] | (report.Data[12] & 3 << 6) << 2;
            int y4 = report.Data[14] | (report.Data[12] & 3 << 2) << 6;

            return new int[4,2] {{x1,y1}, {x2,y2},{x3,y3},{x4,y4}};
        }

    }

}


text:
node.default['nginx']['init_style'] = "init"
node.default['nginx']['install_method'] = 'source'
node.default['nginx']['source']['version'] = '1.4.1'
node.default['nginx']['source']['url'] = "http://nginx.org/download/nginx-#{node['nginx']['source']['version']}.tar.gz"
node.default['nginx']['source']['prefix']                  = "/opt/nginx-#{node['nginx']['source']['version']}"
node.default['nginx']['source']['conf_path']               = "#{node['nginx']['dir']}/nginx.conf"
node.default['nginx']['source']['sbin_path']               = "#{node['nginx']['source']['prefix']}/sbin/nginx"
node.default['nginx']['source']['default_configure_flags'] = [
  "--prefix=#{node['nginx']['source']['prefix']}",
  "--conf-path=#{node['nginx']['dir']}/nginx.conf",
  "--sbin-path=#{node['nginx']['source']['sbin_path']}"
]

# Set sendfile to off when in development mode.
# http://smotko.si/nginx-static-file-problem/
if node['gamification']['debug']
    node.default['nginx']['sendfile'] = 'off'
end

include_recipe 'nginx::default'

template "nginx_proxy_config" do
  path File.join(node['nginx']['dir'], 'proxy.conf')
  source 'proxy.conf.erb'
end

template "gamification_nginx_config" do
  path "#{node['nginx']['dir']}/sites-enabled/gamification.conf"
  source "gamification.conf.erb"
  notifies :reload, "service[nginx]", :immediately
end


text:
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

from dv_apps.dvobjects.models import DvObject
from dv_apps.datasets.models import DatasetVersion
from dv_apps.dataverses.models import Template

class MetadataBlock(models.Model):
    displayname = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    owner = models.ForeignKey(DvObject, blank=True, null=True)

    def __str__(self):
        return '%s (%s)' % (self.name, self.displayname)

    class Meta:
        managed = False
        db_table = 'metadatablock'

class DatasetFieldType(models.Model):
    name = models.TextField(blank=True, null=True)
    required = models.BooleanField()
    title = models.TextField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    fieldtype = models.CharField(max_length=255)

    advancedsearchfieldtype = models.BooleanField()
    allowcontrolledvocabulary = models.BooleanField()
    allowmultiples = models.BooleanField()

    displayformat = models.CharField(max_length=255, blank=True, null=True)
    displayoncreate = models.BooleanField()
    displayorder = models.IntegerField(blank=True, null=True)
    facetable = models.BooleanField()

    watermark = models.CharField(max_length=255, blank=True, null=True)

    metadatablock = models.ForeignKey(MetadataBlock, blank=True, null=True)
    parentdatasetfieldtype = models.ForeignKey('self', blank=True, null=True)

    def __str__(self):
        return '%s (%s)' % (self.name, self.fieldtype)

    class Meta:
        managed = False
        db_table = 'datasetfieldtype'

class ControlledVocabularyValue(models.Model):
    strvalue = models.TextField()
    datasetfieldtype = models.ForeignKey(DatasetFieldType)
    identifier = models.CharField(max_length=255, blank=True, null=True)
    displayorder = models.IntegerField()

    def __str__(self):
        return self.strvalue

    class Meta:
        ordering = ('displayorder',)
        managed = False
        db_table = 'controlledvocabularyvalue'

class DatasetField(models.Model):
    #id = models.IntegerField(primary_key=True)
    datasetfieldtype = models.ForeignKey(DatasetFieldType)
    datasetversion = models.ForeignKey(DatasetVersion, blank=True, null=True)
    parentdatasetfieldcompoundvalue = models.ForeignKey('DatasetFieldCompoundValue', blank=True, null=True)
    template = models.ForeignKey(Template, blank=True, null=True)

    def allow_multiples(self):
        """
        Retrieve the "allowmultiples" from the DatasetFieldType
        """
        return self.datasetfieldtype.allowmultiples

    def __str__(self):
        if not self.id:
            return '(not saved)'
        return '%d' % (self.id)
        #return '%s v%s' % (self.datasetfieldtype, self.datasetversion)

    class Meta:
        managed = False
        db_table = 'datasetfield'

@python_2_unicode_compatible
class DatasetFieldControlledVocabularyValue(models.Model):
    datasetfield = models.ForeignKey(DatasetField, primary_key=True)
    controlledvocabularyvalues = models.ForeignKey(ControlledVocabularyValue)

    def __str__(self):
        return '%s' % self.datasetfield

    class Meta:
        managed = False
        db_table = 'datasetfield_controlledvocabularyvalue'
        unique_together = (('datasetfield', 'controlledvocabularyvalues'),)
        #unique_together = (('datasetfield_id', 'controlledvocabularyvalues_id'),)

'''
class DatasetFieldControlledVocabularyValue(models.Model):
    """
    Change name of
    """
    datasetfield = models.ForeignKey(DatasetField)
    controlledvocabularyvalues = models.ForeignKey(ControlledVocabularyValue)

    def __str__(self):
        return '%s - %s' % (self.datasetfield.id, self.controlledvocabularyvalues)

    class Meta:
        managed = False
        ordering = ('datasetfield', 'controlledvocabularyvalues')
        db_table = 'datasetfield_controlledvocabularyvalue'
        unique_together = (('datasetfield', 'controlledvocabularyvalues'),)
'''

class DatasetFieldCompoundValue(models.Model):
    displayorder = models.IntegerField(blank=True, null=True)
    parentdatasetfield = models.ForeignKey(DatasetField, blank=True, null=True)

    def __str__(self):
        if not self.id:
            return '(not saved)'
        return '%s' % self.id
        #return '%s (%s) ' % (self.parentdatasetfield, self.displayorder, )

    class Meta:
        managed = False
        db_table = 'datasetfieldcompoundvalue'

@python_2_unicode_compatible
class DatasetFieldValue(models.Model):
    displayorder = models.IntegerField(blank=True, null=True)
    value = models.TextField(blank=True, null=True)
    datasetfield = models.ForeignKey(DatasetField)

    def __str__(self):
        return '%s' % (self.value)

    class Meta:
        managed = False
        db_table = 'datasetfieldvalue'


text:
console.log("I've been required by Webpack");
import style from "../scss/main.scss";


text:
/*
* PROJECT:          Atomix Development
* LICENSE:          BSD 3-Clause (LICENSE.md)
* PURPOSE:          Literal Assembly Codes
* PROGRAMMERS:      Aman Priyadarshi (aman.eureka@gmail.com)
*/

namespace Atomixilc.Machine
{
    public class Literal : Instruction
    {
        string mCode;

        public Literal(string aCode)
            : base(string.Empty)
        {
            mCode = aCode;
        }

        public Literal(string aCode, params object[] aParams)
            : base(string.Empty)
        {
            mCode = string.Format(aCode, aParams);
        }

        public override string ToString()
        {
            return mCode;
        }
    }
}


text:
/* jshint esnext: true */

import IntlMessageFormat from 'intl-messageformat';
import IntlRelativeFormat from 'intl-relativeformat';

import defaultLocale from './en';

import IntlMixin from './mixin';
import FormattedDate from './components/date';
import FormattedTime from './components/time';
import FormattedRelative from './components/relative';
import FormattedNumber from './components/number';
import FormattedMessage from './components/message';
import FormattedHTMLMessage from './components/html-message';

export {
    IntlMixin,
    FormattedDate,
    FormattedTime,
    FormattedRelative,
    FormattedNumber,
    FormattedMessage,
    FormattedHTMLMessage
};

export function __addLocaleData(data) {
    IntlMessageFormat.__addLocaleData(data);
    IntlRelativeFormat.__addLocaleData(data);
}

__addLocaleData(defaultLocale);


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from caffe2.python import core

import numpy as np

class ParameterTags(object):
    BIAS = 'BIAS'
    WEIGHT = 'WEIGHT'
    COMPUTED_PARAM = 'COMPUTED_PARAM'

class ParameterType(object):
    DENSE = 'dense'
    SPARSE = 'sparse'

class ParameterInfo(object):

    def __init__(
            self, param_id, param, key=None, shape=None, length=None,
            grad=None, blob_copy=None):
        assert isinstance(param, core.BlobReference)
        self.param_id = param_id
        self.name = str(param)
        self.blob = param
        self.key = key
        self.shape = shape
        self.size = None if shape is None else np.prod(shape)
        self.length = max(1, length if length is not None else 1)
        self.grad = grad
        self._cloned_init_net = None
        # Optionally store equivalent copies of the blob
        # in different precisions (i.e. half and float copies)
        # stored as a dict of TensorProto.DataType -> BlobReference
        self.blob_copy = blob_copy
        # each param_info can have its own optimizer. It can be set within
        # OptimizerContext (caffe2/python/optimizer.py)
        self._optimizer = None

    def grad_type(self):
        # self.grad could be None for model parallelism with parameter server
        if self.grad is None:
            return
        return (
            ParameterType.SPARSE if isinstance(self.grad, core.GradientSlice)
            else ParameterType.DENSE)

    @property
    def parameter(self):
        return self.blob

    @property
    def optimizer(self):
        return self._optimizer

    @optimizer.setter
    def optimizer(self, value):
        assert self._optimizer is None, "optimizer has already been set"
        self._optimizer = value

    def __str__(self):
        return self.name


text:
import {FetchResponse, fetchPolyfill} from '../../src/service/xhr-impl';
import {batchedXhrServiceForTesting} from '../../src/service/batched-xhr-impl';

describes.sandboxed('BatchedXhr', {}, () => {
  // Since if it's the Native fetch, it won't use the XHR object so
  // mocking and testing the request becomes not doable.
  function getPolyfillWin() {
    return {
      location: {href: 'https://acme.com/path'},
      fetch: fetchPolyfill,
    };
  }

  describes.fakeWin('#fetch', getPolyfillWin(), env => {
    const TEST_OBJECT = {a: {b: [{c: 2}, {d: 4}]}};
    const TEST_RESPONSE = JSON.stringify(TEST_OBJECT);
    const mockXhr = {
      status: 200,
      responseText: TEST_RESPONSE,
    };
    const textInit = {headers: {'Accept': 'text/plain'}};
    const jsonInit = {headers: {'Accept': 'application/json'}};
    let xhr;
    let fetchStub;

    beforeEach(() => {
      xhr = batchedXhrServiceForTesting(env.win);
      fetchStub = env.sandbox.stub(xhr, 'fetchAmpCors_',
          () => Promise.resolve(new FetchResponse(mockXhr)));
    });

    it('should fetch a generic request once for identical URLs', () => {
      return Promise.all([
        xhr.fetch('/get?k=v1').then(response => response.text()),
        xhr.fetch('/get?k=v1').then(response => response.text()),
        xhr.fetch('/get?k=v1').then(response => response.text()),
      ]).then(results => {
        expect(fetchStub).to.be.calledOnce;
        expect(results[0]).to.equal(TEST_RESPONSE);
        expect(results[1]).to.equal(TEST_RESPONSE);
        expect(results[2]).to.equal(TEST_RESPONSE);
      });
    });

    it('should separately cache generic fetches with identical URLs' +
        'but different "Accept" headers', () => {
      return Promise.all([
        xhr.fetch('/get?k=v1', textInit).then(response => response.text()),
        xhr.fetch('/get?k=v1', textInit).then(response => response.text()),
        xhr.fetch('/get?k=v1', jsonInit).then(response => response.json()),
        xhr.fetch('/get?k=v1', jsonInit).then(response => response.json()),
      ]).then(results => {
        expect(fetchStub).to.be.calledTwice;
        expect(results[0]).to.equal(TEST_RESPONSE);
        expect(results[1]).to.equal(TEST_RESPONSE);
        expect(results[2]).to.jsonEqual(TEST_OBJECT);
        expect(results[3]).to.jsonEqual(TEST_OBJECT);
      });
    });

    it('should cache the same as the convenience methods', () => {
      return Promise.all([
        xhr.fetch('/get?k=v1', jsonInit).then(response => response.json()),
        xhr.fetchJson('/get?k=v1').then(res => res.json()),
      ]).then(results => {
        expect(fetchStub).to.be.calledOnce;
        expect(results[0]).to.jsonEqual(TEST_OBJECT);
        expect(results[1]).to.jsonEqual(TEST_OBJECT);
      });
    });
  });

  describes.fakeWin('#fetchJson', getPolyfillWin(), env => {
    const TEST_OBJECT = {a: {b: [{c: 2}, {d: 4}]}};
    const TEST_RESPONSE = JSON.stringify(TEST_OBJECT);
    const mockXhr = {
      status: 200,
      responseText: TEST_RESPONSE,
      responseType: 'json',
    };
    let xhr;
    let fetchStub;

    beforeEach(() => {
      xhr = batchedXhrServiceForTesting(env.win);
      fetchStub = env.sandbox.stub(xhr, 'fetchAmpCors_',
          () => Promise.resolve(new FetchResponse(mockXhr)));
    });

    it('should fetch JSON GET requests once for identical URLs', () => {
      return Promise.all([
        xhr.fetchJson('/get?k=v1').then(res => res.json()),
        xhr.fetchJson('/get?k=v1').then(res => res.json()),
      ]).then(results => {
        expect(fetchStub).to.be.calledOnce;
        expect(results[0]).to.jsonEqual(TEST_OBJECT);
        expect(results[1]).to.jsonEqual(TEST_OBJECT);
      });
    });

    it('should not be affected by fragments passed in the URL', () => {
      return Promise.all([
        xhr.fetchJson('/get?k=v1#a.b[0].c').then(res => res.json()),
        xhr.fetchJson('/get?k=v1#a.b[1].d').then(res => res.json()),
      ]).then(results => {
        expect(fetchStub).to.be.calledOnce;
        expect(results[0]).to.jsonEqual(TEST_OBJECT);
        expect(results[1]).to.jsonEqual(TEST_OBJECT);
      });
    });

    it('should not cache for POST requests', () => {
      return Promise.all([
        xhr.fetchJson('/get?k=v1', {method: 'POST', body: {}}),
        xhr.fetchJson('/get?k=v1', {method: 'POST', body: {}}),
      ]).then(() => {
        expect(fetchStub).to.be.calledTwice;
      });
    });
  });

  describes.realWin('#fetchDocument', getPolyfillWin(), env => {
    const TEST_CONTENT = '<b>Hello, world';
    const TEST_RESPONSE_TEXT = '<!doctype html><html><body>' + TEST_CONTENT;
    let xhr;
    let fetchStub;
    let testResponseDoc;

    beforeEach(() => {
      const doc = env.win.document;
      testResponseDoc = doc.implementation.createHTMLDocument();
      testResponseDoc.body.innerHTML = TEST_CONTENT;
      const mockXhr = {
        status: 200,
        responseText: TEST_RESPONSE_TEXT,
        responseXML: testResponseDoc,
        responseType: 'text/html',
      };
      xhr = batchedXhrServiceForTesting(env.win);
      fetchStub = env.sandbox.stub(xhr, 'fetchAmpCors_',
          () => Promise.resolve(new FetchResponse(mockXhr)));
    });

    it('should fetch document GET requests once for identical URLs', () => {
      return Promise.all([
        xhr.fetchDocument('/get?k=v1'),
        xhr.fetchDocument('/get?k=v1'),
      ]).then(results => {
        expect(fetchStub).to.be.calledOnce;
        expect(results[0].isEqualNode(testResponseDoc)).to.be.true;
        expect(results[1].isEqualNode(testResponseDoc)).to.be.true;
      });
    });

    it('should not cache for POST requests', () => {
      return Promise.all([
        xhr.fetchDocument('/get?k=v1', {method: 'POST', body: {}}),
        xhr.fetchDocument('/get?k=v1', {method: 'POST', body: {}}),
      ]).then(results => {
        expect(fetchStub).to.be.calledTwice;
        expect(results[0].isEqualNode(testResponseDoc)).to.be.true;
        expect(results[1].isEqualNode(testResponseDoc)).to.be.true;
      });
    });
  });

  describes.fakeWin('#fetchText', getPolyfillWin(), env => {
    const TEST_RESPONSE = 'Hello, world!';
    const mockXhr = {
      status: 200,
      responseText: TEST_RESPONSE,
    };
    let xhr;
    let fetchStub;

    beforeEach(() => {
      xhr = batchedXhrServiceForTesting(env.win);
      fetchStub = env.sandbox.stub(xhr, 'fetchAmpCors_',
          () => Promise.resolve(new FetchResponse(mockXhr)));
    });

    it('should fetch text GET requests once for identical URLs', () => {
      return Promise.all([
        xhr.fetchText('/get?k=v1').then(res => res.text()),
        xhr.fetchText('/get?k=v1').then(res => res.text()),
      ]).then(results => {
        expect(fetchStub).to.be.calledOnce;
        expect(results[0]).to.equal(TEST_RESPONSE);
        expect(results[1]).to.equal(TEST_RESPONSE);
      });
    });

    it('should not cache for POST requests', () => {
      return Promise.all([
        xhr.fetchText('/get?k=v1', {method: 'POST', body: {}}),
        xhr.fetchText('/get?k=v1', {method: 'POST', body: {}}),
      ]).then(() => {
        expect(fetchStub).to.be.calledTwice;
      });
    });
  });
});


text:
<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Hackathon
 * @package     Hackathon_MageMonitoring
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

interface Hackathon_MageMonitoring_Model_Widget_CacheStat extends Hackathon_MageMonitoring_Model_Widget
{
    /**
     * Returns maximum cache size in bytes or false if not implemented.
     *
     * @return int
     */
    public function getMemoryMax();
    /**
     * Returns used cache size in bytes or false if not implemented.
     *
     * @return int
     */
    public function getMemoryUsed();
    /**
     * Returns cache hit count or false if not implemented.
     *
     * @return int
     */
    public function getCacheHits();
    /**
     * Returns cache miss count or false if not implemented.
     *
     * @return int
     */
    public function getCacheMisses();
    /**
     * Whooosh!
     *
     * @return bool
     */
    public function flushCache();

}


text:
<!DOCTYPE html>

  <meta name="project_path" value="/web/tools/workbox/_project.yaml" />
  <meta name="book_path" value="/web/tools/workbox/_book.yaml" />
  <meta name="gtm_var" data-key="docType" data-value="reference">
  <title>Class: Plugin</title>
  <link href="jsdoc.css" rel="stylesheet">

workbox.<wbr>cacheableResponse.<wbr>Plugin

class   static

              Version
              v3.0.0-beta.0

A class implementing the cacheWillUpdate lifecycle callback. This makes it easier to add in cacheability checks to requests made via Workbox's built-in strategies.

Constructor

Plugin

 new Plugin(config)

To construct a new cacheable response Plugin instance you must provide at least one of the config properties.

If both statuses and headers are specified, then both conditions must be met for the Response to be considered cacheable.

Parameter

config

Object

Values in config have the following properties:

Parameter

statuses

Optional

Array of number

One or more status codes that a
                                  Response can have and be considered cacheable.

headers

Optional

Object with string properties

A mapping of header names and expected values that a Response can have and be considered cacheable. If multiple headers are provided, only one needs to be present.


text:
CouchGrams
==========

N-grams, Markov chains, and karma in CouchDB. Intended as a database for an IRC bot.

Installation
------------

Use the [CouchApp](/couchapp/couchapp) utility or [erica](/benoitc/erica) as follows.

    couchapp push . http://localhost:5984/<your_db>

API
---

The corpus consists of the `text` property of all documents without an `ignore` property.

For a shortcut for adding text to the corpus,

_PUT_ `_design/couchgrams/add_update` with a JSON object in the request body.
The object should have at least a string value for key `text`, and optionally
values for `sender` and `channel`.

To get a random n-gram given a prefix:

_GET_ `_design/couchgrams/_list/pick_ngram/ngrams?group_level=3&startkey=["Cats","are"]&endkey=["Cats","are",{}]&nonempty`

This will return an ngram such as ["Cats","are","cool"] or null if none match.
This address may need a cache-busting string appended to it, e.g. `&random=0981231023` See the example source for more information.

### Karma

Karma for id `name` is incremented by `name++` in the corpus and decremented with `name--` in the corpus. `name++++` increments by 2, `name--++-- decrements by 2, etc. This is in the style of [karma_bot](https://github.com/andrewwong1221/karma_bot).

To get karma for a name:

GET `_design/couchgrams/_rewrite/karma/<name>`

To get karma for all names, sorted by karma descending:

GET `_design/couchgrams/_rewrite/karma`

Append `?format=text` for textual output, otherwise JSON is returned.

Example App
-----------

`_design/couchgrams/index.html`

This simple web app lets you generate text using n-grams from your corpus.

Security
--------

Admins and users with the role `couchgrams` will be able to edit the corpus.

Importing Logs
--------------

There is a script included which lets you import IRC logs into the ngram corpus.
Currently only the irssi log format is supported.
The script `import_log.js` reads couchdb credentials from the same `.couchapprc`
file in the current directory that couchapp/erica reads.

```
./import_log.js ~/irclogs/*/#*.log
```

Todo
----

* Move import script stuff into a separate directory from the couchapp


text:
rs_allocation gIn;
rs_allocation gOut;

rs_script gScript;

// Magic factors
static uint32_t MosiacSize = 40;

// Static variables
static uint32_t _width;
static uint32_t _height;

static void setup() {
	_width = rsAllocationGetDimX(gIn);
	_height = rsAllocationGetDimY(gIn);
}

void filter() {
	setup();
    rsForEach(gScript, gIn, gOut, 0, 0);	// for each element of the input allocation,
    										// call root() method on gScript
}

void root(const uchar4 *v_in, uchar4 *v_out, const void *usrData, uint32_t x, uint32_t y) {
	float4 f4 = rsUnpackColor8888(*v_in);	// extract RGBA values, see rs_core.rsh

    float3 f3;
    float4 theF4;
    if (y % MosiacSize == 0 && x % MosiacSize == 0) {
		theF4 = f4;
	} else {
		uint32_t theX = MosiacSize * (x / MosiacSize);
		uint32_t theY = MosiacSize * (y / MosiacSize);
		theF4 = rsUnpackColor8888(*(const uchar4*)rsGetElementAt(gIn, theX, theY));
	}

    f3 = theF4.rgb;

    *v_out = rsPackColorTo8888(f3);
}


text:
package org.tiogasolutions.identity.engine;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.tiogasolutions.identity.kernel.store.InMemoryStore;
import org.tiogasolutions.lib.spring.TiogaPropertyPlaceholderConfigurer;
import org.tiogasolutions.notify.notifier.Notifier;
import org.tiogasolutions.notify.notifier.send.LoggingNotificationSender;

import java.io.FileNotFoundException;
import java.net.MalformedURLException;

@Profile("test")
@Configuration
@PropertySource("classpath:/tioga-identity-engine/spring-test.properties")
public class IdentityEngineTestSpringConfig {

    @Bean
    public Notifier notifier() {
        return new Notifier(new LoggingNotificationSender());
    }

    @Bean
    public InMemoryStore inMemoryStore() {
        return new InMemoryStore();
    }

    @Bean
    public TiogaPropertyPlaceholderConfigurer tiogaPropertyPlaceholderConfigurer() throws Exception {
        return new TiogaPropertyPlaceholderConfigurer("TIOGA_SECRET_PROPERTIES_FILE", "classpath:/tioga-identity-engine/spring.properties");
    }
}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using TODOAzureSample.Common;
using TODOAzureSample.Services.NavigationService;
using Windows.UI.Xaml.Navigation;

namespace TODOAzureSample.Mvvm
{
    public abstract class ViewModelBase : BindableBase, Services.NavigationService.INavigable
    {
        public virtual void OnNavigatedTo(object parameter, NavigationMode mode, IDictionary<string, object> state) { /* nothing by default */ }
        public virtual Task OnNavigatedFromAsync(IDictionary<string, object> state, bool suspending) { return Task.FromResult<object>(null); }
        public virtual void OnNavigatingFrom(Services.NavigationService.NavigatingEventArgs args) { /* nothing by default */ }

        public NavigationService NavigationService { get; set; }
        public Common.StateItems SessionState { get { return BootStrapper.Current.SessionState; } }

    }
}