text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SAEON.Observations.Data;
using Ext.Net;
using SubSonic;
using System.Text;
using System.Web.Security;

/// <summary>
/// Summary description for Roles
/// </summary>
public partial class _Roles : System.Web.UI.Page
{
	protected void Store1_RefreshData(object sender, StoreRefreshDataEventArgs e)
	{
		this.GridPanel1.GetStore().DataSource = RoleRepository.GetPagedList(e, e.Parameters[this.GridFilters1.ParamPrefix]);
	}

	protected void ValidateField(object sender, RemoteValidationEventArgs e)
	{

		//AspnetRoleCollection roles = new AspnetRoleCollection();

		//string checkColumn = String.Empty,
		//       errorMessage = String.Empty;

		//if (e.ID == "tfRoleName")
		//{
		//    roles = new AspnetRoleCollection().Where(AspnetRole.Columns.RoleName.ToLower(), tfRoleName.Text.ToLower()).Load();
		//    if (roles.Count != 0)
		//    {
		//        errorMessage = "The specified role name already exists";
		//    }

		//}

		//if (errorMessage != "")
		//{
		//    e.Success = false;
		//    e.ErrorMessage = errorMessage;
		//}
		//else
		//    e.Success = true;

	}

	protected void ShowDetails(object sender, DirectEventArgs e)
	{
		lblInfo.Hidden = true;
		lblInfo.Text = "";
		if (e != null)
		{

			string id = e.ExtraParams["id"];
			if (id != null)
			{
				AspnetRole role = new AspnetRole(id);

				tfID.Text = id;
				tfRoleName.Text = role.RoleName;
				tfComment.Text = role.Description;
			}
		}

		this.Window1.Show();
	}

	protected void NewRole(object sender, DirectEventArgs e)
	{
		tfID.Text = "";
		tfRoleName.Text = "";
		tfComment.Text = "";
		ShowDetails(null, null);

	}

	protected void DoDelete(object sender, DirectEventArgs e)
	{
		string ActionType = e.ExtraParams["type"];
		string recordID = e.ExtraParams["id"];

		if (ActionType == "Delete")
		{
			AspnetUsersInRoleCollection UiRCol = new AspnetUsersInRoleCollection().Where(AspnetUsersInRole.Columns.RoleId, SubSonic.Comparison.Equals, recordID).Load();

			if (UiRCol.Count != 0)
			{
				X.Msg.Show(new MessageBoxConfig
				{
					Title = "Error",
					Message = "Roles can't be deleted when they are connected to users.",
					Buttons = MessageBox.Button.OK,
					Icon = MessageBox.Icon.ERROR
				});
			}
			else
			{
				//AspnetRole.Delete(recordID);
				AspnetRole role = new AspnetRole(recordID);
				System.Web.Security.Roles.DeleteRole(role.RoleName);
			}

			GridPanel1.DataBind();

		}

		if (ActionType == "Edit")
		{
			ShowDetails(sender, e);
		}

		else if (ActionType == "RemoveModules")
		{
			RoleModuleCollection RMCol = new RoleModuleCollection().Where("RoleId", e.ExtraParams["RoleID"]).Where("ModuleId", recordID).Load();

			if (RMCol.Count == 1)
			{
				ModuleX module = new ModuleX(recordID);

				///////bad query	// (ModuleX.IdColumn, RoleModule.ModuleIDColumn)
				//SqlQuery q = new Select().From(RoleModule.Schema);
				//q.InnerJoin( ("ModuleX", "ID", "RoleModule", "ModuleID");
				//q.Where(RoleModule.Columns.RoleId).IsEqualTo(e.ExtraParams["RoleID"]);
				//q.And(ModuleX.Columns.ModuleID).IsEqualTo(module.ModuleID);
				//q.ExecuteAsCollection<RoleModuleCollection>();
				//RoleModuleCollection RMColAllInRole =
				VModuleRoleModuleCollection RMColAllInRole = new VModuleRoleModuleCollection()
					.Where(VModuleRoleModule.Columns.RoleId, SubSonic.Comparison.Equals, e.ExtraParams["RoleID"])
					.Where(VModuleRoleModule.Columns.BaseModuleID, SubSonic.Comparison.Equals, module.ModuleID)
					.Load();

				if (RMColAllInRole.Count == 1)
				{
					RoleModuleCollection rm = new RoleModuleCollection().Where("RoleId", e.ExtraParams["RoleID"]).Where("ModuleId", RMColAllInRole[0].BaseModuleID).Load();
					RoleModule.Delete(rm[0].Id);
					//RoleModule.Delete(RMColAllInRole[1].Id);

				}

				RoleModule.Delete(RMCol[0].Id);

				Store4.DataBind();
			}
			else
			{

				X.Msg.Show(new MessageBoxConfig
				{
					Title = "Error",
					Message = "Entry not found",
					Buttons = MessageBox.Button.OK,
					Icon = MessageBox.Icon.ERROR
				});
			}

		}
	}

	protected void SaveRole(object sender, DirectEventArgs e)
	{
		if (tfID.Text != "")
		{
			string id = tfID.Text;

			if (id != null)
			{

				AspnetRole role = new AspnetRole(id);
				//role.RoleName = tfRoleName.Text;
				//role.Description = tfComment.Text;
				//role.Save();
				if (!Roles.RoleExists(tfRoleName.Text))
				{
					string[] users = Roles.GetUsersInRole(role.RoleName);
					Roles.CreateRole(tfRoleName.Text);
					Roles.AddUsersToRole(users, tfRoleName.Text);
					Roles.RemoveUsersFromRole(users, role.RoleName);
					Roles.DeleteRole(role.RoleName);
				}

				role = new AspnetRole("RoleName", tfRoleName.Text);
				role.Description = tfComment.Text;
				role.Save();

				GridPanel1.DataBind();

				Window1.Hide();
			}
		}
		else  //new user
		{

			try
			{
				AspnetApplicationCollection aspApp = new AspnetApplicationCollection().Where(AspnetApplication.Columns.ApplicationName, Membership.ApplicationName).Load();
				AspnetRoleCollection roles = new AspnetRoleCollection().Where(AspnetRole.Columns.RoleName.ToLower(), tfRoleName.Text.ToLower()).Load();

				if ((aspApp.Count == 1) && (roles.Count == 0))
				{
					if (!Roles.RoleExists(tfRoleName.Text))
					{
						Roles.CreateRole(tfRoleName.Text);

						AspnetRole role = new AspnetRole("RoleName", tfRoleName.Text);
						role.Description = tfComment.Text;
						role.Save();
					}

					GridPanel1.DataBind();

					Window1.Hide();

					GridPanel1.DataBind();
				}
				else
				{
					lblInfo.Text = "Duplicate role names are not allowed.";
					lblInfo.Hidden = false;
				}

			}
			catch (Exception ex)
			{
				lblInfo.Text = ex.Message;
				lblInfo.Hidden = false;
				//throw;
			}
		}
	}

	protected void AcceptMod_Click(object sender, DirectEventArgs e)
	{
		StringBuilder result = new StringBuilder();

		RowSelectionModel sm = this.AModsGrid.SelectionModel.Primary as RowSelectionModel;
		RowSelectionModel RoleRow = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;

		string RoleID = RoleRow.SelectedRecordID;

		foreach (SelectedRow row in sm.SelectedRows)
		{
			AspnetRole role = new AspnetRole(AspnetRole.Columns.RoleId, RoleID);
			ModuleX module = new ModuleX(row.RecordID);

			if (module.ModuleID != null)		//auto add the parent module to the RoleModule table
			{

				if (new RoleModuleCollection().Where(RoleModule.Columns.ModuleID, SubSonic.Comparison.Equals, module.ModuleID).Where(RoleModule.Columns.RoleId, SubSonic.Comparison.Equals, role.RoleId).Load().Load().Count() == 0)
				{
					RoleModule roleModBase = new RoleModule();
					roleModBase.RoleId = role.RoleId;
					roleModBase.ModuleID = new Guid(module.ModuleID.ToString());
					roleModBase.Save();
				}
			}

			RoleModule roleMod = new RoleModule();
			roleMod.RoleId = role.RoleId;
			roleMod.ModuleID = module.Id;

			roleMod.Save();
		}

		Store4.DataBind();
		AvailableModsWindow.Hide();
	}

	protected void AMods_RefreshData(object sender, StoreRefreshDataEventArgs e)
	{
		if (e.Parameters["RoleID"] != null && e.Parameters["RoleID"].ToString() != "-1")
		{
			Guid Id = Guid.Parse(e.Parameters["RoleID"].ToString());

			ModuleXCollection ModavailCol = new Select()
					.From(ModuleX.Schema)
					.Where(ModuleX.IdColumn).NotIn(new Select(new String[] { RoleModule.Columns.ModuleID })
																	.From(RoleModule.Schema)
																	.Where(RoleModule.RoleIdColumn).IsEqualTo(Id))
					.And(ModuleX.Columns.ModuleID).IsNotNull()
					.OrderAsc(ModuleX.Columns.ModuleID, ModuleX.Columns.Description)
					.ExecuteAsCollection<ModuleXCollection>();

			Store3.DataSource = ModavailCol.ToList();
			Store3.DataBind();

		}
	}

	protected void ModsGrid_RefreshData(object sender, StoreRefreshDataEventArgs e)
	{

		if (e.Parameters["RoleID"] != null && e.Parameters["RoleID"].ToString() != "-1")
		{

			Guid Id = Guid.Parse(e.Parameters["RoleID"].ToString());

			ModuleXCollection ModCol = new Select()
					  .From(ModuleX.Schema).InnerJoin(RoleModule.ModuleIDColumn, ModuleX.IdColumn)
					  .Where(RoleModule.Columns.RoleId).IsEqualTo(Id).OrderAsc(ModuleX.Columns.ModuleID, ModuleX.Columns.Description)
					  .And(ModuleX.Columns.ModuleID).IsNotNull()
					  .ExecuteAsCollection<ModuleXCollection>();

			this.ModsGrid.GetStore().DataSource = ModCol;
			this.ModsGrid.GetStore().DataBind();
		}
	}
}


text:
'use strict';

const express = require('express');
const serviceLibrary = process.env.NODE_WEB_SERVICE || 'rest.js';
const service = require('./lib/'+serviceLibrary);
const morgan = require('morgan');

// Constants
const PORT = 3000;
const HOST = '0.0.0.0';
const fs = require('fs');
const views = __dirname + '/views/';
const images = __dirname + '/images/';

// App
const app = express();
//app.use(morgan('combined'));

var reqc = 1;

app.get('/getFrame/:type', function(req, res, next) {
    if (req.params.type != 'color' && req.params.type != 'depth') {
        res.send("Invalid frame request");
        next();
    }

    let args = {type: req.params.type};
//    console.log("req" + reqc++);
    service.getFrame(args, (function (error, response, body) {

        if(error) {
            console.log("got error");
            console.log(error);
            if (args.type == 'color') {
                return res.sendFile(images + "color_fail.jpg");

            }
            else {
                return res.sendFile(images + "depth_fail.jpg");
            }
        }
        else {
            var img = new Buffer(body, 'base64');
            res.contentType('image/jpeg');
//            res.end(img);
            return res.send(img);
        }
    }));

});

