text:
#include "evas_common.h"
#include "evas_private.h"
#include "evas_engine.h"
#include "rsxutil.h"
#include "Evas_Engine_PSL1GHT.h"

#include <malloc.h>

int _evas_engine_psl1ght_log_dom = -1;

/* function tables - filled in later (func and parent func) */
static Evas_Func func, pfunc;

/* engine struct data */
typedef struct _Render_Engine Render_Engine;

#define MAX_BUFFERS 2

struct _Render_Engine
{
   Tilebuf        *tb;
   Tilebuf_Rect   *rects;
   Eina_Inlist    *cur_rect;

   /* RSX device context */
   gcmContextData *context;
   void           *host_addr;

   /* The buffers we will be drawing into. */
   rsxBuffer       buffers[MAX_BUFFERS];
   int             currentBuffer;
   int             width;
   int             height;
   RGBA_Image     *rgba_image;
   uint32_t        rgba_image_offset;

   int             end : 1;
};

/* prototypes we will use here */
static void *_output_setup(int w, int h);

static void *eng_info(Evas *e);
static void
             eng_info_free(Evas *e, void *info);
static int
             eng_setup(Evas *e, void *info);
static void
             eng_output_free(void *data);
static void
             eng_output_resize(void *data, int w, int h);
static void
             eng_output_tile_size_set(void *data, int w, int h);
static void
             eng_output_redraws_rect_add(void *data, int x, int y, int w, int h);
static void
             eng_output_redraws_rect_del(void *data, int x, int y, int w, int h);
static void
             eng_output_redraws_clear(void *data);
static void *eng_output_redraws_next_update_get(void *data, int *x, int *y, int *w, int *h, int *cx, int *cy, int *cw, int *ch);
static void
             eng_output_redraws_next_update_push(void *data, void *surface, int x, int y, int w, int h);
static void
             eng_output_flush(void *data);
static void
             eng_output_idle_flush(void *data);

/* internal engine routines */
static void *
_output_setup(int w, int h)
{
   Render_Engine *re;
   int i;
   u16 width, height;
   DATA32 *image_data = NULL;
   int image_size;

   printf ("_output_setup called : %dx%d\n", w, h);
   re = calloc(1, sizeof(Render_Engine));
   if (!re)
     return NULL;

   /* Allocate a 1Mb buffer, alligned to a 1Mb boundary
    * to be our shared IO memory with the RSX. */
   re->host_addr = memalign (1024 * 1024, HOST_SIZE);
   if (re->host_addr == NULL)
     {
        free (re);
        return NULL;
     }
   re->context = initScreen (re->host_addr, HOST_SIZE);
   if (re->context == NULL)
     {
        free (re->host_addr);
        free (re);
        return NULL;
     }
   width = w;
   height = h;
   setResolution (re->context, &width, &height);
   re->currentBuffer = 0;
   re->width = width;
   re->height = height;

   for (i = 0; i < MAX_BUFFERS; i++)
     makeBuffer (&re->buffers[i], width, height, i);

   flipBuffer(re->context, MAX_BUFFERS - 1);

   /* if we haven't initialized - init (automatic abort if already done) */
   evas_common_cpu_init();
   evas_common_blend_init();
   evas_common_image_init();
   evas_common_convert_init();
   evas_common_scale_init();
   evas_common_rectangle_init();
   evas_common_polygon_init();
   evas_common_line_init();
   evas_common_font_init();
   evas_common_draw_init();
   evas_common_tilebuf_init();

   re->tb = evas_common_tilebuf_new(w, h);

   /* in preliminary tests 16x16 gave highest framerates */
   evas_common_tilebuf_set_tile_size(re->tb, TILESIZE, TILESIZE);

   /* Allocate our memaligned backbuffer */
   image_size = ((w * h * sizeof(u32)) + 0xfffff) & - 0x100000;
   image_data = memalign (1024 * 1024, image_size);
   re->rgba_image = (RGBA_Image *)evas_cache_image_data(evas_common_image_cache_get(),
                                                        w, h, image_data, 1, EVAS_COLORSPACE_ARGB8888);
   gcmMapMainMemory(image_data, image_size, &re->rgba_image_offset);

   return re;
}

/* engine api this module provides */
static void *
eng_info(Evas *e)
{
   Evas_Engine_Info_PSL1GHT *info;

   printf ("eng_info called\n");
   info = calloc(1, sizeof(Evas_Engine_Info_PSL1GHT));
   if (!info)
     return NULL;

   info->magic.magic = rand();
   info->render_mode = EVAS_RENDER_MODE_BLOCKING;

   return info;
}

static void
eng_info_free(Evas *e __UNUSED__, void *info)
{
   Evas_Engine_Info_PSL1GHT *in;

   printf ("eng_info_free called\n");
   in = (Evas_Engine_Info_PSL1GHT *)info;
   free(in);
}

static int
eng_setup(Evas *eo_e, void *in)
{
   Evas_Public_Data *e = eo_data_get(eo_e, EVAS_CLASS);
   Evas_Engine_Info_PSL1GHT *info;

   printf ("eng_setup called\n");
   info = (Evas_Engine_Info_PSL1GHT *)in;

   e->engine.data.output = _output_setup(e->output.w, e->output.h);
   if (!e->engine.data.output)
     return 0;

   e->engine.func = &func;
   e->engine.data.context = e->engine.func->context_new(e->engine.data.output);

   return 1;
}

static void
eng_output_free(void *data)
{
   Render_Engine *re;
   int i;

   printf ("eng_output_free called\n");
   re = (Render_Engine *)data;

   gcmSetWaitFlip(re->context);
   for (i = 0; i < MAX_BUFFERS; i++)
     rsxFree (re->buffers[i].ptr);

   if (re->rgba_image)
     {
        DATA32 *image_data;

        image_data = re->rgba_image->image.data;
        evas_cache_image_drop(&re->rgba_image->cache_entry);
        free (image_data);
     }

   freeScreen (re->context);
   free (re->host_addr);

   evas_common_tilebuf_free(re->tb);
   if (re->rects)
     evas_common_tilebuf_free_render_rects(re->rects);

   free(re);

   evas_common_font_shutdown();
   evas_common_image_shutdown();
}

static void
eng_output_resize(void *data, int w, int h)
{
   Render_Engine *re;
   int i;
   u16 width, height;
   DATA32 *image_data;
   int image_size;

   printf ("eng_output_resize called : %dx%d\n", w, h);
   re = (Render_Engine *)data;

   width = w;
   height = h;
   if (setResolution (re->context, &width, &height))
     {
        re->width = width;
        re->height = height;

        gcmSetWaitFlip(re->context);
        for (i = 0; i < MAX_BUFFERS; i++) {
             rsxFree (re->buffers[i].ptr);
             makeBuffer (&re->buffers[i], width, height, i);
          }

        flipBuffer(re->context, MAX_BUFFERS - 1);

        evas_common_tilebuf_free(re->tb);
        re->tb = evas_common_tilebuf_new(w, h);
        evas_common_tilebuf_set_tile_size(re->tb, TILESIZE, TILESIZE);

        /* Realloc our backbuf image */
        if (re->rgba_image)
          {
             image_data = re->rgba_image->image.data;
             evas_cache_image_drop(&re->rgba_image->cache_entry);
             free (image_data);
          }
        image_size = ((w * h * sizeof(u32)) + 0xfffff) & - 0x100000;
        image_data = memalign (1024 * 1024, image_size);
        re->rgba_image = (RGBA_Image *)evas_cache_image_data(evas_common_image_cache_get(),
                                                             w, h, image_data, 1, EVAS_COLORSPACE_ARGB8888);
        gcmMapMainMemory(image_data, image_size, &re->rgba_image_offset);
     }
}

static void
eng_output_tile_size_set(void *data, int w, int h)
{
   Render_Engine *re;

   printf ("eng_output_tile_size_set called : %dx%d\n", w, h);
   re = (Render_Engine *)data;
   evas_common_tilebuf_set_tile_size(re->tb, w, h);
}

static void
eng_output_redraws_rect_add(void *data, int x, int y, int w, int h)
{
   Render_Engine *re;

   //printf ("eng_output_redraws_rect_add called : %d,%d %dx%d\n", x, y, w, h);
   re = (Render_Engine *)data;
   evas_common_tilebuf_add_redraw(re->tb, x, y, w, h);
}

static void
eng_output_redraws_rect_del(void *data, int x, int y, int w, int h)
{
   Render_Engine *re;

   //printf ("eng_output_redraws_rect_del called : %d,%d %dx%d\n", x, y, w, h);
   re = (Render_Engine *)data;
   evas_common_tilebuf_del_redraw(re->tb, x, y, w, h);
}

static void
eng_output_redraws_clear(void *data)
{
   Render_Engine *re;

   //printf ("eng_output_redraws_clear called\n");
   re = (Render_Engine *)data;
   evas_common_tilebuf_clear(re->tb);
}

static void *
eng_output_redraws_next_update_get(void *data, int *x, int *y, int *w, int *h, int *cx, int *cy, int *cw, int *ch)
{
   Render_Engine *re;
   Tilebuf_Rect *rect;
   int ux, uy, uw, uh;

   re = (Render_Engine *)data;
   /*printf ("eng_output_redraws_next_update_get called : %d,%d %dx%d -- %d,%d %dx%d\n",
    *x, *y, *w, *h, *cx, *cy, *cw, *ch);*/
   if (re->end)
     {
        re->end = 0;
        return NULL;
     }
   if (!re->rects)
     {
        re->rects = evas_common_tilebuf_get_render_rects(re->tb);
        re->cur_rect = EINA_INLIST_GET(re->rects);
     }
   if (!re->cur_rect)
     return NULL;

   rect = (Tilebuf_Rect *)re->cur_rect;
   ux = rect->x; uy = rect->y; uw = rect->w; uh = rect->h;
   re->cur_rect = re->cur_rect->next;
   if (!re->cur_rect)
     {
        evas_common_tilebuf_free_render_rects(re->rects);
        re->rects = NULL;
        re->end = 1;
     }

   *x = *cx = ux;
   *y = *cy = uy;
   *w = *cw = uw;
   *h = *ch = uh;
   /*printf ("eng_output_redraws_next_update_get returning : %d,%d %dx%d -- %d,%d %dx%d\n",
    *x, *y, *w, *h, *cx, *cy, *cw, *ch);*/

   return re->rgba_image;
}

static void
eng_output_redraws_next_update_push(void *data, void *surface, int x, int y, int w, int h)
{
   /* Don't do anything, we'll just coy the whole buffer when it's time to flush */
}

