text:
// ReSharper disable All

namespace OpenTl.Schema
{
    using System;
	using System.Collections;

	using OpenTl.Schema;

    public interface IMessagesFilterCommon : IObject
    {

    }
}

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE MagicHash, UnboxedTuples, DeriveDataTypeable #-}

-- |
-- Module      : Data.Primitive.MutVar
-- Copyright   : (c) Justin Bonnar 2011, Roman Leshchinskiy 2011-2012
-- License     : BSD-style
--
-- Maintainer  : Roman Leshchinskiy <rl@cse.unsw.edu.au>
-- Portability : non-portable
--
-- Primitive boxed mutable variables
--

module Data.Primitive.MutVar (
  MutVar(..),

  newMutVar,
  readMutVar,
  writeMutVar,

  atomicModifyMutVar,
  modifyMutVar
) where

import Control.Monad.Primitive ( PrimMonad(..), primitive_ )
import GHC.Prim ( MutVar#, sameMutVar#, newMutVar#,
                  readMutVar#, writeMutVar#, atomicModifyMutVar# )
import Data.Typeable ( Typeable )

-- | A 'MutVar' behaves like a single-element mutable array associated
-- with a primitive state token.
data MutVar s a = MutVar (MutVar# s a)
  deriving ( Typeable )

instance Eq (MutVar s a) where
  MutVar mva# == MutVar mvb# = sameMutVar# mva# mvb#

-- | Create a new 'MutVar' with the specified initial value
newMutVar :: PrimMonad m => a -> m (MutVar (PrimState m) a)
{-# INLINE newMutVar #-}
newMutVar initialValue = primitive $ \s# ->
  case newMutVar# initialValue s# of
    (# s'#, mv# #) -> (# s'#, MutVar mv# #)

-- | Read the value of a 'MutVar'
readMutVar :: PrimMonad m => MutVar (PrimState m) a -> m a
{-# INLINE readMutVar #-}
readMutVar (MutVar mv#) = primitive (readMutVar# mv#)

-- | Write a new value into a 'MutVar'
writeMutVar :: PrimMonad m => MutVar (PrimState m) a -> a -> m ()
{-# INLINE writeMutVar #-}
writeMutVar (MutVar mv#) newValue = primitive_ (writeMutVar# mv# newValue)

-- | Atomically mutate the contents of a 'MutVar'
atomicModifyMutVar :: PrimMonad m => MutVar (PrimState m) a -> (a -> (a,b)) -> m b
{-# INLINE atomicModifyMutVar #-}
atomicModifyMutVar (MutVar mv#) f = primitive $ atomicModifyMutVar# mv# f

-- | Mutate the contents of a 'MutVar'
modifyMutVar :: PrimMonad m => MutVar (PrimState m) a -> (a -> a) -> m ()
{-# INLINE modifyMutVar #-}
modifyMutVar (MutVar mv#) g = primitive_ $ \s# ->
  case readMutVar# mv# s# of
    (# s'#, a #) -> writeMutVar# mv# (g a) s'#


text:
//
//  STDebugKitModuleSlowAnimations.h
//  STDebugKit
//
//  Created by Thomas Dupont on 09/09/13.

#import <UIKit/UIKit.h>

/**
 - Module Slow Animations -
 Allow to slow all the animations of your application in order to polish your UI.

 In order to use it, you should add the below define right before first import of STDebugKit
 #define STDebugKitModuleSlowAnimationsEnabled
 */
@interface STDebugKitModuleSlowAnimations : UIViewController

@end


text:
package com.pinhuba.core.daoimpl;

import org.springframework.stereotype.Repository;

import com.pinhuba.core.pojo.*;
import com.pinhuba.core.dao.*;
/**
 * 表:SYS_MSG 对应daoImpl
 */
@Repository
public class SysMsgDaoImpl extends BaseHapiDaoimpl<SysMsg, Long> implements ISysMsgDao {

   public SysMsgDaoImpl(){
      super(SysMsg.class);
   }
}


text:
CREATE TABLE IF NOT EXISTS `%PREFIX%files` (
  `id` int unsigned NOT NULL auto_increment,
  `item_id` int unsigned NOT NULL,
  `order` int(10) unsigned DEFAULT NULL,
  `size` int unsigned NOT NULL,
  `has_derivative_image` tinyint(1) NOT NULL,
  `authentication` char(32) collate utf8_unicode_ci default NULL,
  `mime_type` varchar(255) collate utf8_unicode_ci default NULL,
  `type_os` varchar(255) collate utf8_unicode_ci default NULL,
  `filename` text collate utf8_unicode_ci NOT NULL,
  `original_filename` text collate utf8_unicode_ci NOT NULL,
  `modified` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  `added` timestamp NOT NULL DEFAULT '2000-01-01 00:00:00',
  `stored` tinyint(1) NOT NULL default '0',
  `metadata` text collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `item_id` (`item_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


text:
@class MTLVertexAttributeDescriptorArray;
@class MTLVertexBufferLayoutDescriptorArray;

METAL_EXPORT_CLASS
@interface MTLVertexDescriptor : NSObject <NSCopying>

+ (MTLVertexDescriptor*)vertexDescriptor STUB_METHOD;

@property (readonly)MTLVertexAttributeDescriptorArray* attributes STUB_PROPERTY;
@property (readonly)MTLVertexBufferLayoutDescriptorArray* layouts STUB_PROPERTY;

- (void)reset STUB_METHOD;

@end


text:
using Gibraltar.Agent;
using NUnit.Framework;

namespace Loupe.Agent.Web.Module.Tests
{
    [SetUpFixture]
    public class AssemblySetup
    {
        [OneTimeSetUp]
        public void Setup()
        {
            Log.Initializing += Log_Initializing;

            Log.StartSession("Start HTTP Module Test Suite");
        }

        [OneTimeTearDown]
        public void TearDown()
        {
            Log.EndSession("Test suite complete.");
        }

        void Log_Initializing(object sender, LogInitializingEventArgs e)
        {
            var publisherConfig = e.Configuration.Publisher;
            publisherConfig.ApplicationDescription = "HTTp Module Unit Tests";
            publisherConfig.ApplicationName = "Unit Tests";
            publisherConfig.ProductName = "Loupe.Agent.Web.Module";
            publisherConfig.EnvironmentName = "Development";

        }
    }
}


text:
package apple.uikit.enums;

import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NInt;

@Generated
public final class UITableViewCellAccessoryType {
    /**
     * don't show any accessory view
     */
    @Generated @NInt public static final long None = 0x0000000000000000L;
    /**
     * regular chevron. doesn't track
     */
    @Generated @NInt public static final long DisclosureIndicator = 0x0000000000000001L;
    /**
     * info button w/ chevron. tracks
     */
    @Generated @NInt public static final long DetailDisclosureButton = 0x0000000000000002L;
    /**
     * checkmark. doesn't track
     */
    @Generated @NInt public static final long Checkmark = 0x0000000000000003L;
    /**
     * info button. tracks
     */
    @Generated @NInt public static final long DetailButton = 0x0000000000000004L;

    @Generated
    private UITableViewCellAccessoryType() {
    }
}


text:
package benchmark

import (
	"fmt"
	"github.com/golang/glog"
	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/kubernetes/plugin/pkg/scheduler"
	testutils "k8s.io/kubernetes/test/utils"
	"math"
	"strconv"
	"testing"
	"time"
)

const (
	warning3K    = 100
	threshold3K  = 30
	threshold30K = 30
	threshold60K = 30
)

var (
	basePodTemplate = &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			GenerateName: "sched-perf-pod-",
		},
		// TODO: this needs to be configurable.
		Spec: testutils.MakePodSpec(),
	}
	baseNodeTemplate = &v1.Node{
		ObjectMeta: metav1.ObjectMeta{
			GenerateName: "sample-node-",
		},
		Spec: v1.NodeSpec{
			// TODO: investigate why this is needed.
			ExternalID: "foo",
		},
		Status: v1.NodeStatus{
			Capacity: v1.ResourceList{
				v1.ResourcePods:   *resource.NewQuantity(110, resource.DecimalSI),
				v1.ResourceCPU:    resource.MustParse("4"),
				v1.ResourceMemory: resource.MustParse("32Gi"),
			},
			Phase: v1.NodeRunning,
			Conditions: []v1.NodeCondition{
				{Type: v1.NodeReady, Status: v1.ConditionTrue},
			},
		},
	}
)

// TestSchedule100Node3KPods schedules 3k pods on 100 nodes.
func TestSchedule100Node3KPods(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping because we want to run short tests")
	}

	config := getBaseConfig(100, 3000)
	err := writePodAndNodeTopologyToConfig(config)
	if err != nil {
		t.Errorf("Misconfiguration happened for nodes/pods chosen to have predicates and priorities")
	}
	min := schedulePods(config)
	if min < threshold3K {
		t.Errorf("Failing: Scheduling rate was too low for an interval, we saw rate of %v, which is the allowed minimum of %v ! ", min, threshold3K)
	} else if min < warning3K {
		fmt.Printf("Warning: pod scheduling throughput for 3k pods was slow for an interval... Saw a interval with very low (%v) scheduling rate!", min)
	} else {
		fmt.Printf("Minimal observed throughput for 3k pod test: %v\n", min)
	}
}

// TestSchedule2000Node60KPods schedules 60k pods on 2000 nodes.
// This test won't fit in normal 10 minutes time window.
// func TestSchedule2000Node60KPods(t *testing.T) {
// 	if testing.Short() {
// 		t.Skip("Skipping because we want to run short tests")
// 	}
// 	config := defaultSchedulerBenchmarkConfig(2000, 60000)
// 	if min := schedulePods(config); min < threshold60K {
// 		t.Errorf("To small pod scheduling throughput for 60k pods. Expected %v got %v", threshold60K, min)
// 	} else {
// 		fmt.Printf("Minimal observed throughput for 60k pod test: %v\n", min)
// 	}
// }

// testConfig contains the some input parameters needed for running test-suite
type testConfig struct {
	numPods                   int
	numNodes                  int
	mutatedNodeTemplate       *v1.Node
	mutatedPodTemplate        *v1.Pod
	schedulerSupportFunctions scheduler.Configurator
	destroyFunc               func()
}

// getBaseConfig returns baseConfig after initializing number of nodes and pods.
func getBaseConfig(nodes int, pods int) *testConfig {
	schedulerConfigFactory, destroyFunc := mustSetupScheduler()
	return &testConfig{
		schedulerSupportFunctions: schedulerConfigFactory,
		destroyFunc:               destroyFunc,
		numNodes:                  nodes,
		numPods:                   pods,
	}
}

// schedulePods schedules specific number of pods on specific number of nodes.
// This is used to learn the scheduling throughput on various
// sizes of cluster and changes as more and more pods are scheduled.
// It won't stop until all pods are scheduled.
// It returns the minimum of throughput over whole run.
func schedulePods(config *testConfig) int32 {
	defer config.destroyFunc()
	prev := 0
	// On startup there may be a latent period where NO scheduling occurs (qps = 0).
	// We are interested in low scheduling rates (i.e. qps=2),
	minQps := int32(math.MaxInt32)
	start := time.Now()
	// Bake in time for the first pod scheduling event.
	for {
		time.Sleep(50 * time.Millisecond)
		scheduled, err := config.schedulerSupportFunctions.GetScheduledPodLister().List(labels.Everything())
		if err != nil {
			glog.Fatalf("%v", err)
		}
		// 30,000 pods -> wait till @ least 300 are scheduled to start measuring.
		// TODO Find out why sometimes there may be scheduling blips in the beggining.
		if len(scheduled) > config.numPods/100 {
			break
		}
	}
	// map minimum QPS entries in a counter, useful for debugging tests.
	qpsStats := map[int]int{}

	// Now that scheduling has started, lets start taking the pulse on how many pods are happening per second.
	for {
		// This can potentially affect performance of scheduler, since List() is done under mutex.
		// Listing 10000 pods is an expensive operation, so running it frequently may impact scheduler.
		// TODO: Setup watch on apiserver and wait until all pods scheduled.
		scheduled, err := config.schedulerSupportFunctions.GetScheduledPodLister().List(labels.Everything())
		if err != nil {
			glog.Fatalf("%v", err)
		}

		// We will be completed when all pods are done being scheduled.
		// return the worst-case-scenario interval that was seen during this time.
		// Note this should never be low due to cold-start, so allow bake in sched time if necessary.
		if len(scheduled) >= config.numPods {
			fmt.Printf("Scheduled %v Pods in %v seconds (%v per second on average). min QPS was %v\n",
				config.numPods, int(time.Since(start)/time.Second), config.numPods/int(time.Since(start)/time.Second), minQps)
			return minQps
		}

		// There's no point in printing it for the last iteration, as the value is random
		qps := len(scheduled) - prev
		qpsStats[qps] += 1
		if int32(qps) < minQps {
			minQps = int32(qps)
		}
		fmt.Printf("%ds\trate: %d\ttotal: %d (qps frequency: %v)\n", time.Since(start)/time.Second, qps, len(scheduled), qpsStats)
		prev = len(scheduled)
		time.Sleep(1 * time.Second)
	}
}

// mutateNodeTemplate returns the modified node needed for creation of nodes.
func (na nodeAffinity) mutateNodeTemplate(node *v1.Node) {
	labels := make(map[string]string)
	for i := 0; i < na.LabelCount; i++ {
		value := strconv.Itoa(i)
		key := na.nodeAffinityKey + value
		labels[key] = value
	}
	node.ObjectMeta.Labels = labels
	return
}

// mutatePodTemplate returns the modified pod template after applying mutations.
func (na nodeAffinity) mutatePodTemplate(pod *v1.Pod) {
	var nodeSelectorRequirements []v1.NodeSelectorRequirement
	for i := 0; i < na.LabelCount; i++ {
		value := strconv.Itoa(i)
		key := na.nodeAffinityKey + value
		nodeSelector := v1.NodeSelectorRequirement{Key: key, Values: []string{value}, Operator: v1.NodeSelectorOpIn}
		nodeSelectorRequirements = append(nodeSelectorRequirements, nodeSelector)
	}
	pod.Spec.Affinity = &v1.Affinity{
		NodeAffinity: &v1.NodeAffinity{
			RequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{
				NodeSelectorTerms: []v1.NodeSelectorTerm{
					{
						MatchExpressions: nodeSelectorRequirements,
					},
				},
			},
		},
	}
}

// generateNodes generates nodes to be used for scheduling.
func (inputConfig *schedulerPerfConfig) generateNodes(config *testConfig) {
	for i := 0; i < inputConfig.NodeCount; i++ {
		config.schedulerSupportFunctions.GetClient().CoreV1().Nodes().Create(config.mutatedNodeTemplate)

	}
	for i := 0; i < config.numNodes-inputConfig.NodeCount; i++ {
		config.schedulerSupportFunctions.GetClient().CoreV1().Nodes().Create(baseNodeTemplate)

	}
}

// generatePods generates pods to be used for scheduling.
func (inputConfig *schedulerPerfConfig) generatePods(config *testConfig) {
	testutils.CreatePod(config.schedulerSupportFunctions.GetClient(), "sample", inputConfig.PodCount, config.mutatedPodTemplate)
	testutils.CreatePod(config.schedulerSupportFunctions.GetClient(), "sample", config.numPods-inputConfig.PodCount, basePodTemplate)
}

// generatePodAndNodeTopology is the wrapper function for modifying both pods and node objects.
func (inputConfig *schedulerPerfConfig) generatePodAndNodeTopology(config *testConfig) error {
	if config.numNodes < inputConfig.NodeCount || config.numPods < inputConfig.PodCount {
		return fmt.Errorf("NodeCount cannot be greater than numNodes")
	}
	nodeAffinity := inputConfig.NodeAffinity
	// Node template that needs to be mutated.
	mutatedNodeTemplate := baseNodeTemplate
	// Pod template that needs to be mutated.
	mutatedPodTemplate := basePodTemplate
	if nodeAffinity != nil {
		nodeAffinity.mutateNodeTemplate(mutatedNodeTemplate)
		nodeAffinity.mutatePodTemplate(mutatedPodTemplate)

	} // TODO: other predicates/priorities will be processed in subsequent if statements or a switch:).
	config.mutatedPodTemplate = mutatedPodTemplate
	config.mutatedNodeTemplate = mutatedNodeTemplate
	inputConfig.generateNodes(config)
	inputConfig.generatePods(config)
	return nil
}

// writePodAndNodeTopologyToConfig reads a configuration and then applies it to a test configuration.
//TODO: As of now, this function is not doing anything except for reading input values to priority structs.
func writePodAndNodeTopologyToConfig(config *testConfig) error {
	// High Level structure that should be filled for every predicate or priority.
	inputConfig := &schedulerPerfConfig{
		NodeCount: 100,
		PodCount:  3000,
		NodeAffinity: &nodeAffinity{
			nodeAffinityKey: "kubernetes.io/sched-perf-node-affinity-",
			LabelCount:      10,
		},
	}
	err := inputConfig.generatePodAndNodeTopology(config)
	if err != nil {
		return err
	}
	return nil
}


text:
package controle;

import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelo.Usuario;
import dao.UsuarioDAO;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author LoboMau
 */
@WebServlet(name = "UsuarioServlet", urlPatterns = {"/UsuarioServlet"})
public class UsuarioServlet extends HttpServlet {

    private UsuarioDAO usuarioDAO;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException, SQLException {

        usuarioDAO = new UsuarioDAO();

        String id_usuario = request.getParameter("id_usuario");
        String nome = request.getParameter("name");
        String apelido = request.getParameter("apelido");
        String email = request.getParameter("email");
        String senha = request.getParameter("senha");
        String operation = request.getParameter("operation");

        Usuario usuario = new Usuario(id_usuario, nome, apelido, email, senha);

        if (operation.equalsIgnoreCase("inserir")) {
            usuarioDAO.inserir(usuario);
            request.setAttribute("usuario", usuario);
        } else if (operation.equalsIgnoreCase("Edit")) {
            usuarioDAO.atualizar(usuario);
            Usuario buscarUsuario = (Usuario) usuarioDAO.listar();
            request.setAttribute("usuario", buscarUsuario);
        } else if (operation.equalsIgnoreCase("Delete")) {
            usuarioDAO.excluir(usuario);
        } else if (operation.equalsIgnoreCase("Buscar")) {
            Usuario buscarUsuario = null;
            usuarioDAO.buscar(usuario);
            request.setAttribute("usuario", buscarUsuario);
        }
        request.getRequestDispatcher("usuarioinfo.jsp").forward(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(UsuarioServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(UsuarioServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(UsuarioServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(UsuarioServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public String getServletInfo() {
        return "Breve descrição";
    }
}


text:
require 'spec_helper'
require 'sprockets'

describe MultiSync::ManifestSource do
  before do
    FileUtils.mkdir_p('tmp/local-manifest')
    File.open('tmp/local-manifest/foo.txt', File::CREAT | File::RDWR) do |f| f.write('foo') end
    File.open('tmp/local-manifest/bar.txt', File::CREAT | File::RDWR) do |f| f.write('bar') end
    FileUtils.mkdir_p('tmp/local-manifest/in-a-dir')
    File.open('tmp/local-manifest/in-a-dir/baz.html', File::CREAT | File::RDWR) do |f| f.write('baz') end
    File.open('tmp/local-manifest/in-a-dir/baz.txt', File::CREAT | File::RDWR) do |f| f.write('baz') end

    env = Sprockets::Environment.new('.') do |e|
      e.append_path('tmp/local-manifest')
    end
    manifest = Sprockets::Manifest.new(env, 'tmp/local-manifest')
    manifest.compile('foo.txt', 'bar.txt', 'in-a-dir/baz.html', 'in-a-dir/baz.txt')
  end

  describe :files do
    it 'should find files' do
      source = MultiSync::ManifestSource.new(source_dir: 'tmp/local-manifest')
      expect(source.files.size).to eq(4)
    end

    it 'should ignore found files' do
      source = MultiSync::ManifestSource.new(source_dir: 'tmp/local-manifest', include: '**/*', exclude: '*/*.html')
      expect(source.files.size).to eq(3)
    end

    it 'should find files (recursively)' do
      source = MultiSync::ManifestSource.new(source_dir: 'tmp/local-manifest', include: '**/*')
      expect(source.files.size).to eq(4)
    end

    it 'should find files (by type)' do
      source = MultiSync::ManifestSource.new(source_dir: 'tmp/local-manifest', include: '**/*.txt')
      expect(source.files.size).to eq(3)
    end

    context :with_root do
      it 'should return files with the root' do
        source = MultiSync::ManifestSource.new(source_dir: 'tmp/local-manifest')
        expect(source.files[0].path_with_root.to_s).to include 'tmp/local-manifest'
      end
    end

    context :without_root do
      it 'should return files without the root' do
        source = MultiSync::ManifestSource.new(source_dir: 'tmp/local-manifest')
        expect(source.files[0].path_without_root.to_s).to_not include 'tmp/local-manifest'
      end
    end
  end
end


text:
import React, { Component } from 'react'
import {
  Container,
  Row,
  Col,
  Collapse,
} from 'reactstrap'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'

import imgLayers from './layers.png'
import imgCR from './cr.png'
import imgCC from './cc.png'
import imgCPD from './cpd.png'

import Page from './page'

class ExpandableContent extends Component {
  handleClick (props) {
    if (this.props.handler) {
      this.props.handler()
    }
  }

  render () {
    return (

        { !this.props.open &&

 this.handleClick() }>

              { this.props.title }

              <FontAwesomeIcon icon="chevron-down" />

        }
        <Collapse isOpen={!!this.props.open}>

            {this.props.children}

        </Collapse>

    )
  }
}

class Project extends Component {
  constructor (props) {
    super(props)
    this.state = { openSection: false }
  }

  setSection (section) {
    this.setState({ openSection: section })
  }

  render () {
    const spaced = {
      marginBottom: '30px'
    }
    return (
      <Page>
        <Container id='project' className="content text-justify">
          <Row style={spaced}>
            <Col md={12} style={{textAlign: 'center'}}>

Nuestro Proyecto

                Tejido Social se plantea como tema central la relación del ciudadano mexicano con la democracia. Para abordar el tema se propone un proyecto en capas que en primera instancia aborda la relación de la ciudadanía con sus representantes, una segunda capa es dedicada a la relación de la ciudadanía con su ciudad y por último se aborda la relación de la ciudadanía con los procesos democráticos. Cada capa del proyecto irá acompañada de un experimento democrático y generará distintos contenidos.

            </Col>
            <Col md={12}>

            </Col>
          </Row>

          <Row style={spaced}>
            <Col md={3} className='text-center'>

            </Col>
            <Col md={9}>
              <ExpandableContent
                title="Monitor legislativo + Experimento democracia líquida"
                open={this.state.openSection === 'cr'}
                handler={() => this.setSection('cr')}
              >

Consideramos que mientras no existan mecanismos de participación más directa, es importante mantener bajo observación a quienes se encuentran en el poder. La propuesta insiste en una rendición de cuentas en tiempo real y en una comunicación bidireccional entre las y los representantes y la ciudadanía a la que representan.

No se debería ser una persona experta para poder entender lo que sucede en el Congreso. Sabemos que las y los diputados nos representan, pero ¿qué es exactamente lo que hacen en nuestro nombre? Una herramienta como el monitor legislativo hará más sencillo saber quienes nos representan, qué temas se están debatiendo y cómo se está votando.

Tejido Social propone desarrollar una plataforma en la que cualquier persona pueda, con tan sólo introducir su dirección o código postal, descifrar: quién es su representante ante el Congreso, a qué comisiones pertenece, qué posibles conflictos de interés podría tener, de qué manera ha votado en comparación al resto de sus compañerxs, con qué frecuencia se presenta y cuántas iniciativas de ley plantea. Para todo esto se pretende utilizar un programa de visualización de datos que permita que la plataforma sea sencilla de entender y muy ilustrativa. Así mismo, se propone poner a disposición de cualquier persona la información de contacto y redes sociales de cada representante, con la idea de fomentar la interacción con aquellas personas interesadas en el trabajo desarrollado.

En esta capa del proyecto, dedicada a la representación política, se plantea un experimento de democracia líquida. La idea de fondo de la democracia líquida es permitir que todo aquel sector de la ciudadanía que desee implicarse en política pueda hacerlo. Para ello, es necesario que se le reconozca a cada ciudadano y ciudadana la posibilidad de votar en decisiones y de formular propuestas, ya sea mediante su voto directo o cediéndolo a quienes consideren su mejor representante (según la decisión en la que se quiere participar).

              </ExpandableContent>
            </Col>
          </Row>

          <Row style={spaced}>
            <Col md={{ size: 3, order: 2 }} className='text-center'>

            </Col>
            <Col md={{ size: 9, order: 1 }}>
              <ExpandableContent
                title="Reporte ciudadano + Imaginario urbano (URBANAmente)"
                open={this.state.openSection === 'cc'}
                handler={() => this.setSection('cc')}
              >

La segunda capa del proyecto busca redefinir la participación de la ciudadanía con respecto a su ciudad. Se propone desarrollar una plataforma en la que las personas puedan hacer llegar a sus respectivas autoridades municipales cualquier inconformidad referente al espacio público.

En la plataforma cualquier persona podrá hacer un pequeño reporte acerca de lo que quiere notificar al municipio, situar en el mapa de su ciudad el reporte y adjuntar alguna fotografía que sustente su reporte. Otras personas podrán ver en el mapa los distintos reportes que se van efectuando en la ciudad. La idea es que este espacio no sólo sea un espacio para presentar quejas, sino también una plataforma para que las personas puedan visualizar las distintas problemáticas reportadas por sus conciudadanxs y darles seguimiento.

En esta segunda capa se propone experimentar con el imaginario urbano de las personas. La idea de fondo de este experimento, que hemos llamado URBANAmente, es fomentar la reapropiación del espacio público. En Tejido Social queremos que las personas se sientan propietarias y responsables, no sólo de los espacios que habitan (casas), sino de todos los espacios comunes que comparten en el día a día con otras personas.

              </ExpandableContent>
            </Col>
          </Row>

          <Row>
            <Col md={3} className='text-center'>

            </Col>
            <Col md={9}>
              <ExpandableContent
                title="Mapeo electoral + Cultura democrática"
                open={this.state.openSection === 'cpd'}
                handler={() => this.setSection('cpd')}
              >

En una tercera capa del proyecto nos proponemos abordar la relación de la ciudadanía con los procesos democráticos existentes. Se propone utilizar una herramienta de mapeo (Ushahidi) para realizar una vigilancia ciudadana o monitoreo colectivo de procesos electorales. Esto se ha utilizado en otras ocasiones pero se plantea que la plataforma esté disponible para cualquier proceso electoral que tenga lugar en el territorio nacional.

Se puede decir que esta plataforma busca proteger el voto de las y los ciudadanos. De nada sirve efectuar un voto cuando quien se encarga de capturar los conteos puede alterar los resultados. Desafortunadamente se han vivido experiencias como ésta en nuestro país. Mientras sigamos viviendo en una democracia representativa consideramos esencial defender la idea de que cada voto cuenta.

En esta capa, el experimento propuesto por Tejido Social es un intervención en escuelas de nivel básico y medio superior. La idea central es hacer un trabajo pedagógico acerca de la participación. Proponemos un programa de intervención democrática que pretende ampliar el entendimiento acerca de lo que es una democracia entre niñas y niños, y entre jóvenes cercanos a la mayoría de edad. Con esto se busca preparar a los jóvenes para comprender las implicaciones de vivir en una democracia, más allá del ejercicio de su voto.

              </ExpandableContent>
            </Col>
          </Row>
        </Container>
      </Page>
    )
  }
}

export default Project


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IMU3D
{
    // Left-handed quarternion, does not compatible to other quarternion definitions
    public class Quaternion : Matrix
    {
        // Constructors
        public Quaternion() : base(4, 1) { }
        public Quaternion(double x, double y, double z, double w) : base(4, 1, new double[] { x, y, z, w }) { }
        public Quaternion(Vector v, double w) : base(4, 1, new double[] { v.X, v.Y, v.Z, w }) { }
        public Quaternion(Matrix m)
            : this()
        {
            if (m.N != 4 || m.M != 1) throw new MatrixException("Quaternion initialization failed because invalid input");
            for (int i = 0; i < 4; i++)
                data[i, 0] = m[i, 0];
        }

        // Referencing properties
        public double this[int i]
        {
            get { return data[i, 0]; }
            set { data[i, 0] = value; }
        }
        public double X
        {
            get { return data[0, 0]; }
            set { data[0, 0] = value; }
        }
        public double Y
        {
            get { return data[1, 0]; }
            set { data[1, 0] = value; }
        }
        public double Z
        {
            get { return data[2, 0]; }
            set { data[2, 0] = value; }
        }
        public double W
        {
            get { return data[3, 0]; }
            set { data[3, 0] = value; }
        }

        // Multiplication
        public static Quaternion operator *(Quaternion a, Quaternion b)
        {
            return new Quaternion(a.Left * b);
        }

        // Multiplication in matrix representation
        public Matrix Left
        {
            get
            {
                return new Matrix(4, 4, new double[] {
                    W, Z, -Y, X,
                    -Z, W, X, Y,
                    Y, -X, W, Z,
                    -X, -Y, -Z, W
                });
            }
        }
        public Matrix Right
        {
            get
            {
                return new Matrix(4, 4, new double[] {
                    W, -Z, Y, X,
                    Z, W, -X, Y,
                    -Y, X, W, Z,
                    -X, -Y, -Z, W
                });
            }
        }

        // Length and Unit vector
        public double Length
        {
            get { return Math.Sqrt(LengthSquare); }
        }
        public double LengthSquare
        {
            get { return X * X + Y * Y + Z * Z + W * W; }
        }
        public Vector Unit
        {
            get { return Vector / Length; }
        }

        // Zero-order integrator in matrix representation
        public static Matrix ZeroOrderIntergrator(Vector v, double t)
        {
            double w = v.Length; // Length of v
            return Math.Cos(w * t / 2) * Matrix.Identity(4) + (Math.Sin(w * t / 2) / w * v).Omega;
        }

        // First-order integrator in matrix representation
        public static Matrix FirstOrderIntergrator(Vector v1, Vector v2, double t)
        {
            Vector v = (v1 + v2) / 2;
            Matrix o1 = (t * t / 48 * v1).Omega, o2 = v2.Omega;
            return ZeroOrderIntergrator(v, t) + (o2 * o1 - o1 * o2);
        }

        // Get vector of this quaternion
        public Vector Vector
        {
            get
            {
                return new Vector(X, Y, Z);
            }
        }
        // Rotation matrix of the quaternion
        public Matrix RotationMatrix
        {
            get
            {
                return (Identity(3) - (2 * W * Vector).Cross + 2 * Vector.CrossSquare);
            }
        }
        // Get from axis-angle representation
        public static Quaternion FromAxisAngle(Vector v, double a)
        {
            double w = Math.Cos(a / 2);
            Vector vq = v.Unit * Math.Sin(a / 2);
            return new Quaternion(vq, w);
        }
    }
}


text:
package cc.mallet.topics;

import java.util.ArrayList;
import java.util.Arrays;
import java.io.*;

import cc.mallet.types.*;
import cc.mallet.util.Randoms;

import gnu.trove.*;

public class HierarchicalLDA {

    InstanceList instances;
    InstanceList testing;

    NCRPNode rootNode, node;

    int numLevels;
    int numDocuments;
    int numTypes;

    double alpha; // smoothing on topic distributions
    double gamma; // "imaginary" customers at the next, as yet unused table
    double eta;   // smoothing on word distributions
    double etaSum;

    int[][] levels; // indexed < doc, token >
    NCRPNode[] documentLeaves; // currently selected path (ie leaf node) through the NCRP tree

	int totalNodes = 0;

	String stateFile = "hlda.state";

    Randoms random;

	boolean showProgress = true;

	int displayTopicsInterval = 50;
	int numWordsToDisplay = 10;

    public HierarchicalLDA () {
		alpha = 10.0;
		gamma = 1.0;
		eta = 0.1;
    }

	public void setAlpha(double alpha) {
		this.alpha = alpha;
	}

	public void setGamma(double gamma) {
		this.gamma = gamma;
	}

	public void setEta(double eta) {
		this.eta = eta;
	}

	public void setStateFile(String stateFile) {
		this.stateFile = stateFile;
	}

	public void setTopicDisplay(int interval, int words) {
		displayTopicsInterval = interval;
		numWordsToDisplay = words;
	}

	/**
	 *  This parameter determines whether the sampler outputs
	 *   shows progress by outputting a character after every iteration.
	 */
	public void setProgressDisplay(boolean showProgress) {
		this.showProgress = showProgress;
	}

    public void initialize(InstanceList instances, InstanceList testing,
						   int numLevels, Randoms random) {
		this.instances = instances;
		this.testing = testing;
		this.numLevels = numLevels;
		this.random = random;

		if (! (instances.get(0).getData() instanceof FeatureSequence)) {
			throw new IllegalArgumentException("Input must be a FeatureSequence, using the --feature-sequence option when impoting data, for example");
		}

		numDocuments = instances.size();
		numTypes = instances.getDataAlphabet().size();

		etaSum = eta * numTypes;

		// Initialize a single path

		NCRPNode[] path = new NCRPNode[numLevels];

		rootNode = new NCRPNode(numTypes);

		levels = new int[numDocuments][];
		documentLeaves = new NCRPNode[numDocuments];

		// Initialize and fill the topic pointer arrays for
		//  every document. Set everything to the single path that
		//  we added earlier.
		for (int doc=0; doc < numDocuments; doc++) {
            FeatureSequence fs = (FeatureSequence) instances.get(doc).getData();
            int seqLen = fs.getLength();

			path[0] = rootNode;
			rootNode.customers++;
			for (int level = 1; level < numLevels; level++) {
				path[level] = path[level-1].select();
				path[level].customers++;
			}
			node = path[numLevels - 1];

			levels[doc] = new int[seqLen];
			documentLeaves[doc] = node;

			for (int token=0; token < seqLen; token++) {
				int type = fs.getIndexAtPosition(token);
				levels[doc][token] = random.nextInt(numLevels);
				node = path[ levels[doc][token] ];
				node.totalTokens++;
				node.typeCounts[type]++;
			}
		}
	}

	public void estimate(int numIterations) {
		for (int iteration = 1; iteration <= numIterations; iteration++) {
			for (int doc=0; doc < numDocuments; doc++) {
				samplePath(doc, iteration);
			}
			for (int doc=0; doc < numDocuments; doc++) {
				sampleTopics(doc);
			}

			if (showProgress) {
				System.out.print(".");
				if (iteration % 50 == 0) {
					System.out.println(" " + iteration);
				}
			}

			if (iteration % displayTopicsInterval == 0) {
				printNodes();
			}
		}
    }

    public void samplePath(int doc, int iteration) {
		NCRPNode[] path = new NCRPNode[numLevels];
		NCRPNode node;
		int level, token, type, topicCount;
		double weight;

		node = documentLeaves[doc];
		for (level = numLevels - 1; level >= 0; level--) {
			path[level] = node;
			node = node.parent;
		}

		documentLeaves[doc].dropPath();

		TObjectDoubleHashMap<NCRPNode> nodeWeights =
			new TObjectDoubleHashMap<NCRPNode>();

		// Calculate p(c_m | c_{-m})
		calculateNCRP(nodeWeights, rootNode, 0.0);

		// Add weights for p(w_m | c, w_{-m}, z)

		// The path may have no further customers and therefore
		//  be unavailable, but it should still exist since we haven't
		//  reset documentLeaves[doc] yet...

		TIntIntHashMap[] typeCounts = new TIntIntHashMap[numLevels];

		int[] docLevels;

		for (level = 0; level < numLevels; level++) {
			typeCounts[level] = new TIntIntHashMap();
		}

		docLevels = levels[doc];
		FeatureSequence fs = (FeatureSequence) instances.get(doc).getData();

		// Save the counts of every word at each level, and remove
		//  counts from the current path

		for (token = 0; token < docLevels.length; token++) {
			level = docLevels[token];
			type = fs.getIndexAtPosition(token);

			if (! typeCounts[level].containsKey(type)) {
				typeCounts[level].put(type, 1);
			}
			else {
				typeCounts[level].increment(type);
			}

			path[level].typeCounts[type]--;
			assert(path[level].typeCounts[type] >= 0);

			path[level].totalTokens--;
			assert(path[level].totalTokens >= 0);
		}

		// Calculate the weight for a new path at a given level.
		double[] newTopicWeights = new double[numLevels];
		for (level = 1; level < numLevels; level++) {  // Skip the root...
			int[] types = typeCounts[level].keys();
			int totalTokens = 0;

			for (int t: types) {
				for (int i=0; i<typeCounts[level].get(t); i++) {
					newTopicWeights[level] +=
						Math.log((eta + i) / (etaSum + totalTokens));
					totalTokens++;
				}
			}

			//if (iteration > 1) { System.out.println(newTopicWeights[level]); }
		}

		calculateWordLikelihood(nodeWeights, rootNode, 0.0, typeCounts, newTopicWeights, 0, iteration);

		NCRPNode[] nodes = nodeWeights.keys(new NCRPNode[] {});
		double[] weights = new double[nodes.length];
		double sum = 0.0;
		double max = Double.NEGATIVE_INFINITY;

		// To avoid underflow, we're using log weights and normalizing the node weights so that
		//  the largest weight is always 1.
		for (int i=0; i<nodes.length; i++) {
			if (nodeWeights.get(nodes[i]) > max) {
				max = nodeWeights.get(nodes[i]);
			}
		}

		for (int i=0; i<nodes.length; i++) {
			weights[i] = Math.exp(nodeWeights.get(nodes[i]) - max);

			/*
			  if (iteration > 1) {
			  if (nodes[i] == documentLeaves[doc]) {
			  System.out.print("* ");
			  }
			  System.out.println(((NCRPNode) nodes[i]).level + "\t" + weights[i] +
			  "\t" + nodeWeights.get(nodes[i]));
			  }
			*/

			sum += weights[i];
		}

		//if (iteration > 1) {System.out.println();}

		node = nodes[ random.nextDiscrete(weights, sum) ];

		// If we have picked an internal node, we need to
		//  add a new path.
		if (! node.isLeaf()) {
			node = node.getNewLeaf();
		}

		node.addPath();
		documentLeaves[doc] = node;

		for (level = numLevels - 1; level >= 0; level--) {
			int[] types = typeCounts[level].keys();

			for (int t: types) {
				node.typeCounts[t] += typeCounts[level].get(t);
				node.totalTokens += typeCounts[level].get(t);
			}

			node = node.parent;
		}
    }

    public void calculateNCRP(TObjectDoubleHashMap<NCRPNode> nodeWeights,
							  NCRPNode node, double weight) {
		for (NCRPNode child: node.children) {
			calculateNCRP(nodeWeights, child,
						  weight + Math.log((double) child.customers / (node.customers + gamma)));
		}

		nodeWeights.put(node, weight + Math.log(gamma / (node.customers + gamma)));
    }

    public void calculateWordLikelihood(TObjectDoubleHashMap<NCRPNode> nodeWeights,
										NCRPNode node, double weight,
										TIntIntHashMap[] typeCounts, double[] newTopicWeights,
										int level, int iteration) {

		// First calculate the likelihood of the words at this level, given
		//  this topic.
		double nodeWeight = 0.0;
		int[] types = typeCounts[level].keys();
		int totalTokens = 0;

		//if (iteration > 1) { System.out.println(level + " " + nodeWeight); }

		for (int type: types) {
			for (int i=0; i<typeCounts[level].get(type); i++) {
				nodeWeight +=
					Math.log((eta + node.typeCounts[type] + i) /
							 (etaSum + node.totalTokens + totalTokens));
				totalTokens++;

				/*
				  if (iteration > 1) {
				  System.out.println("(" +eta + " + " + node.typeCounts[type] + " + " + i + ") /" +
				  "(" + etaSum + " + " + node.totalTokens + " + " + totalTokens + ")" +
				  " : " + nodeWeight);
				  }
				*/

			}
		}

		//if (iteration > 1) { System.out.println(level + " " + nodeWeight); }

		// Propagate that weight to the child nodes

		for (NCRPNode child: node.children) {
            calculateWordLikelihood(nodeWeights, child, weight + nodeWeight,
									typeCounts, newTopicWeights, level + 1, iteration);
        }

		// Finally, if this is an internal node, add the weight of
		//  a new path

		level++;
		while (level < numLevels) {
			nodeWeight += newTopicWeights[level];
			level++;
		}

		nodeWeights.adjustValue(node, nodeWeight);

    }

    /** Propagate a topic weight to a node and all its children.
		weight is assumed to be a log.
	*/
    public void propagateTopicWeight(TObjectDoubleHashMap<NCRPNode> nodeWeights,
									 NCRPNode node, double weight) {
		if (! nodeWeights.containsKey(node)) {
			// calculating the NCRP prior proceeds from the
			//  root down (ie following child links),
			//  but adding the word-topic weights comes from
			//  the bottom up, following parent links and then
			//  child links. It's possible that the leaf node may have
			//  been removed just prior to this round, so the current
			//  node may not have an NCRP weight. If so, it's not
			//  going to be sampled anyway, so ditch it.
			return;
		}

		for (NCRPNode child: node.children) {
			propagateTopicWeight(nodeWeights, child, weight);
		}

		nodeWeights.adjustValue(node, weight);
    }

    public void sampleTopics(int doc) {
		FeatureSequence fs = (FeatureSequence) instances.get(doc).getData();
		int seqLen = fs.getLength();
		int[] docLevels = levels[doc];
		NCRPNode[] path = new NCRPNode[numLevels];
		NCRPNode node;
		int[] levelCounts = new int[numLevels];
		int type, token, level;
		double sum;

		// Get the leaf
		node = documentLeaves[doc];
		for (level = numLevels - 1; level >= 0; level--) {
			path[level] = node;
			node = node.parent;
		}

		double[] levelWeights = new double[numLevels];

		// Initialize level counts
		for (token = 0; token < seqLen; token++) {
			levelCounts[ docLevels[token] ]++;
		}

		for (token = 0; token < seqLen; token++) {
			type = fs.getIndexAtPosition(token);

			levelCounts[ docLevels[token] ]--;
			node = path[ docLevels[token] ];
			node.typeCounts[type]--;
			node.totalTokens--;

			sum = 0.0;
			for (level=0; level < numLevels; level++) {
				levelWeights[level] =
					(alpha + levelCounts[level]) *
					(eta + path[level].typeCounts[type]) /
					(etaSum + path[level].totalTokens);
				sum += levelWeights[level];
			}
			level = random.nextDiscrete(levelWeights, sum);

			docLevels[token] = level;
			levelCounts[ docLevels[token] ]++;
			node = path[ level ];
			node.typeCounts[type]++;
			node.totalTokens++;
		}
    }

	/**
	 *  Writes the current sampling state to the file specified in stateFile.
	 */
	public void printState() throws IOException, FileNotFoundException {
		printState(new PrintWriter(new BufferedWriter(new FileWriter(stateFile))));
	}

	/**
	 *  Write a text file describing the current sampling state.
	 */
    public void printState(PrintWriter out) throws IOException {
		int doc = 0;

		Alphabet alphabet = instances.getDataAlphabet();

		for (Instance instance: instances) {
			FeatureSequence fs = (FeatureSequence) instance.getData();
			int seqLen = fs.getLength();
			int[] docLevels = levels[doc];
			NCRPNode node;
			int type, token, level;

			StringBuffer path = new StringBuffer();

			// Start with the leaf, and build a string describing the path for this doc
			node = documentLeaves[doc];
			for (level = numLevels - 1; level >= 0; level--) {
				path.append(node.nodeID + " ");
				node = node.parent;
			}

			for (token = 0; token < seqLen; token++) {
				type = fs.getIndexAtPosition(token);
				level = docLevels[token];

				// The "" just tells java we're not trying to add a string and an int
				out.println(path + "" + type + " " + alphabet.lookupObject(type) + " " + level + " ");
			}

			doc++;
		}
	}

    public void printNodes() {
		printNode(rootNode, 0, false);
    }

    public void printNodes(boolean withWeight) {
		printNode(rootNode, 0, withWeight);
    }

    public void printNode(NCRPNode node, int indent, boolean withWeight) {
		StringBuffer out = new StringBuffer();
		for (int i=0; i<indent; i++) {
			out.append("  ");
		}

		out.append(node.totalTokens + "/" + node.customers + " ");
		out.append(node.getTopWords(numWordsToDisplay, withWeight));
		System.out.println(out);

		for (NCRPNode child: node.children) {
			printNode(child, indent + 1, withWeight);
		}
    }

    /** For use with empirical likelihood evaluation:
     *   sample a path through the tree, then sample a multinomial over
     *   topics in that path, then return a weighted sum of words.
     */
    public double empiricalLikelihood(int numSamples, InstanceList testing)  {
		NCRPNode[] path = new NCRPNode[numLevels];
		NCRPNode node;
		double weight;
		path[0] = rootNode;

		FeatureSequence fs;
		int sample, level, type, token, doc, seqLen;

		Dirichlet dirichlet = new Dirichlet(numLevels, alpha);
		double[] levelWeights;
		double[] multinomial = new double[numTypes];

		double[][] likelihoods = new double[ testing.size() ][ numSamples ];

		for (sample = 0; sample < numSamples; sample++) {
			Arrays.fill(multinomial, 0.0);

			for (level = 1; level < numLevels; level++) {
				path[level] = path[level-1].selectExisting();
			}

			levelWeights = dirichlet.nextDistribution();

			for (type = 0; type < numTypes; type++) {
				for (level = 0; level < numLevels; level++) {
					node = path[level];
					multinomial[type] +=
						levelWeights[level] *
						(eta + node.typeCounts[type]) /
						(etaSum + node.totalTokens);
				}

			}

			for (type = 0; type < numTypes; type++) {
				multinomial[type] = Math.log(multinomial[type]);
			}

			for (doc=0; doc<testing.size(); doc++) {
                fs = (FeatureSequence) testing.get(doc).getData();
                seqLen = fs.getLength();

                for (token = 0; token < seqLen; token++) {
                    type = fs.getIndexAtPosition(token);
                    likelihoods[doc][sample] += multinomial[type];
                }
            }
		}

        double averageLogLikelihood = 0.0;
        double logNumSamples = Math.log(numSamples);
        for (doc=0; doc<testing.size(); doc++) {
            double max = Double.NEGATIVE_INFINITY;
            for (sample = 0; sample < numSamples; sample++) {
                if (likelihoods[doc][sample] > max) {
                    max = likelihoods[doc][sample];
                }
            }

            double sum = 0.0;
            for (sample = 0; sample < numSamples; sample++) {
                sum += Math.exp(likelihoods[doc][sample] - max);
            }

            averageLogLikelihood += Math.log(sum) + max - logNumSamples;
        }

		return averageLogLikelihood;
    }

	/**
	 *  This method is primarily for testing purposes. The {@link cc.mallet.topics.tui.HierarchicalLDATUI}
	 *   class has a more flexible interface for command-line use.
	 */
    public static void main (String[] args) {
		try {
			InstanceList instances = InstanceList.load(new File(args[0]));
			InstanceList testing = InstanceList.load(new File(args[1]));

			HierarchicalLDA sampler = new HierarchicalLDA();
			sampler.initialize(instances, testing, 5, new Randoms());
			sampler.estimate(250);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

    class NCRPNode {
		int customers;
		ArrayList<NCRPNode> children;
		NCRPNode parent;
		int level;

		int totalTokens;
		int[] typeCounts;

		public int nodeID;

		public NCRPNode(NCRPNode parent, int dimensions, int level) {
			customers = 0;
			this.parent = parent;
			children = new ArrayList<NCRPNode>();
			this.level = level;

			//System.out.println("new node at level " + level);

			totalTokens = 0;
			typeCounts = new int[dimensions];

			nodeID = totalNodes;
			totalNodes++;
		}

		public NCRPNode(int dimensions) {
			this(null, dimensions, 0);
		}

		public NCRPNode addChild() {
			NCRPNode node = new NCRPNode(this, typeCounts.length, level + 1);
			children.add(node);
			return node;
		}

		public boolean isLeaf() {
			return level == numLevels - 1;
		}

		public NCRPNode getNewLeaf() {
			NCRPNode node = this;
			for (int l=level; l<numLevels - 1; l++) {
				node = node.addChild();
			}
			return node;
		}

		public void dropPath() {
			NCRPNode node = this;
			node.customers--;
			if (node.customers == 0) {
				node.parent.remove(node);
			}
			for (int l = 1; l < numLevels; l++) {
				node = node.parent;
				node.customers--;
				if (node.customers == 0) {
					node.parent.remove(node);
				}
			}
		}

		public void remove(NCRPNode node) {
			children.remove(node);
		}

		public void addPath() {
			NCRPNode node = this;
			node.customers++;
			for (int l = 1; l < numLevels; l++) {
				node = node.parent;
				node.customers++;
			}
		}

		public NCRPNode selectExisting() {
			double[] weights = new double[children.size()];

			int i = 0;
			for (NCRPNode child: children) {
				weights[i] = (double) child.customers / (gamma + customers);
				i++;
			}

			int choice = random.nextDiscrete(weights);
			return children.get(choice);
		}

		public NCRPNode select() {
			double[] weights = new double[children.size() + 1];

			weights[0] = gamma / (gamma + customers);

			int i = 1;
			for (NCRPNode child: children) {
				weights[i] = (double) child.customers / (gamma + customers);
				i++;
			}

			int choice = random.nextDiscrete(weights);
			if (choice == 0) {
				return(addChild());
			}
			else {
				return children.get(choice - 1);
			}
		}

		public String getTopWords(int numWords, boolean withWeight) {
			IDSorter[] sortedTypes = new IDSorter[numTypes];

			for (int type=0; type < numTypes; type++) {
				sortedTypes[type] = new IDSorter(type, typeCounts[type]);
			}
			Arrays.sort(sortedTypes);

			Alphabet alphabet = instances.getDataAlphabet();
			StringBuffer out = new StringBuffer();
			for (int i = 0; i < numWords; i++) {
				if (withWeight){
					out.append(alphabet.lookupObject(sortedTypes[i].getID()) + ":" + sortedTypes[i].getWeight() + " ");
				}else
					out.append(alphabet.lookupObject(sortedTypes[i].getID()) + " ");
			}
			return out.toString();
		}

    }
}


text:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Umbraco.Core;
using Umbraco.Core.Composing;

namespace Umbraco.Web.HealthCheck
{
    /// <summary>
    /// Provides a base class for health checks.
    /// </summary>
    [DataContract(Name = "healtCheck", Namespace = "")]
    public abstract class HealthCheck : IDiscoverable
    {
        protected HealthCheck()
        {
            //Fill in the metadata
            var thisType = GetType();
            var meta = thisType.GetCustomAttribute<HealthCheckAttribute>(false);
            if (meta == null)
                throw new InvalidOperationException($"The health check {thisType} requires a {typeof (HealthCheckAttribute)}");
            Name = meta.Name;
            Description = meta.Description;
            Group = meta.Group;
            Id = meta.Id;
        }

        [DataMember(Name = "id")]
        public Guid Id { get; private set; }

        [DataMember(Name = "name")]
        public string Name { get; private set; }

        [DataMember(Name = "description")]
        public string Description { get; private set; }

        [DataMember(Name = "group")]
        public string Group { get; private set; }

        /// <summary>
        /// Get the status for this health check
        /// </summary>
        /// <returns></returns>
        public abstract IEnumerable<HealthCheckStatus> GetStatus();

        /// <summary>
        /// Executes the action and returns it's status
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public abstract HealthCheckStatus ExecuteAction(HealthCheckAction action);

        //TODO: What else?
    }
}


text:
@interface PodsDummy_GSCaptchaButton : NSObject
@end
@implementation PodsDummy_GSCaptchaButton
@end


text: A mathematics library for node and crazy numbers


text:
'use strict';

// Conexión a mongo
var mongoose = require('mongoose'),
    conf     = require('./db-conf');

/* Schema Definitions */
var Schema     = mongoose.Schema,
    taskSchema = new Schema({
        name: String,
        description: String,
        priority: String,
        progress: Number,
        done: Boolean,
        project: String,
        startAt: Date,
        endAt: Date,
        createdAt: Date,
        updatedAt: Date,
    }),
    projectSchema = new Schema({
        name: String,
        description: String,
        location: String,
        startAt: Date,
        endAt: Date,
        createdAt: Date,
        updatedAt: Date,
    }),
    timeSchema = new Schema({
        name: String,
        description: String,
        startAt: String,
        endAt: String,
        createdAt: Date,
        updatedAt: Date,
    });

var Task    = mongoose.model('Task', taskSchema),
    Project = mongoose.model('Project', projectSchema),
    Time    = mongoose.model('Time', timeSchema);

Task.getObjectId    = mongoose.Types.ObjectId;
Project.getObjectId = mongoose.Types.ObjectId;
Time.getObjectId    = mongoose.Types.ObjectId;

mongoose.connect('mongodb://' + conf.mongoDB.host + '/' + conf.mongoDB.database,
    function(err) {
        if (err) {
            console.log(' ERROR al conectar con la BDs');
            process.exit(1);
        }

        console.log('Conection to DB Established');
    }
);

module.exports = {
    Task: Task,
    Project: Project,
    Time: Time,
};


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">

    </group>

    <item android:title="Community">
        <menu>
            <item
                android:id="@+id/Profile"
                android:icon="@drawable/ic_menu_gallery"
                android:title="Profile" />
            <item
                android:id="@+id/Level_Bound"
                android:icon="@drawable/ic_menu_gallery"
                android:title="LeaderBoard" />
            <item
                android:id="@+id/Activity_Log"
                android:icon="@drawable/ic_menu_share"
                android:title="Activity Log" />

            <item
                android:id="@+id/Intelligence"
                android:icon="@drawable/ic_menu_manage"
                android:title="Intelligence" />
            <item
                android:id="@+id/Fitness"
                android:icon="@drawable/ic_menu_send"
                android:title="Fitness" />
            <item
                android:id="@+id/Society"
                android:icon="@drawable/ic_menu_gallery"
                android:title="Society" />
            <item
                android:id="@+id/Setting"
                android:icon="@drawable/ic_menu_manage"
                android:title="Setting" />
        </menu>
    </item>

</menu>


text:
/**
 * Jakarta Bean Validation TCK
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.beanvalidation.tck.tests.constraints.inheritance.method.validdeclarations.constraint;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import org.hibernate.beanvalidation.tck.tests.constraints.inheritance.method.validdeclarations.model.CalendarEvent;

/**
 * @author Gunnar Morling
 */
public class ValidBusinessCalendarEventValidator
		implements ConstraintValidator<ValidBusinessCalendarEvent, CalendarEvent> {

	@Override
	public boolean isValid(CalendarEvent value, ConstraintValidatorContext context) {
		return false;
	}
}


text:
package com.github.sormuras.listing.unit;

import static java.util.Objects.requireNonNull;

import com.github.sormuras.listing.Listable;
import com.github.sormuras.listing.Listing;
import com.github.sormuras.listing.Name;
import com.github.sormuras.listing.Tool;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Predicate;

/**
 * An import declaration allows a named type or a static member to be referred to by a simple name
 * (§6.2) that consists of a single identifier.
 *
 * @see https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.5
 */
public class ImportDeclarations implements Listable, Predicate<Name> {

  private Set<Name> onDemandStaticImports = new TreeSet<>();
  private Set<Name> onDemandTypeImports = new TreeSet<>();
  private Set<Name> singleStaticImports = new TreeSet<>();
  private Set<Name> singleTypeImports = new TreeSet<>();

  /**
   * Single static (enum) import declaration.
   *
{@code import static java.lang.Thread.State.NEW;}
   *
https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.5.3
   */
  public ImportDeclarations addSingleStaticImport(Enum<?> constant) {
    singleStaticImports.add(Name.of(requireNonNull(constant, "constant")));
    return this;
  }

  /**
   * Single static (member) import declaration.
   *
{@code import static java.util.Collections.shuffle;}
   *
https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.5.3
   */
  public ImportDeclarations addSingleStaticImport(Name name) {
    singleStaticImports.add(requireNonNull(name, "name"));
    return this;
  }

  /**
   * Single static (member) import declaration.
   *
{@code import static java.util.Collections.shuffle;}
   *
https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.5.3
   */
  public ImportDeclarations addSingleStaticImport(Member member) {
    Tool.assume(Modifier.isStatic(member.getModifiers()), "member %s must be static", member);
    singleStaticImports.add(Name.of(member));
    return this;
  }

  /**
   * Single type.
   *
{@code import java.util.Collections;}
   *
https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.5.1
   */
  public ImportDeclarations addSingleTypeImport(Class<?> type) {
    return addSingleTypeImport(Name.of(type));
  }

  /**
   * A single-type-import declaration imports a single type by giving its canonical name, making it
   * available under a simple name in the class and interface declarations of the compilation unit
   * in which the single-type-import declaration appears.
   *
{@code import java.util.Collections;}
   *
https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.5.1
   */
  public ImportDeclarations addSingleTypeImport(Name typeName) {
    singleTypeImports.add(typeName);
    return this;
  }

  /**
   * A static-import-on-demand declaration allows all accessible static members of a
   * named type to be imported as needed.
   *
{@code import static java.util.Collections.*;}
   *
https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.5.4
   */
  public ImportDeclarations addStaticImportOnDemand(Name typeName) {
    onDemandStaticImports.add(typeName);
    return this;
  }

  /**
   * A type-import-on-demand declaration allows all accessible types of a named package or
   * type to be imported as needed.
   *
{@code import java.util.*;}
   *
https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.5.2
   */
  public ImportDeclarations addTypeImportOnDemand(Name packageOrTypeName) {
    onDemandTypeImports.add(packageOrTypeName);
    return this;
  }

  @Override
  public Listing apply(Listing listing) {
    if (isEmpty()) {
      return listing;
    }
    listing.newline();
    if (!onDemandStaticImports.isEmpty()) {
      onDemandStaticImports.forEach(
          n -> listing.add("import static ").add(n.getCanonicalName()).add(".*;").newline());
    }
    if (!singleStaticImports.isEmpty()) {
      singleStaticImports.forEach(
          n -> listing.add("import static ").add(n.getCanonicalName()).add(';').newline());
    }
    listing.newline();
    if (!onDemandTypeImports.isEmpty()) {
      onDemandTypeImports.forEach(
          n -> listing.add("import ").add(n.getCanonicalName()).add(".*;").newline());
    }
    if (!singleTypeImports.isEmpty()) {
      singleTypeImports.forEach(
          n -> listing.add("import ").add(n.getCanonicalName()).add(';').newline());
    }
    listing.trim();
    return listing;
  }

  @Override
  public boolean isEmpty() {
    return singleTypeImports.isEmpty()
        && onDemandTypeImports.isEmpty()
        && singleStaticImports.isEmpty()
        && onDemandStaticImports.isEmpty();
  }

  @Override
  public boolean test(Name name) {
    // simple 1:1 match with a single (static) import
    if (singleTypeImports.contains(name) || singleStaticImports.contains(name)) {
      return true;
    }
    // on demand test...
    Optional<Name> enclosing = name.getEnclosing();
    if (enclosing.isPresent()) {
      name = enclosing.get();
      if (onDemandStaticImports.contains(name) || onDemandTypeImports.contains(name)) {
        return true;
      }
    }
    return false;
  }
}


text:
package com.sun.tools.rngom.digested;

import com.sun.tools.rngom.nc.NameClass;

/**
 * @author Kohsuke Kawaguchi (kk@kohsuke.org)
 */
public class DAttributePattern extends DXmlTokenPattern {
    public DAttributePattern(NameClass name) {
        super(name);
    }
    public Object accept( DPatternVisitor visitor ) {
        return visitor.onAttribute(this);
    }
}


text:
require_relative 'attractor'
require_relative 'mover'

attr_reader :attractor, :attractor_mover

def setup
  sketch_title 'Attraction'
  @attractor_mover = Mover.new
  @attractor = Attractor.new(location: Vec2D.new(width / 2, height / 2))
end

def draw
  background(255)
  attraction = attractor.attract(mover: attractor_mover)
  attractor_mover.apply_force(force: attraction)
  attractor_mover.update
  attractor.drag(position: Vec2D.new(mouse_x, mouse_y))
  attractor.hover(position: Vec2D.new(mouse_x, mouse_y))
  attractor.display
  attractor_mover.display
end

def mouse_pressed
  attractor.clicked(position: Vec2D.new(mouse_x, mouse_y))
end

def mouse_released
  attractor.stop_dragging
end

def settings
  size(640, 360)
end


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function ~adaptive_pool_base</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../interprocess/acknowledgements_notes.html#header.boost.interprocess.allocators.adaptive_pool_hpp" title="Header <boost/interprocess/allocators/adaptive_pool.hpp>">
<link rel="prev" href="adaptive_pool__idp48163344.html" title="Function template adaptive_pool_base">
<link rel="next" href="../adaptive_pool_v1.html" title="Class template adaptive_pool_v1">

Home
Libraries
People
FAQ
More

Function ~adaptive_pool_base

boost::interprocess::~adaptive_pool_base

Synopsis

// In header: <boost/interprocess/allocators/adaptive_pool.hpp>

 ~adaptive_pool_base();

Description

Destructor, removes node_pool_t from memory if its reference count reaches to zero. Never throws

Copyright © 2005-2012 Ion Gaztanaga

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package org.apache.camel.processor.aggregator;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.ThreadPoolRejectedPolicy;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.ThreadPoolProfileSupport;
import org.apache.camel.processor.BodyInAggregatingStrategy;
import org.apache.camel.spi.ThreadPoolProfile;

/**
 * @version
 */
public class AggregateThreadPoolProfileTest extends ContextTestSupport {

    public void testAggregateThreadPoolProfile() throws Exception {
        getMockEndpoint("mock:aggregated").expectedBodiesReceived("A+B+C");

        template.sendBodyAndHeader("direct:start", "A", "id", 123);
        template.sendBodyAndHeader("direct:start", "B", "id", 123);
        template.sendBodyAndHeader("direct:start", "C", "id", 123);

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                // create and register thread pool profile
                ThreadPoolProfile profile = new ThreadPoolProfileSupport("myProfile");
                profile.setPoolSize(2);
                profile.setMaxPoolSize(8);
                profile.setRejectedPolicy(ThreadPoolRejectedPolicy.Abort);
                context.getExecutorServiceStrategy().registerThreadPoolProfile(profile);

                from("direct:start")
                    .aggregate(header("id"), new BodyInAggregatingStrategy())
                        // use our custom thread pool profile
                        .completionSize(3).executorServiceRef("myProfile")
                        .to("log:foo")
                        .to("mock:aggregated");
            }
        };
    }
}


text:
// Copyright (c) 2013 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.

#include <memory>

#include "base/command_line.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/test/base/chrome_test_utils.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/cloud/cloud_policy_client.h"
#include "components/policy/core/common/cloud/device_management_service.h"
#include "components/policy/core/common/cloud/mock_cloud_policy_client.h"
#include "components/policy/core/common/policy_switches.h"
#include "components/policy/core/common/policy_test_utils.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_test.h"
#include "net/base/net_errors.h"
#include "net/http/http_status_code.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/network/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/ash/policy/core/user_cloud_policy_manager_ash.h"
#else
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#endif

using content::BrowserThread;
using testing::_;
using testing::AnyNumber;
using testing::InvokeWithoutArgs;
using testing::Mock;

namespace em = enterprise_management;

namespace policy {

namespace {

// Parses the upload data in |request| into |request_msg|, and validates the
// request. The query string in the URL must contain the |expected_type| for
// the "request" parameter. Returns true if all checks succeeded, and the
// request data has been parsed into |request_msg|.
bool ValidRequest(const std::string& method,
                  const GURL& url,
                  const std::string& data,
                  const std::string& expected_type,
                  em::DeviceManagementRequest* request_msg) {
  if (method != "POST")
    return false;
  std::string spec = url.spec();
  if (spec.find("request=" + expected_type) == std::string::npos)
    return false;

  if (!request_msg->ParseFromString(data))
    return false;

  return true;
}

void RespondWithBadResponse(const network::ResourceRequest& request,
                            network::TestURLLoaderFactory* factory) {
  network::URLLoaderCompletionStatus status;
  factory->AddResponse(
      request.url, network::mojom::URLResponseHead::New(), std::string(),
      network::URLLoaderCompletionStatus(net::ERR_NETWORK_CHANGED));
}

void RespondToRegisterWithSuccess(em::DeviceRegisterRequest::Type expected_type,
                                  bool expect_reregister,
                                  const network::ResourceRequest& request,
                                  network::TestURLLoaderFactory* factory) {
  em::DeviceManagementRequest request_msg;
  if (!ValidRequest(request.method, request.url,
                    network::GetUploadData(request), "register",
                    &request_msg)) {
    RespondWithBadResponse(request, factory);
    return;
  }

  if (!request_msg.has_register_request() ||
      request_msg.has_unregister_request() ||
      request_msg.has_policy_request() ||
      request_msg.has_device_status_report_request() ||
      request_msg.has_session_status_report_request() ||
      request_msg.has_auto_enrollment_request()) {
    RespondWithBadResponse(request, factory);
    return;
  }

  const em::DeviceRegisterRequest& register_request =
      request_msg.register_request();
  if (expect_reregister &&
      (!register_request.has_reregister() || !register_request.reregister())) {
    RespondWithBadResponse(request, factory);
    return;
  } else if (!expect_reregister && register_request.has_reregister() &&
             register_request.reregister()) {
    RespondWithBadResponse(request, factory);
    return;
  }

  if (!register_request.has_type() ||
      register_request.type() != expected_type) {
    RespondWithBadResponse(request, factory);
    return;
  }

  std::string content;
  network::URLLoaderCompletionStatus status;

  em::DeviceManagementResponse response;
  em::DeviceRegisterResponse* register_response =
      response.mutable_register_response();
  register_response->set_device_management_token("s3cr3t70k3n");
  response.SerializeToString(&content);

  status.decoded_body_length = content.size();

  auto head = network::CreateURLResponseHead(net::HTTP_OK);
  head->mime_type = "application/protobuf";

  factory->AddResponse(request.url, std::move(head), content, status);
}

}  // namespace

// Tests the cloud policy stack using a URLRequestJobFactory::ProtocolHandler
// to intercept requests and produce canned responses.
class CloudPolicyManagerTest : public PlatformBrowserTest {
 protected:
  CloudPolicyManagerTest() {}
  ~CloudPolicyManagerTest() override {}

  void SetUpInProcessBrowserTestFixture() override {
    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    command_line->AppendSwitchASCII(switches::kDeviceManagementUrl,
                                    "http://localhost");
    ChromeBrowserPolicyConnector::EnableCommandLineSupportForTesting();

    // Set retry delay to prevent timeouts.
    policy::DeviceManagementService::SetRetryDelayForTesting(0);
  }

  void SetUpOnMainThread() override {
    PlatformBrowserTest::SetUpOnMainThread();

    ASSERT_TRUE(PolicyServiceIsEmpty(g_browser_process->policy_service()))
        << "Pre-existing policies in this machine will make this test fail.";

    test_url_loader_factory_ =
        std::make_unique<network::TestURLLoaderFactory>();

#if BUILDFLAG(IS_CHROMEOS_LACROS)
    base::FilePath dest_path =
        g_browser_process->profile_manager()->user_data_dir();
    profile_ = Profile::CreateProfile(
        dest_path.Append(FILE_PATH_LITERAL("New Profile 1")), nullptr,
        Profile::CreateMode::CREATE_MODE_SYNCHRONOUS);
#endif

    BrowserPolicyConnector* connector =
        g_browser_process->browser_policy_connector();
    connector->ScheduleServiceInitialization(0);

#if BUILDFLAG(IS_CHROMEOS_ASH)
    policy_manager()->core()->client()->SetURLLoaderFactoryForTesting(
        test_url_loader_factory_->GetSafeWeakWrapper());
#else
    // Mock a signed-in user. This is used by the UserCloudPolicyStore to pass
    // the username to the UserCloudPolicyValidator.
    identity_test_env_ = std::make_unique<signin::IdentityTestEnvironment>();
    identity_test_env_->MakePrimaryAccountAvailable(
        "user@example.com", signin::ConsentLevel::kSync);

    ASSERT_TRUE(policy_manager());
    policy_manager()->Connect(
        g_browser_process->local_state(),
        UserCloudPolicyManager::CreateCloudPolicyClient(
            connector->device_management_service(),
            test_url_loader_factory_->GetSafeWeakWrapper()));
#endif
  }

  void TearDownOnMainThread() override {
    // Verify that all the expected requests were handled.
    EXPECT_EQ(0, test_url_loader_factory_->NumPending());
    identity_test_env_.reset();
#if BUILDFLAG(IS_CHROMEOS_LACROS)
    profile_.reset();
#endif
  }

#if BUILDFLAG(IS_CHROMEOS_ASH)
  UserCloudPolicyManagerAsh* policy_manager() {
    return chrome_test_utils::GetProfile(this)->GetUserCloudPolicyManagerAsh();
  }
#elif BUILDFLAG(IS_CHROMEOS_LACROS)
  UserCloudPolicyManager* policy_manager() {
    return profile_->GetUserCloudPolicyManager();
  }
#else
  UserCloudPolicyManager* policy_manager() {
    return chrome_test_utils::GetProfile(this)->GetUserCloudPolicyManager();
  }
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

  // Register the client of the policy_manager() using a bogus auth token, and
  // returns once the registration gets a result back.
  void Register() {
    ASSERT_TRUE(policy_manager());
    ASSERT_TRUE(policy_manager()->core()->client());

    base::RunLoop run_loop;
    MockCloudPolicyClientObserver observer;
    EXPECT_CALL(observer, OnRegistrationStateChanged(_))
        .Times(AnyNumber())
        .WillRepeatedly(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
    EXPECT_CALL(observer, OnClientError(_))
        .Times(AnyNumber())
        .WillRepeatedly(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
    policy_manager()->core()->client()->AddObserver(&observer);

    // Give a bogus OAuth token to the |policy_manager|. This should make its
    // CloudPolicyClient fetch the DMToken.
    CloudPolicyClient::RegistrationParameters parameters(
#if BUILDFLAG(IS_CHROMEOS_ASH)
        em::DeviceRegisterRequest::USER,
#else
        em::DeviceRegisterRequest::BROWSER,
#endif
        em::DeviceRegisterRequest::FLAVOR_USER_REGISTRATION);
    policy_manager()->core()->client()->Register(
        parameters, std::string() /* client_id */,
        "oauth_token_unused" /* oauth_token */);
    run_loop.Run();
    Mock::VerifyAndClearExpectations(&observer);
    policy_manager()->core()->client()->RemoveObserver(&observer);
  }

  std::unique_ptr<signin::IdentityTestEnvironment> identity_test_env_;
  std::unique_ptr<network::TestURLLoaderFactory> test_url_loader_factory_;
#if BUILDFLAG(IS_CHROMEOS_LACROS)
  // For Lacros use non-main profile in these tests.
  std::unique_ptr<Profile> profile_;
#endif
};

IN_PROC_BROWSER_TEST_F(CloudPolicyManagerTest, Register) {
  test_url_loader_factory_->SetInterceptor(
      base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
        // Accept one register request. The initial request should not include
        // the reregister flag.
        em::DeviceRegisterRequest::Type expected_type =
#if BUILDFLAG(IS_CHROMEOS_ASH)
            em::DeviceRegisterRequest::USER;
#else
            em::DeviceRegisterRequest::BROWSER;
#endif
        RespondToRegisterWithSuccess(expected_type, /*expect_reregister=*/false,
                                     request, test_url_loader_factory_.get());
      }));

  EXPECT_FALSE(policy_manager()->core()->client()->is_registered());
  ASSERT_NO_FATAL_FAILURE(Register());
  EXPECT_TRUE(policy_manager()->core()->client()->is_registered());
}

IN_PROC_BROWSER_TEST_F(CloudPolicyManagerTest, RegisterFails) {
  test_url_loader_factory_->SetInterceptor(
      base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
        test_url_loader_factory_->AddResponse(request.url.spec(), std::string(),
                                              net::HTTP_BAD_REQUEST);
      }));

  EXPECT_FALSE(policy_manager()->core()->client()->is_registered());
  ASSERT_NO_FATAL_FAILURE(Register());
  EXPECT_FALSE(policy_manager()->core()->client()->is_registered());
}

IN_PROC_BROWSER_TEST_F(CloudPolicyManagerTest, RegisterFailsWithRetries) {
  // Fail 4 times with ERR_NETWORK_CHANGED; the first 3 will trigger a retry,
  // the last one will forward the error to the client and unblock the
  // register process.
  int count = 0;
  test_url_loader_factory_->SetInterceptor(
      base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
        network::URLLoaderCompletionStatus status(net::ERR_NETWORK_CHANGED);
        test_url_loader_factory_->AddResponse(
            request.url, network::mojom::URLResponseHead::New(), std::string(),
            status);
        ++count;
      }));

  EXPECT_FALSE(policy_manager()->core()->client()->is_registered());
  ASSERT_NO_FATAL_FAILURE(Register());
  EXPECT_FALSE(policy_manager()->core()->client()->is_registered());
  EXPECT_EQ(4, count);
}

IN_PROC_BROWSER_TEST_F(CloudPolicyManagerTest, RegisterWithRetry) {
  test_url_loader_factory_->SetInterceptor(
      base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
        em::DeviceRegisterRequest::Type expected_type =
#if BUILDFLAG(IS_CHROMEOS_ASH)
            em::DeviceRegisterRequest::USER;
#else
            em::DeviceRegisterRequest::BROWSER;
#endif

        // Accept one register request after failing once. The retry request
        // should set the reregister flag.
        static bool gave_error = false;
        if (!gave_error) {
          gave_error = true;
          network::URLLoaderCompletionStatus status(net::ERR_NETWORK_CHANGED);
          test_url_loader_factory_->AddResponse(
              request.url, network::mojom::URLResponseHead::New(),
              std::string(), status);
          return;
        }

        RespondToRegisterWithSuccess(expected_type, /*expect_reregister=*/true,
                                     request, test_url_loader_factory_.get());
      }));

  EXPECT_FALSE(policy_manager()->core()->client()->is_registered());
  ASSERT_NO_FATAL_FAILURE(Register());
  EXPECT_TRUE(policy_manager()->core()->client()->is_registered());
}

}  // namespace policy


text:
@interface BadgeButton : UIButton
@property(nonatomic,copy)NSString *badgeValue;
@end


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

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.sns.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * GetSMSAttributesRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetSMSAttributesRequestMarshaller implements Marshaller<Request<GetSMSAttributesRequest>, GetSMSAttributesRequest> {

    public Request<GetSMSAttributesRequest> marshall(GetSMSAttributesRequest getSMSAttributesRequest) {

        if (getSMSAttributesRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<GetSMSAttributesRequest> request = new DefaultRequest<GetSMSAttributesRequest>(getSMSAttributesRequest, "AmazonSNS");
        request.addParameter("Action", "GetSMSAttributes");
        request.addParameter("Version", "2010-03-31");
        request.setHttpMethod(HttpMethodName.POST);

        if (!getSMSAttributesRequest.getAttributes().isEmpty()
                || !((com.amazonaws.internal.SdkInternalList<String>) getSMSAttributesRequest.getAttributes()).isAutoConstruct()) {
            com.amazonaws.internal.SdkInternalList<String> attributesList = (com.amazonaws.internal.SdkInternalList<String>) getSMSAttributesRequest
                    .getAttributes();
            int attributesListIndex = 1;

            for (String attributesListValue : attributesList) {
                if (attributesListValue != null) {
                    request.addParameter("attributes.member." + attributesListIndex, StringUtils.fromString(attributesListValue));
                }
                attributesListIndex++;
            }
        }

        return request;
    }

}


text:
package xhandler

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"context"

	"github.com/stretchr/testify/assert"
)

var testRequest, _ = http.NewRequest("GET", "/", nil)

func TestAppendHandlerC(t *testing.T) {
	init := 0
	h1 := func(next HandlerC) HandlerC {
		init++
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			ctx = context.WithValue(ctx, "test", 1)
			next.ServeHTTPC(ctx, w, r)
		})
	}
	h2 := func(next HandlerC) HandlerC {
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			ctx = context.WithValue(ctx, "test", 2)
			next.ServeHTTPC(ctx, w, r)
		})
	}
	c := Chain{}
	c.UseC(h1)
	c.UseC(h2)
	assert.Len(t, c, 2)

	h := c.Handler(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		// Test ordering
		assert.Equal(t, 2, ctx.Value("test"), "second handler should overwrite first handler's context value")
	}))

	h.ServeHTTP(nil, testRequest)
	h.ServeHTTP(nil, testRequest)
	assert.Equal(t, 1, init, "handler init called once")
}

func TestAppendHandler(t *testing.T) {
	init := 0
	h1 := func(next HandlerC) HandlerC {
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			ctx = context.WithValue(ctx, "test", 1)
			next.ServeHTTPC(ctx, w, r)
		})
	}
	h2 := func(next http.Handler) http.Handler {
		init++
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Change r and w values
			w = httptest.NewRecorder()
			r = &http.Request{}
			next.ServeHTTP(w, r)
		})
	}
	c := Chain{}
	c.UseC(h1)
	c.Use(h2)
	assert.Len(t, c, 2)

	h := c.Handler(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		// Test ordering
		assert.Equal(t, 1, ctx.Value("test"),
			"the first handler value should be pass through the second (non-aware) one")
		// Test r and w overwrite
		assert.NotNil(t, w)
		assert.NotNil(t, r)
	}))

	h.ServeHTTP(nil, testRequest)
	h.ServeHTTP(nil, testRequest)
	// There's no safe way to not initialize non ctx aware handlers on each request :/
	//assert.Equal(t, 1, init, "handler init called once")
}

func TestChainHandlerC(t *testing.T) {
	handlerCalls := 0
	h1 := func(next HandlerC) HandlerC {
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			handlerCalls++
			ctx = context.WithValue(ctx, "test", 1)
			next.ServeHTTPC(ctx, w, r)
		})
	}
	h2 := func(next HandlerC) HandlerC {
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			handlerCalls++
			ctx = context.WithValue(ctx, "test", 2)
			next.ServeHTTPC(ctx, w, r)
		})
	}

	c := Chain{}
	c.UseC(h1)
	c.UseC(h2)
	h := c.HandlerC(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		handlerCalls++

		assert.Equal(t, 2, ctx.Value("test"),
			"second handler should overwrite first handler's context value")
		assert.Equal(t, 1, ctx.Value("mainCtx"),
			"the mainCtx value should be pass through")
	}))

	mainCtx := context.WithValue(context.Background(), "mainCtx", 1)
	h.ServeHTTPC(mainCtx, nil, testRequest)

	assert.Equal(t, 3, handlerCalls, "all handler called once")
}

func TestAdd(t *testing.T) {
	handlerCalls := 0
	h1 := func(next HandlerC) HandlerC {
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			handlerCalls++
			ctx = context.WithValue(ctx, "test", 1)
			next.ServeHTTPC(ctx, w, r)
		})
	}
	h2 := func(next http.Handler) http.Handler {
		handlerCalls++
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Change r and w values
			w = httptest.NewRecorder()
			r = &http.Request{}
			next.ServeHTTP(w, r)
		})
	}
	h3 := func(next HandlerC) HandlerC {
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			handlerCalls++
			ctx = context.WithValue(ctx, "test", 2)
			next.ServeHTTPC(ctx, w, r)
		})
	}

	c := Chain{}
	c.Add(h1, h2, h3)
	h := c.HandlerC(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		handlerCalls++

		assert.Equal(t, 2, ctx.Value("test"),
			"third handler should overwrite first handler's context value")
		assert.Equal(t, 1, ctx.Value("mainCtx"),
			"the mainCtx value should be pass through")
	}))

	mainCtx := context.WithValue(context.Background(), "mainCtx", 1)
	h.ServeHTTPC(mainCtx, nil, testRequest)
	assert.Equal(t, 4, handlerCalls, "all handler called once")
}

func TestWith(t *testing.T) {
	handlerCalls := 0
	h1 := func(next HandlerC) HandlerC {
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			handlerCalls++
			ctx = context.WithValue(ctx, "test", 1)
			next.ServeHTTPC(ctx, w, r)
		})
	}
	h2 := func(next http.Handler) http.Handler {
		handlerCalls++
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Change r and w values
			w = httptest.NewRecorder()
			r = &http.Request{}
			next.ServeHTTP(w, r)
		})
	}
	h3 := func(next HandlerC) HandlerC {
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			handlerCalls++
			ctx = context.WithValue(ctx, "test", 2)
			next.ServeHTTPC(ctx, w, r)
		})
	}

	c := Chain{}
	c.Add(h1)
	d := c.With(h2, h3)

	h := c.HandlerC(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		handlerCalls++

		assert.Equal(t, 1, ctx.Value("test"),
			"third handler should not overwrite the first handler's context value")
		assert.Equal(t, 1, ctx.Value("mainCtx"),
			"the mainCtx value should be pass through")
	}))
	i := d.HandlerC(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		handlerCalls++

		assert.Equal(t, 2, ctx.Value("test"),
			"third handler should overwrite first handler's context value")
		assert.Equal(t, 1, ctx.Value("mainCtx"),
			"the mainCtx value should be pass through")
	}))

	mainCtx := context.WithValue(context.Background(), "mainCtx", 1)
	h.ServeHTTPC(mainCtx, nil, testRequest)
	assert.Equal(t, 2, handlerCalls, "all handlers called once")
	handlerCalls = 0
	i.ServeHTTPC(mainCtx, nil, testRequest)
	assert.Equal(t, 4, handlerCalls, "all handler called once")
}


text:
{-# LANGUAGE FlexibleInstances #-}

-- | The RLP module provides a framework within which serializers can be built, described in the Ethereum Yellowpaper (<http://gavwood.com/paper.pdf>).
--
-- The 'RLPObject' is an intermediate data container, whose serialization rules are well defined.  By creating code that converts from a
-- given type to an 'RLPObject', full serialization will be specified.  The 'RLPSerializable' class provides functions to do this conversion.
module Blockchain.Data.RLP
  ( RLPObject(..)
  , formatRLPObject
  , RLPSerializable(..)
  , rlpSplit
  , rlpSerialize
  , rlpDeserialize
  ) where

import Data.Bits
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BC
import Data.ByteString.Internal
import Data.Word
import Numeric
import Text.PrettyPrint.ANSI.Leijen hiding ((<$>))

import Blockchain.Data.Util

-- | An internal representation of generic data, with no type information.
--
-- End users will not need to directly create objects of this type (an 'RLPObject' can be created using 'rlpEncode'),
-- however the designer of a new type will need to create conversion code by making their type an instance
-- of the RLPSerializable class.
data RLPObject
  = RLPScalar Word8
  | RLPString B.ByteString
  | RLPArray [RLPObject]
  deriving (Show, Eq, Ord)

-- | Converts objects to and from 'RLPObject's.
class RLPSerializable a where
  rlpDecode :: RLPObject -> a
  rlpEncode :: a -> RLPObject

instance Pretty RLPObject where
  pretty (RLPArray objects) =
    encloseSep (text "[") (text "]") (text ", ") $ pretty <$> objects
  pretty (RLPScalar n) = text $ "0x" ++ showHex n ""
  pretty (RLPString s) = text $ "0x" ++ BC.unpack (B16.encode s)

formatRLPObject :: RLPObject -> String
formatRLPObject = show . pretty

splitAtWithError :: Int -> B.ByteString -> (B.ByteString, B.ByteString)
splitAtWithError i s
  | i > B.length s = error "splitAtWithError called with n > length arr"
splitAtWithError i s = B.splitAt i s

getLength :: Int -> B.ByteString -> (Integer, B.ByteString)
getLength sizeOfLength bytes =
  ( bytes2Integer $ B.unpack $ B.take sizeOfLength bytes
  , B.drop sizeOfLength bytes)

rlpSplit :: B.ByteString -> (RLPObject, B.ByteString)
rlpSplit input =
  case B.head input of
    x
      | x >= 192 && x <= 192 + 55 ->
        let (arrayData, nextRest) =
              splitAtWithError (fromIntegral x - 192) $ B.tail input
        in (RLPArray $ getRLPObjects arrayData, nextRest)
    x
      | x >= 0xF8 && x <= 0xFF ->
        let (arrLength, restAfterLen) =
              getLength (fromIntegral x - 0xF7) $ B.tail input
            (arrayData, nextRest) =
              splitAtWithError (fromIntegral arrLength) restAfterLen
        in (RLPArray $ getRLPObjects arrayData, nextRest)
    x
      | x >= 128 && x <= 128 + 55 ->
        let (strList, nextRest) =
              splitAtWithError (fromIntegral $ x - 128) $ B.tail input
        in (RLPString strList, nextRest)
    x
      | x >= 0xB8 && x <= 0xBF ->
        let (strLength, restAfterLen) =
              getLength (fromIntegral x - 0xB7) $ B.tail input
            (strList, nextRest) =
              splitAtWithError (fromIntegral strLength) restAfterLen
        in (RLPString strList, nextRest)
    x
      | x < 128 -> (RLPScalar x, B.tail input)
    x -> error ("Missing case in rlpSplit: " ++ show x)

getRLPObjects :: ByteString -> [RLPObject]
getRLPObjects x
  | B.null x = []
getRLPObjects theData = obj : getRLPObjects rest
  where
    (obj, rest) = rlpSplit theData

int2Bytes :: Int -> [Word8]
int2Bytes val
  | val < 0x100 = map (fromIntegral . (val `shiftR`)) [0]
int2Bytes val
  | val < 0x10000 = map (fromIntegral . (val `shiftR`)) [8, 0]
int2Bytes val
  | val < 0x1000000 = map (fromIntegral . (val `shiftR`)) [16, 8, 0]
int2Bytes val
  | val < 0x100000000 = map (fromIntegral . (val `shiftR`)) [24,16 .. 0]
int2Bytes val
  | val < 0x10000000000 = map (fromIntegral . (val `shiftR`)) [32,24 .. 0]
int2Bytes _ = error "int2Bytes not defined for val >= 0x10000000000."

rlp2Bytes :: RLPObject -> [Word8]
rlp2Bytes (RLPScalar val) = [fromIntegral val]
rlp2Bytes (RLPString s)
  | B.length s <= 55 = 0x80 + fromIntegral (B.length s) : B.unpack s
rlp2Bytes (RLPString s) =
  [0xB7 + fromIntegral (length lengthAsBytes)] ++ lengthAsBytes ++ B.unpack s
  where
    lengthAsBytes = int2Bytes $ B.length s
rlp2Bytes (RLPArray innerObjects) =
  if length innerBytes <= 55
    then 0xC0 + fromIntegral (length innerBytes) : innerBytes
    else let lenBytes = int2Bytes $ length innerBytes
         in [0xF7 + fromIntegral (length lenBytes)] ++ lenBytes ++ innerBytes
  where
    innerBytes = concat $ rlp2Bytes <$> innerObjects

--TODO- Probably should just use Data.Binary's 'Binary' class for this
-- | Converts bytes to 'RLPObject's.
--
-- Full deserialization of an object can be obtained using @rlpDecode . rlpDeserialize@.
rlpDeserialize :: B.ByteString -> RLPObject
rlpDeserialize s =
  case rlpSplit s of
    (o, x)
      | B.null x -> o
    _ ->
      error
        ("parse error converting ByteString to an RLP Object: " ++
         show (B.unpack s))

-- | Converts 'RLPObject's to bytes.
--
-- Full serialization of an object can be obtained using @rlpSerialize . rlpEncode@.
rlpSerialize :: RLPObject -> B.ByteString
rlpSerialize o = B.pack $ rlp2Bytes o

instance RLPSerializable Integer where
  rlpEncode 0 = RLPString B.empty
  rlpEncode x
    | x < 128 = RLPScalar $ fromIntegral x
  rlpEncode x = RLPString $ B.pack $ integer2Bytes x
  rlpDecode (RLPScalar x) = fromIntegral x
  rlpDecode (RLPString s) = byteString2Integer s
  rlpDecode (RLPArray _) = error "rlpDecode called for Integer for array"

instance RLPSerializable String where
  rlpEncode s = rlpEncode $ BC.pack s
  rlpDecode (RLPString s) = BC.unpack s
  rlpDecode (RLPScalar n) = [w2c $ fromIntegral n]
  rlpDecode (RLPArray x) =
    error $
    "Malformed RLP in call to rlpDecode for String: RLPObject is an array: " ++
    show (pretty x)

instance RLPSerializable B.ByteString where
  rlpEncode x
    | B.length x == 1 && B.head x < 128 = RLPScalar $ B.head x
  rlpEncode s = RLPString s
  rlpDecode (RLPScalar x) = B.singleton x
  rlpDecode (RLPString s) = s
  rlpDecode x = error ("rlpDecode for ByteString not defined for: " ++ show x)