// Usage: /mixFrame/yourLocalImage&type&operand
// Example: /mixFrame/example&color&+
// A copyright free image called "example" is provided for testing purposes
app.get('/mixFrame/:image&:type&:op', function(req, res, next) {

    // check parameters validity
    if (req.params.type != 'color' && req.params.type != 'depth') {
        res.send("Invalid frame request");
        next();
    }

    // local read of file to be sent
    var content = fs.readFileSync(req.params.image+".jpg", "base64");

    let args = {image: content, type: req.params.type, op: req.params.op};
    service.mixFrame(args, (function (error, response, body) {
        if(error) {
            console.log("got error");
//            console.log(error);
            if (args.type == 'color') {
                return res.sendFile(images + "color_fail.jpg");

            }
            else {
                return res.sendFile(images + "depth_fail.jpg");
            }
        }
        else {
            // convert response to jpg
            var img = new Buffer(body, 'base64');
            res.contentType('image/jpeg');
//            res.end(img);
            return res.send(img);
            next();
        }
    }));

});

app.get('/api/:apiCall', function(req, res, next) {

    if (process.env.NODE_WEB_SERVICE !== 'rest') {
        res.send("API Calls work only on rest mode");
        next();
    }

    let args = {apiCall: req.params.apiCall};
    service.apiCall(args, (function (error, response, body) {

        console.log('error:', error); // Print the error if one occurred
        console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
        console.log('body:', body); // Print the HTML for the Google homepage.

        res.status(response && response.statusCode || 500);

        if(error) {
            res.send(error);
            next();
        }
        else {
            res.send(body);
            next();
        }

    }));

});

app.get('/doCanny/:filename', function(req, res, next) {

    soap.createClient(url, function(err, client) {
    	let args = {filename: req.params.filename};
        client.doCanny(args, function(err, result) {
            if(err) {
                console.log("got error");
                console.log(err);
                res.send(err);
                next();
            }
            else {
            	var img = new Buffer(result.return, 'base64');
                res.contentType('image/jpeg');
                res.end(img);
                next();
            }
        });
    });

});

app.get('/', (req, res) => {
    if (process.env.NODE_ENV === 'demo') {
        res.sendFile(views + "demo.html");
    }
    else {
        res.sendFile(views + "index.html");
    }
});

app.get('/color', (req, res) => {
    res.sendFile(views + "color.html");
});

app.get('/depth', (req, res) => {
    res.sendFile(views + "depth.html");
});

app.patch("/:type", function (req, res, next) {
    if (req.params.type != 'mix_color' && req.params.type != 'mix_depth'
        && req.params.type != 'mix_canny' && req.params.type != 'canny'
        && req.params.type != 'contour') {
        res.send("Invalid frame request");
        next();
    }
    let uri = "";
    console.log(req.params.type);
    if(req.params.type == "mix_color") {
        uri = "/mix/color";
    } else if (req.params.type == "mix_depth") {
        uri = "/mix/depth";
    } else if (req.params.type == "mix_canny") {
        uri = "/mix/canny";
    } else if (req.params.type == "canny") {
        uri = "/opencv/canny";
    } else if (req.params.type == "contour") {
        uri = "/opencv/contour";
    } else {
        console.log("invalid argument for flag setting")
    }

    let args = {flag: uri};
    service.enableFlag(args, (function (error, response, body) {

        if(error) {
            console.log("got error");
            console.log(error);
            res.send(error);
            next();
        }
        else {
            res.sendFile(views + "index.html");
        }

    }));
});

app.delete("/:type", function (req, res, next) {

    if (req.params.type != 'mix_color' && req.params.type != 'mix_depth'
        && req.params.type != 'mix_canny' && req.params.type != 'canny'
        && req.params.type != 'contour') {
        res.send("Invalid frame request");
        next();
    }
    let uri = "";
    console.log(req.params.type);
    if(req.params.type == "mix_color" || req.params.type == "mix_depth"
    || req.params.type == "mix_canny") {
        uri = "/mix";
    } else if (req.params.type == "canny") {
        uri = "/opencv/canny";
    } else if (req.params.type == "contour") {
        uri = "/opencv/contour";
    } else {
        console.log("invalid argument for flag setting")
    }

    let args = {flag: uri};
    service.disableFlag(args, (function (error, response, body) {

        if(error) {
            console.log("got error");
            console.log(error);
            res.send(error);
            next();
        }
        else {
            res.sendFile(views + "index.html");
        }

    }));

});

app.listen(PORT, HOST);
console.log((process.env.NODE_WEB_SERVICE || 'soap') + ` client HTTP Service Running on http://${HOST}:${PORT}`);

redpajama_set_name: RedPajamaGithub


text:
package org.example4.declaration.data

class X


text:
require 'rugged'
require 'fileutils'
require 'core_ext/string'

module Daun
  # Implementation of daun using Rugged library.
  class RuggedDaun
    # Creates a new RuggedDaun instance. An empty git repository will be initialized in the specified repository_path.
    #
    # @param repository_path [String] the path where the git repository will be created
    def initialize(repository_path)
      @repository = Rugged::Repository.init_at(repository_path)
      @logger = Logging.logger[self]
    end

    # Bootstraps the git repository with the git remote repository URL and the default daun configurations.
    #
    # @param remote_url [String] the git remote repository to be fetched every time {#checkout} is called
    def init(remote_url)
      @repository.remotes.create('origin', remote_url)
      @repository.config['daun.tag.blacklist'] = ''
      @repository.config['daun.tag.limit'] = '-1'
      @repository.config['daun.branch.blacklist'] = ''
    end

    # Returns the git repository config as hash.
    def config
      @repository.config
    end

    # Returns the remote url set to this repository.
    def remote_url
      @repository.remotes['origin'].url
    end

    # Checkout git branches and tags in the git repository working directory.
    #
    # This method will fetch the latest update from `git remote origin` configured
    # in the {#init} method.
    # Once the references are fetch, it will detect if there are new references,
    # updated references, and deleted references then act upon them
    # accordingly.
    def checkout(credentials = nil)
      @logger.info 'Fetching git repository..'

      fetch_options = {}
      fetch_options[:credentials] = credentials unless credentials.nil?

      refs_diff = fetch_refs fetch_options

      refs_diff.added(:remotes).each do |refs|
        @logger.info "Adding #{refs}.."
        checkout_remote_branch refs.to_local_branch, get_checkout_directory(refs)
      end

      refs_diff.updated(:remotes).each do |refs|
        @logger.info "Updating #{refs}.."
        checkout_remote_branch refs.to_local_branch, get_checkout_directory(refs)
      end

      refs_diff.deleted(:remotes).each do |refs|
        @logger.info "Deleting #{refs}.."
        FileUtils.rm_rf get_checkout_directory refs
      end

      refs_diff.added(:tags).each do |refs|
        @logger.info "Adding #{refs}.."
        checkout_tag refs.to_tag, get_checkout_directory(refs)
      end

      refs_diff.updated(:tags).each do |refs|
        @logger.info "Updating #{refs}.."
        checkout_tag(refs.to_tag, get_checkout_directory(refs), force: true)
      end

      refs_diff.deleted(:tags).each do |refs|
        @logger.info "Deleting #{refs}.."
        FileUtils.rm_rf get_checkout_directory refs
      end

      @logger.info "Finished checking out #{@repository.remotes['origin'].url} to #{@repository.workdir}"
    end

    private

    # Fetch refs from origin.
    def fetch_refs(fetch_options = {})
      before_fetch = Hash[@repository.refs.collect { |r| [r.name, r.target_id] }]

      # Prune is not supported by rugged! Deleting all remote refs and re-fetch
      delete_all_remote_branches
      delete_all_tags

      @repository.remotes['origin'].fetch(nil, fetch_options)

      delete_all_remote_branches @repository.config['daun.branch.blacklist'].split
      delete_all_tags @repository.config['daun.tag.blacklist'].split
      if @repository.config['daun.tag.limit'].to_i > -1
        keep_new_tags @repository.config['daun.tag.limit'].to_i
      end

      after_fetch = Hash[@repository.refs.collect { |r| [r.name, r.target_id] }]

      Daun::RefsDiff.new(before_fetch, after_fetch)
    end

    def checkout_remote_branch(branch, target_dir)
      FileUtils.mkdir_p target_dir
      @repository.checkout("origin/#{branch}",
                           strategy: :force, target_directory: target_dir)
    end

    def checkout_tag(tag, target_dir, options = { force: false })
      if File.exist?(target_dir) && options[:force]
        # checkout --force is somehow not working to update the tag
        FileUtils.rm_rf target_dir
      end
      FileUtils.mkdir_p target_dir
      @repository.checkout(@repository.tags[tag].target.oid,
                           strategy: :force, target_directory: target_dir)
    end

    def delete_all_remote_branches(patterns = ['*'])
      patterns.each do |pattern|
        @repository.branches.each_name(:remote) do |branch|
          if File.fnmatch? "origin/#{pattern}", branch
            @repository.branches.delete branch
          end
        end
      end
    end

    def delete_all_tags(patterns = ['*'])
      patterns.each do |pattern|
        @repository.tags.each_name do |tag|
          @repository.tags.delete tag if File.fnmatch? pattern, tag
        end
      end
    end

    def keep_new_tags(limit)
      if @repository.tags.count > limit
        @repository.tags.sort_by { |tag| tag.target.time }
          .take(@repository.tags.count - limit)
          .each { |t| @repository.tags.delete t.name }
      end
    end

    def get_checkout_directory(refs)
      if refs.start_with? 'refs/remotes'
        File.join(@repository.workdir, 'branches', refs.to_local_branch)
      elsif refs.start_with? 'refs/tags'
        File.join(@repository.workdir, 'tags', refs.to_tag)
      else
        raise "#{refs} is unsupported"
      end
    end
  end
end


text:
#include "GpuProfiler.h"
#include <vxEngineLib/Graphics/Font.h>
#include <Windows.h>
#include <vxLib/memory.h>
#include <vxGL/gl.h>
#include "Graphics/TextRenderer.h"

namespace
{
	inline void	incrementCycle(u8* pval, u8 array_size)
	{
		s32 val = *pval;
		++val;

		if (val >= (s32)(array_size))
			val = 0;

		*pval = val;
	}

	inline void	incrementCycle(s32* pval, size_t array_size)
	{
		s32 val = *pval;
		++val;

		if (val >= (s32)(array_size))
			val = 0;

		*pval = val;
	}

	inline void	incrementCycle(s64* pval, size_t array_size)
	{
		s64 val = *pval;
		++val;

		if (val >= (s64)(array_size))
			val = 0;

		*pval = val;
	}

	inline void	incrementCycle(u32* pval, size_t array_size)
	{
		s64 val = *pval;
		++val;

		if (val >= (s64)(array_size))
			val = 0;

		*pval = val;
	}

	inline void	decrementCycle(u32* pval, size_t array_size)
	{
		s64 val = *pval;
		--val;

		if (val < 0)
			val = (s64)(array_size - 1);

		*pval = val;
	}

	inline void	decrementCycle(s64* pval, size_t array_size)
	{
		s64 val = *pval;
		--val;

		if (val < 0)
			val = (s64)(array_size - 1);

		*pval = val;
	}
}

struct GpuProfiler::EntryGpu
{
	u32 time{ 0 };
	u32 timeMin{ 0xffffffff };
	u32 timeMax{ 0 };
	char name[s_maxCharacters];
	u8 layer{ 0 };
	u32 queryStart{ 0 };
	u32 queryEnd{ 0 };

	EntryGpu()
	{
		name[0] = '\0';
	}
};

GpuProfiler::GpuProfiler()
	:m_currentFrame(0),
	m_gpuThreadInfo(),
	m_entriesGpuByName(),
	m_entryGpuCount(0),
	m_entriesGpu(),
	m_textRenderer(nullptr),
	m_position(0, 0)
{
}