static void
eng_output_flush(void *data)
{
   Render_Engine *re;
   rsxBuffer *buffer;
   int width;
   int height;

   //printf ("eng_output_flush called\n");
   re = (Render_Engine *)data;
   buffer = &re->buffers[re->currentBuffer];
   width = re->rgba_image->cache_entry.w;
   height = re->rgba_image->cache_entry.h;

   /* Wait for the flip before copying the buffer */
   waitFlip ();

   if (re->width == width &&
       re->height == height)
     {
        /* DMA the back buffer into the rsx buffer */
         rsxSetTransferImage (re->context,
                              GCM_TRANSFER_MAIN_TO_LOCAL,
                              buffer->offset, buffer->width * sizeof(u32),
                              0, 0,
                              re->rgba_image_offset, re->width * sizeof(u32),
                              0, 0, re->width, re->height, sizeof(u32));
     }
   else
     {
        gcmTransferScale gcm_scale;
        gcmTransferSurface gcm_surface;

        gcm_surface.format = GCM_TRANSFER_SURFACE_FORMAT_A8R8G8B8;
        gcm_surface.pitch = buffer->width * sizeof(u32);
        gcm_surface._pad0[0] = gcm_surface._pad0[1] = 0;
        gcm_surface.offset = buffer->offset;

        gcm_scale.interp = GCM_TRANSFER_INTERPOLATOR_LINEAR;
        gcm_scale.conversion = GCM_TRANSFER_CONVERSION_TRUNCATE;
        gcm_scale.format = GCM_TRANSFER_SCALE_FORMAT_A8R8G8B8;
        gcm_scale.origin = GCM_TRANSFER_ORIGIN_CORNER;
        gcm_scale.operation = GCM_TRANSFER_OPERATION_SRCCOPY;
        gcm_scale.offset = re->rgba_image_offset;
        gcm_scale.clipX = 0;
        gcm_scale.clipY = 0;
        gcm_scale.clipW = re->width;
        gcm_scale.clipH = re->height;
        gcm_scale.outX = 0;
        gcm_scale.outY = 0;
        gcm_scale.outW = re->width;
        gcm_scale.outH = re->height;
        gcm_scale.ratioX = rsxGetFixedSint32 ((float)width / (float)re->width);
        gcm_scale.ratioY = rsxGetFixedSint32 ((float)height / (float)re->height);
        gcm_scale.inX = 0;
        gcm_scale.inY = 0;
        gcm_scale.inW = (width & ~1); // Width must be a multiple of 2
        gcm_scale.inH = height;
        if (gcm_scale.inW < 2) // Minimum inW value is 2
          gcm_scale.inW = 2;
        if (gcm_scale.inW > 2046) // Maximum inW value is 2046
          gcm_scale.inW = 2046;
        if (gcm_scale.inH < 1) // Minimum inH value is 1
          gcm_scale.inH = 1;
        if (gcm_scale.inH > 2047) // Maximum inW value is 2047
          gcm_scale.inH = 2047;
        gcm_scale.pitch = sizeof(u32) * width;

        rsxSetTransferScaleMode (re->context, GCM_TRANSFER_MAIN_TO_LOCAL, GCM_TRANSFER_SURFACE);
        rsxSetTransferScaleSurface (re->context, &gcm_scale, &gcm_surface);
     }
   /* Wait for the DMA to finish */
   flushRSX (re->context);

   /* Flip buffer onto screen */
   flipBuffer (re->context, re->currentBuffer);
   re->currentBuffer = (re->currentBuffer + 1) % MAX_BUFFERS;
}

static void
eng_output_idle_flush(void *data)
{
   Render_Engine *re;

   printf ("eng_output_idle_flush called\n");
   re = (Render_Engine *)data;
}

static Eina_Bool
eng_canvas_alpha_get(void *data, void *context __UNUSED__)
{
   Render_Engine *re;

   // printf ("eng_output_alpha_get called\n");
   re = (Render_Engine *)data;
   return EINA_TRUE;
}

/* module advertising code */
static int
module_open(Evas_Module *em)
{
   if (!em) return 0;
   /* get whatever engine module we inherit from */
   if (!_evas_module_engine_inherit(&pfunc, "software_generic")) return 0;
   _evas_engine_psl1ght_log_dom = eina_log_domain_register
       ("evas-psl1ght", EVAS_DEFAULT_LOG_COLOR);
   if (_evas_engine_psl1ght_log_dom < 0)
     {
        EINA_LOG_ERR("Can not create a module log domain.");
        return 0;
     }

   /* store it for later use */
   func = pfunc;
   /* now to override methods */
#define ORD(f) EVAS_API_OVERRIDE(f, &func, eng_)
   ORD(info);
   ORD(info_free);
   ORD(setup);
   ORD(canvas_alpha_get);
   ORD(output_free);
   ORD(output_resize);
   ORD(output_tile_size_set);
   ORD(output_redraws_rect_add);
   ORD(output_redraws_rect_del);
   ORD(output_redraws_clear);
   ORD(output_redraws_next_update_get);
   ORD(output_redraws_next_update_push);
   ORD(output_flush);
   ORD(output_idle_flush);

   /* now advertise out own api */
   em->functions = (void *)(&func);
   return 1;
}

static void
module_close(Evas_Module *em __UNUSED__)
{
   eina_log_domain_unregister(_evas_engine_psl1ght_log_dom);
}

static Evas_Module_Api evas_modapi =
{
   EVAS_MODULE_API_VERSION,
   "psl1ght",
   "none",
   {
      module_open,
      module_close
   }
};

EVAS_MODULE_DEFINE(EVAS_MODULE_TYPE_ENGINE, engine, psl1ght);

#ifndef EVAS_STATIC_BUILD_PSL1GHT
EVAS_EINA_MODULE_DEFINE(engine, psl1ght);
#endif


text:
<?php

namespace PhpDesignPatternsCheatsheet\Creational\Factory;

class RendererFactory
{
    const JSON = 'json';
    const XML = 'xml';

    /**
     * @param string $type
     * @return RendererInterface
     */
    public function create(string $type): RendererInterface
    {
        switch ($type) {
            case self::JSON:
                return new JsonRenderer();

            case self::XML:
                return new XmlRenderer();
        }

        throw new \InvalidArgumentException('Invalid renderer type.');
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.flipkart.perf.server.util;

import org.codehaus.jackson.map.ObjectMapper;

/**
 * Created with IntelliJ IDEA.
 * User: nitinka
 * Date: 13/4/13
 * Time: 10:10 AM
 * To change this template use File | Settings | File Templates.
 */
public class ObjectMapperUtil<T> {
    private static ObjectMapper objectMapper;

    public static ObjectMapper instance() {
        if(objectMapper == null) {
        	synchronized(ObjectMapperUtil.class) {
            	objectMapper = new ObjectMapper();
        	}
        }
        return objectMapper;
    }
}


text:
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( 'shared.lua' )

// This is the spawn function. It's called when a client calls the entity to be spawned.
// If you want to make your SENT spawnable you need one of these functions to properly create the entity
//
// ply is the name of the player that is spawning it
// tr is the trace from the player's eyes
//
function ENT:SpawnFunction( ply, tr )

	if ( !tr.Hit ) then return end

	local SpawnPos = tr.HitPos + tr.HitNormal * 16

	local ent = ents.Create( "sent_ball" )
		ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()

	return ent

end

--[[---------------------------------------------------------
   Name: Initialize
---------------------------------------------------------]]
function ENT:Initialize()

	// Use the helibomb model just for the shadow (because it's about the same size)
	self.Entity:SetModel( "models/Combine_Helicopter/helicopter_bomb01.mdl" )

	// Don't use the model's physics - create a sphere instead
	self.Entity:PhysicsInitSphere( 16, "metal_bouncy" )

	// Wake the physics object up. It's time to have fun!
	local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
	end

	// Set collision bounds exactly
	self.Entity:SetCollisionBounds( Vector( -16, -16, -16 ), Vector( 16, 16, 16 ) )

end

--[[---------------------------------------------------------
   Name: PhysicsCollide
---------------------------------------------------------]]
function ENT:PhysicsCollide( data, physobj )

	// Play sound on bounce
	if (data.Speed > 80 && data.DeltaTime > 0.2 ) then
		self.Entity:EmitSound( "Rubber.BulletImpact" )
	end

	// Bounce like a crazy bitch
	local LastSpeed = math.max( data.OurOldVelocity:Length(), data.Speed )
	local NewVelocity = physobj:GetVelocity()
	NewVelocity:Normalize()

	LastSpeed = math.max( NewVelocity:Length(), LastSpeed )

	local TargetVelocity = NewVelocity * LastSpeed * 0.9

	physobj:SetVelocity( TargetVelocity )

end

--[[---------------------------------------------------------
   Name: OnTakeDamage
---------------------------------------------------------]]
function ENT:OnTakeDamage( dmginfo )

	// React physically when shot/getting blown
	self.Entity:TakePhysicsDamage( dmginfo )

end

--[[---------------------------------------------------------
   Name: Use
---------------------------------------------------------]]
function ENT:Use( activator, caller )

	self.Entity:Remove()

	if ( activator:IsPlayer() ) then

		// Give the collecting player some free health
		local health = activator:Health()
		activator:SetHealth( health + 5 )
		activator:SendLua( "achievements.EatBall()" );

	end

end


text:
namespace Uncas.WebTester.Utilities.Tests.Unit
{
    using System;
    using System.Net;
    using NUnit.Framework;

    [TestFixture]
    public abstract class BrowserUtilityTestsBase
    {
        protected readonly Uri NonExistingServer =
            new Uri("http://lqkweoi.uncasxxx.dkxx");

        private IBrowserUtility utility;

        protected Uri ExistingUrl
        {
            get
            {
                return this.GetUrl("Test/ValidPage");
            }
        }

        protected Uri NonExistingUrl
        {
            get
            {
                return this.GetUrl("Test/NotFound");
            }
        }

        protected Uri Error500Url
        {
            get
            {
                return this.GetUrl("Test/Error500");
            }
        }

        protected Uri PageWithEmptyLink
        {
            get
            {
                return this.GetUrl("Test/EmptyLink");
            }
        }

        protected virtual int WebsitePort
        {
            get
            {
                return 52349;
            }
        }

        [SetUp]
        public void BeforeEach()
        {
            this.utility = this.GetBrowserUtility();
        }

        [TearDown]
        public void AfterEach()
        {
            this.utility = null;
        }

        [Test]
        public void NavigateTo_Google_Ok()
        {
            // Arrange:
            var url = this.ExistingUrl;

            // Act:
            NavigateResult result = this.utility.NavigateTo(url);

            // Assert:
            Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK));
        }

        [Test]
        public void NavigateTo_NonExisting_NotFound()
        {
            // Arrange:
            var url = this.NonExistingUrl;

            // Act:
            NavigateResult result = this.utility.NavigateTo(url);

            // Assert:
            Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
        }

        [Test]
        public void NavigateTo_Error500Page_GetsError500()
        {
            // Arrange:
            var url = this.Error500Url;

            // Act:
            NavigateResult result = this.utility.NavigateTo(url);

            // Assert:
            Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.InternalServerError));
        }

        [Test]
        public void NavigateTo_PageWithEmptyLink_HandledOk()
        {
            // Arrange:
            var url = this.PageWithEmptyLink;

            // Act:
            NavigateResult result = this.utility.NavigateTo(url);

            // Assert:
            Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK));
        }

        [Test]
        public void NavigateTo_NonExistingServer_HandledOk()
        {
            // Arrange:
            var url = this.NonExistingServer;

            // Act:
            NavigateResult result = this.utility.NavigateTo(url);
        }

        protected abstract IBrowserUtility GetBrowserUtility();

        private Uri GetUrl(string path)
        {
            string uriString = string.Format(
                "http://localhost:{0}/{1}",
                this.WebsitePort,
                path);
            return new Uri(uriString);
        }
    }
}


text:
var helper = require('./test_helper');
var it = helper.it;
var migrates = helper.migrates;

describe('custom app name', function(){
  before(function(){
    this.migrator = helper.migrator({
      inputFixtures: 'custom_app_name',
      rootAppName: 'MyApp'
    });
    this.migrator.run();
  });

  after(function(){
    this.migrator.clean();
  });

  describe('single export file', function(){
    it(migrates('models/comment-activity.js'));
  });
});


text: CKEDITOR.plugins.setLang("preview","is",{preview:"Forskoða"});


text:
#pragma once
#include <iostream>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <vector>
#include "State.h"
#include "Input.h"
#include "Game/CollisionDetector.h"
#include "Graphics/GraphicEngine.h"
#include "Menu/State_Menu.h"
#include "Game/State_Game.h"
#include "Menu/Menu.h"
#include "Singleton.h"

//class State;
class InputHandler;

class GameEngine : public Singleton <GameEngine>
{
	friend class InputHandler;
	friend Singleton < GameEngine > ;

	//consts
	const int WIDTH = 800;  // to be changed
	const int HEIGHT = 600;
	const float FPS = 60.0f;

	//primitive inits
	bool done;
	bool render;

	//Handlers inits
	/*
	MapHandler *mapHandler;
	CameraInstance *Camera;
	LogicHandler *logicHandler
	*/
	InputHandler *input;
	CollisionDetector *collisionDetector;

	State_Menu *menuState;
	State_Game *gameState;

	//allegro variables
	ALLEGRO_DISPLAY *display;
	ALLEGRO_EVENT_QUEUE *eventQueue;
	ALLEGRO_EVENT event;
	ALLEGRO_TIMER *timer;
	//ALLEGRO_FONT *font18;

