text:
@class TestContext;

@interface TestState : RCSBaseState

@end

@interface TestPushdownState : RCSBasePushdownState

@end

@implementation TestState

@end

@implementation TestPushdownState

@end

@interface TestState (Transitions)

- (void)start:(TestContext *)context;
- (void)gotoA:(TestContext *)context;

@end

@interface TestContext : NSObject <RCSStateContext>

@property (nonatomic, weak) TestState *state;
@property (nonatomic, assign) BOOL enteredStateA;

@end

@interface TestPushdownStateContext : NSObject <RCSPushdownStateContext>

@property (nonatomic, weak) TestPushdownState *state;
@property (nonatomic, strong) NSMutableArray *pushdownStack;
@property (nonatomic, assign) BOOL enteredSubA;

@end

@implementation TestContext

- (id)init
{
    self = [super init];
    if (self)
    {
        _state = [[TestState state] startState];
    }
    return self;
}

- (void)stateContextDidEnterErrorState
{
    [NSException raise:NSInternalInconsistencyException format:@"TestContext did enter error state"];
}

- (void)_enteringStateA
{
    self.enteredStateA = YES;
}

@end

@implementation TestPushdownStateContext

- (id)init
{
    self = [super init];
    if (self) {
        _state = [[TestPushdownState state] startState];
        _pushdownStack = [NSMutableArray new];
    }
    return self;
}

- (id<RCSPushdownState>)pushState
{
    id<RCSPushdownState> result = self.state;
    if (result) [_pushdownStack addObject:result];
    return result;
}

- (id<RCSPushdownState>)popState
{
    id<RCSPushdownState> result = [_pushdownStack lastObject];
    if (result) [_pushdownStack removeLastObject];
    return result;
}

- (void)_enteringSubA
{
    self.enteredSubA = YES;
}

- (void)stateContextDidEnterErrorState
{
    [NSException raise:NSInternalInconsistencyException format:@"TestPushdownStateContext did enter error PushdownState"];
}

@end

@implementation RCSFSMTests
{
    TestContext *_ctx;
    TestPushdownStateContext *_pushdownStateCtx;
}

+ (void)initialize
{
    if (self == [RCSFSMTests class])
    {
        id <RCSState> Base = [TestState state];
        id <RCSState> Error = [Base stateNamed:@"Error"];
        id <RCSState> Start = [Base stateNamed:@"Start"];
        id <RCSState> Running = [Base stateNamed:@"Running"];
        id <RCSState> StateA = [Base stateNamed:@"StateA"];
        id <RCSState> StateB = [Base stateNamed:@"StateB"];

        [Base declareErrorState:Error];
        [Base declareStartState:Start];

        SEL start = [Base transitionToErrorStateWhen:@selector(start:)];
        [Start when:start transitionTo:Running];

        SEL gotoA = [Running when:@selector(gotoA:) transitionTo:StateA];

        [StateA whenEnteringPerform:@selector(_enteringStateA)];

        id <RCSPushdownState> PushdownStateBase = [TestPushdownState state];
        id <RCSPushdownState> PushdownStateError = [PushdownStateBase stateNamed:@"Error"];
        id <RCSPushdownState> PushdownStateStart = [PushdownStateBase stateNamed:@"Start"];

        id <RCSPushdownState> PushdownStateSubA = [PushdownStateBase stateNamed:@"SubA"];

        [PushdownStateBase declareErrorState:PushdownStateError];
        [PushdownStateBase declareStartState:PushdownStateStart];

        [PushdownStateSubA whenEnteringPerform:@selector(_enteringSubA)];
    }
}

- (void)setUp
{
    [super setUp];
    _ctx = [[TestContext alloc] init];
    _pushdownStateCtx = [[TestPushdownStateContext alloc] init];
}

- (void)tearDown
{
    // Tear-down code here.
    _pushdownStateCtx = nil;
    _ctx = nil;
    [super tearDown];
}

- (void)testInitialize
{
    STAssertNotNil(NSClassFromString(@"TestStateStart"), @"Start state class not found");
    STAssertEquals([[TestState state] stateNamed:@"Start"], [[TestState state] startState], @"start state not set");
    STAssertEquals([[TestState state] stateNamed:@"Start"], [[[TestState state] stateNamed:@"Start"] startState], @"start state not set");

    STAssertEquals([[TestState state] stateNamed:@"Error"], [[TestState state] errorState], @"error state not set on Base state");
    STAssertEquals([[TestState state] stateNamed:@"Error"], [[[TestState state] stateNamed:@"Start"] errorState], @"error state not set on Start state");
}

- (void)testInit
{
    STAssertNotNil(_ctx, @"context doesn't exist");
    STAssertEquals([_ctx state], [[TestState state] startState], @"context should start in the Start state");
}

- (void)testTransition
{
    [_ctx.state transition:_ctx to:[[TestState state] stateNamed:@"StateB"]];
    STAssertEquals(_ctx.state, [[TestState state] stateNamed:@"StateB"], nil);
}

- (void)testTransitionStartToRunning
{
    [_ctx.state start:_ctx];
    STAssertEquals([_ctx state], [[TestState state] stateNamed:@"Running"], @"context should start in the Running state");
}

- (void)testStateContextDidEnterErrorState
{
    [_ctx.state start:_ctx];
    // the Running state doesn't implement the start: transition, so it should run the base implementation with transitions to Error
    // the context class implements stateContextDidEnterErrorState which throws an exception
    STAssertThrows([_ctx.state start:_ctx], @"start from Running should transition to error state, which should throw an exception");
}

- (void)testWhenEnteringPerform
{
    [_ctx.state start:_ctx];
    [_ctx.state gotoA:_ctx];
    STAssertTrue(_ctx.enteredStateA, nil);
}

- (void)testPush
{
    [_pushdownStateCtx.state transition:_pushdownStateCtx push:[[TestPushdownState state] stateNamed:@"SubA"]];
    STAssertEquals(_pushdownStateCtx.state, [[TestPushdownState state] stateNamed:@"SubA"], nil);
    STAssertEquals([_pushdownStateCtx.pushdownStack count], (NSUInteger)1, nil);
    STAssertEquals([_pushdownStateCtx.pushdownStack lastObject], [[TestPushdownState state] startState], nil);
    STAssertTrue(_pushdownStateCtx.enteredSubA, nil);
}

- (void)testPop
{
    [_pushdownStateCtx.state transition:_pushdownStateCtx push:[[TestPushdownState state] stateNamed:@"SubA"]];
    [_pushdownStateCtx.state pop:_pushdownStateCtx];
    STAssertEquals([_pushdownStateCtx.pushdownStack count], (NSUInteger)0, nil);
    STAssertEquals(_pushdownStateCtx.state, [[TestPushdownState state] startState], nil);
}

@end


text:
package com.intellij.openapi.wm.impl;

public interface FloatingDecoratorMarker {
}

redpajama_set_name: RedPajamaGithub


text:
package org.jboss.modules;

import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.util.Iterator;

import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

/**
 * Test to verify the functionality of the LocalModuleLoader.
 *
 * @author John Bailey
 */
public class LocalModuleLoaderTest extends AbstractModuleTestCase {
    private ModuleLoader moduleLoader;

    @Before
    public void setupModuleLoader() throws Exception {
        final File repoRoot = getResource("test/repo");
        System.setProperty("foo.bar", "substituted_value");
        moduleLoader = new LocalModuleLoader(new File[] {repoRoot});
    }

    @Test
    public void testBasicLoad() throws Exception {
        Module module = moduleLoader.loadModule("test.test");
        assertNotNull(module);
    }

    @Test
    public void testCurrent() throws Exception {
        ModuleLoader loader = Module.getCallerModuleLoader();
        System.out.println(loader);
    }

    @Test
    public void testLoadWithDeps() throws Exception {
        Module module = moduleLoader.loadModule(ModuleIdentifier.fromString("test.with-deps"));
        assertNotNull(module);
    }

    @Test
    public void testLoadWithBadDeps() throws Exception {
        try {
            moduleLoader.loadModule(ModuleIdentifier.fromString("test.bad-deps.1_0"));
            fail("Should have thrown a ModuleNotFoundException");
        } catch(ModuleNotFoundException expected) {}
    }

    @Test
    public void testLoadWithCircularDeps() throws Exception {
        assertNotNull(moduleLoader.loadModule(ModuleIdentifier.fromString("test.circular-deps-A")));
        assertNotNull(moduleLoader.loadModule(ModuleIdentifier.fromString("test.circular-deps-B")));
        assertNotNull(moduleLoader.loadModule(ModuleIdentifier.fromString("test.circular-deps-C")));
        assertNotNull(moduleLoader.loadModule(ModuleIdentifier.fromString("test.circular-deps-D")));
    }

    @Test
    public void testAbsentModule() throws Exception {
        try {
            moduleLoader.loadModule("test.absent");
            fail("Should have thrown a ModuleNotFoundException");
        } catch(ModuleNotFoundException expected) {}
    }

    @Test
    public void testIterateModules() throws Exception {
        Iterator<String> names = moduleLoader.iterateModules((String) null, true);
        while (names.hasNext()) {
            String name = names.next();
            assertNotEquals("test.absent", name);
            if (!name.equals("test.bad-deps")) {
                Module module = moduleLoader.loadModule(name);
                assertNotNull(module);
            }
        }
    }
}


text:
{% if site.google_analytics %}
	<!-- Google Analytics UA -->
	<script>
		(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
		(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
		m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
		})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

		ga('create', '{{ site.google_analytics }}', 'auto');
		ga('send', 'pageview', {
		  'page': '{{ site.baseurl }}{{ page.url }}',
		  'title': '{{ page.title | replace: "'", "\\'" }}'
		});
	</script>
	<!-- End Google Analytics -->
{% endif %}

<!-- Global site tag (gtag.js) - Google Analytics GA4 -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-DVEF9XK6SS"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-DVEF9XK6SS');

  // All this is new...........
  const mcid = new URLSearchParams(location.search).get('mcid');
  if (mcid) {
    // send it to Google Analytics
    // @see: https://support.google.com/analytics/answer/10075209
    gtag("event", "mailchimp_mailshot", {
      mcid: mcid,
    });
  }
</script>


text:
package org.hisp.dhis.trackedentity.action.validation;

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

import org.hisp.dhis.common.comparator.IdentifiableObjectNameComparator;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramService;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;
import org.hisp.dhis.validation.ValidationCriteria;
import org.hisp.dhis.validation.ValidationCriteriaService;

import com.opensymphony.xwork2.Action;

/**
 * @author Chau Thu Tran
 * @version GetValidationCriteriaAction.java Apr 29, 2010 10:45:36 AM
 */
public class GetValidationCriteriaAction
    implements Action
{
    // -------------------------------------------------------------------------
    // Dependency
    // -------------------------------------------------------------------------

    private ValidationCriteriaService validationCriteriaService;

    public void setValidationCriteriaService( ValidationCriteriaService validationCriteriaService )
    {
        this.validationCriteriaService = validationCriteriaService;
    }

    private ProgramService programService;

    public void setProgramService( ProgramService programService )
    {
        this.programService = programService;
    }

    // -------------------------------------------------------------------------
    // Input && Output
    // -------------------------------------------------------------------------

    private int id;

    private int programId;

    private List<TrackedEntityAttribute> attribute = new ArrayList<>();

    private ValidationCriteria validationCriteria;

    private Program program;

    // -------------------------------------------------------------------------
    // Getter && Setter
    // -------------------------------------------------------------------------

    public void setId( int id )
    {
        this.id = id;
    }

    public void setProgramId( int programId )
    {
        this.programId = programId;
    }

    public ValidationCriteria getValidationCriteria()
    {
        return validationCriteria;
    }

    public List<TrackedEntityAttribute> getattribute()
    {
        return attribute;
    }

    public Program getProgram()
    {
        return program;
    }

    // -------------------------------------------------------------------------
    // Action Implementation
    // -------------------------------------------------------------------------

    @Override
    public String execute()
        throws Exception
    {
        validationCriteria = validationCriteriaService.getValidationCriteria( id );

        program = programService.getProgram( programId );

        attribute = program.getTrackedEntityAttributes();

        Collections.sort( attribute, IdentifiableObjectNameComparator.INSTANCE );

        return SUCCESS;
    }

}