GpuProfiler::~GpuProfiler()
{
}

bool GpuProfiler::initialize(const vx::float2 &position, Graphics::TextRenderer* textRenderer, vx::StackAllocator* pAllocator)
{
	m_entriesGpuByName = vx::sorted_array<vx::StringID, u32>(s_markersGpu, pAllocator);
	m_entriesGpu = vx::make_unique<EntryGpu[]>(s_markersGpu);

	for (auto i = 0u; i < s_markersGpu; ++i)
	{
		glCreateQueries(GL_TIMESTAMP, 1, &m_gpuThreadInfo.markers[i].id_query_start);
		glCreateQueries(GL_TIMESTAMP, 1, &m_gpuThreadInfo.markers[i].id_query_end);
	}

	m_textRenderer = textRenderer;
	m_position = position;

	return true;
}

void GpuProfiler::update()
{
	char buffer[64];

	vx::float2 position = m_position;
	vx::float2 currentPosition = m_position;
	for (auto i = 0u; i < m_entryGpuCount; ++i)
	{
		auto &entry = m_entriesGpu[i];
		auto entryName = entry.name;
		auto layer = entry.layer;
		f32 time = entry.time * 1.0e-6;

		int strSize = sprintf_s(buffer, "%s %.6f", entryName, time);
		strSize = std::min(strSize, 47);
		char text[48];
		strncpy(text, buffer, strSize);
		text[strSize] = '\0';
		//std::string text;
		//text.reserve(strSize);
		//text.assign(buffer, buffer + strSize);

		auto layerOffset = layer * 10.0f;

		currentPosition.x = position.x + layerOffset;
		m_textRenderer->pushEntry(text, strSize, currentPosition, vx::float3(1, 0, 1));

		currentPosition.y -= 15;

		/*auto layerOffset = entry.layer * 10.0f;

		auto currentPos = *cursorPos;
		currentPos.x += layerOffset;

		strSize = sprintf_s(buffer, "%.6f ms", entry.time * 1.0e-6);
		currentPos.x = cursorPos->x + 150;

		strSize = sprintf_s(buffer, "%.6f ms\n", entry.timeMin * 1.0e-6);

		currentPos.x = cursorPos->x + 275;

		*cursorPos = currentPos;*/
		entry.timeMin = 0xFFFFFFFF;
	}
}

void GpuProfiler::frame()
{
	++m_currentFrame;

	m_gpuThreadInfo.m_pushedMarkers = 0;

	s64 displayed_frame = m_currentFrame - s_numFramesDelay - 1;
	if (displayed_frame < 0) // don't draw anything during the first frames
		return;

	for (auto i = 0u; i < s_markersGpu; ++i)
	{
		auto &marker = m_gpuThreadInfo.markers[i];

		if (marker.frame == displayed_frame)
		{
			GLint start_ok = 0;
			GLint end_ok = 0;
			glGetQueryObjectiv(marker.id_query_start, GL_QUERY_RESULT_AVAILABLE, &start_ok);
			glGetQueryObjectiv(marker.id_query_end, GL_QUERY_RESULT_AVAILABLE, &end_ok);
			bool ok = (bool)(start_ok && end_ok);

			if (ok)
			{
				u64 start, end;
				glGetQueryObjectui64v(marker.id_query_start, GL_QUERY_RESULT, &start);
				glGetQueryObjectui64v(marker.id_query_end, GL_QUERY_RESULT, &end);

				marker.end = 0;

				vx::StringID sid = vx::make_sid(marker.name);
				auto it = m_entriesGpuByName.find(sid);

				if (it == m_entriesGpuByName.end())
				{
					EntryGpu entry;
					strncpy(entry.name, marker.name, s_maxCharacters);
					entry.layer = marker.layer;

					m_entriesGpu[m_entryGpuCount] = entry;

					it = m_entriesGpuByName.insert(sid, m_entryGpuCount);

					++m_entryGpuCount;
				}
				auto &entry = m_entriesGpu[*it];
				entry.layer = marker.layer;
				entry.time = end - start;

				entry.timeMax = fmax(entry.timeMin, entry.timeMax);
				entry.timeMin = fmin(entry.timeMin, entry.time);
			}
		}
	}
}

void GpuProfiler::pushGpuMarker(const char *name)
{
	GpuThreadInfo& ti = m_gpuThreadInfo;
	GpuMarker& marker = ti.markers[ti.currentWriteId];
	VX_ASSERT(ti.currentWriteId < 255u);

	glQueryCounter(marker.id_query_start, GL_TIMESTAMP);

	// Fill in marker
	marker.start = 0;
	marker.end = 0;
	marker.layer = ti.m_pushedMarkers;
	strncpy(marker.name, name, s_maxCharacters);
	marker.frame = m_currentFrame;
	incrementCycle(&ti.currentWriteId, s_markersGpu);
	++ti.m_pushedMarkers;
}

void GpuProfiler::popGpuMarker()
{
	GpuThreadInfo& ti = m_gpuThreadInfo;
	// Get the most recent marker that has not been closed yet
	//auto index = ti.currentWriteId - 1;
	u32 index = (ti.currentWriteId == 0) ? s_markersGpu - 1 : ti.currentWriteId - 1;
	//VX_ASSERT(index != -1, "Invalid index !");
	while (ti.markers[index].end != 0) // skip closed markers
		decrementCycle(&index, (u32)s_markersGpu);

	GpuMarker& marker = ti.markers[index];

	marker.end = 1;
	glQueryCounter(marker.id_query_end, GL_TIMESTAMP);

	--ti.m_pushedMarkers;
}


text:
class Version;

namespace base {
namespace win {
class RegKey;
}
}

namespace installer {

class InstallationState;

// A representation of a product's state on the machine based on the contents
// of the Windows registry.
// TODO(grt): Pull this out into its own file.
class ProductState {
 public:
  ProductState();

  // Returns true if the product is installed (i.e., the product's Clients key
  // exists and has a "pv" value); false otherwise.
  bool Initialize(bool system_install,
                  BrowserDistribution::Type type);
  bool Initialize(bool system_install,
                  BrowserDistribution* distribution);

  // Returns the product's channel info (i.e., the Google Update "ap" value).
  const ChannelInfo& channel() const { return channel_; }

  // Returns the path to the product's "setup.exe"; may be empty.
  FilePath GetSetupPath() const;

  // Returns the product's version.  This method may only be called on an
  // instance that has been initialized for an installed product.
  const Version& version() const;

  // Returns the current version of the product if a new version is awaiting
  // update; may be NULL.  Ownership of a returned value is not passed to the
  // caller.
  const Version* old_version() const { return old_version_.get(); }

  // Returns the brand code the product is currently installed with.
  const std::wstring& brand() const { return brand_; }

  // Returns the command to be used to update to the new version that is
  // awaiting update; may be empty.
  const std::wstring& rename_cmd() const { return rename_cmd_; }

  // Returns true and populates |eula_accepted| if the product has such a value;
  // otherwise, returns false and does not modify |eula_accepted|.  Expected
  // values are 0 (false) and 1 (true), although |eula_accepted| is given
  // whatever is found.
  bool GetEulaAccepted(DWORD* eula_accepted) const;

  // Returns true and populates |oem_install| if the product has such a value;
  // otherwise, returns false and does not modify |oem_install|.  Expected
  // value is "1", although |oem_install| is given whatever is found.
  bool GetOemInstall(std::wstring* oem_install) const;

  // Returns true and populates |usagestats| if the product has such a value;
  // otherwise, returns false and does not modify |usagestats|.  Expected values
  // are 0 (false) and 1 (true), although |usagestats| is given whatever is
  // found.
  bool GetUsageStats(DWORD* usagestats) const;

  // True if the "msi" value in the ClientState key is present and non-zero.
  bool is_msi() const { return msi_; }

  // The command to uninstall the product; may be empty.
  const CommandLine& uninstall_command() const { return uninstall_command_; }

  // True if |uninstall_command| contains --multi-install.
  bool is_multi_install() const { return multi_install_; }

  // Returns the set of Google Update commands.
  const AppCommands& commands() const { return commands_; }

  // Returns this object a la operator=().
  ProductState& CopyFrom(const ProductState& other);

  // Clears the state of this object.
  void Clear();

 protected:
  static bool InitializeCommands(const base::win::RegKey& version_key,
                                 AppCommands* commands);

  ChannelInfo channel_;
  scoped_ptr<Version> version_;
  scoped_ptr<Version> old_version_;
  std::wstring brand_;
  std::wstring rename_cmd_;
  std::wstring oem_install_;
  CommandLine uninstall_command_;
  AppCommands commands_;
  DWORD eula_accepted_;
  DWORD usagestats_;
  bool msi_ : 1;
  bool multi_install_ : 1;
  bool has_eula_accepted_ : 1;
  bool has_oem_install_ : 1;
  bool has_usagestats_ : 1;

 private:
  friend class InstallationState;

  DISALLOW_COPY_AND_ASSIGN(ProductState);
};  // class ProductState

// Encapsulates the state of all products on the system.
// TODO(grt): Rename this to MachineState and put it in its own file.
class InstallationState {
 public:
  InstallationState();

  // Initializes this object with the machine's current state.
  void Initialize();

  // Returns the state of a product or NULL if not installed.
  // Caller does NOT assume ownership of returned pointer.
  const ProductState* GetProductState(bool system_install,
                                      BrowserDistribution::Type type) const;

  // Returns the state of a product, even one that has not yet been installed.
  // This is useful during first install, when some but not all ProductState
  // information has been written by Omaha. Notably absent from the
  // ProductState returned here are the version numbers. Do NOT try to access
  // the version numbers from a ProductState returned by this method.
  // Caller does NOT assume ownership of returned pointer. This method will
  // never return NULL.
  const ProductState* GetNonVersionedProductState(
      bool system_install, BrowserDistribution::Type type) const;

 protected:
  enum {
    CHROME_BROWSER_INDEX,
    CHROME_FRAME_INDEX,
    CHROME_BINARIES_INDEX,
    CHROME_APP_HOST_INDEX,
    NUM_PRODUCTS
  };

  static int IndexFromDistType(BrowserDistribution::Type type);

  ProductState user_products_[NUM_PRODUCTS];
  ProductState system_products_[NUM_PRODUCTS];

 private:
  DISALLOW_COPY_AND_ASSIGN(InstallationState);
};  // class InstallationState

}  // namespace installer

#endif  // CHROME_INSTALLER_UTIL_INSTALLATION_STATE_H_


text:
package com.cloud.hypervisor.ovm3.resources.helpers;

import java.util.ArrayList;
import java.util.List;

import javax.naming.ConfigurationException;

import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckNetworkCommand;
import com.cloud.agent.api.PingTestCommand;
import com.cloud.hypervisor.ovm3.objects.CloudStackPluginTest;
import com.cloud.hypervisor.ovm3.objects.ConnectionTest;
import com.cloud.hypervisor.ovm3.objects.NetworkTest;
import com.cloud.hypervisor.ovm3.objects.XenTest;
import com.cloud.hypervisor.ovm3.objects.XmlTestResultTest;
import com.cloud.hypervisor.ovm3.resources.Ovm3HypervisorResource;
import com.cloud.hypervisor.ovm3.resources.Ovm3HypervisorResourceTest;
import com.cloud.hypervisor.ovm3.support.Ovm3SupportTest;
import com.cloud.network.PhysicalNetworkSetupInfo;

import org.junit.Test;