	std::vector <State*> activeStates;
	std::vector <State*> states;
protected:
	GameEngine();
	~GameEngine();
public:
	State_Game * GetGameState() const { return gameState; }
	State_Menu * GetMenuState() const { return menuState; }
	CollisionDetector * GetCollisionDetector() const { return collisionDetector; }

	void StartGame();

	void Init();

	void ChangeState(State* state);
	void PushState(State* state);
	void PopState();

	void Escaper();
	void Update();
	void Render();

	void Flush();
	void Destroy();

	void Continue();
	void Quit();

	bool Done() const;
	bool IsGameStateActive() const { return activeStates.back() == gameState; }

	ALLEGRO_EVENT_QUEUE * GetEventQueue() const { return eventQueue; }
	ALLEGRO_EVENT * GetEvent() { return &event; }
	ALLEGRO_DISPLAY * GetDisplay() { return display; }
};


text:
"""
Quick script to upload existing markers to S3 using Bucketeer created creds
"""
import os
from os.path import join

from boto.s3.connection import S3Connection
from boto.s3.key import Key

aws_bucket_url = os.environ['BUCKETEER_AWS_PUBLIC_URL']
aws_access_key = os.environ['BUCKETEER_AWS_ACCESS_KEY_ID']
aws_secret = os.environ['BUCKETEER_AWS_SECRET_ACCESS_KEY']
conn = S3Connection(aws_access_key, aws_secret)

bucket_name = os.environ['BUCKETEER_BUCKET_NAME']
bucket = conn.create_bucket(bucket_name)

def list_items():
    """list items in bucket"""
    for k in bucket.list():
        print k.name, k.size

def get_key_names():
    """get key names"""
    knames = []
    for k in bucket.list():
        knames.append(k.name)
    return knames

def add_markers(overwrite=False, markers_only=False):
    """add markers"""

    marker_dir = '/app/media/logos' # Heroku directory.  Local would be '../media/logos'
    fnames = os.listdir(marker_dir)

    if markers_only:
        # Only upload files ending in "_markers."
        fnames = [x for x in fnames if x.find('_markers.') > -1]

    current_keys = get_key_names()

    cnt = 0
    for marker_name in fnames:
        cnt+=1
        print '\n%s) %s' % (cnt, marker_name)

        key_name = 'logos/%s' % marker_name
        print '     key_name: %s' % key_name

        # have we already uploaded this?
        if key_name in current_keys:
            print 'already in S3'
            if not overwrite:
                print 'go to next item..'
                continue
            else:
                print 'overwrite it..'

        # grab file contents
        full_name = join(marker_dir, marker_name)
        fcontents = open(full_name, 'rb').read()

        # upload to S3
        k = Key(bucket)
        k.key = key_name
        k.set_contents_from_string(fcontents)
        print 'uploaded: %s' % key_name

        # allow public read of item
        bucket.set_acl('public-read', key_name)
        print 'allow public read: %s/%s' % (aws_bucket_url, key_name)

if __name__=='__main__':
    #list_items()
    add_markers(overwrite=True)


text:
import re
import hashlib
from datetime import datetime
from time import mktime, gmtime
from urlparse import urlparse

def getCurrentTime():
    return datetime.today().strftime("%Y-%m-%d %H:%M:%S")

def countryUri(x):
    "Return a URI for a country given its name."
    import re

    x = re.sub('[^A-Za-z0-9]+', '', x)
    return x.lower()

def personNameUri(x):
    "Return a URI for a person name."
    import re

    x = re.sub('[^A-Za-z0-9]+', '', x.strip())
    return x.lower()

def toTitleCaseIfUpper(x):
    "Return the string in title case if it is all upper, otherwise leave capitalization alone."
    x = x.strip()
    if x.isupper():
        return x.title()
    else:
        return x

def nonWhitespace(x):
    "Return the string removing all spaces."
    import re

    y = re.sub(r'\s+', '', x.strip())
    return y

def toTitleCaseCleaned(x):
    "Return the string in title case cleaning spaces."
    import re

    y = re.sub(r'\s+', ' ', x.strip())
    return y.title()

def nonAsciiChars(x):
    "Return a set of the non-ascii chars in x"
    import re

    return set(re.sub('[\x00-\x7f]', '', x))

def nonAsciiCharsAsString(x):
    "Return a string containing a comma-separated list of non-ascii chars in x"
    y = list(nonAsciiChars(x))
    y.sort()
    return ', '.join(y)

def asciiChars(x):
    "Remove non-ascii chars in x replacing consecutive ones with a single space"
    import re

    return re.sub(r'[^\x00-\x7F]+', ' ', x)

def alphaNumeric(x):
    "Replace consecutive non-alphanumeric bya single space"
    return re.sub('[^A-Za-z0-9]+', ' ', x)

def alphaNumericOnly(x):
    "Remove non-alphanumerics"
    return re.sub('[^A-Za-z0-9]+', '', x)

def numericOnly(x):
    "Remove non-numeric chars from the string x"
    return re.sub('[^0-9]+', '', x)

def alphaOnly(x):
    "Remove non-alphabetic chars from the string x"
    return re.sub('[^A-Za-z]+', '', x)

def alphaOnlyPreserveSpace(x):
    x = re.sub('[^A-Za-z\s]+', '', x)
    y = re.sub(r'\s+', ' ', x.strip())
    return y

def isSymbol(char1):
    if char1.isalnum():
        return False
    return True

def fingerprintString(x):
    "Make a fingerprint like the one google refine makes"
    x = alphaNumeric(asciiChars(x)).lower()
    y = list(set(x.split()))
    y.sort()
    return '_'.join(y)

def mungeForUri(x):
    "Take an arbitrary string and make it into something that can be used as a URI"
    return alphaNumericOnly(asciiChars(x)).lower()

def md5Hash(x):
    "Return md5 hash of x"
    import hashlib

    return hashlib.md5(x).hexdigest()

def tenDigitPhoneNumber(x):
    """Return the 10-digit phone number of a phone, as 10 consecutive digits"""
    return re.sub('[^0-9]+', '', x)

def iso8601date(date, format=None):
    """Convert a date to ISO8601 date format

input format: YYYY-MM-DD HH:MM:SS GMT (works less reliably for other TZs)
or            YYYY-MM-DD HH:MM:SS.0
or            YYYY-MM-DD
or            epoch (13 digit, indicating ms)
or            epoch (10 digit, indicating sec)
output format: iso8601

"""

    try:
        return datetime.strptime(date, "%Y-%m-%d %H:%M:%S %Z").isoformat()
    except Exception:
        pass

    if format:
        try:
            return datetime.strptime(date, format).isoformat()
        except Exception:
            pass

    try:
        return datetime.strptime(date, "%Y-%m-%d %H:%M:%S.0").isoformat()
    except:
        pass

    try:
        return datetime.strptime(date, "%Y-%m-%d").isoformat()
    except:
        pass

    try:
        date = int(date)
        if 1000000000000 < date and date < 9999999999999:
            # 13 digit epoch
            return datetime.fromtimestamp(mktime(gmtime(date / 1000))).isoformat()
    except:
        pass

    try:
        date = int(date)
        if 1000000000 < date and date < 9999999999:
            # 10 digit epoch
            return datetime.fromtimestamp(mktime(gmtime(date))).isoformat()
    except:
        pass
    # If all else fails, return input
    return ''

def getYearFromISODate(isoDate):
    if isoDate:
        return isoDate[0:4]
    return ''

def getWebsiteDomain(url):
    parsed_uri = urlparse(url)
    if parsed_uri:
        domain = parsed_uri.netloc
        if domain:
            if domain.startswith("www."):
                domain = domain[4:]
            return domain
    return ''

def getTextHash(text):
    if text:
        return hashlib.sha1(text.encode('utf-8')).hexdigest()
    return ''


text:
#ifndef __ESPPARTICLESCALEEFFECTOR_H__
#define __ESPPARTICLESCALEEFFECTOR_H__

#include "../BlammoEngine/Colour.h"
#include "../BlammoEngine/Vector.h"

#include "ESPEffector.h"

class ESPParticleScaleEffector;

class ScaleEffect {
    friend class ESPParticleScaleEffector;
public:
	// Variables for pulse effects
	float pulseRate;				// (Hz) Pulse rate in number of pulses per second
	float pulseGrowthScale;	// Amount of growth of a single pulse from smallest scale to largest

    ScaleEffect() : isInit(false), pulseRate(0), pulseGrowthScale(1) {}
    ScaleEffect(float pulseRate, float pulseGrowthScale) : isInit(false), pulseRate(pulseRate), pulseGrowthScale(pulseGrowthScale) {}
    ScaleEffect(const ScaleEffect& copy) : isInit(copy.isInit), pulseRate(copy.pulseRate), pulseGrowthScale(copy.pulseGrowthScale) {}

    ScaleEffect& operator=(const ScaleEffect& copy) {
        this->isInit = copy.isInit;
        this->pulseRate = copy.pulseRate;
        this->pulseGrowthScale = copy.pulseGrowthScale;
        return *this;
    }
private:
    bool isInit;
};

class ESPParticleScaleEffector : public ESPEffector {
public:
    ESPParticleScaleEffector(const Vector2D& startScale, const Vector2D& endScale);
    ESPParticleScaleEffector(float startScale, float endScale);
    ESPParticleScaleEffector(const ScaleEffect& effect);
    ESPParticleScaleEffector(const ESPParticleScaleEffector& copy);
    ~ESPParticleScaleEffector();

    const Vector2D& GetEndScale() const {
        return this->endScale;
    }

    void ResetScaleEffect(const ScaleEffect& effect) {
        assert(this->effect.isInit);
        this->effect = effect;
        this->effect.isInit = true;
    }

    void AffectParticleOnTick(double dT, ESPParticle* particle);
    void AffectBeamOnTick(double dT, ESPBeam* beam);

    ESPEffector* Clone() const;

    ESPParticleScaleEffector& operator=(const ESPParticleScaleEffector& copy);

private:
    ESPParticleScaleEffector() {}

	ScaleEffect effect;
	Vector2D startScale, endScale;
};

inline ESPParticleScaleEffector::ESPParticleScaleEffector(const ESPParticleScaleEffector& copy) {
    *this = copy;
}

inline ESPEffector* ESPParticleScaleEffector::Clone() const {
    return new ESPParticleScaleEffector(*this);
}

inline ESPParticleScaleEffector& ESPParticleScaleEffector::operator=(const ESPParticleScaleEffector& copy) {
    this->effect = copy.effect;
    this->startScale = copy.startScale;
    this->endScale = copy.endScale;
    return *this;
}

#endif


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Show Foo</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="./Show Foo (Foo just created)_files/main.css">
<link rel="stylesheet" href="./Show Foo (Foo just created)_files/mobile.css">
<link rel="stylesheet" href="./Show Foo (Foo just created)_files/scaffold.css">
<link rel="stylesheet" href="./Show Foo (Foo just created)_files/application.css">

        <meta name="layout" content="main">

Home

Controllers

            Skip to content…

        Skip to content…

Home

Foo List

New Foo

Show Foo

Foo 2 created

            My Bool

False

            My Date

2016-01-17 00:00:00 CET

            My Int

2

            My String

sample text

            <form action="http://localhost:8080/foo/delete/2" method="post"><input type="hidden" name="_method" value="DELETE" id="_method">
                <fieldset class="buttons">
                    Edit
                    <input class="delete" type="submit" value="Delete" onclick="return confirm('Are you sure?');">
                </fieldset>
            </form>

Loading…

                    Powered by
                    Grails


text:
package com.microsoft.bingads.bulk.entities;

import com.microsoft.bingads.bulk.BulkServiceManager;
import com.microsoft.bingads.bulk.BulkFileReader;
import com.microsoft.bingads.bulk.BulkFileWriter;
import com.microsoft.bingads.bulk.BulkOperation;