text:
package ca.ipredict.helpers;
import java.util.ArrayList;
import java.util.List;

public class MemoryLogger {

	public static List<Integer> mMemoryUsage = new ArrayList<Integer>(); //used for memory usage

	public MemoryLogger() {
		// should not be instantiated
	}

	public static void reset() {
		mMemoryUsage.clear();
	}

	public static void addUpdate() {
		mMemoryUsage.add(getUsedMemory());
	}

	public static int getUsedMemory() {

		int mb = 1024*1024; // 1mb  = 1024 * 1024 bytes
        Runtime runtime = Runtime.getRuntime();

        int usage = (int)( runtime.totalMemory() - runtime.freeMemory() ) / mb;

        return usage;
	}

	public static int getMaxMemory() {
		int mb = 1024*1024; // 1mb  = 1024 * 1024 bytes
        Runtime runtime = Runtime.getRuntime();

        int usage = (int)( runtime.totalMemory() ) / mb;

        return usage;
	}

	public static void displayUsage() {

		int max = 0;
		String output = "Memory history: ";
		for(int i: mMemoryUsage) {
			output += i + " ";
			if(i > max)
				max = i;
		}
		System.out.println(output);
		System.out.println("Max memory used: " + max + "mb");
	}

}


text:
Vimporter is a thought experiment.

The goal is to provide functionality to build static-plugins with Vim. To be
more precise, goal is for Vim plugins to depend on other plugins, without
needing the user to actually install those other plugins as shared libraries.

## How it works

A plugin specifies a `requirements.vim.txt` file, which can be used by
Vimporter, itself a Vim plugin.

## Installing

With Vundle:

```
Plugin 'Kashomon/vimporter`
```

## requirements.vim.txt

```
namespace: example
requirements:
- google/vim-maktaba >= 0.15.0
- zorp >= 0.1.0
```

Opening `requirements.vim.txt` in Vim and running `:Vimporter import` clones
the plugins' autoload directories and renames them appropriately.

So, for the example plugin, these libraries would be copied as:

Note: I've used YAML here for the format.

## Analysis

* Makes it easier to copy-and-paste plugin code
* Can't really do interesting dependency analysis: would need to copy the whole
  plugins.


text:
hackemu
=======

Emulator for the Hack (and HACK+) architecture described in "The Elements of Computing Systems."


text:
package engine

type engine struct {
	db        DeploymentRepository
	chartsDir string
}

func New(repository DeploymentRepository, savedChartsDir string) DeploymentEngine {
	return &engine{
		db:        repository,
		chartsDir: savedChartsDir,
	}
}


text:
//#actor
//###replace: package actors;
package javaguide.akka;

import akka.actor.*;
//###replace: import actors.HelloActorProtocol.*;
import javaguide.akka.HelloActorProtocol.*;

public class HelloActor extends UntypedActor {

    public static Props props = Props.create(HelloActor.class);

    public void onReceive(Object msg) throws Exception {
        if (msg instanceof SayHello) {
            sender().tell("Hello, " + ((SayHello) msg).name, self());
        }
    }
}
//#actor


text:
#include "projectile.h"

#define METER 0.00168

ObjGeometry *Missile::missileMesh;

ObjGeometry *Bomb::bombMesh;

Projectile::Projectile(Model *src) {
    source = src;

    /* Calculate projectile location and velocity. */
    Eigen::Vector3f center = source->position;
    float offset = source->radius;
    float rotationY = source->rotate.y();
    float rotationX = source->rotate.x();

    rotationY = DEGREES_TO_RADIANS(-rotationY);
    rotationX = DEGREES_TO_RADIANS(-rotationX);

    /* Basically start with unit vector centered at origin
     * Rotate it, then scale it based on radius of our ship
     * finally translate its center to be the center of the ship */
    Eigen::Vector3f projPos = center;
    Eigen::Vector3f unitPos = Eigen::Vector3f(1.0, 0.0, 0.0);

    Eigen::Matrix3f rotationMatrixY, rotationMatrixX;
    rotationMatrixY << cos(rotationY), 0, -sin(rotationY), 0, 1, 0, sin(rotationY), 0, cos(rotationY);
    rotationMatrixX << 1, 0, 0, 0, cos(rotationX), sin(rotationX), 0, -sin(rotationX), cos(rotationX);

    unitPos = rotationMatrixX * rotationMatrixY * unitPos;
    unitPos *= offset;
    projPos += unitPos;

    Eigen::Vector3f bombVel = projPos - center;

    velocity = bombVel;
    position = projPos;
    rotate = source->rotate;
}

Projectile::Projectile(Eigen::Vector3f pos, Eigen::Vector3f vel) : ActiveModel(pos, vel) {
    source = NULL;
}

Projectile::~Projectile() {
    if (bs) {
        delete bs;
    }
}

Missile::Missile(Model *src) : Projectile(src) {
    init();
    playAudio("missile");
}

Missile::Missile(Eigen::Vector3f pos, Eigen::Vector3f vel) : Projectile(pos, vel) {
    init();
    scale = Eigen::Vector3f(.01, .01, .01);
    velocity *= 5;
}

void Missile::init() {
    mesh = missileMesh;
    radius = 0.050;
    velocity *= 2.5;
    shipPart = true;
    scale = Eigen::Vector3f(3, 3, 2);
    t = 0;
    color = Eigen::Vector3f(0, 1.0, 0);
    calculateTransform();
    bs = new BoundingSphere(this);
    bs->update(mesh);
    bs->transform(&transM, scale[1]);
}

void Missile::die() {
    if (dead) {
        return;
    }
    mesh = NULL;
    dead = true;
}

void Missile::loadMeshes() {
    missileMesh = new ObjGeometry("geometry/laser.obj");
    debug("Loaded missile mesh");
}

Bomb::Bomb(float power, Model *src) : Projectile(src) {
    mesh = bombMesh;
    t = 0;
    color = Eigen::Vector3f(1.0, 0, 0);
    radius = 0.050;
    velocity += 2*velocity*power;
    scale = Eigen::Vector3f(.05, .05, .05);

    calculateTransform();
    bs = new BoundingSphere(this);
    bs->update(mesh);
    bs->radius = radius;
    bs->transform(&transM, scale[0]);
}

void Bomb::applyForce(Force *force) {
    if (dead) return;

    force->affect(this);
}

void Bomb::hit(Model *model){
    model->bs->center = model->position;
    model->bs->bounce(&position, &velocity, radius);
}

void Bomb::loadMeshes() {
    bombMesh = new ObjGeometry("geometry/ball.obj");
    debug("Loaded bomb mesh");
}

MissileList *Bomb::explode() {
    MissileList *specks = new MissileList();
    for (unsigned int i = 0; i < 2; i++) {
        for (unsigned int j = 0; j < 2; j++) {
            for (unsigned int k = 0; k < 2; k++) {
                specks->push_back(new Missile(position,
                    Eigen::Vector3f((i?1:-1)*0.033, (j?1:-1)*0.033, (k?1:-1)*0.033)));
            }
        }
    }
    specks->push_back(new Missile(position, Eigen::Vector3f(0, 0.033, 0)));
    specks->push_back(new Missile(position, Eigen::Vector3f(0, -0.033, 0)));

    die();

    return specks;
}


text:
FROM openjdk:8-jre-alpine
MAINTAINER Apache MiNiFi <dev@nifi.apache.org>

# Values are set by Maven
ARG UID
ARG GID
ARG MINIFI_VERSION
ARG MINIFI_BINARY

ENV MINIFI_BASE_DIR /opt/minifi
ENV MINIFI_HOME $MINIFI_BASE_DIR/minifi-current

# Setup MiNiFi user
RUN addgroup -g $GID minifi || groupmod -n minifi `getent group $GID | cut -d: -f1`
RUN adduser -S -H -G minifi minifi
RUN mkdir -p $MINIFI_BASE_DIR

ADD $MINIFI_BINARY $MINIFI_BASE_DIR
RUN ln -s $MINIFI_BASE_DIR/minifi-$MINIFI_VERSION $MINIFI_HOME
RUN chown -R -L minifi:minifi $MINIFI_HOME

USER minifi

# Startup MiNiFi
CMD $MINIFI_HOME/bin/minifi.sh run


text:
<?php
/**
 * Created by PhpStorm.
 * Project: vfsStream
 * User: Sebastian Hopfe
 * Date: 14.07.16
 * Time: 14:07
 */

namespace org\bovigo\vfs;

class vfsStreamDirectoryIssue134TestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * access to root directory
     *
     * @var  vfsStreamDirectory
     */
    protected $rootDirectory;

    /**
     * set up test environment
     */
    public function setUp()
    {
        $this->rootDirectory = vfsStream::newDirectory('/');
        $this->rootDirectory->addChild(vfsStream::newDirectory('var/log/app'));

    }

    /**
     * Test: should save directory name as string internal
     *
     * @small
     */
    public function testShouldSaveDirectoryNameAsStringInternal()
    {
        $dir = $this->rootDirectory->getChild('var/log/app');

        $dir->addChild(vfsStream::newDirectory(80));

        static::assertNotNull($this->rootDirectory->getChild('var/log/app/80'));
    }

    /**
     * Test: should rename directory name as string internal
     *
     * @small
     */
    public function testShouldRenameDirectoryNameAsStringInternal()
    {
        $dir = $this->rootDirectory->getChild('var/log/app');

        $dir->addChild(vfsStream::newDirectory(80));

        $child = $this->rootDirectory->getChild('var/log/app/80');
        $child->rename(90);

        static::assertNotNull($this->rootDirectory->getChild('var/log/app/90'));
    }
}


text:
#ifndef APRINTER_SDIO_SDCARD_H
#define APRINTER_SDIO_SDCARD_H

#include <stddef.h>
#include <stdint.h>
#include <limits.h>

#include <aprinter/meta/WrapFunction.h>
#include <aprinter/meta/BasicMetaUtils.h>
#include <aprinter/meta/ServiceUtils.h>
#include <aprinter/base/Object.h>
#include <aprinter/base/DebugObject.h>
#include <aprinter/base/Assert.h>
#include <aprinter/base/Callback.h>
#include <aprinter/hal/generic/SdioInterface.h>
#include <aprinter/misc/ClockUtils.h>

#include <aprinter/BeginNamespace.h>

template <typename Arg>
class SdioSdCard {
    using Context        = typename Arg::Context;
    using ParentObject   = typename Arg::ParentObject;
    using InitHandler    = typename Arg::InitHandler;
    using CommandHandler = typename Arg::CommandHandler;
    using Params         = typename Arg::Params;

public:
    struct Object;

private:
    using ProgrammingTimeout = AMBRO_WRAP_DOUBLE(3.0);

    using TheDebugObject = DebugObject<Context, Object>;
    struct SdioCommandHandler;
    APRINTER_MAKE_INSTANCE(TheSdio, (Params::SdioService::template Sdio<Context, Object, SdioCommandHandler, ProgrammingTimeout>))
    using TheClockUtils = ClockUtils<Context>;
    using TimeType = typename TheClockUtils::TimeType;

    enum {
        STATE_INACTIVE, STATE_POWERON, STATE_POWER_CLOCKS, STATE_GO_IDLE, STATE_IF_COND,
        STATE_OP_COND_APP, STATE_OP_COND, STATE_SEND_CID, STATE_RELATIVE_ADDR,
        STATE_SEND_CSD, STATE_SELECT, STATE_WIDEBUS_APP, STATE_WIDEBUS,
        STATE_RUNNING
    };

    enum {IO_STATE_IDLE, IO_STATE_DATA, IO_STATE_STOP, IO_STATE_WAIT_BUSY};

    static TimeType const PowerOnTimeTicks        = 0.0015                      * TheClockUtils::time_freq;
    static TimeType const PowerClocksTimeTicks    = 0.001                       * TheClockUtils::time_freq;
    static TimeType const InitTimeoutTicks        = 1.2                         * TheClockUtils::time_freq;
    static TimeType const ProgrammingTimeoutTicks = ProgrammingTimeout::value() * TheClockUtils::time_freq;

    static uint8_t const StopAttemptCount = 5;

    static uint32_t const IfCondArgumentResponse = UINT32_C(0x1AA);
    static uint32_t const OpCondArgument = UINT32_C(0x40100000);

    static uint32_t const R1ResponseErrorMask = UINT32_C(0xFDF9E008);
    static uint32_t const R1OutOfRangeError   = UINT32_C(0x80000000);

    static const uint8_t CMD_GO_IDLE_STATE = 0;
    static const uint8_t CMD_ALL_SEND_CID = 2;
    static const uint8_t CMD_SEND_RELATIVE_ADDR = 3;
    static const uint8_t CMD_SELECT_DESELECT = 7;
    static const uint8_t CMD_SEND_IF_COND = 8;
    static const uint8_t CMD_SEND_CSD = 9;
    static const uint8_t CMD_STOP_TRANSMISSION = 12;
    static const uint8_t CMD_SEND_STATUS = 13;
    static const uint8_t CMD_READ_SINGLE_BLOCK = 17;
    static const uint8_t CMD_READ_MULTIPLE_BLOCKS = 18;
    static const uint8_t CMD_WRITE_BLOCK = 24;
    static const uint8_t CMD_WRITE_MULTIPLE_BLOCKS = 25;
    static const uint8_t CMD_APP_CMD = 55;
    static const uint8_t ACMD_SET_BUS_WIDTH = 6;
    static const uint8_t ACMD_SD_SEND_OP_COND = 41;

    static const uint32_t OCR_CCS = (UINT32_C(1) << 30);
    static const uint32_t OCR_CPUS = (UINT32_C(1) << 31);

public:
    using BlockIndexType = uint32_t;
    static size_t const BlockSize = TheSdio::BlockSize;
    using DataWordType = uint32_t;
    static size_t const MaxIoBlocks = TheSdio::MaxIoBlocks;
    static int const MaxIoDescriptors = TheSdio::MaxIoDescriptors;

    static void init (Context c)
    {
        auto *o = Object::self(c);

        TheSdio::init(c);
        o->timer.init(c, APRINTER_CB_STATFUNC_T(&SdioSdCard::timer_handler));
        o->state = STATE_INACTIVE;

        TheDebugObject::init(c);
    }

    static void deinit (Context c)
    {
        auto *o = Object::self(c);
        TheDebugObject::deinit(c);

        o->timer.deinit(c);
        TheSdio::deinit(c);
    }

    static void activate (Context c)
    {
        auto *o = Object::self(c);
        TheDebugObject::access(c);
        AMBRO_ASSERT(o->state == STATE_INACTIVE)

        TheSdio::startPowerOn(c, SdioIface::InterfaceParams{false, false});
        o->timer.appendAfter(c, PowerOnTimeTicks);
        o->state = STATE_POWERON;
    }

    static void deactivate (Context c)
    {
        auto *o = Object::self(c);
        TheDebugObject::access(c);
        AMBRO_ASSERT(o->state != STATE_INACTIVE)

        deactivate_common(c);
    }

    static BlockIndexType getCapacityBlocks (Context c)
    {
        auto *o = Object::self(c);
        TheDebugObject::access(c);
        AMBRO_ASSERT(o->state == STATE_RUNNING)
        AMBRO_ASSERT(o->capacity_blocks > 0)

        return o->capacity_blocks;
    }

    static bool isWritable (Context c)
    {
        auto *o = Object::self(c);
        TheDebugObject::access(c);
        AMBRO_ASSERT(o->state == STATE_RUNNING)

        // TBD: checks if card is actually writable
        return true;
    }

    static void startReadOrWrite (Context c, bool is_write, BlockIndexType block, size_t num_blocks, TransferVector<DataWordType> data_vector)
    {
        auto *o = Object::self(c);
        TheDebugObject::access(c);
        AMBRO_ASSERT(o->state == STATE_RUNNING)
        AMBRO_ASSERT(o->io_state == IO_STATE_IDLE)
        AMBRO_ASSERT(block <= o->capacity_blocks)
        AMBRO_ASSERT(num_blocks > 0)
        AMBRO_ASSERT(num_blocks <= o->capacity_blocks - block)

        o->multi_block = (num_blocks > 1);
        uint8_t cmd = is_write ?
            (o->multi_block ? CMD_WRITE_MULTIPLE_BLOCKS : CMD_WRITE_BLOCK) :
            (o->multi_block ? CMD_READ_MULTIPLE_BLOCKS : CMD_READ_SINGLE_BLOCK);
        SdioIface::DataDirection dir = is_write ? SdioIface::DATA_DIR_WRITE : SdioIface::DATA_DIR_READ;
        uint32_t addr = o->is_sdhc ? block : (block * 512);
        TheSdio::startCommand(c, SdioIface::CommandParams{cmd, addr, SdioIface::RESPONSE_SHORT, 0, dir, num_blocks, data_vector});
        o->io_state = IO_STATE_DATA;
        o->is_write = is_write;
    }

    using GetSdio = TheSdio;

private:
    static void timer_handler (Context c)
    {
        auto *o = Object::self(c);
        TheDebugObject::access(c);

        switch (o->state) {
            case STATE_POWERON: {
                TheSdio::completePowerOn(c);
                TimeType timer_time = Context::Clock::getTime(c) + PowerClocksTimeTicks;
                o->timer.appendAt(c, timer_time);
                o->state = STATE_POWER_CLOCKS;
            } break;

            case STATE_POWER_CLOCKS: {
                TheSdio::startCommand(c, SdioIface::CommandParams{CMD_GO_IDLE_STATE, 0, SdioIface::RESPONSE_NONE});
                o->state = STATE_GO_IDLE;
            } break;

            default: AMBRO_ASSERT(false);
        }
    }

    static void sdio_command_handler (Context c, SdioIface::CommandResults results, SdioIface::DataErrorCode data_error)
    {
        auto *o = Object::self(c);
        TheDebugObject::access(c);

        switch (o->state) {
            case STATE_GO_IDLE: {
                if (results.error_code != SdioIface::CMD_ERROR_NONE) {
                    return init_error(c, 1);
                }
                TheSdio::startCommand(c, SdioIface::CommandParams{CMD_SEND_IF_COND, IfCondArgumentResponse, SdioIface::RESPONSE_SHORT});
                o->state = STATE_IF_COND;
            } break;

            case STATE_IF_COND: {
                if (results.error_code != SdioIface::CMD_ERROR_NONE) {
                    return init_error(c, 2);
                }
                if (results.response[0] != IfCondArgumentResponse) {
                    return init_error(c, 3);
                }
                send_app_cmd(c, 0);
                o->state = STATE_OP_COND_APP;
                o->poll_timer.setAfter(c, InitTimeoutTicks);
            } break;

            case STATE_OP_COND_APP: {
                if (!check_r1_response(results)) {
                    return init_error(c, 4);
                }
                TheSdio::startCommand(c, SdioIface::CommandParams{ACMD_SD_SEND_OP_COND, OpCondArgument, SdioIface::RESPONSE_SHORT, SdioIface::CMD_FLAG_NO_CRC_CHECK|SdioIface::CMD_FLAG_NO_CMDNUM_CHECK});
                o->state = STATE_OP_COND;
            } break;

            case STATE_OP_COND: {
                if (results.error_code != SdioIface::CMD_ERROR_NONE) {
                    return init_error(c, 5);
                }
                uint32_t ocr = results.response[0];
                if (!(ocr & OCR_CPUS)) {
                    if (o->poll_timer.isExpired(c)) {
                        return init_error(c, 6);
                    }
                    send_app_cmd(c, 0);
                    o->state = STATE_OP_COND_APP;
                    return;
                }
                o->is_sdhc = ocr & OCR_CCS;
                TheSdio::startCommand(c, SdioIface::CommandParams{CMD_ALL_SEND_CID, 0, SdioIface::RESPONSE_LONG, SdioIface::CMD_FLAG_NO_CMDNUM_CHECK});
                o->state = STATE_SEND_CID;
            } break;

            case STATE_SEND_CID: {
                if (results.error_code != SdioIface::CMD_ERROR_NONE) {
                    return init_error(c, 7);
                }
                TheSdio::startCommand(c, SdioIface::CommandParams{CMD_SEND_RELATIVE_ADDR, 0, SdioIface::RESPONSE_SHORT});
                o->state = STATE_RELATIVE_ADDR;
            } break;

            case STATE_RELATIVE_ADDR: {
                if (results.error_code != SdioIface::CMD_ERROR_NONE) {
                    return init_error(c, 8);
                }
                uint32_t response = results.response[0];
                if ((response & UINT32_C(0xE000))) {
                    return init_error(c, 9);
                }
                o->rca = response >> 16;
                TheSdio::reconfigureInterface(c, SdioIface::InterfaceParams{true, false});
                TheSdio::startCommand(c, SdioIface::CommandParams{CMD_SEND_CSD, (uint32_t)o->rca << 16, SdioIface::RESPONSE_LONG, SdioIface::CMD_FLAG_NO_CMDNUM_CHECK});
                o->state = STATE_SEND_CSD;
            } break;

            case STATE_SEND_CSD: {
                if (results.error_code != SdioIface::CMD_ERROR_NONE) {
                    return init_error(c, 9);
                }
                if (o->is_sdhc) {
                    uint32_t c_size = (results.response[2] >> 16) | ((results.response[1] & 0x3f) << 16);
                    if (c_size >= UINT32_C(0x3fffff)) {
                        return init_error(c, 11);
                    }
                    o->capacity_blocks = (c_size + 1) * UINT32_C(1024);
                } else {
                    uint8_t read_bl_len = (results.response[1] >> 16) & 0xf;
                    uint8_t c_size_mult = (results.response[2] >> 15) & 0x7;
                    uint16_t c_size = (results.response[2] >> 30) | ((results.response[1] & 0x3ff) << 2);
                    uint16_t mult = ((uint16_t)1 << (c_size_mult + 2));
                    uint32_t blocknr = (uint32_t)(c_size + 1) * mult;
                    uint16_t block_len = (uint16_t)1 << read_bl_len;
                    o->capacity_blocks = blocknr * (block_len / 512);
                }
                if (o->capacity_blocks == 0) {
                    return init_error(c, 10);
                }
                TheSdio::startCommand(c, SdioIface::CommandParams{CMD_SELECT_DESELECT, (uint32_t)o->rca << 16, SdioIface::RESPONSE_SHORT_BUSY});
                o->state = STATE_SELECT;
            } break;

            case STATE_SELECT: {
                if (!check_r1_response(results)) {
                    return init_error(c, 11);
                }
                if (!TheSdio::IsWideMode) {
                    return complete_init(c);
                }
                send_app_cmd(c, o->rca);
                o->state = STATE_WIDEBUS_APP;
            } break;

            case STATE_WIDEBUS_APP: {
                if (!check_r1_response(results)) {
                    return init_error(c, 12);
                }
                TheSdio::startCommand(c, SdioIface::CommandParams{ACMD_SET_BUS_WIDTH, 2, SdioIface::RESPONSE_SHORT});
                o->state = STATE_WIDEBUS;
            } break;

            case STATE_WIDEBUS: {
                if (!check_r1_response(results)) {
                    return init_error(c, 13);
                }
                TheSdio::reconfigureInterface(c, SdioIface::InterfaceParams{true, true});
                return complete_init(c);
            } break;

            case STATE_RUNNING: {
                switch (o->io_state) {
                    case IO_STATE_DATA: {
                        o->io_error = (!check_r1_response(results) || data_error != SdioIface::DATA_ERROR_NONE);
                        if (o->multi_block) {
                            send_stop_command(c);
                            o->stop_attempts_left = StopAttemptCount;
                            o->io_state = IO_STATE_STOP;
                            return;
                        }
                        return continue_after_io_stopped(c);
                    } break;

                    case IO_STATE_STOP: {
                        if (!check_r1_response(results, get_io_status_error_bits(c))) {
                            o->io_error = true;
                            if (results.error_code != SdioIface::CMD_ERROR_BUSY_TIMEOUT && o->stop_attempts_left > 1) {
                                o->stop_attempts_left--;
                                send_stop_command(c);
                                return;
                            }
                        }
                        return continue_after_io_stopped(c);
                    } break;

                    case IO_STATE_WAIT_BUSY: {
                        if (!check_r1_response(results)) {
                            o->io_error = true;
                        } else {
                            uint8_t card_state = (results.response[0] >> 9) & 0xF;
                            if (card_state == 6 || card_state == 7) {
                                if (!o->poll_timer.isExpired(c)) {
                                    send_status_command(c);
                                    return;
                                }
                                o->io_error = true;
                            }
                        }
                        return complete_operation(c, o->io_error);
                    } break;

                    default:
                        AMBRO_ASSERT(false);
                }
            } break;

            default:
                AMBRO_ASSERT(false);
        }
    }
    struct SdioCommandHandler : public AMBRO_WFUNC_TD(&SdioSdCard::sdio_command_handler) {};

    static void deactivate_common (Context c)
    {
        auto *o = Object::self(c);

        o->timer.unset(c);
        TheSdio::reset(c);
        o->state = STATE_INACTIVE;
    }

    static void init_error (Context c, uint8_t error_code)
    {
        deactivate_common(c);

        return InitHandler::call(c, error_code);
    }

    static bool check_r1_response (SdioIface::CommandResults results, uint32_t error_bits=R1ResponseErrorMask)
    {
        return results.error_code == SdioIface::CMD_ERROR_NONE && !(results.response[0] & error_bits);
    }

    static void send_app_cmd (Context c, uint16_t rca)
    {
        TheSdio::startCommand(c, SdioIface::CommandParams{CMD_APP_CMD, (uint32_t)rca << 16, SdioIface::RESPONSE_SHORT});
    }

    static void complete_init (Context c)
    {
        auto *o = Object::self(c);

        o->state = STATE_RUNNING;
        o->io_state = IO_STATE_IDLE;

        return InitHandler::call(c, 0);
    }

    static void complete_operation (Context c, bool error)
    {
        auto *o = Object::self(c);
        AMBRO_ASSERT(o->state == STATE_RUNNING)
        AMBRO_ASSERT(o->io_state != IO_STATE_IDLE)

        o->io_state = IO_STATE_IDLE;

        return CommandHandler::call(c, error);
    }

    static void continue_after_io_stopped (Context c)
    {
        auto *o = Object::self(c);

        if (!o->is_write) {
            return complete_operation(c, o->io_error);
        }
        o->poll_timer.setAfter(c, ProgrammingTimeoutTicks);
        send_status_command(c);
        o->io_state = IO_STATE_WAIT_BUSY;
    }

    static void send_stop_command (Context c)
    {
        TheSdio::startCommand(c, SdioIface::CommandParams{CMD_STOP_TRANSMISSION, 0, SdioIface::RESPONSE_SHORT_BUSY});
    }

    static void send_status_command (Context c)
    {
        auto *o = Object::self(c);
        TheSdio::startCommand(c, SdioIface::CommandParams{CMD_SEND_STATUS, (uint32_t)o->rca << 16, SdioIface::RESPONSE_SHORT});
    }

    static uint32_t get_io_status_error_bits (Context c)
    {
        auto *o = Object::self(c);

        return (!o->is_write && o->multi_block) ? (R1ResponseErrorMask&~R1OutOfRangeError) : R1ResponseErrorMask;
    }

public:
    struct Object : public ObjBase<SdioSdCard, ParentObject, MakeTypeList<
        TheDebugObject,
        TheSdio
    >> {
        typename Context::EventLoop::TimedEvent timer;
        uint8_t state;
        typename TheClockUtils::PollTimer poll_timer;
        bool is_sdhc;
        uint16_t rca;
        uint32_t capacity_blocks;
        uint8_t io_state;
        uint8_t stop_attempts_left;
        bool is_write;
        bool multi_block;
        bool io_error;
    };
};

APRINTER_ALIAS_STRUCT_EXT(SdioSdCardService, (
    APRINTER_AS_TYPE(SdioService)
), (
    APRINTER_ALIAS_STRUCT_EXT(SdCard, (
        APRINTER_AS_TYPE(Context),
        APRINTER_AS_TYPE(ParentObject),
        APRINTER_AS_TYPE(InitHandler),
        APRINTER_AS_TYPE(CommandHandler)
    ), (
        using Params = SdioSdCardService;
        APRINTER_DEF_INSTANCE(SdCard, SdioSdCard)
    ))
))

#include <aprinter/EndNamespace.h>

#endif


text:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes                 #-}
{-# LANGUAGE TemplateHaskell            #-}
-- |

module Hask8080.CPU where

import           Control.Applicative
import           Control.Lens
import           Control.Monad.State.Strict
import           Data.Bits.Bitwise          (joinAt, splitAt)
import           Data.Bits.Lens
import qualified Data.Vector.Unboxed        as V
import           Prelude                    hiding (splitAt)
import           System.IO                  (Handle)

import           Hask8080.Types

data Registers = Registers
  { _regA :: Byte
  , _regF :: Byte
  , _regB :: Byte
  , _regC :: Byte
  , _regD :: Byte
  , _regE :: Byte
  , _regH :: Byte
  , _regL :: Byte
  } deriving (Show, Eq)

makeLenses ''Registers

_Bytes :: Iso' Address (Byte,Byte)
_Bytes = iso (over both fromIntegral . splitAt 8)
             (uncurry (joinAt 8) . over both fromIntegral)

mkReg16 :: Reg -> Reg -> Lens' Registers Address
mkReg16 hr lr = lens get_ set_
  where
    -- construct an Address from a pair of Bytes at the given
    -- registers
    get_ rs = _Bytes # (rs ^. reg hr, rs ^. reg lr)
    -- destruct an Address into a pair of Bytes and set the given
    -- registers with the high and low bytes, respectively.
    set_ rs addr = case addr ^. _Bytes of
      (hb,lb) -> rs & reg hr .~ hb & reg lr .~ lb

class HasReg a where
  reg :: Reg -> Lens' a Byte

instance HasReg Registers where
  reg A = regA
  reg F = regF
  reg B = regB
  reg C = regC
  reg D = regD
  reg E = regE
  reg H = regH
  reg L = regL
  reg M = error "fatal: tried to access main memory as a register"

data Flag = S | Z | P | Ca | AC deriving (Show, Eq)

class HasFlag a where
  flag :: Flag -> Lens' a Bool

instance HasFlag Registers where
  flag f = reg F . bitAt b
    where b = case f of
                S  -> 7
                Z  -> 6
                P  -> 2
                Ca -> 1
                AC -> 4

type Memory = V.Vector Byte

data Processor = Processor
  { _cycles    :: !Int
  , _registers :: !Registers
  , _memory    :: !Memory
  , _ie        :: !Bool
  , _sp        :: !Address
  , _pc        :: !Address
  , _in        :: !Handle
  , _out       :: !Handle
  } deriving (Show, Eq)

makeLenses ''Processor

reg16 :: Reg16 -> Lens' Processor Address
reg16 SP = sp
reg16 PC = pc
reg16 rp = registers . rpl
  where
    rpl = case rp of
      AF -> mkReg16 A F
      BC -> mkReg16 B C
      DE -> mkReg16 B C
      HL -> mkReg16 H L
      SP -> error "tried to access Stack Pointer as a register pair"
      PC -> error "tried to access Program Counter as a register pair"

regMem :: Reg16 -> Lens' Processor Byte
regMem rp = lens get_ set_
  where
    get_ p   = p ^?! mem (p ^. reg16 rp)
    set_ p a = p   & mem (p ^. reg16 rp) .~ a

instance HasReg Processor where
  reg r = registers . reg r

instance HasFlag Processor where
  flag f = registers . flag f

mem :: Address -> Traversal' Processor Byte
mem addr = memory . ix (fromIntegral addr)

newtype CPU' m a = CPU' (StateT Processor m a)
  deriving (Functor, Applicative, Monad, MonadIO, MonadState Processor)

type CPU a = CPU' IO a

runCPU :: CPU a -> Processor -> IO Processor
runCPU (CPU' k) = execStateT k

memAt :: Address -> CPU Byte
memAt addr = fmap (V.! fromIntegral addr) (use memory)

nextByte :: CPU Byte
nextByte = memAt . succ =<< use pc

nextByte2 :: CPU Byte
nextByte2 = memAt . succ . succ =<< use pc

nextBytes :: CPU (Byte,Byte)
nextBytes = liftA2 (,) nextByte nextByte2

nextAddr :: CPU Address
nextAddr = fmap (_Bytes #) nextBytes


text:
from sqlalchemy import Boolean, Column, DateTime, ForeignKey
from sqlalchemy import Integer, MetaData, String, Table, Text

def upgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine
    instance_actions = Table('instance_actions', meta, autoload=True)
    instance_actions.drop()

def downgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    instances = Table('instances', meta, autoload=True,
                      autoload_with=migrate_engine)

    instance_actions = Table('instance_actions', meta,
            Column('created_at', DateTime(timezone=False)),
            Column('updated_at', DateTime(timezone=False)),
            Column('deleted_at', DateTime(timezone=False)),
            Column('deleted', Boolean(create_constraint=True, name=None)),
            Column('id', Integer(), primary_key=True, nullable=False),
            Column('instance_id',
                   Integer(),
                   ForeignKey('instances.id')),
            Column('action',
                   String(length=255, convert_unicode=False,
                          assert_unicode=None,
                          unicode_error=None, _warn_on_bytestring=False)),
            Column('error',
                   Text(length=None, convert_unicode=False,
                        assert_unicode=None,
                        unicode_error=None, _warn_on_bytestring=False)),
            )
    instance_actions.create()


text:
// [START kms_update_key_remove_rotation_schedule]

using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;

public class UpdateKeyRemoveRotationSample
{
    public CryptoKey UpdateKeyRemoveRotation(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            CryptoKeyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId),
            RotationPeriod = null,
            NextRotationTime = null,
        };

        // Build the update mask.
        FieldMask fieldMask = new FieldMask
        {
            Paths = { "rotation_period", "next_rotation_time" },
        };

        // Call the API.
        CryptoKey result = client.UpdateCryptoKey(key, fieldMask);

        // Return the updated key.
        return result;
    }
}
// [END kms_update_key_remove_rotation_schedule]


text:
(function ($) {
    $.extend($.inputmask.defaults.aliases, {
        'phone': {
            url: "phone-codes/phone-codes.js",
            countrycode: "",
            mask: function (opts) {
                opts.definitions['#'] = opts.definitions['9'];
                var maskList = [];
                $.ajax({
                    url: opts.url,
                    async: false,
                    dataType: 'json',
                    success: function (response) {
                        maskList = response;
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(thrownError + " - " + opts.url);
                    }
                });

                maskList = maskList.sort(function (a, b) {
                    return (a["mask"] || a) < (b["mask"] || b) ? -1 : 1;
                });

                return maskList;
            },
            keepStatic: false,
            nojumps: true,
            nojumpsThreshold: 1,
            onBeforeMask: function (value, opts) {
                var processedValue = value.replace(/^0/g, "");
                if (processedValue.indexOf(opts.countrycode) > 1 || processedValue.indexOf(opts.countrycode) == -1) {
                    processedValue = "+" + opts.countrycode + processedValue;
                }

                return processedValue;
            }
        },
        'phonebe': {
            alias: "phone",
            url: "phone-codes/phone-be.js",
            countrycode: "32",
            nojumpsThreshold: 4
        }
    });
    return $.fn.inputmask;
})(jQuery);


text:
<?php

	/**
	 *	EXAMPLES OF USE
	 *************************************
	 *
	 *	Download and unzip your custom framework.  Then create the database connection file.
	 *
	 *	$install = new installer();
	 *	$install->download('http://your-domain.com/framework.zip');
	 *	$install->unpack();
	 *	$cred = array(
	 *		'DB_HOST' => 'localhost',
	 *		'DB_DATABASE' => 'user_db12',
	 *		'DB_USER' => 'user_kewl',
	 *		'DB_PASSWORD' => 'abc123456'
	 *	);
	 *	$install->create($cred, 'config.php');
	 *
	 *
	 *	...OR...
	 *
	 *
	 *	Download and unzip Wordpress (or a framework of your choosing).
	 *
	 *	$install = new installer($url);
	 *	$install->download($install->framework['wordpress']);
	 *	$install->unpack();
	 *
	 **/

	class installer{

		public $installer;
		public $framework = array(
			'wordpress' => 'https://wordpress.org/latest.zip',
			'joomla' => 'https://github.com/joomla/joomla-cms/releases/download/3.4.8/Joomla_3.4.8-Stable-Full_Package.zip',
			'druplal' => 'https://ftp.drupal.org/files/projects/drupal-8.0.4.zip',
			'concrete5' => 'https://www.concrete5.org/download_file/-/view/85780/',
			'opencart' => 'https://codeload.github.com/opencart/opencart/zip/2.1.0.2'
		);

		public function __construct(){
			$this->installer = 'install-'.time().'.zip';
			$this->zipUrl = $_zipUrl;
		}

		private function checkFile($url){
			if(fopen($url, 'r'))
				return true;

			return false;
		}

		public function download($url){
			if($this->checkFile($url)):
				$fp = fopen($this->installer, 'w');
				$ch = curl_init($url);
				curl_setopt($ch, CURLOPT_FILE, $fp);
				$data = curl_exec($ch);
				curl_close($ch);
				fclose($fp);
			else:
				print __CLASS__.': File does not exist.'."\n";
			endif;
		}

		public function unpack(){
			if($this->checkFile($this->installer)):
				$zip = new ZipArchive();
				if($zip->open(dirname(__FILE__).'/'.$this->installer) === TRUE):
					$zip->extractTo(dirname(__FILE__).'/');
					$zip->close();
					unlink($this->installer);
					print __CLASS__.': Install Complete.'."\n";
				else:
					print __CLASS__.': Could not extract zip.'."\n";
				endif;
			else:
				print __CLASS__.': Installer zip does not exist.'."\n";
			endif;
		}

		public function create($inputs=array(), $filename='db_config.php'){
			$config = '<?php'."\n\n";
			foreach($inputs as $k=>$v):
				$config .= "\tdefine('".strtoupper($k)."', '".$v."');\n";
			endforeach;
			$config .= "\n".'?>';
			file_put_contents($filename, $config);
		}

	}

?>


text:
#include <aws/redshift/model/DescribeHsmConfigurationsResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>

#include <utility>

using namespace Aws::Redshift::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;

DescribeHsmConfigurationsResult::DescribeHsmConfigurationsResult()
{
}

DescribeHsmConfigurationsResult::DescribeHsmConfigurationsResult(const AmazonWebServiceResult<XmlDocument>& result)
{
  *this = result;
}

DescribeHsmConfigurationsResult& DescribeHsmConfigurationsResult::operator =(const AmazonWebServiceResult<XmlDocument>& result)
{
  const XmlDocument& xmlDocument = result.GetPayload();
  XmlNode rootNode = xmlDocument.GetRootElement();
  XmlNode resultNode = rootNode;
  if (rootNode.GetName() != "DescribeHsmConfigurationsResult")
  {
    resultNode = rootNode.FirstChild("DescribeHsmConfigurationsResult");
  }

  if(!resultNode.IsNull())
  {
    XmlNode markerNode = resultNode.FirstChild("Marker");
    if(!markerNode.IsNull())
    {
      m_marker = StringUtils::Trim(markerNode.GetText().c_str());
    }
    XmlNode hsmConfigurationsNode = resultNode.FirstChild("HsmConfigurations");
    if(!hsmConfigurationsNode.IsNull())
    {
      XmlNode hsmConfigurationsMember = hsmConfigurationsNode.FirstChild("HsmConfiguration");
      while(!hsmConfigurationsMember.IsNull())
      {
        m_hsmConfigurations.push_back(hsmConfigurationsMember);
        hsmConfigurationsMember = hsmConfigurationsMember.NextNode("HsmConfiguration");
      }

    }
  }

  XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
  m_responseMetadata = responseMetadataNode;
  AWS_LOGSTREAM_DEBUG("Aws::Redshift::Model::DescribeHsmConfigurationsResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );

  return *this;
}


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		$this->load->view('login');
	}

        function dashboard() {
            $this->load->model(array('m_apps','m_config'));
            $tahun = (get_safe('tahun') !== '')?get_safe('tahun'):date("Y");
            $data['jumlah_ruas'] = $this->m_apps->get_jumlah_ruas_jalan($tahun);
            $data['total_panjang'] = $this->m_apps->get_total_panjang_ruas_jalan($tahun);
            $data['kondisi_mantap'] = $this->m_apps->get_kondisi_ruas_jalan($tahun, 'mantap');
            $data['kondisi_tidak_mantap'] = $this->m_apps->get_kondisi_ruas_jalan($tahun, 'tidak mantap');
            $data['sepuluh_jalan'] = $this->m_config->data_top10_pekerjaan_jalan();
            $this->load->view('dashboard', $data);
        }
}


text:
package seedu.address.model;

import javafx.collections.ObservableList;
import seedu.address.model.task.DeadlineTask;
import seedu.address.model.task.EventTask;
import seedu.address.model.task.FloatingTask;

/**
 * Unmodifiable view of a task book.
 */
public interface ReadOnlyTaskBook {

    /**
     * Returns an unmodifiable view of the FloatingTasks list.
     */
    ObservableList<FloatingTask> getFloatingTasks();

    /**
     * Returns an unmodifiable view of the DeadlineTasks list.
     */
    ObservableList<DeadlineTask> getDeadlineTasks();

    /**
     * Returns an unmodifiable view of the EventTasks list.
     */
    ObservableList<EventTask> getEventTasks();

}


text:
from typing import Callable, Optional, Sequence, Tuple, Union

import jax.lax as lax
import jax.numpy as jnp
import jax.random
import numpy as np
from jaxtyping import Array

from ..module import Module, static_field

class Pool(Module):
    """General N-dimensional downsampling over a sliding window."""

    init: Union[int, float, Array]
    operation: Callable[[Array, Array], Array]
    num_spatial_dims: int = static_field()
    kernel_size: Sequence[int] = static_field()
    stride: Sequence[int] = static_field()
    padding: Sequence[Tuple[int, int]] = static_field()
    use_ceil: bool = static_field()

    def __init__(
        self,
        init: Union[int, float, Array],
        operation: Callable[[Array, Array], Array],
        num_spatial_dims: int,
        kernel_size: Union[int, Sequence[int]],
        stride: Union[int, Sequence[int]] = 1,
        padding: Union[int, Sequence[int], Sequence[Tuple[int, int]]] = 0,
        use_ceil: bool = False,
        **kwargs,
    ):
        """**Arguments:**

        - `init`: The initial value for the reduction.
        - `operation`: The operation applied to the inputs of each window.
        - `num_spatial_dims`: The number of spatial dimensions.
        - `kernel_size`: The size of the convolutional kernel.
        - `stride`: The stride of the convolution.
        - `padding`: The amount of padding to apply before and after each
            spatial dimension.
        - `use_ceil`: If `True`, then `ceil` is used to compute the final output
            shape instead of `floor`. For `ceil`, if required, extra padding is added.
            Defaults to `False`.

        !!! info

            In order for `Pool` to be differentiable, `operation(init, x) == x` needs to
            be true for all finite `x`. For further details see
            [https://www.tensorflow.org/xla/operation_semantics#reducewindow](https://www.tensorflow.org/xla/operation_semantics#reducewindow)
            and [https://github.com/google/jax/issues/7718](https://github.com/google/jax/issues/7718).
        """
        super().__init__(**kwargs)

        self.operation = operation
        self.init = init
        self.num_spatial_dims = num_spatial_dims
        self.use_ceil = use_ceil

        if isinstance(kernel_size, int):
            self.kernel_size = (kernel_size,) * num_spatial_dims
        elif isinstance(kernel_size, Sequence):
            self.kernel_size = kernel_size
        else:
            raise ValueError(
                "`kernel_size` must either be an int or tuple of length "
                f"{num_spatial_dims} containing ints."
            )

        if isinstance(stride, int):
            self.stride = (stride,) * num_spatial_dims
        elif isinstance(stride, Sequence):
            self.stride = stride
        else:
            raise ValueError(
                "`stride` must either be an int or tuple of length "
                f"{num_spatial_dims} containing ints."
            )

        if isinstance(padding, int):
            self.padding = tuple((padding, padding) for _ in range(num_spatial_dims))
        elif isinstance(padding, Sequence) and len(padding) == num_spatial_dims:
            if all(isinstance(element, Sequence) for element in padding):
                self.padding = padding
            else:
                self.padding = tuple((p, p) for p in padding)
        else:
            raise ValueError(
                "`padding` must either be an int or tuple of length "
                f"{num_spatial_dims} containing ints or tuples of length 2."
            )

    def _update_padding_for_ceil(self, input_shape):
        new_padding = []
        for input_size, (left_padding, right_padding), kernel_size, stride in zip(
            input_shape[1:], self.padding, self.kernel_size, self.stride
        ):
            if (input_size + left_padding + right_padding - kernel_size) % stride == 0:
                new_padding.append((left_padding, right_padding))
            else:
                new_padding.append((left_padding, right_padding + stride))
        return tuple(new_padding)

    def _check_is_padding_valid(self, padding):
        for (left_padding, right_padding), kernel_size in zip(
            padding, self.kernel_size
        ):
            if max(left_padding, right_padding) > kernel_size:
                raise RuntimeError(
                    "Paddings should be less than the size of the kernel. "
                    f"Padding {(left_padding, right_padding)} received for kernel size {kernel_size}."
                )

    def __call__(
        self, x: Array, *, key: Optional["jax.random.PRNGKey"] = None
    ) -> Array:
        """**Arguments:**

        - `x`: The input. Should be a JAX array of shape `(channels, dim_1, ..., dim_N)`, where
            `N = num_spatial_dims`.
        - `key`: Ignored; provided for compatibility with the rest of the Equinox API.
            (Keyword only argument.)

        **Returns:**

        A JAX array of shape `(channels, new_dim_1, ..., new_dim_N)`.
        """
        assert len(x.shape) == self.num_spatial_dims + 1, (
            f"Input should have {self.num_spatial_dims} spatial dimensions, "
            f"but input has shape {x.shape}"
        )

        if self.use_ceil:
            padding = self._update_padding_for_ceil(x.shape)
        else:
            padding = self.padding

        self._check_is_padding_valid(padding)

        x = jnp.moveaxis(x, 0, -1)
        x = jnp.expand_dims(x, axis=0)
        x = lax.reduce_window(
            x,
            self.init,
            self.operation,
            (1,) + self.kernel_size + (1,),
            (1,) + self.stride + (1,),
            ((0, 0),) + padding + ((0, 0),),
        )

        x = jnp.squeeze(x, axis=0)
        x = jnp.moveaxis(x, -1, 0)
        return x

class AvgPool1d(Pool):
    """One-dimensional downsample using an average over a sliding window."""

    def __init__(
        self,
        kernel_size,
        stride,
        padding=0,
        use_ceil=False,
        **kwargs,
    ):
        """**Arguments:**

        - `kernel_size`: The size of the convolutional kernel.
        - `stride`: The stride of the convolution.
        - `padding`: The amount of padding to apply before and after each
            spatial dimension.
        - `use_ceil`: If `True`, then `ceil` is used to compute the final output
            shape instead of `floor`. For `ceil`, if required, extra padding is added.
            Defaults to `False`.
        """

        super().__init__(
            init=0,
            operation=lax.add,
            num_spatial_dims=1,
            kernel_size=kernel_size,
            stride=stride,
            padding=padding,
            use_ceil=use_ceil,
            **kwargs,
        )

    def __call__(
        self, x: Array, *, key: Optional["jax.random.PRNGKey"] = None
    ) -> Array:
        """**Arguments:**

        - `x`: The input. Should be a JAX array of shape `(channels, dim)`.
        - `key`: Ignored; provided for compatibility with the rest of the Equinox API.
            (Keyword only argument.)

        **Returns:**

        A JAX array of shape `(channels, new_dim)`.
        """

        return super().__call__(x) / np.prod(self.kernel_size)

class MaxPool1d(Pool):
    """One-dimensional downsample using the maximum over a sliding window."""

    def __init__(
        self,
        kernel_size,
        stride,
        padding=0,
        use_ceil=False,
        **kwargs,
    ):
        """**Arguments:**

        - `kernel_size`: The size of the convolutional kernel.
        - `stride`: The stride of the convolution.
        - `padding`: The amount of padding to apply before and after each
            spatial dimension.
        - `use_ceil`: If `True`, then `ceil` is used to compute the final output
            shape instead of `floor`. For `ceil`, if required, extra padding is added.
            Defaults to `False`.
        """

        super().__init__(
            init=-jnp.inf,
            operation=lax.max,
            num_spatial_dims=1,
            kernel_size=kernel_size,
            stride=stride,
            padding=padding,
            use_ceil=use_ceil,
            **kwargs,
        )

    # Redefined to get them in the right order in docs
    def __call__(
        self, x: Array, *, key: Optional["jax.random.PRNGKey"] = None
    ) -> Array:
        """**Arguments:**

        - `x`: The input. Should be a JAX array of shape `(channels, dim)`.
        - `key`: Ignored; provided for compatibility with the rest of the Equinox API.
            (Keyword only argument.)

        **Returns:**

        A JAX array of shape `(channels, new_dim)`.
        """

        return super().__call__(x)

class AvgPool2d(Pool):
    """Two-dimensional downsample using an average over a sliding window."""

    def __init__(
        self,
        kernel_size,
        stride,
        padding=0,
        use_ceil=False,
        **kwargs,
    ):
        """**Arguments:**

        - `kernel_size`: The size of the convolutional kernel.
        - `stride`: The stride of the convolution.
        - `padding`: The amount of padding to apply before and after each
            spatial dimension.
        - `use_ceil`: If `True`, then `ceil` is used to compute the final output
            shape instead of `floor`. For `ceil`, if required, extra padding is added.
            Defaults to `False`.
        """

        super().__init__(
            init=0,
            operation=lax.add,
            num_spatial_dims=2,
            kernel_size=kernel_size,
            stride=stride,
            padding=padding,
            use_ceil=use_ceil,
            **kwargs,
        )

    def __call__(
        self, x: Array, *, key: Optional["jax.random.PRNGKey"] = None
    ) -> Array:
        """**Arguments:**

        - `x`: The input. Should be a JAX array of shape `(channels, dim_1, dim_2)`.
        - `key`: Ignored; provided for compatibility with the rest of the Equinox API.
            (Keyword only argument.)

        **Returns:**

        A JAX array of shape `(channels, new_dim_1, new_dim_2)`.
        """

        return super().__call__(x) / np.prod(self.kernel_size)

class MaxPool2d(Pool):
    """Two-dimensional downsample using the maximum over a sliding window."""

    def __init__(
        self,
        kernel_size,
        stride,
        padding=0,
        use_ceil=False,
        **kwargs,
    ):
        """**Arguments:**

        - `kernel_size`: The size of the convolutional kernel.
        - `stride`: The stride of the convolution.
        - `padding`: The amount of padding to apply before and after each
            spatial dimension.
        - `use_ceil`: If `True`, then `ceil` is used to compute the final output
            shape instead of `floor`. For `ceil`, if required, extra padding is added.
            Defaults to `False`.
        """

        super().__init__(
            init=-jnp.inf,
            operation=lax.max,
            num_spatial_dims=2,
            kernel_size=kernel_size,
            stride=stride,
            padding=padding,
            use_ceil=use_ceil,
            **kwargs,
        )

    # Redefined to get them in the right order in docs
    def __call__(
        self, x: Array, *, key: Optional["jax.random.PRNGKey"] = None
    ) -> Array:
        """**Arguments:**

        - `x`: The input. Should be a JAX array of shape `(channels, dim_1, dim_2)`.
        - `key`: Ignored; provided for compatibility with the rest of the Equinox API.
            (Keyword only argument.)

        **Returns:**

        A JAX array of shape `(channels, new_dim_1, new_dim_2)`.
        """

        return super().__call__(x)

class AvgPool3d(Pool):
    """Three-dimensional downsample using an average over a sliding window."""

    def __init__(
        self,
        kernel_size,
        stride,
        padding=0,
        use_ceil=False,
        **kwargs,
    ):
        """**Arguments:**

        - `kernel_size`: The size of the convolutional kernel.
        - `stride`: The stride of the convolution.
        - `padding`: The amount of padding to apply before and after each
            spatial dimension.
        - `use_ceil`: If `True`, then `ceil` is used to compute the final output
            shape instead of `floor`. For `ceil`, if required, extra padding is added.
            Defaults to `False`.
        """

        super().__init__(
            init=0,
            operation=lax.add,
            num_spatial_dims=3,
            kernel_size=kernel_size,
            stride=stride,
            padding=padding,
            use_ceil=use_ceil,
            **kwargs,
        )

    def __call__(
        self, x: Array, *, key: Optional["jax.random.PRNGKey"] = None
    ) -> Array:
        """**Arguments:**

        - `x`: The input. Should be a JAX array of shape
            `(channels, dim_1, dim_2, dim_3)`.
        - `key`: Ignored; provided for compatibility with the rest of the Equinox API.
            (Keyword only argument.)

        **Returns:**

        A JAX array of shape `(channels, new_dim_1, new_dim_2, new_dim_3)`.
        """

        return super().__call__(x) / np.prod(self.kernel_size)

class MaxPool3d(Pool):
    """Three-dimensional downsample using the maximum over a sliding window."""

    def __init__(
        self,
        kernel_size,
        stride,
        padding=0,
        use_ceil=False,
        **kwargs,
    ):
        """**Arguments:**

        - `kernel_size`: The size of the convolutional kernel.
        - `stride`: The stride of the convolution.
        - `padding`: The amount of padding to apply before and after each
            spatial dimension.
        - `use_ceil`: If `True`, then `ceil` is used to compute the final output
            shape instead of `floor`. For `ceil`, if required, extra padding is added.
            Defaults to `False`.
        """

        super().__init__(
            init=-jnp.inf,
            operation=lax.max,
            num_spatial_dims=3,
            kernel_size=kernel_size,
            stride=stride,
            padding=padding,
            use_ceil=use_ceil,
            **kwargs,
        )

    def __call__(
        self, x: Array, *, key: Optional["jax.random.PRNGKey"] = None
    ) -> Array:
        """**Arguments:**

        - `x`: The input. Should be a JAX array of shape
            `(channels, dim_1, dim_2, dim_3)`.
        - `key`: Ignored; provided for compatibility with the rest of the Equinox API.
            (Keyword only argument.)

        **Returns:**

        A JAX array of shape `(channels, new_dim_1, new_dim_2, new_dim_3)`.
        """

        return super().__call__(x)

# Backward compatability: these were originally misnamed.
AvgPool1D = AvgPool1d
AvgPool2D = AvgPool2d
AvgPool3D = AvgPool3d
MaxPool1D = MaxPool1d
MaxPool2D = MaxPool2d
MaxPool3D = MaxPool3d

def _adaptive_pool1d(x: Array, target_size: int, operation: Callable) -> Array:
    """**Arguments:**

    - `x`: The input. Should be a JAX array of shape `(dim,)`.
    - `target_size`: The shape of the output after the pooling operation `(target_size,)`.
    - `operation`: The pooling operation to be performed on the input array.

    **Returns:**

    A JAX array of shape `(1, target_shape)`.
    """
    dims = jnp.size(x)
    num_head_arrays = dims % target_size
    if num_head_arrays != 0:
        head_end_index = num_head_arrays * (dims // target_size + 1)
        head_op = jax.vmap(operation)(x[:head_end_index].reshape(num_head_arrays, -1))
        tail_op = jax.vmap(operation)(
            x[head_end_index:].reshape(-1, dims // target_size)
        )
        outputs = jnp.concatenate([head_op, tail_op])
    else:
        outputs = jax.vmap(operation)(
            jax.vmap(operation)(x.reshape(-1, dims // target_size))
        )
    return outputs

class AdaptivePool(Module):
    """General N dimensional adaptive downsampling to a target shape."""

    target_shape: Sequence[int] = static_field()
    operation: Callable

    def __init__(
        self,
        target_shape: Union[int, Sequence[int]],
        num_spatial_dims: int,
        operation: Callable,
        **kwargs,
    ):
        """**Arguments:**

        - `target_shape`: The target output shape.
        - `num_spatial_dims`: The number of spatial dimensions.
        - `operation`: The operation applied for downsample.
        """
        super().__init__(**kwargs)
        self.operation = operation
        if isinstance(target_shape, int):
            self.target_shape = (target_shape,) * num_spatial_dims
        elif (
            isinstance(target_shape, Sequence) and len(target_shape) == num_spatial_dims
        ):
            self.target_shape = target_shape
        else:
            raise ValueError(
                "`target_size` must either be an int or tuple of length "
                f"{num_spatial_dims} containing ints."
            )

    def __call__(
        self, x: Array, *, key: Optional["jax.random.PRNGKey"] = None
    ) -> Array:
        """**Arguments:**

        - `x`: The input. Should be a JAX array of shape
            `(channels, dim_1, dim_2, ... )`.
        - `key`: Ignored; provided for compatibility with the rest of the Equinox API.
            (Keyword only argument.)

        **Returns:**

        A JAX array of shape `(channels,) + target_shape`.
        """
        if x.ndim - 1 != len(self.target_shape):
            raise ValueError(
                f"Expected input with {len(self.target_shape)} dimensions, "
                f"received {x.ndim-1} instead."
            )
        for i in range(1, x.ndim):
            op = jax.vmap(
                _adaptive_pool1d, (0, None, None), 0
            )  # batching over channels by default
            for j in range(1, x.ndim):
                if i == j:
                    continue
                op = jax.vmap(op, in_axes=(j, None, None), out_axes=j)
            x = op(x, self.target_shape[i - 1], self.operation)
        return x

class AdaptiveAvgPool1d(AdaptivePool):
    """Adaptive one-dimensional downsampling using average for the target shape."""

    def __init__(self, target_shape: Union[int, Sequence[int]], **kwargs):
        """**Arguments:**

        - `target_shape`: The target output shape.
        """
        super().__init__(target_shape, num_spatial_dims=1, operation=jnp.mean, **kwargs)

class AdaptiveAvgPool2d(AdaptivePool):
    """Adaptive two-dimensional downsampling using average for the target shape."""

    def __init__(self, target_shape: Union[int, Sequence[int]], **kwargs):
        """**Arguments:**

        - `target_shape`: The target output shape.
        """
        super().__init__(target_shape, num_spatial_dims=2, operation=jnp.mean, **kwargs)

class AdaptiveAvgPool3d(AdaptivePool):
    """Adaptive three-dimensional downsampling using average for the target shape."""

    def __init__(self, target_shape: Union[int, Sequence[int]], **kwargs):
        """**Arguments:**

        - `target_shape`: The target output shape.
        """
        super().__init__(target_shape, num_spatial_dims=3, operation=jnp.mean, **kwargs)

class AdaptiveMaxPool1d(AdaptivePool):
    """Adaptive one-dimensional downsampling using maximum for the target shape."""

    def __init__(self, target_shape: Union[int, Sequence[int]], **kwargs):
        """**Arguments:**

        - `target_shape`: The target output shape.
        """
        super().__init__(target_shape, num_spatial_dims=1, operation=jnp.max, **kwargs)

class AdaptiveMaxPool2d(AdaptivePool):
    """Adaptive two-dimensional downsampling using maximum for the target shape."""

    def __init__(self, target_shape: Union[int, Sequence[int]], **kwargs):
        """**Arguments:**

        - `target_shape`: The target output shape.
        """
        super().__init__(target_shape, num_spatial_dims=2, operation=jnp.max, **kwargs)

class AdaptiveMaxPool3d(AdaptivePool):
    """Adaptive three-dimensional downsampling using maximum for the target shape."""

    def __init__(self, target_shape: Union[int, Sequence[int]], **kwargs):
        """**Arguments:**

        - `target_shape`: The target output shape.
        """
        super().__init__(target_shape, num_spatial_dims=3, operation=jnp.max, **kwargs)


text:
class CBC_QRCoderVersion;
class CBC_QRCoderMode {
 private:
  int32_t* m_characterCountBitsForVersions;
  int32_t m_bits;
  CFX_ByteString m_name;
  CBC_QRCoderMode(int32_t* characterCountBitsForVersions,
                  int32_t x1,
                  int32_t x2,
                  int32_t x3,
                  int32_t bits,
                  CFX_ByteString name);
  CBC_QRCoderMode();

 public:
  static CBC_QRCoderMode* sBYTE;
  static CBC_QRCoderMode* sNUMERIC;
  static CBC_QRCoderMode* sALPHANUMERIC;
  static CBC_QRCoderMode* sKANJI;
  static CBC_QRCoderMode* sECI;
  static CBC_QRCoderMode* sGBK;
  static CBC_QRCoderMode* sTERMINATOR;
  static CBC_QRCoderMode* sFNC1_FIRST_POSITION;
  static CBC_QRCoderMode* sFNC1_SECOND_POSITION;
  static CBC_QRCoderMode* sSTRUCTURED_APPEND;
  virtual ~CBC_QRCoderMode();

  static void Initialize();
  static void Finalize();
  static CBC_QRCoderMode* ForBits(int32_t bits, int32_t& e);
  int32_t GetCharacterCountBits(CBC_QRCoderVersion* version, int32_t& e);
  int32_t GetBits();
  CFX_ByteString GetName();
  static void Destroy();
};
#endif


text:
using System;
using System.Net;
using Core.Application.Models;

namespace Core.Application.Broadcasters
{
	public interface INetworkEventBroadcaster
	{
		void RegisterNetworkErrorHandler (EventHandler<NetworkErrorEventArgs> handler);
		void RegisterErrorHandler(EventHandler<NetworkErrorEventArgs> handler);
		void RegisterNetworkUsageStart (EventHandler handler);
		void RegisterNetworkUsageEnd(EventHandler handler);

		void RaiseNetworkErrorEvent (WebException ex, bool suppress);
		void RaiseErrorEvent (Exception ex, bool suppress);
		void RaiseNetworkUsageStart ();
		void RaiseNetworkUsageEnd ();
	}
}


text:
package org.achtern.AchternEngine.core.audio.openal;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.achtern.AchternEngine.core.bootstrap.NativeObject;
import org.achtern.AchternEngine.core.math.Vector3f;

@Getter
@Setter
@AllArgsConstructor
public class AudioSource extends NativeObject {

    /**
     * Associated {@link org.achtern.AchternEngine.core.audio.openal.AudioBuffer}
     *
     * @param buffer New buffer to use with this AudioSource
     * @return the currently assoc. AudioBuffer
     */
    protected AudioBuffer buffer;

    /**
     * Position of this AudioSource in 3D space.
     *
     * This can be both in absolute or relative coordinates to the
     *  {@link org.achtern.AchternEngine.core.audio.openal.AudioListener}.
     *
     * @see org.achtern.AchternEngine.core.audio.openal.AudioSource#isRelative()
     *
     * @param position Sets the new position
     * @return current position
     */
    protected Vector3f position;

    /**
     * The velocity of the AudioSource, for doppler effects etc.
     *
     * Not needed in most cases.
     *
     * @param velocity new velocity
     * @return current velocity
     */
    protected Vector3f velocity;

    /**
     * Indicates whether this AudioSource should be played in a loop.
     *
     * @param loop if it should be looped
     * @return if it will loop
     */
    protected boolean loop;

    /**
     * If this AudioSource is not relative, {@link #getPosition()} will be interpreted
     *  as absolute world coordiantes, otherwise as offset from the
     *  {@link org.achtern.AchternEngine.core.audio.openal.AudioListener}.
     *
     * @param relative if position is relative
     * @return if position is relative
     */
    protected boolean relative;

    /**
     * Gain of this AudioSource. 0.0f is minimum and 1.0f maximum.
     *
     * Defaults to 1.0f
     *
     * NOTE: the 1.0f maximum is NOT enforced. Some drivers may allow gain over 1.0f
     *
     * @param gain gain of the AudioSource
     * @return current gain of the AudioSource.
     */
    protected float gain;

    /**
     * Stores the current state of this AudioSource.
     *
     * @return current state
     */
    protected AudioSourceState state;

    public AudioSource(AudioBuffer buffer) {
        this(buffer, null, null);
    }

    public AudioSource(AudioBuffer buffer, Vector3f position, Vector3f velocity) {
        this(buffer, position, velocity, false, false, 1.0f, AudioSourceState.STOPPED);
    }

    /**
     * internal use only.
     * Stores the current state of this AudioSource
     * @param playing the new state
     */
    public void setState(AudioSourceState playing) {
        this.state = playing;
    }

    @Override
    public String toString() {
        return "AudioSource{" +
                "buffer=" + buffer +
                ", position=" + position +
                ", velocity=" + velocity +
                ", loop=" + loop +
                ", relative=" + relative +
                ", gain=" + gain +
                ", state=" + state +
                '}';
    }
}


text:
module Clustering

  using MIToS.MSA

  export Clusters, getnclusters, getweight, nsequences,

  percentidentity,

  hobohmI

  include("Clusters.jl")
  include("Identity.jl")
  include("Hobohm.jl")

end


text:
{-# LANGUAGE BangPatterns #-}

module Tests.Distribution where

import Control.Monad
import qualified System.Random.MWC as MWC

import Language.Hakaru.Types
import Language.Hakaru.Util.Coda
import Language.Hakaru.Distribution hiding (choose)

import Test.QuickCheck
import Test.QuickCheck.Monadic as QM
import Test.Framework.Providers.QuickCheck2 (testProperty)

fromDiscreteToNum = fromIntegral . fromEnum . fromDiscrete
sq x = x * x

almostEqual :: (Fractional a, Ord a) => a -> a -> a -> Bool
almostEqual tol x y | abs (x - y) < tol = True
almostEqual tol x y = (abs $ (x - y) / (x + y)) < tol

quickArg :: IO ()
quickArg = quickCheckWith stdArgs {maxSuccess = 2000} (\ x -> almostEqual tol x x)
  where tol :: Double
        tol = 1e-5

qtest = [testProperty "checking beta" $ QM.monadicIO betaTest,
         testProperty "checking bern" $ QM.monadicIO bernTest,
         testProperty "checking gamma" $ QM.monadicIO gammaTest,
         testProperty "checking normal" $ QM.monadicIO normalTest,
         testProperty "checking laplace" $ QM.monadicIO laplaceTest,
         testProperty "checking poisson" $ QM.monadicIO poissonTest]

betaTest = do
  Positive a <- QM.pick arbitrary
  Positive b <- QM.pick arbitrary
  g <- QM.run $ MWC.create
  samples <- QM.run $ replicateM 1000 $ distSample (beta a b) g
  let (mean, variance) = meanVariance (map fromLebesgue samples)
  QM.assert $ (almostEqual tol mean     (mu  a b)) &&
              (almostEqual tol variance (var a b))
  where tol     = 1e-1
        mu a b  = a / (a + b)
        var a b = a*b / ((sq $ a + b) * (a + b + 1))

bernTest = do
   p <- QM.pick $ choose (0, 1)
   g <- QM.run $ MWC.create
   samples <- QM.run $ replicateM 1000 $ distSample (bern p) g
   let (mean, variance) = meanVariance (map fromDiscreteToNum samples)
   QM.assert $ (almostEqual tol mean     (mu  p)) &&
               (almostEqual tol variance (var p))
   where tol   = 1e-1
         mu p  = p
         var p = p*(1-p)

poissonTest = do
   lam <- QM.pick $ choose (1, 10)
   g <- QM.run $ MWC.create
   samples <- QM.run $ replicateM 1000 $ distSample (poisson lam) g
   let (mean, variance) = meanVariance (map (fromIntegral . fromDiscrete) samples)
   QM.assert $ (almostEqual tol mean     (mu  lam)) &&
               (almostEqual tol variance (var lam))
   where tol     = 1e-1
         mu  lam = lam
         var lam = lam

normalTest = do
  mu <- QM.pick arbitrary
  sd <- QM.pick $ choose (1, 10)
  g <- QM.run $ MWC.create
  let nsamples = floor (1000 * sd)  -- larger standard deviations need more samples
                                    -- to be shown as correct
  samples <- QM.run $ replicateM nsamples $ distSample (normal mu sd) g
  let (mean, variance) = meanVariance (map fromLebesgue samples)
  QM.assert $ (almostEqual tol mean     mu ) &&
              (almostEqual tol variance (var sd))
  where tol = 1e-1
        var sd = sq sd

laplaceTest = do
  mu <- QM.pick arbitrary
  sd <- QM.pick $ choose (1, 10)
  g <- QM.run $ MWC.create
  let nsamples = floor (1000 * sd)  -- larger standard deviations need more samples
                                    -- to be shown as correct
  samples <- QM.run $ replicateM nsamples $ distSample (laplace mu sd) g
  let (mean, variance) = meanVariance (map fromLebesgue samples)
  QM.assert $ (almostEqual tol mean     mu ) &&
              (almostEqual tol variance (var sd))
  where tol = 1e-1
        var sd = 2*(sq sd)

gammaTest = do
  a <- QM.pick $ choose (1, 10)
  b <- QM.pick $ choose (1, 10)
  g <- QM.run $ MWC.create
  samples <- QM.run $ replicateM 1000 $ distSample (gamma a b) g
  let (mean, variance) = meanVariance (map fromLebesgue samples)
  QM.assert $ (almostEqual tol mean     (mu  a b)) &&
              (almostEqual tol variance (var a b))
  where tol     = 1e-1
        mu a b  = a * b
        var a b = a * (b * b)


text:
package com.wind.web.controller.rest;

import com.wind.mybatis.pojo.CarFee;
import com.wind.web.common.ExtendController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/rest/car_fee")
public class CarFeeRest extends ExtendController<CarFee> {
}


text:
Besides putting the module in `MODPATH` and enabling it in `bootstrap.php,`
you should:

  1. Create the directory `APPPATH/assets/`.
  2. Create the directory `DOCROOT/assets/`, and make sure PHP has permission to write to it.
  3. Make sure that in your server configuration files that exist are served
     directly (e.g. `RewriteCond %{REQUEST_FILENAME} !-f` before rewriting to
     index.php for Apache servers).
  3. Copy the config file to your application


text:
require 'deep_merge/core'

module DeepMerge
  # Implements a deep merge with default options
  module DeepMergeHash
    # deep_merge! will merge and overwrite any unmergeables in destination hash
    def deep_merge!(source, options = {})
      default_opts = { preserve_unmergeables: false }
      DeepMerge.deep_merge!(source, self, default_opts.merge(options))
    end
  end
end

# Extends hash with deep merge
class Hash
  include DeepMerge::DeepMergeHash
end


text:
package psidev.psi.mi.jami.utils.comparator.cooperativity;

import org.junit.Assert;
import org.junit.Test;
import psidev.psi.mi.jami.model.CooperativeEffect;
import psidev.psi.mi.jami.model.impl.*;

/**
 * Unit tester for
 *
 * @author Marine Dumousseau (marine@ebi.ac.uk)
 * @version $Id$
 * @since
31/05/13

 */

public class UnambiguousCooperativeEffectBaseComparatorTest {

    private UnambiguousCooperativeEffectBaseComparator comparator = new UnambiguousCooperativeEffectBaseComparator();

    @Test
    public void test_cooperative_effect_null_after() throws Exception {
        CooperativeEffect effect1 = null;
        CooperativeEffect effect2 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"));

        Assert.assertTrue(comparator.compare(effect1, effect2) > 0);
        Assert.assertTrue(comparator.compare(effect2, effect1) < 0);

        Assert.assertFalse(UnambiguousCooperativeEffectBaseComparator.areEquals(effect1, effect2));
        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.hashCode(effect1) != UnambiguousCooperativeEffectBaseComparator.hashCode(effect2));
    }

    @Test
    public void test_compare_different_outcome() throws Exception {
        CooperativeEffect effect1 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome 2"));
        CooperativeEffect effect2 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"));

        Assert.assertTrue(comparator.compare(effect1, effect2) > 0);
        Assert.assertTrue(comparator.compare(effect2, effect1) < 0);

        Assert.assertFalse(UnambiguousCooperativeEffectBaseComparator.areEquals(effect1, effect2));
        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.hashCode(effect1) != UnambiguousCooperativeEffectBaseComparator.hashCode(effect2));
    }

    @Test
    public void test_compare_same_outcome() throws Exception {
        CooperativeEffect effect1 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"));
        CooperativeEffect effect2 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"));

        Assert.assertTrue(comparator.compare(effect1, effect2) == 0);
        Assert.assertTrue(comparator.compare(effect2, effect1) == 0);

        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.areEquals(effect1, effect2));
        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.hashCode(effect1) == UnambiguousCooperativeEffectBaseComparator.hashCode(effect2));
    }

    @Test
    public void test_compare_same_outcome_different_response() throws Exception {
        CooperativeEffect effect1 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"), new DefaultCvTerm("test response 2"));
        CooperativeEffect effect2 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"), new DefaultCvTerm("test response"));

        Assert.assertTrue(comparator.compare(effect1, effect2) > 0);
        Assert.assertTrue(comparator.compare(effect2, effect1) < 0);

        Assert.assertFalse(UnambiguousCooperativeEffectBaseComparator.areEquals(effect1, effect2));
        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.hashCode(effect1) != UnambiguousCooperativeEffectBaseComparator.hashCode(effect2));
    }

    @Test
    public void test_compare_same_response() throws Exception {
        CooperativeEffect effect1 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"), new DefaultCvTerm("test response"));
        CooperativeEffect effect2 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"), new DefaultCvTerm("test response"));

        Assert.assertTrue(comparator.compare(effect1, effect2) == 0);
        Assert.assertTrue(comparator.compare(effect2, effect1) == 0);

        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.areEquals(effect1, effect2));
        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.hashCode(effect1) == UnambiguousCooperativeEffectBaseComparator.hashCode(effect2));
    }

    @Test
    public void test_compare_same_response_different_evidences() throws Exception {
        CooperativeEffect effect1 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"), new DefaultCvTerm("test response"));
        effect1.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12345")));
        effect1.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12346")));
        CooperativeEffect effect2 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"), new DefaultCvTerm("test response"));
        effect2.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12345")));

        Assert.assertTrue(comparator.compare(effect1, effect2) > 0);
        Assert.assertTrue(comparator.compare(effect2, effect1) < 0);

        Assert.assertFalse(UnambiguousCooperativeEffectBaseComparator.areEquals(effect1, effect2));
        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.hashCode(effect1) != UnambiguousCooperativeEffectBaseComparator.hashCode(effect2));
    }

    @Test
    public void test_compare_same_evidences() throws Exception {
        CooperativeEffect effect1 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"), new DefaultCvTerm("test response"));
        effect1.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12345")));
        effect1.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12346")));
        CooperativeEffect effect2 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"), new DefaultCvTerm("test response"));
        effect2.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12346")));
        effect2.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12345")));
        Assert.assertTrue(comparator.compare(effect1, effect2) == 0);
        Assert.assertTrue(comparator.compare(effect2, effect1) == 0);

        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.areEquals(effect1, effect2));
        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.hashCode(effect1) == UnambiguousCooperativeEffectBaseComparator.hashCode(effect2));
    }

    @Test
    public void test_compare_same_evidences_different_affected_interactions() throws Exception {
        CooperativeEffect effect1 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"), new DefaultCvTerm("test response 2"));
        effect1.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12345")));
        effect1.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12346")));
        effect1.getAffectedInteractions().add(new DefaultModelledInteraction("test 1"));
        effect1.getAffectedInteractions().add(new DefaultModelledInteraction("test 2"));
        CooperativeEffect effect2 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"), new DefaultCvTerm("test response"));
        effect2.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12346")));
        effect2.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12345")));
        effect2.getAffectedInteractions().add(new DefaultModelledInteraction("test 1"));

        Assert.assertTrue(comparator.compare(effect1, effect2) > 0);
        Assert.assertTrue(comparator.compare(effect2, effect1) < 0);

        Assert.assertFalse(UnambiguousCooperativeEffectBaseComparator.areEquals(effect1, effect2));
        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.hashCode(effect1) != UnambiguousCooperativeEffectBaseComparator.hashCode(effect2));
    }

    @Test
    public void test_compare_same_affected_interactions() throws Exception {
        CooperativeEffect effect1 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"), new DefaultCvTerm("test response"));
        effect1.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12345")));
        effect1.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12346")));
        effect1.getAffectedInteractions().add(new DefaultModelledInteraction("test 1"));
        effect1.getAffectedInteractions().add(new DefaultModelledInteraction("test 2"));
        CooperativeEffect effect2 = new DefaultCooperativeEffect(new DefaultCvTerm("test outcome"), new DefaultCvTerm("test response"));
        effect2.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12346")));
        effect2.getCooperativityEvidences().add(new DefaultCooperativityEvidence(new DefaultPublication("12345")));
        effect2.getAffectedInteractions().add(new DefaultModelledInteraction("test 2"));
        effect2.getAffectedInteractions().add(new DefaultModelledInteraction("test 1"));
        Assert.assertTrue(comparator.compare(effect1, effect2) == 0);
        Assert.assertTrue(comparator.compare(effect2, effect1) == 0);

        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.areEquals(effect1, effect2));
        Assert.assertTrue(UnambiguousCooperativeEffectBaseComparator.hashCode(effect1) == UnambiguousCooperativeEffectBaseComparator.hashCode(effect2));
    }
}


text:
echo "Hello";
echo "Linea Agregada por Alan xD"


text:
<?php

class Lookup extends CActiveRecord {

    /**
     * The followings are the available columns in table 'tbl_lookup':
     * @var integer $id
     * @var string $object_type
     * @var integer $code
     * @var string $name_en
     * @var string $name_fr
     * @var integer $sequence
     * @var integer $status
     */
    private static $_items = array();

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'lookup';
    }

    /**
     * Returns the items for the specified type.
     * @param string item type (e.g. 'PostStatus').
     * @return array item names indexed by item code. The items are order by their position values.
     * An empty array is returned if the item type does not exist.
     */
    public static function items($type) {
        if (!isset(self::$_items[$type]))
            self::loadItems($type);
        return self::$_items[$type];
    }

    /**
     * Returns the item name for the specified type and code.
     * @param string the item type (e.g. 'PostStatus').
     * @param integer the item code (corresponding to the 'code' column value)
     * @return string the item name for the specified the code. False is returned if the item type or code does not exist.
     */
    public static function item($type, $code) {
        if (!isset(self::$_items[$type]))
            self::loadItems($type);
        return isset(self::$_items[$type][$code]) ? self::$_items[$type][$code] : false;
    }

    /**
     * Loads the lookup items for the specified type from the database.
     * @param string the item type
     */
    private static function loadItems($type) {
        self::$_items[$type] = array();
        $models = self::model()->findAll(array(
            'condition' => 'type=:type',
            'params' => array(':type' => $type),
            'order' => 'position',
                ));
        foreach ($models as $model)
            self::$_items[$type][$model->code] = $model->name;
    }

}