public class Ovm3HypervisorNetworkTest {
  ConnectionTest con = new ConnectionTest();
  Ovm3ConfigurationTest configTest = new Ovm3ConfigurationTest();
  Ovm3SupportTest support = new Ovm3SupportTest();
  Ovm3HypervisorResource hypervisor = new Ovm3HypervisorResource();
  Ovm3HypervisorResourceTest hyperTest = new Ovm3HypervisorResourceTest();
  CloudStackPluginTest csp = new CloudStackPluginTest();
  XenTest xen = new XenTest();
  NetworkTest network = new NetworkTest();
  XmlTestResultTest results = new XmlTestResultTest();

  @Test
  public void CheckNetworkCommandTest() throws ConfigurationException {
    hypervisor = support.prepare(configTest.getParams());
    final List<PhysicalNetworkSetupInfo> setups = new ArrayList<PhysicalNetworkSetupInfo>();
    final PhysicalNetworkSetupInfo networkInfo = new PhysicalNetworkSetupInfo();
    setups.add(networkInfo);
    final CheckNetworkCommand cmd = new CheckNetworkCommand(setups);
    final Answer ra = hypervisor.executeRequest(cmd);
    results.basicBooleanTest(ra.getResult());
  }

  @Test
  public void CheckNetworkCommandGuestFailTest() throws ConfigurationException {
    hypervisor = support.prepare(configTest.getParams());
    final List<PhysicalNetworkSetupInfo> setups = new ArrayList<PhysicalNetworkSetupInfo>();
    final PhysicalNetworkSetupInfo networkInfo = new PhysicalNetworkSetupInfo();
    networkInfo.setGuestNetworkName(network.getInterface() + "." + 3000);
    setups.add(networkInfo);
    final CheckNetworkCommand cmd = new CheckNetworkCommand(setups);
    final Answer ra = hypervisor.executeRequest(cmd);
    results.basicBooleanTest(ra.getResult(), false);
  }

  @Test
  public void CheckNetworkCommandPublicFailTest() throws ConfigurationException {
    hypervisor = support.prepare(configTest.getParams());
    final List<PhysicalNetworkSetupInfo> setups = new ArrayList<PhysicalNetworkSetupInfo>();
    final PhysicalNetworkSetupInfo networkInfo = new PhysicalNetworkSetupInfo();
    networkInfo.setPublicNetworkName(network.getInterface() + "." + 3000);
    setups.add(networkInfo);
    final CheckNetworkCommand cmd = new CheckNetworkCommand(setups);
    final Answer ra = hypervisor.executeRequest(cmd);
    results.basicBooleanTest(ra.getResult(), false);
  }

  @Test
  public void CheckNetworkCommandPrivateFailTest() throws ConfigurationException {
    hypervisor = support.prepare(configTest.getParams());
    final List<PhysicalNetworkSetupInfo> setups = new ArrayList<PhysicalNetworkSetupInfo>();
    final PhysicalNetworkSetupInfo networkInfo = new PhysicalNetworkSetupInfo();
    networkInfo.setPrivateNetworkName(network.getInterface() + "." + 3000);
    setups.add(networkInfo);
    final CheckNetworkCommand cmd = new CheckNetworkCommand(setups);
    final Answer ra = hypervisor.executeRequest(cmd);
    results.basicBooleanTest(ra.getResult(), false);
  }

  @Test
  public void CheckNetworkCommandStorageFalseTest() throws ConfigurationException {
    hypervisor = support.prepare(configTest.getParams());
    final List<PhysicalNetworkSetupInfo> setups = new ArrayList<PhysicalNetworkSetupInfo>();
    final PhysicalNetworkSetupInfo networkInfo = new PhysicalNetworkSetupInfo();
    networkInfo.setStorageNetworkName(network.getInterface() + "." + 3000);
    setups.add(networkInfo);
    final CheckNetworkCommand cmd = new CheckNetworkCommand(setups);
    final Answer ra = hypervisor.executeRequest(cmd);
    results.basicBooleanTest(ra.getResult());
  }

  @Test
  public void PingTestCommandWeDontPingRouterTest() throws ConfigurationException {
    hypervisor = support.prepare(configTest.getParams());
    final PingTestCommand cmd = new PingTestCommand(csp.getDom0Ip(), csp.getDomrIp());
    final Answer ra = hypervisor.executeRequest(cmd);
    results.basicBooleanTest(ra.getResult(), false);
  }

  @Test
  public void PingTestCommandComputeTest() throws ConfigurationException {
    hypervisor = support.prepare(configTest.getParams());
    final PingTestCommand cmd = new PingTestCommand(csp.getDom0Ip());
    final Answer ra = hypervisor.executeRequest(cmd);
    results.basicBooleanTest(ra.getResult());
  }

  @Test
  public void PingTestCommandComputeFalseTest() throws ConfigurationException {
    hypervisor = support.prepare(configTest.getParams());
    support.getConnection().setMethodResponse("ping", results.simpleResponseWrap("boolean", "0"));
    final PingTestCommand cmd = new PingTestCommand(csp.getDom0Ip());
    final Answer ra = hypervisor.executeRequest(cmd);
    results.basicBooleanTest(ra.getResult(), false);
  }
}


text:
<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>WTForms Documentation</title>
    <link rel="stylesheet" href="_static/main.css" type="text/css">
    <link rel="stylesheet" href="_static/docstyles.css" type="text/css">
    <link rel="stylesheet" href="_static/print.css" type="text/css" media="print">
    <link rel="stylesheet" href="_static/pygments.css" type="text/css">

    <link rel="contents" title="Global table of contents" href="contents.html">
    <link rel="index" title="Global index" href="genindex.html">
    <link rel="search" title="Search" href="search.html">
    <link rel="top" title="WTForms 1.0.3 documentation" href="index.html">
    <link rel="next" title="FAQ" href="faq.html">
    <link rel="prev" title="Widgets" href="widgets.html">

Website

Documentation

FAQ

Mailing List

Code

Table Of Contents

Extensions

Appengine

Model Forms

Datastore-backed Fields

Dateutil

Django

Templatetags

Model forms

ORM-backed fields

SQLAlchemy

ORM-backed fields

CSRF

Creating your own CSRF implementation

Session-based CSRF implementation

Extensions¶

WTForms ships with a number of extensions that make it easier to work with
other frameworks and libraries, such as Django.

Appengine¶

WTForms now includes support for AppEngine fields as well as auto-form
generation.

Model Forms¶

See the module docstring for examples on how to use <tt class="xref py py-func docutils literal">model_form()</tt>.

<tt class="descclassname">wtforms.ext.appengine.db.</tt><tt class="descname">model_form</tt><big>(</big>model, base_class=Form, only=None, exclude=None, field_args=None, converter=None<big>)</big>¶

Creates and returns a dynamic <tt class="docutils literal">wtforms.Form</tt> class for a given
<tt class="docutils literal">db.Model</tt> class. The form class can be used as it is or serve as a base
for extended form classes, which can then mix non-model related fields,
subforms with other model forms, among other possibilities.

<col class="field-name" />
<col class="field-body" />

Parameters:

model – The <tt class="docutils literal">db.Model</tt> class to generate a form for.

base_class – Base form class to extend from. Must be a <tt class="docutils literal">wtforms.Form</tt> subclass.

only – An optional iterable with the property names that should be included in
the form. Only these properties will have fields.

exclude – An optional iterable with the property names that should be excluded
from the form. All other properties will have fields.

field_args – An optional dictionary of field names mapping to keyword arguments
used to construct each field object.

converter – A converter to generate the fields based on the model properties. If
not set, <tt class="docutils literal">ModelConverter</tt> is used.

Datastore-backed Fields¶

class <tt class="descclassname">wtforms.ext.appengine.fields.</tt><tt class="descname">ReferencePropertyField</tt><big>(</big>default field arguments, reference_class=None, get_label=None, allow_blank=False, blank_text=u''<big>)</big>¶

A field for <tt class="docutils literal">db.ReferenceProperty</tt>. The list items are rendered in a
select.

<col class="field-name" />
<col class="field-body" />

Parameters:

reference_class – A db.Model class which will be used to generate the default query
to make the list of items. If this is not specified, The query
property must be overridden before validation.

get_label – If a string, use this attribute on the model class as the label
associated with each option. If a one-argument callable, this callable
will be passed model instance and expected to return the label text.
Otherwise, the model object’s __str__ or __unicode__ will be used.

allow_blank – If set to true, a blank choice will be added to the top of the list
to allow None to be chosen.

blank_text – Use this to override the default blank option’s label.

class <tt class="descclassname">wtforms.ext.appengine.fields.</tt><tt class="descname">StringListPropertyField</tt><big>(</big>default field arguments<big>)</big>¶

A field for <tt class="docutils literal">db.StringListProperty</tt>. The list items are rendered in a
textarea.

class <tt class="descclassname">wtforms.ext.appengine.fields.</tt><tt class="descname">GeoPtPropertyField</tt><big>(</big>default field arguments<big>)</big>¶

Dateutil¶

For better date-time parsing using the python-dateutil  package,
<tt class="xref py py-mod docutils literal">wtforms.ext.dateutil</tt> provides a set of fields to use to accept a wider
range of date input.

class <tt class="descclassname">wtforms.ext.dateutil.fields.</tt><tt class="descname">DateTimeField</tt><big>(</big>default field arguments, parse_kwargs=None, display_format='%Y-%m-%d %H:%M'<big>)</big>¶

DateTimeField represented by a text input, accepts all input text formats
that dateutil.parser.parse will.

<col class="field-name" />
<col class="field-body" />

Parameters:

parse_kwargs – A dictionary of keyword args to pass to the dateutil parse() function.
See dateutil docs for available keywords.

display_format – A format string to pass to strftime() to format dates for display.

class <tt class="descclassname">wtforms.ext.dateutil.fields.</tt><tt class="descname">DateField</tt><big>(</big>default field arguments, parse_kwargs=None, display_format='%Y-%m-%d'<big>)</big>¶

Same as the DateTimeField, but stores only the date portion.

Django¶

This extension provides templatetags to make it easier to work with Django
templates and WTForms’ html attribute rendering. It also provides a generator
for automatically creating forms based on Django ORM models.

Templatetags¶

Django templates does not allow arbitrarily calling functions with parameters,
making it impossible to use the html attribute rendering feature of WTForms. To
alleviate this, we provide a templatetag.

Adding <tt class="xref py py-mod docutils literal">wtforms.ext.django</tt> to your INSTALLED_APPS will make the wtforms
template library available to your application.  With this you can pass extra
attributes to form fields similar to the usage in jinja:

{% load wtforms %}

{% form_field form.username class="big_text" onclick="do_something()" %}

Note By default, using the {{ form.field }} syntax in django models will
be auto-escaped.  To avoid this happening, use Django’s {% autoescape off %}
block tag or use WTForms’ form_field template tag.

Model forms¶

<tt class="descclassname">wtforms.ext.django.orm.</tt><tt class="descname">model_form</tt><big>(</big>model, base_class=Form, only=None, exclude=None, field_args=None, converter=None<big>)</big>¶

Create a wtforms Form for a given Django model class:

from wtforms.ext.django.orm import model_form
from myproject.myapp.models import User
UserForm = model_form(User)

<col class="field-name" />
<col class="field-body" />

Parameters:

model – A Django ORM model class

base_class – Base form class to extend from. Must be a <tt class="docutils literal">wtforms.Form</tt> subclass.

only – An optional iterable with the property names that should be included in
the form. Only these properties will have fields.