/**
 * Represents an ad group level image ad extension. This class exposes
 * properties that can be read and written as fields of the Ad Group Image Ad
 * Extension record in a bulk file.
 *
 *

 * For more information, see Ad Group Image Ad Extension at
 * http://go.microsoft.com/fwlink/?LinkID=511551.
 *

 *
 * @see BulkServiceManager
 * @see BulkOperation
 * @see BulkFileReader
 * @see BulkFileWriter
 *
 */
public class BulkAdGroupImageAdExtension extends BulkAdGroupAdExtension {
}


text:
require 'set'
require 'digest/md5'
require 'digest/sha1'

module LintFu
  module Core
  end
end

require 'lint_fu/core/file_range'
require 'lint_fu/core/eidos'
require 'lint_fu/core/eidos_container'
require 'lint_fu/core/eidos_builder'
require 'lint_fu/core/issue'
require 'lint_fu/core/blessing'
require 'lint_fu/core/scan'
require 'lint_fu/core/checker'
require 'lint_fu/core/visitor'


text:
Readme file for TLDR project.

This cd contains the source code for TLDR under the /compiler.
We recomend using monodevelop (xamarin for windows) for compiling the compiler. The compiler takes a .tldr source file as argument, this file will be compiled. This file can be changed under project prefrences under general.

Some sample programs and check for the compilere are included under /SamplePrograms, for testing.

The repport are included in a pdf format at /report.pdf

The file compiler.exe is an executebale version of the compiler that takes a .tldr file as input.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>M-Index</title>
<meta name="date" content="2012-08-08">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G K L M N O P R S T U W

M

Manager - Class in <Unnamed>

Swartz Center For Computational Neuroscience, Matthew Burns 2012 mdburns@ucsd.edu
 Used to manage Amazon EC2 instances for bcilab.

Manager(ManagerSetup) - Constructor for class Manager

Create a new manager object with attributes derived from ManagerSetup
 object.

Manager.ThreadListener - Class in <Unnamed>

Used to keep an eye on ssh_threads

Manager.ThreadListener() - Constructor for class Manager.ThreadListener

ManagerSetup - Class in <Unnamed>

Used set up the Manager object.

ManagerSetup() - Constructor for class ManagerSetup

mode - Variable in class ManagerSetup

Prints the output of one node to screen.

A B C D E F G K L M N O P R S T U W

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
Dir.chdir File.join File.dirname(__FILE__), '../../'
require './lib/flok'

#Testing the compilation of controller/action user files into javascript counterparts
RSpec.describe "Transition compiler" do
  #Return a v8 instance of a compiled js file
  def compile fn
    compiler = Flok::TransitionCompiler
    js_src(fn)
    js_res = compiler.compile(js_src(fn))
    ctx = V8::Context.new
    ctx.eval js_res
    ctx
  end

  #Get the source for a file in  ./user_compiler/*.rb
  def js_src fn
    Dir.chdir File.join(File.dirname(__FILE__), "transition_compiler") do
      return File.read(fn+'.rb')
    end
  end

  it "Can insert a hook into ${controller_name}_will_goto and this hook is invoked" do

  end

  it "Can load the ruby module" do
    compiler = Flok::TransitionCompiler
  end

  it "Can compile a controller" do
    ctx = compile "trans0"
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>RegexResultPair</title>
<meta name="date" content="2014-01-26">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.bionic_gaming.apps.obj

Class RegexResultPair

java.lang.Object

com.bionic_gaming.apps.obj.RegexResultPair

public class RegexResultPair
extends java.lang.Object

 RegexResultPair is a class that is used by RegexProcessor. It contains a line
 number and a regexResult. This class is used in RegexProcessor when
 processing files.

Version:

0.1a 01/26/2014

Author:

Adam

Constructor Summary

Constructors

Constructor and Description

RegexResultPair(java.lang.Long lineNumber,
               RegexResult regexResult)

 Creates a new RegexResultPair and sets the line number and RegexResult
 for this pair.

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.Long
getLineNumber()

 Gets the lineNumber for this RegexResultPair.

RegexResult
getRegexResult()

 Gets the RegexResult for this RegexResultPair.

void
setLineNumber(java.lang.Long lineNumber)

 Sets the lineNumber for this RegexResultPair.

void
setRegexResult(RegexResult regexResult)

 Sets the RegexResult for this RegexResultPair.

java.lang.String
toString()

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

RegexResultPair

public RegexResultPair(java.lang.Long lineNumber,
               RegexResult regexResult)

 Creates a new RegexResultPair and sets the line number and RegexResult
 for this pair.

Parameters:

lineNumber - - Long

regexResult - - RegexResult

Method Detail

getLineNumber

public java.lang.Long getLineNumber()

 Gets the lineNumber for this RegexResultPair.

Returns:

Long

setLineNumber

public void setLineNumber(java.lang.Long lineNumber)

 Sets the lineNumber for this RegexResultPair.

 --Warning-- If this is set manually you lose the
 lineNumber that was set by the RegexProcessor

Parameters:

lineNumber - - Long

getRegexResult

public RegexResult getRegexResult()

 Gets the RegexResult for this RegexResultPair.

Returns:

RegexResult

setRegexResult

public void setRegexResult(RegexResult regexResult)

 Sets the RegexResult for this RegexResultPair.

 --Warning-- If this is set manually you lose the
 RegexResult that was set by the RegexProcessor.

Parameters:

regexResult - - RegexResult

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
require "spec_helper"

describe AppsController do
  describe "routing" do

    it "routes to #index" do
      get("/apps").should route_to("apps#index")
    end

    it "routes to #show" do
      get("/apps/1").should route_to("apps#show", id: "1")
    end

    it "routes to #edit" do
      get("/apps/1/edit").should route_to("apps#edit", id: "1")
    end

    it "routes to #create" do
      post("/apps").should route_to("apps#create")
    end

    it "routes to #update" do
      put("/apps/1").should route_to("apps#update", id: "1")
    end

    it "routes to #destroy" do
      delete("/apps/1").should route_to("apps#destroy", id: "1")
    end

  end
end


text:
module StructCore
	class SpecConfigurationDSL20X
		def initialize
			@configuration = nil
		end

		attr_accessor :configuration

		def override(key = nil, value = nil)
			return unless key.is_a?(String) && !key.empty? && value.is_a?(String)
			@configuration.overrides[key] = value
		end

		def type(type = nil)
			return unless type.is_a?(String) || type.is_a?(Symbol)
			type = type.to_s
			return if type.empty?

			@configuration.raw_type = type
		end

		def source(source = nil)
			return unless source.is_a?(String) && !source.empty?
			@configuration.source = source
		end

		def respond_to_missing?(_, _)
			true
		end

		def method_missing(_, *_)
			# Do nothing if a method is missing
		end
	end
end


text:
OS=`cat /etc/os-release | grep '^NAME=' |  tr -d \" | sed 's/\n//g' | sed 's/NAME=//g'`
if [ "$OS" == "Ubuntu" ]; then
    USER=ubuntu
    USER_HOME=/home/$USER
    PROFILE_PATH=$USER_HOME/.profile
    apt-get -y install sqlite3 git gcc make curl build-essential
elif [ "$OS" == "Debian GNU/Linux" ]; then
    USER=admin
    USER_HOME=/home/$USER
    PROFILE_PATH=$USER_HOME/.profile
    apt-get -y install sqlite3 git gcc make curl
elif [ "$OS" == "Amazon Linux AMI" ]; then
    USER=ec2-user
    USER_HOME=/home/$USER
    PROFILE_PATH=$USER_HOME/.bash_profile
    yum -y install sqlite git gcc make curl
elif [ "$OS" == "Red Hat Enterprise Linux Server" ]; then
    USER=ec2-user
    USER_HOME=/home/$USER
    PROFILE_PATH=$USER_HOME/.bash_profile
    yum -y install sqlite git gcc make curl
elif [ "$OS" == "CentOS Linux" ]; then
    USER=centos
    USER_HOME=/home/$USER
    PROFILE_PATH=$USER_HOME/.bash_profile
    yum -y install sqlite git gcc make curl
else
    echo "os $OS unsupported for this script"
    exit 1
fi

# Golang install
GO_VERSION=1.9.4
TAR_FILE=go$GO_VERSION.linux-amd64.tar.gz
curl -O https://dl.google.com/go/$TAR_FILE
tar -C /usr/local -xzf $TAR_FILE; rm $TAR_FILE

# For root
mkdir $HOME/go
export GOPATH=$HOME/go
export PATH=$PATH:/usr/local/go/bin:$HOME/go/bin

# Required dirs
mkdir -p /var/log/vuls
chown $USER /var/log/vuls
mkdir -p $GOPATH/src/github.com/kotakanbe
mkdir $GOPATH/src/github.com/future-architect

# CVE dictionnary
cd $GOPATH/src/github.com/kotakanbe
git clone https://github.com/kotakanbe/go-cve-dictionary.git
cd go-cve-dictionary
make install

# Oval dictionnary
cd $GOPATH/src/github.com/kotakanbe
git clone https://github.com/kotakanbe/goval-dictionary.git
cd goval-dictionary
make install

# Install Vuls
cd $GOPATH/src/github.com/future-architect
git clone https://github.com/future-architect/vuls.git
cd vuls
make install