exclude – An optional iterable with the property names that should be excluded
from the form. All other properties will have fields.

field_args – An optional dictionary of field names mapping to keyword arguments used
to construct each field object.

converter – A converter to generate the fields based on the model properties. If
not set, <tt class="docutils literal">ModelConverter</tt> is used.

<tt class="xref py py-func docutils literal">model_form()</tt> attempts to glean as much metadata as possible from
inspecting the model’s fields, and will even attempt to guess at what
validation might be wanted based on the field type. For example, converting
an EmailField will result in a <tt class="xref py py-class docutils literal">TextField</tt> with
the <tt class="xref py py-func docutils literal">email()</tt> validator on it. if the blank
property is set on a model field, the resulting form field will have the
<tt class="xref py py-func docutils literal">optional()</tt> validator set.

Just like any other Form, forms created by ModelForm can be extended via
inheritance:

UserFormBase = model_form(User)

class UserForm(UserFormBase):
    new_pass     = PasswordField('', [validators.optional(), validators.equal_to('confirm_pass')])
    confirm_pass = PasswordField()

When combined with <tt class="xref py py-meth docutils literal">form iteration</tt>,
model_form is a handy way to generate dynamic CRUD forms which update with
added fields to the model. One must be careful though, as it’s possible the
generated form fields won’t be as strict with validation as a hand-written
form might be.

ORM-backed fields¶

While linking data to most fields is fairly easy, making drop-down select lists
using django ORM data can be quite repetitive. To this end, we have added some
helpful tools to use the django ORM along with wtforms.

class <tt class="descclassname">wtforms.ext.django.fields.</tt><tt class="descname">QuerySetSelectField</tt><big>(</big>default field args, queryset=None, get_label=None, allow_blank=False, blank_text=u''<big>)</big>¶

Given a QuerySet either at initialization or inside a view, will display a
select drop-down field of choices. The data property actually will
store/keep an ORM model instance, not the ID. Submitting a choice which is
not in the queryset will result in a validation error.

Specify get_label to customize the label associated with each option. If
a string, this is the name of an attribute on the model object to use as
the label text. If a one-argument callable, this callable will be passed
model instance and expected to return the label text. Otherwise, the model
object’s __str__ or __unicode__ will be used.

If allow_blank is set to True, then a blank choice will be added to the
top of the list. Selecting this choice will result in the data property
being None.  The label for the blank choice can be set by specifying the
blank_text parameter.

class ArticleEdit(Form):
    title    = TextField()
    column   = QuerySetSelectField(get_label='title', allow_blank=True)
    category = QuerySetSelectField(queryset=Category.objects.all())

def edit_article(request, id):
    article = Article.objects.get(pk=id)
    form = ArticleEdit(obj=article)
    form.column.queryset = Column.objects.filter(author=request.user)

As shown in the above example, the queryset can be set dynamically in the
view if needed instead of at form construction time, allowing the select
field to consist of choices only relevant to the user.

class <tt class="descclassname">wtforms.ext.django.fields.</tt><tt class="descname">ModelSelectField</tt><big>(</big>default field args, model=None, get_label='', allow_blank=False, blank_text=u''<big>)</big>¶

Like a QuerySetSelectField, except takes a model class instead of a
queryset and lists everything in it.

SQLAlchemy¶

This extension provides SelectField integration with SQLAlchemy ORM models,
similar to those in the Django extension.

ORM-backed fields¶

These fields are provided to make it easier to use data from ORM objects in
your forms.

def enabled_categories():
    return Category.query.filter_by(enabled=True)

class BlogPostEdit(Form):
    title    = TextField()
    blog     = QuerySelectField(get_label='title')
    category = QuerySelectField(query_factory=enabled_categories, allow_blank=True)

def edit_blog_post(request, id):
    post = Post.query.get(id)
    form = ArticleEdit(obj=post)
    # Since we didn't provide a query_factory for the 'blog' field, we need
    # to set a dynamic one in the view.
    form.blog.query = Blog.query.filter(Blog.author == request.user).order_by(Blog.name)

class <tt class="descclassname">wtforms.ext.sqlalchemy.fields.</tt><tt class="descname">QuerySelectField</tt><big>(</big>default field args, query_factory=None, get_pk=None, get_label=None, allow_blank=False, blank_text=u''<big>)</big>¶

Will display a select drop-down field to choose between ORM results in a
sqlalchemy Query.  The data property actually will store/keep an ORM
model instance, not the ID. Submitting a choice which is not in the query
will result in a validation error.

This field only works for queries on models whose primary key column(s)
have a consistent string representation. This means it mostly only works
for those composed of string, unicode, and integer types. For the most
part, the primary keys will be auto-detected from the model, alternately
pass a one-argument callable to get_pk which can return a unique
comparable key.

The query property on the field can be set from within a view to assign
a query per-instance to the field. If the property is not set, the
query_factory callable passed to the field constructor will be called to
obtain a query.

Specify get_label to customize the label associated with each option. If
a string, this is the name of an attribute on the model object to use as
the label text. If a one-argument callable, this callable will be passed
model instance and expected to return the label text. Otherwise, the model
object’s __str__ or __unicode__ will be used.

If allow_blank is set to True, then a blank choice will be added to the
top of the list. Selecting this choice will result in the data property
being None. The label for this blank choice can be set by specifying the
blank_text parameter.

class <tt class="descclassname">wtforms.ext.sqlalchemy.fields.</tt><tt class="descname">QuerySelectMultipleField</tt><big>(</big>default field args, query_factory=None, get_pk=None, get_label=None, allow_blank=False, blank_text=u''<big>)</big>¶

Very similar to QuerySelectField with the difference that this will
display a multiple select. The data property will hold a list with ORM
model instances and will be an empty list when no value is selected.

If any of the items in the data list or submitted form data cannot be
found in the query, this will result in a validation error.

CSRF¶

The CSRF package includes tools that help you implement checking against
cross-site request forgery (“csrf”). Due to the large number of variations on
approaches people take to CSRF (and the fact that many make compromises) the
base implementation allows you to plug in a number of CSRF validation
approaches.

CSRF implementations are made by subclassing
<tt class="xref py py-class docutils literal">SecureForm</tt>. For utility, we have provided one
possible CSRF implementation in the package that can be used with many
frameworks for session-based hash secure keying,
<tt class="xref py py-class docutils literal">SessionSecureForm</tt>.

All CSRF implementations hinge around creating a special token, which is put in
a hidden field on the form named ‘csrf_token’, which must be rendered in your
template to be passed from the browser back to your view. There are many
different methods of generating this token, but they are usually the result of
a cryptographic hash function against some data which would be hard to forge.

class <tt class="descclassname">wtforms.ext.csrf.form.</tt><tt class="descname">SecureForm</tt><big>(</big>formdata=None, obj=None, prefix=u'', csrf_context=None, **kwargs<big>)</big>¶

Form that enables CSRF processing via subclassing hooks.

<tt class="descname">generate_csrf_token</tt><big>(</big>csrf_context<big>)</big>¶

Implementations must override this to provide a method with which one
can get a CSRF token for this form.

A CSRF token should be a string which can be generated
deterministically so that on the form POST, the generated string is
(usually) the same assuming the user is using the site normally.

<col class="field-name" />
<col class="field-body" />

Parameters:	csrf_context – A transparent object which can be used as contextual info for
generating the token.

<tt class="descname">validate_csrf_token</tt><big>(</big>field<big>)</big>¶

Override this method to provide custom CSRF validation logic.

The default CSRF validation logic simply checks if the recently
generated token equals the one we received as formdata.

Creating your own CSRF implementation¶

Here we will sketch out a simple theoretical CSRF implementation which
generates a hash token based on the user’s IP.

Note This is a simplistic example meant to illustrate creating a CSRF
implementation. This isn’t recommended to be used in production because the
token is deterministic and non-changing per-IP, which means this isn’t the
most secure implementation of CSRF.

First, let’s create our SecureForm base class:

from wtforms.ext.csrf import SecureForm
from hashlib import md5

SECRET_KEY = '1234567890'

class IPSecureForm(SecureForm):
    """
    Generate a CSRF token based on the user's IP. I am probably not very
    secure, so don't use me.
    """

    def generate_csrf_token(self, csrf_context):
        # csrf_context is passed transparently from the form constructor,
        # in this case it's the IP address of the user
        token = md5(SECRET_KEY + csrf_context).hexdigest()
        return token

    def validate_csrf_token(self, field):
        if field.data != field.current_token:
            raise ValueError('Invalid CSRF')

Now that we have this taken care of, let’s write a simple form and view which would implement this:

class RegistrationForm(IPSecureForm):
    name = TextField('Your Name')
    email = TextField('Email', [validators.email()])

def register(request):
    form = RegistrationForm(request.POST, csrf_context=request.ip)

    if request.method == 'POST' and form.validate():
        pass # We're all good, create a user or whatever it is you do
    elif form.csrf_token.errors:
        pass # If we're here we suspect the user of cross-site request forgery
    else:
        pass # Any other errors

    return render('register.html', form=form)

And finally, a simple template:

<form action="register" method="POST">
    {{ form.csrf_token }}
    <p>{{ form.name.label }}: {{ form.name }}</p>
    <p>{{ form.email.label }}: {{ form.email }}</p>
    <input type="submit" value="Register">
</form>

Please note that implementing CSRF detection is not fool-proof, and even with
the best CSRF protection implementation, it’s possible for requests to be
forged by expert attackers. However, a good CSRF protection would make it
infeasible for someone from an external site to hijack a form submission from
another user and perform actions as them without additional a priori knowledge.

In addition, it’s important to understand that very often, the more strict the
CSRF protection, the higher the chance of false positives occurring (ie,
legitimate users getting blocked by your CSRF protection) and choosing a CSRF
implementation is actually a matter of compromise. We will attempt to provide a
handful of usable reference algorithms built in to this library in the future, to
allow that choice to be easy.

Some tips on criteria people often examine when evaluating CSRF implementations:

Reproducability If a token is based on attributes about the user, it
gains the advantage that one does not need secondary storage in which to
store the value between requests. However, if the same attributes can be
reproduced by an attacker, then the attacker can potentially forge this
information.

Reusability. It might be desired to make a completely different token
every use, and disallow users from re-using past tokens. This is an
extremely powerful protection, but can have consequences on if the user uses
the back button (or in some cases runs forms simultaneously in multiple
browser tabs) and submits an old token, or otherwise. A possible compromise
is to allow reusability in a time window (more on that later).

Time Ranges Many CSRF approaches use time-based expiry to make sure that
a token cannot be (re)used beyond a certain point. Care must be taken in
choosing the time criteria for this to not lock out legitimate users. For
example, if a user might walk away while filling out a long-ish form, or to
go look for their credit card, the time for expiry should take that into
consideration to provide a balance between security and limiting user
inconvenience.

Requirements Some CSRF-prevention methods require the use of browser
cookies, and some even require client-side scripting support. The webmaster
implementing the CSRF needs to consider that such requirements (though
effective) may lock certain legitimate users out, and make this
determination whether it is a good idea to use. For example, for a site
already using cookies for login, adding another for CSRF isn’t as big of a
deal, but for other sites it may not be feasible.

Session-based CSRF implementation¶

A provided CSRF implementation which puts CSRF data in a session.

This can be used fairly comfortably with many request.session type
objects, including the Werkzeug/Flask session store, Django sessions, and
potentially other similar objects which use a dict-like API for storing
session keys.

The basic concept is a randomly generated value is stored in the user’s
session, and an hmac-sha1 of it (along with an optional expiration time,
for extra security) is used as the value of the csrf_token. If this token
validates with the hmac of the random value + expiration time, and the
expiration time is not passed, the CSRF validation will pass.

Usage

First, create a SessionSecureForm subclass that you can use as your base class
for any forms you want CSRF support for:

from wtforms.ext.csrf.session import SessionSecureForm

class MyBaseForm(SessionSecureForm):
    SECRET_KEY = 'EPj00jpfj8Gx1SjnyLxwBBSQfnQ9DJYe0Ym'
    TIME_LIMIT = timedelta(minutes=20)

Now incorporate it into any form/view by further subclassing:

class Registration(MyBaseForm):
    name = TextField()

def view(request):
    form = Registration(request.POST, csrf_context=request.session)
    # rest of view here

Note that request.session is passed as the <tt class="docutils literal">csrf_context=</tt> parameter, this is
so that the CSRF token can be stored in your session for comparison on a later
request.

class <tt class="descclassname">wtforms.ext.csrf.session.</tt><tt class="descname">SessionSecureForm</tt><big>(</big>formdata=None, obj=None, prefix=u'', csrf_context=None, **kwargs<big>)</big>¶

A provided CSRF implementation which puts CSRF data in a session. Must be
subclassed to be used.

Class Attributes

<tt class="descname">SECRET_KEY</tt>¶

Must be set by subclasses to a random byte string that will be used to generate HMAC digests.

<tt class="descname">TIME_LIMIT</tt>¶

If None, CSRF tokens never expire. If set to a <tt class="docutils literal">datetime.timedelta</tt>,
this is how long til a generated token expires. Defaults to
<tt class="docutils literal">timedelta(minutes=30)</tt>

        © Copyright 2010 by the WTForms Team,
        documentation generated by Sphinx


text:
package org.jsimpledb.core;

class SimpleFieldStorageInfo<T> extends FieldStorageInfo {

    final FieldType<T> fieldType;
    final int superFieldStorageId;

    SimpleFieldStorageInfo(SimpleField<T> field, int superFieldStorageId) {
        this(field, field.fieldType, superFieldStorageId);
    }

    SimpleFieldStorageInfo(SimpleField<T> field, FieldType<T> fieldType, int superFieldStorageId) {
        super(field);
        this.fieldType = fieldType;
        this.superFieldStorageId = superFieldStorageId;
    }

    @Override
    public boolean isSubField() {
        return this.superFieldStorageId != 0;
    }

    CoreIndex<T, ObjId> getSimpleFieldIndex(Transaction tx) {
        if (this.superFieldStorageId != 0)
            throw new RuntimeException("internal error");
        return new CoreIndex<T, ObjId>(tx, new IndexView<T, ObjId>(this.storageId, this.fieldType, FieldTypeRegistry.OBJ_ID));
    }

// Object

    @Override
    public String toString() {
        return "simple field with " + this.fieldType;
    }

    @Override
    public final boolean equals(Object obj) {
        if (obj == this)
            return true;
        if (!super.equals(obj))
            return false;
        final SimpleFieldStorageInfo<?> that = (SimpleFieldStorageInfo<?>)obj;
        return this.fieldTypeEquals(that) && this.superFieldStorageId == that.superFieldStorageId;
    }

    @Override
    public int hashCode() {
        return super.hashCode() ^ this.fieldTypeHashCode() ^ this.superFieldStorageId;
    }

    protected boolean fieldTypeEquals(SimpleFieldStorageInfo<?> that) {
        return this.fieldType.equals(that.fieldType);
    }

    protected int fieldTypeHashCode() {
        return this.fieldType.hashCode();
    }
}


text:
<?php

namespace Vulah\Core\Entity;

use Doctrine\ORM\Mapping as ORM;
use Vulah\Core\DTO\Casting\CharacterOverviewCasting;
use Vulah\Core\DTO\Casting\MediaOverviewCasting;
use Vulah\Core\DTO\Casting\PersonOverviewCasting;

/**
 * @ORM\Entity
 * @ORM\Table(name="media_people")
 **/
class Casting
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     **/
    private $id;

    /**
     * @var \Vulah\Core\Entity\Media
     *
     * @ORM\ManyToOne(targetEntity="Media", inversedBy="castings")
     * @ORM\JoinColumn(name="media_id", referencedColumnName="id")
     */
    private $media;

    /**
     * @var \Vulah\Core\Entity\Character
     *
     * @ORM\ManyToOne(targetEntity="Character", inversedBy="castings")
     * @ORM\JoinColumn(name="character_id", referencedColumnName="id")
     */
    private $character;

    /**
     * @var \Vulah\Core\Entity\Person
     *
     * @ORM\ManyToOne(targetEntity="Person", inversedBy="castings")
     * @ORM\JoinColumn(name="person_id", referencedColumnName="id")
     */
    private $person;

    /**
     * @ORM\Column(type="string", length=100)
     * @var string
     */
    private $type;

    /**
     * @ORM\Column(type="string", length=20)
     * @var string
     */
    private $characterRole;

    /**
     * @ORM\Column(type="string", length=2)
     * @var string
     */
    private $language;

    public function toMediaOverviewDto(): MediaOverviewCasting
    {
        $dto = new MediaOverviewCasting;
        $dto->person = $this->person->toSimpleDto();
        $dto->type = $this->type;
        $dto->characterRole = $this->characterRole;
        $dto->language = $this->language;

        if ($this->character) {
            $dto->character = $this->character->toSimpleDto();
        }

        return $dto;
    }

    public function toCharacterOverviewDto(): CharacterOverviewCasting
    {
        $dto = new CharacterOverviewCasting;
        $dto->media = $this->media->toSimpleDto();
        $dto->person = $this->person->toSimpleDto();

        return $dto;
    }

    public function toPersonOverviewDto(): PersonOverviewCasting
    {
        $dto = new PersonOverviewCasting;
        $dto->media = $this->media->toSimpleDto();

        if ($this->character) {
            $dto->character = $this->character->toSimpleDto();
        }

        return $dto;
    }
}


text:
package com.example.cesar.vego;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.graphics.Path;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.graphics.Color;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.content.pm.PackageManager;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.BitmapDescriptor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import android.content.DialogInterface;
import java.net.URLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.Reader;
import org.json.JSONException;
import org.json.JSONObject;
//import com.google.code.gson;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private Button btnFindPath;
    private Button btnStart;
    private Button btnEnd;

    private EditText etDestination;
    private List<Marker> originMarkers = new ArrayList<>(); // marker de inico sera de color Verde
    private List<Marker> destinationMarkers = new ArrayList<>();// marker de llegada de color Negro
    private ProgressDialog progressDialog;
    private Marker markerOrigin;
    private Marker markerDestintion;

    private RadioGroup rg;
    private RadioButton rb;

//    private UserFunctions userFunction = new UserFunctions();

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        btnFindPath = (Button) findViewById(R.id.btnFindPath);
        etDestination = (EditText) findViewById(R.id.etDestination);

        /**   btnFindPath.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View v) {
        sendRequest();
        }
        });*/
        //Cuando se presione en btnStart, aparesca el icono marker verde
        //Cuando se presione en btnEnd, aparesca el icono marker negro
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
        rg =(RadioGroup) findViewById(R.id.rgroup);
    }
/*
    private void sendRequest (){

        String destination = etDestination.getText().toString();

        if (destination.isEmpty()){
            Toast.makeText(this, "Holanda, pon tu destino!", Toast.LENGTH_SHORT).show();// aca pone la mierda que debe salir en el labelText
        }

        try{
            new Path.Direction()
        }
    }*/

    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng hcmus = new LatLng(-16.3900397, -71.5356918);
        LatLng hcmus_2 = new LatLng(-16.3921694, -71.5357161);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(hcmus, 15));
        /*originMarkers.add(mMap.addMarker(new MarkerOptions()
                .title("You are Aqui")
                .position(hcmus)
                .draggable(true)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))));
            */
        //hcmus = markerOrigin.getPosition();
        markerOrigin = mMap.addMarker(new MarkerOptions()
                .title("You are Aqui")
                .position(hcmus)
                .draggable(true)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

        markerDestintion = mMap.addMarker(new MarkerOptions()
                .title("You are here")
                .position(hcmus_2)
                .draggable(false)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mMap.setMyLocationEnabled(true);
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Maps Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.example.cesar.vego/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Maps Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.example.cesar.vego/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }

    public void rbclick(View v)
    {
        int radionButtonId = rg.getCheckedRadioButtonId();
        rb = (RadioButton)findViewById(radionButtonId);
        Toast.makeText(getBaseContext(),rb.getText(),Toast.LENGTH_LONG).show();
        /*    if(rb.getText()=="Start") {
                markerOrigin = mMap.addMarker(new MarkerOptions()
                        .title("You are Aqui")
                        .draggable(true)
                        .s
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

            }
        markerDestintion.setVisible(false);
            if(rb.getText()=="End") {

                markerDestintion.setVisible(true);
            }
        markerOrigin.isVisible();*/
    }

/**
        public void findPath(View v) {
            Gson gson = new Gson();

            int entero = 2;
            Log.d("Formato Json entero",gson.toJson(entero));

            String cadena ="Gson";
            Log.d("Formato Json cadena",gson.toJson(cadena));

            int arreglo[] ={1,2,3,4};
            Log.d("Formato Json arreglo",gson.toJson(arreglo));

            String mensage = "Ubicacion: " + markerOrigin.getPosition().longitude + "-" + markerOrigin.getPosition().latitude;
            new AlertDialog.Builder(this)
                    .setTitle("Delete entry")
                    .setMessage(mensage)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // continue with delete
                        }
                    })
                    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
        }*/

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */

}


text:
package buildcraft.api.filler;

public class FillerManager {

	public static IFillerRegistry registry;

}


text:
package bstar

import (
	"fmt"
	"time"

	"github.com/quintans/gomsg"
)

// heavely inspiried in http://zguide.zeromq.org/java:bstar

const (
	REQUEST_TIMEOUT = time.Second
	SETTLE_DELAY    = REQUEST_TIMEOUT * 2 //  Before failing over
)

type BStarClient struct {
	client    *gomsg.Client
	servers   []string
	serverNbr int
}

func NewBStarClient(primary string, backup string) BStarClient {
	this := BStarClient{
		client:  gomsg.NewClient().SetCodec(codec),
		servers: []string{primary, backup},
	}
	this.client.SetDefaultTimeout(time.Second)
	this.client.Connect(primary)

	return this
}

// Request sends a request to the Binary Star.
// If there's no reply within our timeout, we close the socket and try again.
// In Binary Star, it's the client vote that decides which
// server is primary; the client must therefore try to connect
// to each server in turn:
func (bsc BStarClient) Request(name string, payload interface{}, handler interface{}, timeout time.Duration) {
	expectReply := true
	// A request is used so that the bstar server can decide not to reply
	// if there is an inconsistent server state
	ch := bsc.client.RequestTimeout(name, payload, handler, timeout)
	for expectReply {
		err := <-ch
		if err == nil {
			expectReply = false
		} else {
			fmt.Println("W: no response from server, failing over. error:", err)
			//  client is confused; close it and open a new one
			bsc.client.Destroy()
			bsc.serverNbr = (bsc.serverNbr + 1) % 2
			<-time.After(SETTLE_DELAY)
			fmt.Printf("I: connecting to server at %s...\n", bsc.servers[bsc.serverNbr])
			bsc.client = gomsg.NewClient().SetCodec(codec)
			bsc.client.Connect(bsc.servers[bsc.serverNbr])

			//  Send request again, on new client
			ch = bsc.client.RequestTimeout(name, payload, handler, timeout)
		}
	}
}