# Moving Go resources to USER_HOME (as cloud-init executes a root)
mkdir $USER_HOME/go
cp -R $GOPATH/* $USER_HOME/go
echo "export GOPATH=\$HOME/go" >> $PROFILE_PATH
echo "export PATH=\$PATH:/usr/local/go/bin:\$HOME/go/bin" >> $PROFILE_PATH

# Generate SSH key for remotes scans. Public key need to be added to ~/.ssh/authorized_keys on remote hosts to be scanned
ssh-keygen -t rsa -N "" -f $USER_HOME/.ssh/id_rsa

# Prepare toml local files for remote scans
/bin/cat > $USER_HOME/config.toml <<EOF
[servers]

[servers.localhost]
host        = "localhost"
port        = "local"

# [servers.debian]
# host      = "..."    # remote host address
# port      = "22"     # for remote ssh scans
# user      = "admin"  # user for remote ssh scans
# keyPath   = "$USER_HOME/.ssh/id_rsa" # Local priv key to SSH connect to scanned target. Targets need to have pub key in their ~/.ssh/authorized_keys
EOF

FETCH_DATA_FILENAME=fetch-nvd-oval-cve-data.sh
/bin/cat > $USER_HOME/$FETCH_DATA_FILENAME <<EOF
source $PROFILE_PATH

# Fetch vulnerability data from NVD
# Takes about 10 minutes
for i in \`seq 2002 $(date +\"%Y\")\`; do go-cve-dictionary fetchnvd -years \$i; done

# Fetch OVAL data for some commonf distro (or what os need to be scanned)
goval-dictionary fetch-debian 7 8 9 10
goval-dictionary fetch-ubuntu 12 14 16
EOF

chmod +x $USER_HOME/$FETCH_DATA_FILENAME
# Since we created files as root and moved root resource to USER_HOME
chown -R $USER:$USER $USER_HOME


text:
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.api
  .accounts(accountSid)
  .outgoingCallerIds // filter callerids to include only those that have the following number
  .each({ phoneNumber: '+14158675309' }, callerId => console.log(callerId.sid));


text:
static int delay_timeout(struct client_state_t *cs, size_t numpackets)
{
    int to = 64;
    char tot[] = { 4, 8, 16, 32, 64 };
    if (numpackets < sizeof tot)
        to = tot[numpackets];
    // Distribution is a bit biased but it doesn't really matter.
    return to * 1000 + (int)(nk_random_u32(&cs->rnd_state) % 1000);
}

static void reinit_shared_deconfig(struct client_state_t *cs)
{
    nk_random_init(&cs->rnd_state);
    advance_xid(cs);
    cs->clientAddr = 0;
    cs->num_dhcp_requests = 0;
    cs->num_dhcp_renews = 0;
    cs->server_arp_sent = 0;
    cs->router_arp_sent = 0;
    cs->server_arp_state = ARP_QUERY;
    cs->router_arp_state = ARP_QUERY;
    cs->fp_state = FPRINT_NONE;
    cs->check_fingerprint = false;
    cs->sent_renew_or_rebind = false;
    cs->sent_gw_query = false;
    cs->sent_first_announce = false;
    cs->sent_second_announce = false;
    memset(&cs->routerArp, 0, sizeof cs->routerArp);
    memset(&cs->serverArp, 0, sizeof cs->serverArp);
    arp_reset_state(cs);
}

static void reinit_selecting(struct client_state_t *cs, int timeout)
{
    reinit_shared_deconfig(cs);
    cs->dhcp_wake_ts = curms() + timeout;
    start_dhcp_listen(cs);
}

// Triggered after a DHCP lease request packet has been sent and no reply has
// been received within the response wait time.  If we've not exceeded the
// maximum number of request retransmits, then send another packet and wait
// again.  Otherwise, return to the DHCP initialization state.
static int requesting_timeout(struct client_state_t *cs,
                               long long nowts)
{
    if (cs->num_dhcp_requests >= 5) {
        reinit_selecting(cs, 0);
        return REQ_TIMEOUT;
    }
    if (send_selecting(cs) < 0) {
        log_line("%s: Failed to send a selecting request packet.",
                 client_config.interface);
        return REQ_FAIL;
    }
    cs->dhcp_wake_ts = nowts + delay_timeout(cs, cs->num_dhcp_requests);
    cs->num_dhcp_requests++;
    return REQ_SUCCESS;
}

// Called by renewing_timeout() to try to renew the lease.  If all
// timeouts expire, then expire the lease and notify the caller.
static int rebinding_timeout(struct client_state_t *cs,
                             long long nowts)
{
    long long elt = cs->leaseStartTime + cs->lease * 1000;
    if (nowts >= elt) {
        log_line("%s: Lease expired.  Searching for a new lease...",
                 client_config.interface);
        reinit_selecting(cs, 0);
        return BTO_EXPIRED;
    }
    start_dhcp_listen(cs);
    if (send_rebind(cs) < 0) {
        log_line("%s: Failed to send a rebind request packet.",
                 client_config.interface);
        return BTO_HARDFAIL;
    }
    cs->sent_renew_or_rebind = true;
    long long ts0 = nowts + (50 + nk_random_u32(&cs->rnd_state) % 20) * 1000;
    cs->dhcp_wake_ts = ts0 < elt ? ts0 : elt;
    return BTO_WAIT;
}

// Called by bound_timeout() to try to renew the lease.
static int renewing_timeout(struct client_state_t *cs,
                            long long nowts)
{
    long long rbt = cs->leaseStartTime + cs->rebindTime * 1000;
    if (nowts >= rbt || cs->num_dhcp_renews >= IGNORED_RENEWS_BEFORE_REBIND)
        return rebinding_timeout(cs, nowts);
    start_dhcp_listen(cs);
    if (send_renew(cs) < 0) {
        log_line("%s: Failed to send a renew request packet.",
                 client_config.interface);
        return BTO_HARDFAIL;
    }
    cs->sent_renew_or_rebind = true;
    ++cs->num_dhcp_renews;
    long long ts0 = nowts + (50 + nk_random_u32(&cs->rnd_state) % 20) * 1000;
    cs->dhcp_wake_ts = ts0 < rbt ? ts0 : rbt;
    return BTO_WAIT;
}

// Called to handle dhcp state timeouts, such as when RENEW or REBIND
// DHCPREQUESTs must be sent.  Can return BTO_(WAIT|EXPIRED|HARDFAIL).
static int bound_timeout(struct client_state_t *cs, long long nowts)
{
    long long rnt = cs->leaseStartTime + cs->renewTime * 1000;
    if (nowts < rnt) {
        cs->dhcp_wake_ts = rnt;
        return BTO_WAIT;
    }
    return renewing_timeout(cs, nowts);
}

static void get_leasetime(struct client_state_t *cs,
                          struct dhcpmsg *packet)
{
    cs->lease = get_option_leasetime(packet);
    cs->leaseStartTime = curms();
    if (!cs->lease) {
        log_line("%s: No lease time received; assuming 1h.",
                 client_config.interface);
        cs->lease = 60 * 60;
    } else {
        if (cs->lease < 60) {
            log_line("%s: Server sent lease of <1m.  Forcing lease to 1m.",
                     client_config.interface);
            cs->lease = 60;
        }
    }
    // Always use RFC2131 'default' values.  It's not worth validating
    // the remote server values, if they even exist, for sanity.
    cs->renewTime = cs->lease >> 1;
    cs->rebindTime = (cs->lease >> 3) * 0x7; // * 0.875
    cs->dhcp_wake_ts = cs->leaseStartTime + cs->renewTime * 1000;
}

static bool validate_acknak(struct client_state_t *cs,
                            struct dhcpmsg *packet,
                            const char *typemsg,
                            uint32_t srcaddr)
{
    // Don't validate the server id.  Instead validate that the
    // yiaddr matches.  Some networks have multiple servers
    // that don't respect the serverid that was specified in
    // our DHCPREQUEST.
    if (memcmp(&packet->yiaddr, &cs->clientAddr, 4))
        return false;

    int found;
    uint32_t sid = get_option_serverid(packet, &found);
    if (!found) {
        log_line("%s: Received %s with no server id.  Ignoring it.",
                 client_config.interface, typemsg);
        return false;
    }
    if (cs->serverAddr != sid) {
        cs->serverAddr = sid;
        cs->srcAddr = srcaddr;
    }
    return true;
}

static int extend_packet(struct client_state_t *cs,
                         struct dhcpmsg *packet, uint8_t msgtype,
                         uint32_t srcaddr)
{
    (void)srcaddr;
    if (msgtype == DHCPACK) {
        if (!validate_acknak(cs, packet, "DHCPACK", srcaddr))
            return ANP_IGNORE;
        cs->sent_renew_or_rebind = false;
        cs->num_dhcp_renews = 0;
        get_leasetime(cs, packet);

        // Did we receive a lease with a different IP than we had before?
        if (memcmp(&packet->yiaddr, &cs->clientAddr, 4)) {
            char clibuf[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, &(struct in_addr){.s_addr=cs->clientAddr},
                      clibuf, sizeof clibuf);
            log_line("%s: Server is now offering IP %s.  Validating...",
                     client_config.interface, clibuf);
            advance_xid(cs);
            return ANP_CHECK_IP;
        } else {
            log_line("%s: Lease refreshed to %u seconds.",
                     client_config.interface, cs->lease);
            if (arp_set_defense_mode(cs) < 0)
                log_line("%s: Failed to create ARP defense socket.",
                         client_config.interface);
            stop_dhcp_listen(cs);
            advance_xid(cs);
            return ANP_SUCCESS;
        }
    } else if (msgtype == DHCPNAK) {
        if (!validate_acknak(cs, packet, "DHCPNAK", srcaddr))
            return ANP_IGNORE;
        cs->sent_renew_or_rebind = false;
        cs->num_dhcp_renews = 0;
        log_line("%s: Our request was rejected.  Searching for a new lease...",
                 client_config.interface);
        reinit_selecting(cs, 3000);
        return ANP_REJECTED;
    }
    return ANP_IGNORE;
}

static int selecting_packet(struct client_state_t *cs,
                            struct dhcpmsg *packet, uint8_t msgtype,
                            uint32_t srcaddr, bool is_requesting)
{
    char clibuf[INET_ADDRSTRLEN];
    char svrbuf[INET_ADDRSTRLEN];
    char srcbuf[INET_ADDRSTRLEN];
    int found;
    if (!is_requesting && msgtype == DHCPOFFER) {
        uint32_t sid = get_option_serverid(packet, &found);
        if (!found) {
            log_line("%s: Invalid offer received: it didn't have a server id.",
                     client_config.interface);
            return ANP_IGNORE;
        }
        cs->xid = packet->xid; // Use for subsequent DHCPREQUESTs
        cs->clientAddr = packet->yiaddr;
        cs->serverAddr = sid;
        cs->srcAddr = srcaddr;
        cs->dhcp_wake_ts = curms();
        cs->num_dhcp_requests = 0;
        inet_ntop(AF_INET, &(struct in_addr){.s_addr=cs->clientAddr},
                  clibuf, sizeof clibuf);
        inet_ntop(AF_INET, &(struct in_addr){.s_addr=cs->serverAddr},
                  svrbuf, sizeof svrbuf);
        inet_ntop(AF_INET, &(struct in_addr){.s_addr=cs->srcAddr},
                  srcbuf, sizeof srcbuf);
        log_line("%s: Received IP offer: %s from server %s via %s.",
                 client_config.interface, clibuf, svrbuf, srcbuf);
        return ANP_SUCCESS;
    } else if (is_requesting && msgtype == DHCPACK) {
        if (!validate_acknak(cs, packet, "DHCPACK", srcaddr))
            return ANP_IGNORE;
        get_leasetime(cs, packet);

        inet_ntop(AF_INET, &(struct in_addr){.s_addr=cs->clientAddr},
                  clibuf, sizeof clibuf);
        inet_ntop(AF_INET, &(struct in_addr){.s_addr=cs->serverAddr},
                  svrbuf, sizeof svrbuf);
        inet_ntop(AF_INET, &(struct in_addr){.s_addr=cs->srcAddr},
                  srcbuf, sizeof srcbuf);
        log_line("%s: Received ACK: %s from server %s via %s.  Validating...",
                 client_config.interface, clibuf, svrbuf, srcbuf);
        return ANP_CHECK_IP;
    }
    return ANP_IGNORE;
}

// Triggered after a DHCP discover packet has been sent and no reply has
// been received within the response wait time.  If we've not exceeded the
// maximum number of discover retransmits, then send another packet and wait
// again.  Otherwise fail.
static int selecting_timeout(struct client_state_t *cs,
                              long long nowts)
{
    if (cs->program_init && cs->num_dhcp_requests >= 2) {
        if (client_config.abort_if_no_lease)
            suicide("%s: No lease; failing.", client_config.interface);
    }
    if (send_discover(cs) < 0) {
        log_line("%s: Failed to send a discover request packet.",
                 client_config.interface);
        return SEL_FAIL;
    }
    cs->dhcp_wake_ts = nowts + delay_timeout(cs, cs->num_dhcp_requests);
    cs->num_dhcp_requests++;
    return SEL_SUCCESS;
}

// Called for a release signal during SELECTING or REQUESTING.
static void print_release(struct client_state_t *cs)
{
    log_line("%s: ndhc going to sleep.  Wake it by sending a SIGUSR1.",
             client_config.interface);
    reinit_shared_deconfig(cs);
    cs->dhcp_wake_ts = -1;
    stop_dhcp_listen(cs);
}

// Called for a release signal during BOUND, RENEWING, or REBINDING.
static int xmit_release(struct client_state_t *cs)
{
    char clibuf[INET_ADDRSTRLEN];
    char svrbuf[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &(struct in_addr){.s_addr=cs->clientAddr},
              clibuf, sizeof clibuf);
    inet_ntop(AF_INET, &(struct in_addr){.s_addr=cs->serverAddr},
              svrbuf, sizeof svrbuf);
    log_line("%s: Unicasting a release of %s to %s.", client_config.interface,
             clibuf, svrbuf);
    if (send_release(cs) < 0) {
        log_line("%s: Failed to send a release request packet.",
                 client_config.interface);
        return -1;
    }
    print_release(cs);
    return 0;
}

// Called for a renewing signal during BOUND or RELEASED
static int frenew(struct client_state_t *cs, bool is_bound)
{
    if (is_bound) {
        log_line("%s: Forcing a DHCP renew...", client_config.interface);
        start_dhcp_listen(cs);
        if (send_renew(cs) < 0) {
            log_line("%s: Failed to send a renew request packet.",
                     client_config.interface);
            return -1;
        }
    } else { // RELEASED
        reinit_selecting(cs, 0);
    }
    return 0;
}

// If we have a lease, check to see if our gateway is still valid via ARP.
// If it fails, state -> SELECTING.
static int ifup_action(struct client_state_t *cs)
{
    if (cs->routerAddr && cs->serverAddr) {
        const bool fp_server = cs->server_arp_state == ARP_FOUND;
        const bool fp_router = (cs->routerAddr != cs->serverAddr) ? (cs->router_arp_state == ARP_FOUND) : fp_server;
        if ((!fp_server && !fp_router) || cs->fp_state == FPRINT_NONE)
            goto no_fingerprint;
        if (cs->fp_state == FPRINT_INPROGRESS) {
            suicide("%s: Carrier lost during initial fingerprint.  Forcing restart.",
                    client_config.interface);
        }
        if (arp_gw_check(cs) >= 0) {
            log_line("%s: Interface is back.  Revalidating lease...",
                     client_config.interface);
            return IFUP_REVALIDATE;
        } else {
            log_line("%s: arp_gw_check could not make arp socket.",
                     client_config.interface);
            return IFUP_FAIL;
        }
    }
no_fingerprint:
    log_line("%s: Interface is back.  Searching for new lease...",
             client_config.interface);
    return IFUP_NEWLEASE;
}

// If ret == 0: do nothing
//    ret == 1: ret = COR_ERROR; scrReturn(ret); continue
//    ret == 2: goto skip_to_released
//    ret == 3: break
static int signal_check_nolease(struct client_state_t *cs)
{
    for (;;) {
        int s = signals_flagged();
        if (s == SIGNAL_NONE) break;
        if (s == SIGNAL_EXIT) signal_exit(EXIT_SUCCESS);
        if (s == SIGNAL_RELEASE) {
            print_release(cs);
            return 2;
        }
    }
    return 0;
}
static int signal_check_havelease(struct client_state_t *cs)
{
    for (;;) {
        int s = signals_flagged();
        if (s == SIGNAL_NONE) break;
        if (s == SIGNAL_EXIT) signal_exit(EXIT_SUCCESS);
        if (s == SIGNAL_RELEASE) {
            int r = xmit_release(cs);
            if (r) return 1;
            return 2;
        }
        if (s == SIGNAL_RENEW) {
            int r = frenew(cs, true);
            if (r) return 1;
        }
    }
    return 0;
}
static int signal_check_released(struct client_state_t *cs)
{
    (void)cs;
    for (;;) {
        int s = signals_flagged();
        if (s == SIGNAL_NONE) break;
        if (s == SIGNAL_EXIT) signal_exit(EXIT_SUCCESS);
        if (s == SIGNAL_RENEW) return 3;
    }
    return 0;
}
#define SIGNAL_CHECK(NAME) \
{ \
    int tt = signal_check_ ## NAME(cs); \
    if (tt == 1) { \
        ret = COR_ERROR; \
        scrReturn(ret); \
        continue; \
    } \
    if (tt == 2) goto skip_to_released; \
    if (tt == 3) break; \
}

#define BAD_STATE() suicide("%s(%d): bad state", __func__, __LINE__)

// XXX: Should be re-entrant so as to handle multiple servers.
int dhcp_handle(struct client_state_t *cs, long long nowts,
                bool sev_dhcp, struct dhcpmsg *dhcp_packet,
                uint8_t dhcp_msgtype, uint32_t dhcp_srcaddr, bool sev_arp,
                bool force_fingerprint, bool dhcp_timeout, bool arp_timeout)
{
    scrBegin;
reinit:
    // We're in the SELECTING state here.
    for (;;) {
        int ret = COR_SUCCESS;
        SIGNAL_CHECK(nolease);
        if (sev_dhcp) {
            int r = selecting_packet(cs, dhcp_packet, dhcp_msgtype,
                                     dhcp_srcaddr, false);
            if (r == ANP_SUCCESS) {
                // Send a request packet to the answering DHCP server.
                sev_dhcp = false;
                goto skip_to_requesting;
            }
        }
        if (dhcp_timeout) {
            int r = selecting_timeout(cs, nowts);
            if (r == SEL_SUCCESS) {
            } else if (r == SEL_FAIL) {
                ret = COR_ERROR;
            } else BAD_STATE();
        }
        scrReturn(ret);
    }
    scrReturn(COR_SUCCESS);
    // We're in the REQUESTING state here.
    for (;;) {
        int ret;
skip_to_requesting:
        ret = COR_SUCCESS;
        SIGNAL_CHECK(nolease);
        if (sev_dhcp) {
            int r = selecting_packet(cs, dhcp_packet, dhcp_msgtype,
                                     dhcp_srcaddr, true);
            if (r == ANP_IGNORE) {
            } else if (r == ANP_CHECK_IP) {
                if (arp_check(cs, dhcp_packet) < 0) {
                    log_line("%s: Failed to make arp socket.  Searching for new lease...",
                             client_config.interface);
                    reinit_selecting(cs, 3000);
                    sev_dhcp = false;
                    goto reinit;
                }
                break;
            } else BAD_STATE();
        }
        if (dhcp_timeout) {
            // Send a request packet to the answering DHCP server.
            int r = requesting_timeout(cs, nowts);
            if (r == REQ_SUCCESS) {
            } else if (r == REQ_TIMEOUT) {
                // We timed out.  Send another packet.
                sev_dhcp = false;
                goto reinit;
            } else if (r == REQ_FAIL) {
                // Failed to send packet.  Sleep and retry.
                ret = COR_ERROR;
            } else BAD_STATE();
        }
        scrReturn(ret);
    }
    scrReturn(COR_SUCCESS);
    // We're checking to see if there's a conflict for our IP.  Technically,
    // this is still in REQUESTING.
    for (;;) {
        int ret;
        ret = COR_SUCCESS;
        SIGNAL_CHECK(nolease);
        if (sev_dhcp) {
            // XXX: Maybe I can think of something to do here.  Would
            //      be more relevant if we tracked multiple dhcp servers.
        }
        if (sev_arp) {
            int r = arp_do_collision_check(cs);
            if (r == ARPR_OK) {
            } else if (r == ARPR_CONFLICT) {
                // XXX: If we tracked multiple DHCP servers, then we
                //      could fall back on another one.
                reinit_selecting(cs, 0);
                sev_dhcp = false;
                goto reinit;
            } else if (r == ARPR_FAIL) {
                ret = COR_ERROR;
                scrReturn(ret);
                continue;
            } else BAD_STATE();
        }
        if (arp_timeout) {
            int r = arp_collision_timeout(cs, nowts);
            if (r == ARPR_FREE) {
                arp_query_gateway(cs);
                arp_announce(cs);
                break;
            } else if (r == ARPR_OK) {
            } else if (r == ARPR_FAIL) {
                ret = COR_ERROR;
                scrReturn(ret);
                continue;
            } else BAD_STATE();
        }
        if (dhcp_timeout) {
            // Send a request packet to the answering DHCP server.
            int r = requesting_timeout(cs, nowts);
            if (r == REQ_SUCCESS) {
            } else if (r == REQ_TIMEOUT) {
                // We timed out.  Send another packet.
                sev_dhcp = false;
                goto reinit;
            } else if (r == REQ_FAIL) {
                // Failed to send packet.  Sleep and retry.
                ret = COR_ERROR;
            } else BAD_STATE();
        }
        scrReturn(ret);
    }
    scrReturn(COR_SUCCESS);
    // We're in the BOUND, RENEWING, or REBINDING states here.
    for (;;) {
        int ret = COR_SUCCESS;
        SIGNAL_CHECK(havelease);
        if (sev_dhcp && cs->sent_renew_or_rebind) {
            int r = extend_packet(cs, dhcp_packet, dhcp_msgtype, dhcp_srcaddr);
            if (r == ANP_SUCCESS || r == ANP_IGNORE) {
            } else if (r == ANP_REJECTED) {
                sev_dhcp = false;
                goto reinit;
            } else if (r == ANP_CHECK_IP) {
                if (arp_check(cs, dhcp_packet) < 0) {
                    log_line("%s: Failed to make arp socket.  Searching for new lease...",
                             client_config.interface);
                    reinit_selecting(cs, 3000);
                    sev_dhcp = false;
                    goto reinit;
                }
            } else BAD_STATE();
        }
        if (sev_arp) {
            int r;
            r = arp_do_defense(cs);
            if (r == ARPR_OK) {
            } else if (r == ARPR_CONFLICT) {
                reinit_selecting(cs, 0);
                sev_dhcp = false;
                goto reinit;
            } else if (r == ARPR_FAIL) {
                ret = COR_ERROR;
                scrReturn(ret);
                continue;
            } else BAD_STATE();
            if (cs->router_arp_state == ARP_QUERY || cs->server_arp_state == ARP_QUERY) {
                r = arp_do_gw_query(cs);
                if (r == ARPR_OK) {
                } else if (r == ARPR_FREE) {
                    log_line("%s: Network fingerprinting complete.", client_config.interface);
                    cs->fp_state = FPRINT_DONE;
                } else if (r == ARPR_FAIL) {
                    ret = COR_ERROR;
                    scrReturn(ret);
                    continue;
                } else BAD_STATE();
            } else if (cs->check_fingerprint) {
                r = arp_do_gw_check(cs);
                if (r == ARPR_OK) {
                } else if (r == ARPR_FREE) {
                    cs->check_fingerprint = false;
                } else if (r == ARPR_CONFLICT) {
                    cs->check_fingerprint = false;
                    reinit_selecting(cs, 0);
                    sev_dhcp = false;
                    goto reinit;
                } else if (r == ARPR_FAIL) {
                    ret = COR_ERROR;
                    scrReturn(ret);
                    continue;
                } else BAD_STATE();
            }
        }
        if (arp_timeout) {
            if (cs->sent_first_announce && cs->sent_second_announce)
                arp_defense_timeout(cs, nowts);
            else
                arp_announce_timeout(cs, nowts);
            if (!cs->sent_gw_query)
                arp_query_gateway_timeout(cs, nowts);
            else if (cs->router_arp_state == ARP_QUERY || cs->server_arp_state == ARP_QUERY) {
                int r = arp_gw_query_timeout(cs, nowts);
                if (r == ARPR_OK) {
                } else if (r == ARPR_FAIL) {
                    ret = COR_ERROR;
                    scrReturn(ret);
                    continue;
                } else BAD_STATE();
            } else if (cs->check_fingerprint) {
                int r = arp_gw_check_timeout(cs, nowts);
                if (r == ARPR_OK) {
                } else if (r == ARPR_CONFLICT) {
                    cs->check_fingerprint = false;
                    reinit_selecting(cs, 0);
                    sev_dhcp = false;
                    goto reinit;
                } else if (r == ARPR_FAIL) {
                    ret = COR_ERROR;
                    scrReturn(ret);
                    continue;
                } else BAD_STATE();
            }
        }
        if (force_fingerprint) {
            int r = ifup_action(cs);
            if (r == IFUP_REVALIDATE) {
            } else if (r == IFUP_NEWLEASE) {
                if (ifchange_deconfig(cs) < 0) {
                    // Likely only to fail because of rfkill.
                    ret = COR_ERROR;
                    scrReturn(ret);
                }
                reinit_selecting(cs, 0);
                sev_dhcp = false;
                goto reinit;
            } else if (r == IFUP_FAIL) {
                ret = COR_ERROR;
                scrReturn(ret);
                continue;
            } else BAD_STATE();
        }
        if (dhcp_timeout) {
            int r = bound_timeout(cs, nowts);
            if (r == BTO_WAIT) {
            } else if (r == BTO_EXPIRED) {
                sev_dhcp = false;
                goto reinit;
            } else if (r == BTO_HARDFAIL) {
                ret = COR_ERROR;
            } else
                BAD_STATE();
        }
        scrReturn(ret);
    }
    sev_dhcp = false;
    goto reinit;
    // We're in the RELEASED state here.
    for (;;) {
        int ret;
skip_to_released:
        ret = COR_SUCCESS;
        SIGNAL_CHECK(released);
        scrReturn(ret);
    }
    sev_dhcp = false;
    goto reinit;
    scrFinish(COR_SUCCESS);
}


text:
console.log("Hello World");
console.log("I'm going now!");


text:
class FdoLiteralValue : public FdoValueExpression
{
};
#endif


text:
<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;

/** @var ClassLoader $loader */
$loader = require __DIR__.'/../vendor/autoload.php';