text:
class PaymentsStateAndAssignedToOrderOnly < ActiveRecord::Migration
  def up
    # TODO: migrate existing payments
    rename_column :payments, :payable_id, :order_id
    remove_column :payments, :payable_type
    add_column :payments, :state, :string
  end

  def down
    remove_column :payments, :state
    add_column :payments, :payable_type, :string
    rename_column :payments, :order_id, :payable_id
  end
end


text:
    {{optionData.name}}

      <md-select class="md-primary height32" ng-model="optionData.val" ng-change="optionChanged(optionData.id, optionData.val[0])" style="float: right" ng-disabled="{{(optionData.id)?'false':'true'}}">
        <md-select-label>{{optionData.val[1]}}</md-select-label>
        <md-option ng-value="[i, opt]" ng-repeat="(i, opt) in optionData.options">{{ opt }}</md-option>
      </md-select>

      <md-switch class="md-primary height32" ng-model="optionData.val" ng-change="optionChanged(optionData.id, optionData.val)" aria-label="{{optionData.name}}" ng-disabled="{{(optionData.id)?'false':'true'}}"></md-switch>

      <md-slider class="md-primary height32" ng-model="optionData.val" min="{{optionData.min}}" max="{{optionData.max}}" step="{{optionData.step}}"  ng-change="optionChanged(optionData.id, optionData.val)" aria-label="{{optionData.name}}" ng-disabled="{{(optionData.id)?'false':'true'}}"></md-slider>

      <md-button class="md-raised" ng-click="optionData.action()">{{ (optionData.buttonName) ? optionData.buttonName : optionData.name }}</md-button>

      {{ (optionData.text) ? optionData.text : optionData.name }}

      <bng-option-easy-slider data="optionData.val"></bng-option-easy-slider>

      <bng-option-controllers data="optionData"></bng-option-controllers>

      <bng-option-bindings data="optionData"></bng-option-bindings>


text:
@import './size';
@import './size-lg';
@import './size-md';
@import './size-sm';