$loader->addClassMap([
    'Puli\\GeneratedPuliFactory' => __DIR__.'/../.puli/GeneratedPuliFactory.php',
]);

AnnotationRegistry::registerLoader([$loader, 'loadClass']);

return $loader;


text:
import thread
import time
import random

_gpio_thread_running = False
_callbacks = []

def gpio_thread():
    while True:
        time.sleep(random.random() * 4)  # Sleep somewhere between 0 ... 4
        gpio_pin, callback = random.choice(_callbacks)
        callback(gpio_pin)

def _setup_callback(gpio_pin, callback):
    global _gpio_thread_running, _callbacks

    _callbacks.append((gpio_pin, callback))

    if not _gpio_thread_running:
        thread.start_new_thread(gpio_thread, ())
        _gpio_thread_running = True

class GPIO:
    BCM = 0
    IN = 0
    PUD_UP = 0
    FALLING = 0

    def __init__(self):
        pass

    @staticmethod
    def setmode(value):
        pass

    @staticmethod
    def setwarnings(value):
        pass

    @staticmethod
    def setup(gpio_pin, val1, val2):
        pass

    @staticmethod
    def add_event_detect(gpio_pin, val1, callback, bouncetime=0):
        _setup_callback(gpio_pin, callback)


text:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import App from './app';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

const MemberCards = React.createClass({
  render() {
    return (<App />);
  }
});

AppRegistry.registerComponent('MemberCards', () => MemberCards);


text:
/**
 * @module baasicValueSetService
 * @description Baasic Value Set Service provides an easy way to consume Baasic Value Set REST end-points. In order to obtain needed routes `baasicValueSetService` uses `baasicValueSetRouteService`.
*/
(function (angular, module, undefined) {
    "use strict";
    module.service("baasicValueSetService", ["baasicApiHttp", "baasicApiService", "baasicConstants", "baasicValueSetRouteService",
        function (baasicApiHttp, baasicApiService, baasicConstants, valueSetRouteService) {
            return {
                 /**
                 * Returns a promise that is resolved once the find action has been performed. Success response returns a list of value set resources matching given criteria.
                 * @method
                 * @example
baasicValueSetService.find({
  pageNumber : 1,
  pageSize : 10,
  orderBy : '<field>',
  orderDirection : '<asc|desc>',
  search : '<search-phrase>'
})
.success(function (collection) {
  // perform success action here
})
.error(function (response, status, headers, config) {
  // perform error handling here
});
                 **/
                find: function (options) {
                    return baasicApiHttp.get(valueSetRouteService.find.expand(baasicApiService.findParams(options)));
                },
                 /**
                 * Returns a promise that is resolved once the get action has been performed. Success response returns the specified value set resource.
                 * @method
                 * @example
baasicValueSetService.get('<value-set-name>')
.success(function (data) {
  // perform success action here
})
.error(function (response, status, headers, config) {
  // perform error handling here
});
                **/
                get: function (setName, options) {
                    return baasicApiHttp.get(valueSetRouteService.get.expand(baasicApiService.getParams(setName, options, 'setName')));
                },
                 /**
                 * Returns a promise that is resolved once the create value set action has been performed; this action creates a new value set resource.
                 * @method
                 * @example
baasicValueSetService.create({
   name: '<value-set-name>',
   description: '<description>',
   values: [{value: '<value>'}]
})
.success(function (data) {
  // perform success action here
})
.error(function (response, status, headers, config) {
  // perform error handling here
});
                 **/
                create: function (data) {
                    return baasicApiHttp.post(valueSetRouteService.create.expand({}), baasicApiService.createParams(data)[baasicConstants.modelPropertyName]);
                },
                 /**
                 * Returns a promise that is resolved once the update value set action has been performed; this action updates a value set resource. This route uses HAL enabled objects to obtain routes and therefore it doesn't apply `baasicValueSetService` route template. Here is an example of how a route can be obtained from HAL enabled objects:
```
var params = baasicApiService.removeParams(valueSet);
var uri = params['model'].links('put').href;
```
                 * @method
                 * @example
// valueSet is a resource previously fetched using get action.
valueSet.name = '<new-name>';
baasicValueSetService.update(valueSet)
.success(function (data) {
  // perform success action here
})
.error(function (response, status, headers, config) {
  // perform error handling here
});
				**/
                update: function (data) {
                    var params = baasicApiService.updateParams(data);
                    return baasicApiHttp.put(params[baasicConstants.modelPropertyName].links('put').href, params[baasicConstants.modelPropertyName]);
                },
                 /**
                 * Returns a promise that is resolved once the remove action has been performed. This action will delete a value set resource if the action is completed successfully. This route uses HAL enabled objects to obtain routes and therefore it doesn't apply `baasicValueSetService` route template. Here is an example of how a route can be obtained from HAL enabled objects:
```
var params = baasicApiService.removeParams(valueSet);
var uri = params['model'].links('delete').href;
```
                 * @method
                 * @example
// valueSet is a resource previously fetched using get action.
baasicValueSetService.remove(valueSet)
.success(function (data) {
  // perform success action here
})
.error(function (response, status, headers, config) {
  // perform error handling here
});
				**/
                remove: function (data) {
                    var params = baasicApiService.removeParams(data);
                    return baasicApiHttp.delete(params[baasicConstants.modelPropertyName].links('delete').href);
                },
                /**
                * Provides direct access to `baasicValueSetRouteService`.
                * @method
                * @example baasicValueSetService.routeService.get.expand(expandObject);
                **/
                routeService: valueSetRouteService,
                items: {
                    /**
                    * Returns a promise that is resolved once the find action has been performed. Success response returns a list of value set item resources matching given criteria.
                    * @method items.find
                    * @example
baasicValueSetService.items.find({
  setName: '<value-set-name>',
  pageNumber : 1,
  pageSize : 10,
  orderBy : '<field>',
  orderDirection : '<asc|desc>',
  search : '<search-phrase>'
})
.success(function (collection) {
  // perform success action here
})
.error(function (response, status, headers, config) {
  // perform error handling here
});
                    **/
                    find: function (options) {
                        return baasicApiHttp.get(valueSetRouteService.items.find.expand(baasicApiService.findParams(options)));
                    },
                    /**
                    * Returns a promise that is resolved once the get action has been performed. Success response returns the specified value set item resource.
                    * @method items.get
                    * @example
baasicValueSetService.items.get('<value-set-name>', '<set-item-id>')
.success(function (data) {
  // perform success action here
})
.error(function (response, status, headers, config) {
  // perform error handling here
});
                    **/
                    get: function (setName, id, options) {
                        var params = angular.extend({}, options);
                        params.setName = setName;
                        return baasicApiHttp.get(valueSetRouteService.items.get.expand(baasicApiService.getParams(id, params)));
                    },
                    /**
                    * Returns a promise that is resolved once the create value set item action has been performed; this action creates a new value set item resource.
                    * @method items.create
                    * @example
baasicValueSetService.items.create({
   setId: '<value-set-id>',
   value: '<value>'
})
.success(function (data) {
  // perform success action here
})
.error(function (response, status, headers, config) {
  // perform error handling here
});
                    **/
                    create: function (data) {
                        return baasicApiHttp.post(valueSetRouteService.items.create.expand(data), baasicApiService.createParams(data)[baasicConstants.modelPropertyName]);
                    },
                    /**
                    * Returns a promise that is resolved once the update value set item action has been performed; this action updates a value set item resource. This route uses HAL enabled objects to obtain routes and therefore it doesn't apply `baasicValueSetService` route template. Here is an example of how a route can be obtained from HAL enabled objects:
```
var params = baasicApiService.removeParams(valueSetItem);
var uri = params['model'].links('put').href;
```
                    * @method items.update
                    * @example
// valueSetItem is a resource previously fetched using get action.
valueSetItem.value = '<new-value>';
baasicValueSetService.items.update(valueSetItem)
.success(function (data) {
  // perform success action here
})
.error(function (response, status, headers, config) {
  // perform error handling here
});
				    **/
                    update: function (data) {
                        var params = baasicApiService.updateParams(data);
                        return baasicApiHttp.put(params[baasicConstants.modelPropertyName].links('put').href, params[baasicConstants.modelPropertyName]);
                    },
                    /**
                    * Returns a promise that is resolved once the remove action has been performed. This action will delete a value set item if the action is completed successfully. This route uses HAL enabled objects to obtain routes and therefore it doesn't apply `baasicValueSetService` route template. Here is an example of how a route can be obtained from HAL enabled objects:
```
var params = baasicApiService.removeParams(valueSetItem);
var uri = params['model'].links('delete').href;
```
                    * @method items.remove
                    * @example
// valueSetItem is a resource previously fetched using get action.
baasicValueSetService.items.remove(valueSetItem)
.success(function (data) {
  // perform success action here
})
.error(function (response, status, headers, config) {
  // perform error handling here
});
				    **/
                    remove: function (data) {
                        var params = baasicApiService.removeParams(data);
                        return baasicApiHttp.delete(params[baasicConstants.modelPropertyName].links('delete').href);
                    }
                }
            };
        }]);
}(angular, module));
/**
 * @copyright (c) 2017 Mono Ltd
 * @license MIT
 * @author Mono Ltd
 * @overview
 ***Notes:**
 - Refer to the [Baasic REST API](http://dev.baasic.com/api/reference/home) for detailed information about available Baasic REST API end-points.
 - All end-point objects are transformed by the associated route service.
*/


text:
\subsection{Submission}