text: A [Corsica](https://github.com/mozilla/corsica) plugin.


text:
if (window.location.pathname.indexOf ("/story/" > -1)) {

  alert ('download story');

  $(".btns").children ("div").append ('

Download

Download all the photos from the story

');

  $("div.download_story div.btn_text").click (function () {

    for (var i=0; i<ThisLife.currentStory.moments.length; i++) {

       var moment = ThisLife.currentStory.moments[i];

       console.log ("Moment: " + moment.uid);
     }

  });
}


text:
var header = document.createElement("h1");
header.textContent = "Why are you on BuzzFeed?";
header.style.color = "red";
header.style.float = "left";
header.style.margin = "10% 25% 5% 25%";
var paragraph = document.createElement("p");
paragraph.textContent = "There obviously has to be some mistake. No one in their right mind would even consider visiting this cesspool of internet \'journalism\'. Are you insane? Did you accidentally click a link? Did malware redirect your browser to this page? Did someone else try to show you something they thought was funny? Try navigating to a better website.";
paragraph.style.color = "red";
paragraph.style.float = "left";
paragraph.style.margin = "0% 25% 2% 25%";
var link = document.createElement('a');
var linkText = document.createTextNode("@ethansinjin");
link.appendChild(linkText);
link.title = "Twitter";
link.href = "http://twitter.com/ethansinjin";
document.body.appendChild(link);
link.style.margin = "0% 25% 0% 25%";
document.body.innerHTML = '';
document.body.insertBefore(link, document.body.firstChild);
document.body.insertBefore(paragraph, document.body.firstChild);
document.body.insertBefore(header, document.body.firstChild);


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Mock metrics
 * @type {!Object}
 */
window.metrics = {
  recordEnum: function() {},
  recordSmallCount: function() {},
};

/**
 * Mock chrome APIs.
 * @type {!Object}
 */
let mockChrome;

/**
 * Mock task history.
 * @type {!TaskHistory}
 */
const mockTaskHistory = /** @type {!TaskHistory} */ ({
  getLastExecutedTime: function(id) {
    return 0;
  },
  recordTaskExecuted: function(id) {},
});

// Set up test components.
function setUp() {
  // Mock LoadTimeData strings.
  window.loadTimeData.getString = id => id;

  const mockTask = /** @type {!chrome.fileManagerPrivate.FileTask} */ ({
    taskId: 'handler-extension-id|app|any',
    isDefault: false,
    isGenericFileHandler: true,
  });

  // Mock chome APIs.
  mockChrome = {
    commandLinePrivate: {
      hasSwitch: function(name, callback) {
        callback(false);
      },
    },
    fileManagerPrivate: {
      DriveConnectionStateType: {
        ONLINE: 'ONLINE',
        OFFLINE: 'OFFLINE',
        METERED: 'METERED',
      },
      DriveOfflineReason: {
        NOT_READY: 'NOT_READY',
        NO_NETWORK: 'NO_NETWORK',
        NO_SERVICE: 'NO_SERVICE',
      },
      getFileTasks: function(entries, callback) {
        setTimeout(callback.bind(null, [mockTask]), 0);
      },
      executeTask: function(taskId, entries, onViewFiles) {
        onViewFiles('failed');
      },
      sharePathsWithCrostini: function(vmName, entries, persist, callback) {
        callback();
      },
    },
    runtime: {
      id: 'test-extension-id',
    },
  };

  installMockChrome(mockChrome);
}

/**
 * Fail with an error message.
 * @param {string} message The error message.
 * @param {string=} opt_details Optional details.
 */
function failWithMessage(message, opt_details) {
  if (opt_details) {
    message += ': '.concat(opt_details);
  }
  throw new Error(message);
}

/**
 * Returns mocked file manager components.
 * @return {!Object}
 */
function getMockFileManager() {
  const crostini = createCrostiniForTest();

  const fileManager = {
    volumeManager: /** @type {!VolumeManager} */ ({
      getLocationInfo: function(entry) {
        return {
          rootType: VolumeManagerCommon.RootType.DRIVE,
        };
      },
      getDriveConnectionState: function() {
        return chrome.fileManagerPrivate.DriveConnectionStateType;
      },
      getVolumeInfo: function(entry) {
        return {
          volumeType: VolumeManagerCommon.VolumeType.DRIVE,
        };
      },
    }),
    ui: /** @type {!FileManagerUI} */ ({
      alertDialog: {
        showHtml: function(title, text, onOk, onCancel, onShow) {},
      },
      speakA11yMessage: (text) => {},
    }),
    metadataModel: /** @type {!MetadataModel} */ ({}),
    namingController: /** @type {!NamingController} */ ({}),
    directoryModel: /** @type {!DirectoryModel} */ ({
      getCurrentRootType: function() {
        return null;
      },
    }),
    crostini: crostini,
  };

  fileManager.crostini.initVolumeManager(fileManager.volumeManager);
  return fileManager;
}

/**
 * Returns a promise that resolves when the showHtml method of alert dialog is
 * called with the expected title and text.
 *
 * @param {!Array<!Entry>} entries Entries.
 * @param {string} expectedTitle The expected title.
 * @param {string} expectedText The expected text.
 * @return {!Promise}
 */
function showHtmlOfAlertDialogIsCalled(entries, expectedTitle, expectedText) {
  return new Promise((resolve, reject) => {
    const fileManager = getMockFileManager();
    fileManager.ui.alertDialog.showHtml =
        (title, text, onOk, onCancel, onShow) => {
          assertEquals(expectedTitle, title);
          assertEquals(expectedText, text);
          resolve();
        };

    FileTasks
        .create(
            fileManager.volumeManager, fileManager.metadataModel,
            fileManager.directoryModel, fileManager.ui, entries, [null],
            mockTaskHistory, fileManager.namingController, fileManager.crostini)
        .then(tasks => {
          tasks.executeDefault();
        });
  });
}

/**
 * Returns a promise that resolves when openSuggestAppsDialog is called.
 *
 * @param {!Array<!Entry>} entries Entries.
 * @param {!Array<?string>} mimeTypes Mime types.
 * @return {!Promise}
 */
function openSuggestAppsDialogIsCalled(entries, mimeTypes) {
  return new Promise((resolve, reject) => {
    const fileManager = getMockFileManager();
    fileManager.ui.suggestAppsDialog = {
      showByExtensionAndMime: function(extension, mimeType, onDialogClosed) {
        resolve();
      },
    };

    FileTasks
        .create(
            fileManager.volumeManager, fileManager.metadataModel,
            fileManager.directoryModel, fileManager.ui, entries, mimeTypes,
            mockTaskHistory, fileManager.namingController, fileManager.crostini)
        .then(tasks => {
          tasks.executeDefault();
        });
  });
}

/**
 * Returns a promise that resolves when the task picker is called.
 *
 * @param {!Array<!Entry>} entries Entries.
 * @param {!Array<?string>} mimeTypes Mime types.
 * @return {!Promise}
 */
function showDefaultTaskDialogCalled(entries, mimeTypes) {
  return new Promise((resolve, reject) => {
    const fileManager = getMockFileManager();
    fileManager.ui.defaultTaskPicker = {
      showDefaultTaskDialog: function(
          title, message, items, defaultIdx, onSuccess) {
        resolve();
      },
    };

    FileTasks
        .create(
            fileManager.volumeManager, fileManager.metadataModel,
            fileManager.directoryModel, fileManager.ui, entries, mimeTypes,
            mockTaskHistory, fileManager.namingController, fileManager.crostini)
        .then(tasks => {
          tasks.executeDefault();
        });
  });
}

/**
 * Returns a promise that resolves when showImportCrostiniImageDialog is called.
 *
 * @param {!Array<!Entry>} entries Entries.
 * @return {!Promise}
 */
function showImportCrostiniImageDialogIsCalled(entries) {
  return new Promise((resolve, reject) => {
    const fileManager = getMockFileManager();
    fileManager.ui.importCrostiniImageDialog = {
      showImportCrostiniImageDialog: (entry) => {
        resolve();
      },
    };

    FileTasks
        .create(
            fileManager.volumeManager, fileManager.metadataModel,
            fileManager.directoryModel, fileManager.ui, entries, [null],
            mockTaskHistory, fileManager.namingController, fileManager.crostini)
        .then(tasks => {
          tasks.executeDefault();
        });
  });
}

/**
 * Tests opening a .exe file.
 */
function testToOpenExeFile(callback) {
  const mockFileSystem = new MockFileSystem('volumeId');
  const mockEntry = MockFileEntry.create(mockFileSystem, '/test.exe');

  reportPromise(
      showHtmlOfAlertDialogIsCalled(
          [mockEntry], 'test.exe', 'NO_TASK_FOR_EXECUTABLE'),
      callback);
}

/**
 * Tests opening a .dmg file.
 */
function testToOpenDmgFile(callback) {
  const mockFileSystem = new MockFileSystem('volumeId');
  const mockEntry = MockFileEntry.create(mockFileSystem, '/test.dmg');

  reportPromise(
      showHtmlOfAlertDialogIsCalled([mockEntry], 'test.dmg', 'NO_TASK_FOR_DMG'),
      callback);
}

/**
 * Tests opening a .crx file.
 */
function testToOpenCrxFile(callback) {
  const mockFileSystem = new MockFileSystem('volumeId');
  const mockEntry = MockFileEntry.create(mockFileSystem, '/test.crx');

  reportPromise(
      showHtmlOfAlertDialogIsCalled(
          [mockEntry], 'NO_TASK_FOR_CRX_TITLE', 'NO_TASK_FOR_CRX'),
      callback);
}

/**
 * Tests opening a .rtf file.
 */
function testToOpenRtfFile(callback) {
  const mockFileSystem = new MockFileSystem('volumeId');
  const mockEntry = MockFileEntry.create(mockFileSystem, '/test.rtf');

  reportPromise(
      openSuggestAppsDialogIsCalled([mockEntry], ['application/rtf']),
      callback);
}

/**
 * Tests opening an entry that has external metadata type.
 */
function testOpenSuggestAppsDialogWithMetadata(callback) {
  const showByExtensionAndMimeIsCalled = new Promise((resolve, reject) => {
    const mockFileSystem = new MockFileSystem('volumeId');
    const mockEntry = MockFileEntry.create(mockFileSystem, '/test.rtf');
    const fileManager = getMockFileManager();

    FileTasks
        .create(
            fileManager.volumeManager, fileManager.metadataModel,
            fileManager.directoryModel, /** @type {!FileManagerUI} */ ({
              taskMenuButton: document.createElement('button'),
              fileContextMenu: {
                defaultActionMenuItem: document.createElement('div'),
              },
              suggestAppsDialog: {
                showByExtensionAndMime: function(
                    extension, mimeType, onDialogClosed) {
                  assertEquals('.rtf', extension);
                  assertEquals('application/rtf', mimeType);
                  resolve();
                },
              },
            }),
            [mockEntry], ['application/rtf'], mockTaskHistory,
            fileManager.namingController, fileManager.crostini)
        .then(tasks => {
          tasks.openSuggestAppsDialog(() => {}, () => {}, () => {});
        });
  });

  reportPromise(showByExtensionAndMimeIsCalled, callback);
}

/**
 * Tests opening an entry that has no extension. Since the entry extension and
 * entry MIME type are required, the onFalure method should be called.
 */
function testOpenSuggestAppsDialogFailure(callback) {
  const onFailureIsCalled = new Promise((resolve, reject) => {
    const mockFileSystem = new MockFileSystem('volumeId');
    const mockEntry = MockFileEntry.create(mockFileSystem, '/test');
    const fileManager = getMockFileManager();

    FileTasks
        .create(
            fileManager.volumeManager, fileManager.metadataModel,
            fileManager.directoryModel, fileManager.ui, [mockEntry], [null],
            mockTaskHistory, fileManager.namingController, fileManager.crostini)
        .then(tasks => {
          tasks.openSuggestAppsDialog(() => {}, () => {}, resolve);
        });
  });

  reportPromise(onFailureIsCalled, callback);
}

/**
 * Tests opening the task picker with an entry that does not have a default app
 * but there are multiple apps that could open it.
 */
function testOpenTaskPicker(callback) {
  window.chrome.fileManagerPrivate.getFileTasks = (entries, callback) => {
    setTimeout(
        callback.bind(
            null,
            [
              {
                taskId: 'handler-extension-id1|app|any',
                isDefault: false,
                isGenericFileHandler: false,
                title: 'app 1',
              },
              {
                taskId: 'handler-extension-id2|app|any',
                isDefault: false,
                isGenericFileHandler: false,
                title: 'app 2',
              },
            ]),
        0);
  };

  const mockFileSystem = new MockFileSystem('volumeId');
  const mockEntry = MockFileEntry.create(mockFileSystem, '/test.tiff');

  reportPromise(
      showDefaultTaskDialogCalled([mockEntry], ['image/tiff']), callback);
}

/**
 * Tests opening the task picker with an entry that does not have a default app
 * but there are multiple apps that could open it. The app with the most recent
 * task execution order should execute.
 */
function testOpenWithMostRecentlyExecuted(callback) {
  const latestTaskId = 'handler-extension-most-recently-executed|app|any';
  const oldTaskId = 'handler-extension-executed-before|app|any';

  window.chrome.fileManagerPrivate.getFileTasks = (entries, callback) => {
    setTimeout(
        callback.bind(
            null,
            // File tasks is sorted by last executed time, latest first.
            [
              {
                taskId: latestTaskId,
                isDefault: false,
                isGenericFileHandler: false,
                title: 'app 1',
              },
              {
                taskId: oldTaskId,
                isDefault: false,
                isGenericFileHandler: false,
                title: 'app 2',
              },
              {
                taskId: 'handler-extension-never-executed|app|any',
                isDefault: false,
                isGenericFileHandler: false,
                title: 'app 3',
              },
            ]),
        0);
  };

  const taskHistory = /** @type {!TaskHistory} */ ({
    getLastExecutedTime: function(id) {
      if (id == oldTaskId) {
        return 10000;
      }
      if (id == latestTaskId) {
        return 20000;
      }
      return 0;
    },
    recordTaskExecuted: function(id) {},
  });

  let executedTask = null;
  window.chrome.fileManagerPrivate.executeTask =
      (taskId, entries, onViewFiles) => {
        executedTask = taskId;
        onViewFiles('success');
      };

  const mockFileSystem = new MockFileSystem('volumeId');
  const mockEntry = MockFileEntry.create(mockFileSystem, '/test.tiff');

  const promise = new Promise((resolve, reject) => {
    const fileManager = getMockFileManager();
    fileManager.ui.defaultTaskPicker = {
      showDefaultTaskDialog: function(
          title, message, items, defaultIdx, onSuccess) {
        failWithMessage('should not show task picker');
      },
    };

    FileTasks
        .create(
            fileManager.volumeManager, fileManager.metadataModel,
            fileManager.directoryModel, fileManager.ui, [mockEntry], [null],
            taskHistory, fileManager.namingController, fileManager.crostini)
        .then(tasks => {
          tasks.executeDefault();
          assertEquals(latestTaskId, executedTask);
          resolve();
        });
  });

  reportPromise(promise, callback);
}

/**
 * Tests opening a .zip file.
 */
function testOpenZipWithZipArchiver(callback) {
  const zipArchiverTaskId = 'dmboannefpncccogfdikhmhpmdnddgoe|app|open';

  chrome.commandLinePrivate.hasSwitch = (name, callback) => {
    if (name == 'enable-zip-archiver-unpacker') {
      // This flag used to exist and was used to switch between the "Zip
      // Unpacker" and "Zip Archiver" component extensions.
      failWithMessage('run zip archiver', 'zip archiver flags checked');
    }
    callback(false);
  };

  window.chrome.fileManagerPrivate.getFileTasks = (entries, callback) => {
    setTimeout(
        callback.bind(
            null,
            [
              {
                taskId: zipArchiverTaskId,
                isDefault: false,
                isGenericFileHandler: false,
                title: 'Zip Archiver',
              },
            ]),
        0);
  };

  // None of the tasks has ever been executed.
  const taskHistory = /** @type {!TaskHistory} */ ({
    getLastExecutedTime: function(id) {
      return 0;
    },
    recordTaskExecuted: function(id) {},
  });

  let executedTask = null;
  window.chrome.fileManagerPrivate.executeTask =
      (taskId, entries, onViewFiles) => {
        executedTask = taskId;
        onViewFiles('success');
      };

  const mockFileSystem = new MockFileSystem('volumeId');
  const mockEntry = MockFileEntry.create(mockFileSystem, '/test.zip');

  const promise = new Promise((resolve, reject) => {
    const fileManager = getMockFileManager();
    fileManager.ui.defaultTaskPicker = {
      showDefaultTaskDialog: function(
          title, message, items, defaultIdx, onSuccess) {
        failWithMessage('run zip archiver', 'default task picker was shown');
      },
    };

    FileTasks
        .create(
            fileManager.volumeManager, fileManager.metadataModel,
            fileManager.directoryModel, fileManager.ui, [mockEntry], [null],
            taskHistory, fileManager.namingController, fileManager.crostini)
        .then(tasks => {
          tasks.executeDefault();
          assertEquals(zipArchiverTaskId, executedTask);
          resolve();
        });
  });

  reportPromise(promise, callback);
}

function setUpInstallLinuxPackage() {
  const fileManager = getMockFileManager();
  fileManager.volumeManager.getLocationInfo = entry => {
    return /** @type {!EntryLocation} */ ({
      rootType: VolumeManagerCommon.RootType.CROSTINI,
    });
  };
  const fileTask = {
    taskId: 'test-extension-id|app|install-linux-package',
    isDefault: false,
    isGenericFileHandler: false,
    title: '__MSG_INSTALL_LINUX_PACKAGE__',
  };
  window.chrome.fileManagerPrivate.getFileTasks = (entries, callback) => {
    setTimeout(callback.bind(null, [fileTask]), 0);
  };
  return fileManager;
}

/**
 * Tests opening a .deb file. The crostini linux package install dialog should
 * be called.
 */
function testOpenInstallLinuxPackageDialog(callback) {
  const fileManager = setUpInstallLinuxPackage();
  const mockFileSystem = new MockFileSystem('volumeId');
  const mockEntry = MockFileEntry.create(mockFileSystem, '/test.deb');

  const promise = new Promise((resolve, reject) => {
    fileManager.ui.installLinuxPackageDialog = {
      showInstallLinuxPackageDialog: function(entry) {
        resolve();
      },
    };

    FileTasks
        .create(
            fileManager.volumeManager, fileManager.metadataModel,
            fileManager.directoryModel, fileManager.ui, [mockEntry], [null],
            mockTaskHistory, fileManager.namingController, fileManager.crostini)
        .then(tasks => {
          tasks.executeDefault();
        });
  });

  reportPromise(promise, callback);
}

/**
 * Tests opening a .tini file. The import crostini image dialog should be
 * called.
 */
function testToOpenTiniFileOpensImportCrostiniImageDialog(callback) {
  window.chrome.fileManagerPrivate.getFileTasks = (entries, callback) => {
    setTimeout(
        callback.bind(
            null,
            [
              {
                taskId: 'test-extension-id|app|import-crostini-image',
                isDefault: false,
                isGenericFileHandler: false,
              },
            ]),
        0);
  };

  const mockEntry =
      MockFileEntry.create(new MockFileSystem('testfilesystem'), '/test.tini');

  reportPromise(showImportCrostiniImageDialogIsCalled([mockEntry]), callback);
}

/**
 * Checks that the function that returns a file type for file entry handles
 * correctly identifies files with known and unknown extensions.
 */
function testGetViewFileType() {
  const mockFileSystem = new MockFileSystem('volumeId');
  const testData = [
    {extension: 'log', expected: '.log'},
    {extension: '__unknown_extension__', expected: 'other'},
  ];
  for (const data of testData) {
    const mockEntry =
        MockFileEntry.create(mockFileSystem, `/report.${data.extension}`);
    const type = FileTasks.getViewFileType(mockEntry);
    assertEquals(data.expected, type);
  }
}


text:
template<typename T>
struct VECTOR2
{
	T x;
	T y;
};

//#define iVECTOR2 VECTOR2<int>

enum MouseButtonDownType
{
	LEFT_BUTTON_DOWN = 1,
	RIGHT_BUTTON_DOWN = 2,
	MIDDLE_BUTTON_DOWN = 4,
	SIDE_BUTTON_DOWN = 8,
	SIDE_2_BUTTON_DOWN = 16,
};

struct sMouseEvent
{
	bool isLeftButtonDown;
	bool isRightButtonDown;
	bool isMiddleButtonDown;
	bool isSide1ButtonDown;
	bool isSide2ButtonDown;
	int MouseWheelDelta;
	VECTOR2<int> mpos;
};

#endif