Results can be submitted from April 8 to April 15 via an online evaluation form:
\begin{itemize}
\item[] \href{http://greententacle.techfak.uni-bielefeld.de/~cunger/qald/index.php?x=evaltool&q=6}{\texttt{http://greententacle.techfak.uni-bielefeld.de/\textasciitilde cunger/qald/\\index.php?x=evaltool\&q=6}}
\end{itemize}
This form is available both during training and test phase
(note the drop down box that allows you to either specify {\tt training} or {\tt test})
and you can upload results as often as you like, for example trying different configurations of your system.
During test phase, the upload with the best results will count.
During training phase the evaluation tool will display the achieved results.

All submissions are required to comply with the JSON format specified in the previous section.
For all questions, the dataset ID and question IDs are obligatory.
Also you have to specify the answer(s) your system returned for that question.
The structure of the answers has to comply with the SPARQL result standard: \url{http://www.w3.org/TR/sparql11-results-json/}.
The bindings are obligatory, all other information can be provided or left out.
That is, the minimal form an answer of a \texttt{SELECT} query should have is the following:

\begin{lstlisting}
{ "results": {
     "bindings": [
          { "var": { "value": "42.0" }}
      ]
   }
}
\end{lstlisting}

The full answer could look as follows:

\begin{lstlisting}
{ "head":
   { "link": [],
     "vars": ["var"]
   },
  "results": {
     "distinct": false,
     "ordered":  true,
     "bindings": [
        { "var":
             { "type": "typed-literal",
               "datatype": "http://www.w3.org/2001/XMLSchema#decimal",
               "value": "42.0"
              }
         }
      ]
   }
}
\end{lstlisting}

For \texttt{ASK} queries, the answer structure is the following (with \texttt{head} being optional):

\begin{lstlisting}[escapechar=!]
  {
    "head": { },
    "boolean": true | false
  }
\end{lstlisting}

For questions that are out of the dataset's scope, the file should contain an empty answer set.

You are allowed to change the natural language question or keywords, for example by inserting quotes around named entities,
by reformulating expressions your system struggles with, or even by using some controlled language format.
If you do so, please document these changes, i.e. replace the provided question string or keywords by the input you used.

Also, it is preferred if your submission leaves out all question strings and keywords except for the ones your system worked on.
%So if you have a Spanish question answering system, please only provide the Spanish question string and/or keywords in your submission.
Otherwise please mark the language in either the system name or configuration slot when uploading a submission.
This way we can properly honour your multilingual efforts.

\subsection{Evaluation measures}
\label{evalmeasures}

Participating systems will be evaluated with respect to precision and recall.
Moreover, participants are encouraged to report performance, i.e. the average time their system takes to answer a query.

For each of the questions, your specified answers will be compared to the answers provided by the gold standard.
The evaluation tool computes precision, recall and F-measure for every question $q$:\footnote{In the case of out-of-scope
questions, an empty answer set counts as precision and recall 1, while a non-empty answer set counts as
precision and recall 0.}
\begin{align*}
\text{\em Recall}(q) &\, =\, \begin{array}{c}
                  \text{number of correct system answers} \\
                  \hline
                  \text{number of gold standard answers} \\
                  \end{array} \\
\text{\em Precision}(q) &\, =\, \begin{array}{c}
                  \text{number of correct system answers} \\
                  \hline
                  \text{number of system answers} \\
                  \end{array} \\
\text{\em F-measure}(q) &\, =\, \begin{array}{c}
                      2\times \text{\em Precision}\times \text{\em Recall} \\
                      \hline
                      \text{\em Precision} + \text{\em Recall} \\
                      \end{array} \\
\end{align*}

\vspace*{-.7cm}

The tool then computes both macro and micro precision, recall and F-measure, both globally and locally, i.e. for
\begin{itemize}
  \item all questions, and
  \item only those questions for which your system provides answers.
\end{itemize}
Therefore we recommend to include in your submission only questions that your system attempted to answer; otherwise the global and local scores will be the same.


text:
/*
 * TimeWidget.cpp
 *
 *  Created on: 5 nov. 2014
 *      Author: Briag Le Nabec
 */

#include "TimeWidget.h"

TimeWidget::TimeWidget(wxWindow *parent, wxWindowID id) : DataWidget(parent, id) {

	timeText = new wxStaticText(this, wxID_ANY, wxT("00:00:00"), wxPoint(0,0), wxDefaultSize, wxALIGN_CENTRE_HORIZONTAL);

	this->SetBackgroundColour(wxColour(* wxWHITE));
	this->SetForegroundColour(wxColour(* wxBLUE));
	timeText->SetFont(timeText->GetFont().Scale(2.9));
}

TimeWidget::~TimeWidget() {
	// TODO Auto-generated destructor stub
}

void TimeWidget::updateData(const std::unordered_map<std::string, double> &data ) {

	int time = data.at("LogTime");

	int sec = (time - (time / 100)*100) % 60;
	int min = (time/100 - (time / 10000) * 100) % 60;
	int hour = (time / 10000);

	std::stringstream sstm;
	sstm << "Time \n " << std::setfill ('0') << std::setw (2) << hour << ":" << std::setfill ('0') << std::setw (2) <<  min << ":" << std::setfill ('0') << std::setw (2) << sec;

	timeText->SetLabelText(sstm.str());
}


text:
require 'spec_helper'

describe ActionPubsub do
  before(:all) do
    @messages_received = ::Concurrent::AtomicReference.new
    @messages_received.update{ |_set| [] }

    ::ActionPubsub.on('blog/post/created', :as => 'one') do |record|
      @messages_received.update{|_set|
        _set << record
        _set
      }
    end

    ::ActionPubsub.on('blog/post/created', :as => 'two') do |record|
      @messages_received.update{|_set|
        _set << record
        _set
      }
    end
  end
  it ".exchanges" do
    described_class.exchanges.should be_a(::ActionPubsub::Registry)
  end

  it ".channels" do
    described_class.channels.should be_a(::ActionPubsub::Registry)
  end

  it ".subscriptions" do
    described_class.subscriptions.should be_a(::ActionPubsub::Registry)
  end

  context "publishing" do
    #todo: hmmm i thought atomic reference blocked?

    it do
      ::ActionPubsub.publish('blog/post/created', :publishing_test_blog_post_created)
      sleep(0.1)
      expect(@messages_received.get).to include(:publishing_test_blog_post_created)
    end

    context "each subscriber receives one copy of the message" do
      it do
        ::ActionPubsub.publish('blog/post/created', :publishing_test_blog_post_created_copy)
        sleep(0.1)
        expect(@messages_received.get.select{|item| item == :publishing_test_blog_post_created_copy}.length).to eq 2
      end
    end

    context "duplicate subscribers dont spawn new subscribers" do
      before(:all) do
        ::ActionPubsub.on('blog/post/created', :as => 'one') do |record|
          @messages_received.update{|_set|
            _set << record
            _set
          }
        end
      end

      it do
        ::ActionPubsub.publish('blog/post/created', :publishing_test_blog_post_created_copy_again)
        sleep(0.1)
        expect(@messages_received.get.select{|item| item == :publishing_test_blog_post_created_copy_again}.length).to eq 2
      end
    end
  end
end


text:
package eu.m6r.druid

import java.nio.file.Path
import java.nio.file.Paths

import scala.concurrent.Future
import scala.concurrent.Promise
import scala.concurrent.duration.Duration
import scala.language.implicitConversions

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.twitter
import com.twitter.util.Return
import com.twitter.util.ScheduledThreadPoolTimer
import com.twitter.util.Throw
import scopt.Read

package object client {
  private[druid] lazy val objectMapper = {
    val objectMapper = new ObjectMapper() with ScalaObjectMapper
    objectMapper.registerModule(DefaultScalaModule)
    objectMapper.registerModule(new JodaModule)
    objectMapper
  }

  implicit val timer = new ScheduledThreadPoolTimer()

  implicit def twitterFutureToScala[T](tf: twitter.util.Future[T]): Future[T] = {
    val promise = Promise[T]

    tf respond {
      case Return(r) => promise success r
      case Throw(e) => promise failure e
    }
    promise.future
  }

  implicit def scalaDurationToTwitter(duration: Duration): com.twitter.util.Duration = {
    com.twitter.util.Duration(duration.length, duration.unit)
  }

  implicit def tripleTupleOptionRead[A1: Read, A2: Read, A3: Read]: Read[(A1, A2, Option[A3])] =
    new Read[(A1, A2, Option[A3])] {
      val arity = 2
      val reads: String => (A1, A2, Option[A3]) = { (s: String) =>
        s.split(',') match {
          case Array(first, second) => (
                implicitly[Read[A1]].reads(first),
                implicitly[Read[A2]].reads(second),
                None)
          case Array(first, second, third) => (
              implicitly[Read[A1]].reads(first),
              implicitly[Read[A2]].reads(second),
              Some(implicitly[Read[A3]].reads(third)))
        }
      }
    }

  implicit def pathOptionRead: Read[Path] =
    new Read[Path] {
      val arity = 1
      val reads: String => Path = { (s: String) =>
        Paths.get(s)
      }
    }
}


text:
<add>
<doc>
<field name="uid">doi:10.1371/journal.pntd.0001390</field>
<field name="doi">10.1371/journal.pntd.0001390</field>
<field name="data_source">PLoS Open Access XML</field>
<field name="authors">Francesca Holt, Stephen J. Gillam, Jeremiah M. Ngondi</field>
<field name="title">Improving Access to Medicines for Neglected Tropical Diseases in Developing Countries: Lessons from Three Emerging Economies</field>
<field name="journal">PLoS Neglected Tropical Diseases</field>
<field name="year">2012</field>
<field name="volume">6</field>
<field name="number">2</field>
<field name="pages">e1390</field>
<field name="license">Creative Commons Attribution (CC BY)</field>
<field name="license_url">http://creativecommons.org/licenses/by/3.0/</field>
<field name="fulltext">
Introduction

Neglected tropical diseases (NTDs) are those largely ignored by medical
science, partly because they do not represent a viable commercial market for
private pharmaceutical companies. These diseases are endemic in developing
countries and have a significant impact at both personal and national levels.
Globally, NTDs affect an estimated 2.7 billion people living on less than US$2
per day [1] and potently reinforce the poverty cycle [2]. At present, the
prevailing strategy for improving access to medicines for these NTDs is drug
donation programmes, which, despite providing some of the highest economic
returns of public health programmes at 15%–30% [2], [3], have uncertain
sustainability. Countries in demographic and economic transition are uniquely
poised to be leaders in a shift towards a more sustainable, affordable means
of providing access to medicines for NTDs.

The Position of the Emerging Economies

China, India, and Brazil are three of the largest of more than 20 countries in
economic and demographic transition commonly referred to as emerging economies
[4]. Along with Russia, they are referred to as the "BRIC" countries and are
predicted to overtake the G6 countries (United States, Japan, United Kingdom,
Germany, France, and Italy) in terms of gross domestic product (GDP) by 2040
[5]. Their pharmaceutical industries are concomitantly booming; the
pharmaceutical market in China is expected to drive US$40 billion in growth
through 2013, whilst Brazil and India are each expected to add US$5–15 billion
to the pharmaceutical market [6].

However, in terms of disease burden and health care, these countries continue
to suffer many of the problems found in developing countries, including NTDs.
Brazil is estimated to be afflicted by six of the NTDs, whilst China and India
are thought to harbour four [7]. Furthermore, India, China, and the Americas
account for 59% of the world population without access to essential medicines
[8]. But these countries are unique in that they have managed to cultivate
their own pharmaceutical industry with the capacity to produce affordable
drugs for NTDs for use in domestic and international markets.

A review by Frew et al. identified 78 "innovative home-grown, small to medium-
size health biotechnology companies in the emerging economies in Brazil,
China, India and South Africa". These "had a collective pipeline of nearly 500
products for more than 100 indications". Of the products for HIV, malaria,
tuberculosis, and NTDs, two-fifths (40.5%) of the products on the market and
62.9% of the products in development were for NTDs [9]. For example,
Fungisome, a liposomal amphotericin B used to treat visceral leishmaniasis,
was developed by an Indian company, Lifecare Innovations. Dermacerium, a
topical agent used in the treatment or prophylaxis of skin infections in
patients with leprosy, is produced by Silvestre Labs, Brazil [9]. Clearly,
these countries recognise the worth of investment in developing medicinal
tools to combat NTDs and have the capacity to do so.

Experiences of India and Brazil

So how are the emerging economies working to improve access to medicines for
NTDs? Lower costs are helping to stimulate the development of medicines in
these emerging economies. The cost of research and development (</field></doc>
</add>


text:
import { compile } from '../utils/helpers';

QUnit.module('ember-template-compiler: deprecate-model-render');

QUnit.test('Using `{{render` with model provides a deprecation', function() {
  expect(1);

  let expectedMessage =
    `Please refactor \`{{render "foo-bar" coolModel}}\` to a component and` +
    ` invoke via \`{{foo-bar model=coolModel}}\`. ('baz/foo-bar' @ L1:C0) `;

  expectDeprecation(() => {
    compile('{{render "foo-bar" coolModel}}', {
      moduleName: 'baz/foo-bar'
    });
  }, expectedMessage);
});


text:
<post>

    This content filter can be useful in environments where the content stays the same but tags or tag
        attributes may change, e.g. a simple portal with presentation preferences depicted in CSS or other
        presentation-oriented tags. This tag removes the tags (and any attributes) hence removes the
    part of the response subject to change. The remainder can then be safely compared to an expected value.

    See the <stepref name="verifyContent"/> step for an example of using this content filter.

</post>


text:
declare module "router5/plugins/browser" {
	function browserPlugin(options?: {});
	export default browserPlugin;
}


text:
<!doctype html>

                        Areas

                                        <button id="nuevaA" class="btn btn-success" data-toggle="modal" data-target="#modalNuevaArea">
                                            Nueva Area
                                        </button>

                                        Mis Areas

                                        <?php
                                        include '../Datos/mostrarAreas.php';
                                        ?>

                        <form role="form" id="form1" name="form" >

                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Nueva Area

                                    Nombre del Area
                                    <input id="nombreDeArea" class="form-control" required>

                                    <?php
                                    include '../Datos/mostrarTiposDeAreas.php';
                                    ?>

                                    Observacion
                                    <textarea id="observacionDeArea" class="form-control" rows="3"></textarea>

                                <button type="button"  class="btn btn-default" data-dismiss="modal">Cancelar</button>
                                <button  id="guardarArea" class="btn btn-primary" >Guardar</button>

                        </form>