text:
package org.terasology.rendering;

import com.google.common.collect.Sets;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.Sys;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.assets.ResourceUrn;
import org.terasology.assets.management.AssetManager;
import org.terasology.registry.CoreRegistry;
import org.terasology.rendering.assets.material.Material;
import org.terasology.rendering.assets.material.MaterialData;
import org.terasology.rendering.assets.shader.Shader;
import org.terasology.rendering.assets.texture.Texture;
import org.terasology.rendering.opengl.GLSLMaterial;
import org.terasology.rendering.shader.ShaderParameters;
import org.terasology.rendering.shader.ShaderParametersBlock;
import org.terasology.rendering.shader.ShaderParametersChunk;
import org.terasology.rendering.shader.ShaderParametersDebug;
import org.terasology.rendering.shader.ShaderParametersDefault;
import org.terasology.rendering.shader.ShaderParametersInitialPost;
import org.terasology.rendering.shader.ShaderParametersLightBufferPass;
import org.terasology.rendering.shader.ShaderParametersLightGeometryPass;
import org.terasology.rendering.shader.ShaderParametersLightShafts;
import org.terasology.rendering.shader.ShaderParametersOcDistortion;
import org.terasology.rendering.shader.ShaderParametersParticle;
import org.terasology.rendering.shader.ShaderParametersPost;
import org.terasology.rendering.shader.ShaderParametersPrePostComposite;
import org.terasology.rendering.shader.ShaderParametersSSAO;
import org.terasology.rendering.shader.ShaderParametersShadowMap;
import org.terasology.rendering.shader.ShaderParametersSky;
import org.terasology.rendering.shader.ShaderParametersSobel;
import org.terasology.rendering.shader.ShaderParametersToneMapping;
import org.terasology.utilities.Assets;

import java.util.Optional;
import java.util.Set;

import static com.google.common.base.Preconditions.checkState;

/**
 * Provides support for loading and applying shaders.
 */
public class ShaderManagerLwjgl implements ShaderManager {

    private static final Logger logger = LoggerFactory.getLogger(ShaderManagerLwjgl.class);

    private GLSLMaterial activeMaterial;
    private GLSLMaterial defaultShaderProgram;
    private GLSLMaterial defaultTexturedShaderProgram;

    private Set<GLSLMaterial> progamaticShaders = Sets.newHashSet();

    public ShaderManagerLwjgl() {
        logger.info("Loading Terasology shader manager...");
        logger.info("LWJGL: {} / {}", Sys.getVersion(), LWJGLUtil.getPlatformName());
        logger.info("GL_VENDOR: {}", GL11.glGetString(GL11.GL_VENDOR));
        logger.info("GL_RENDERER: {}", GL11.glGetString(GL11.GL_RENDERER));
        logger.info("GL_VERSION: {}", GL11.glGetString(GL11.GL_VERSION));
        logger.info("SHADING_LANGUAGE VERSION: {}", GL11.glGetString(GL20.GL_SHADING_LANGUAGE_VERSION));

        String extStr = GL11.glGetString(GL11.GL_EXTENSIONS);

        // log shader extensions in smaller packages,
        // because the full string can be extremely long
        int extsPerLine = 8;

        // starting with OpenGL 3.0, extensions can also listed using
        // GL_NUM_EXTENSIONS and glGetStringi(GL_EXTENSIONS, idx)
        String[] exts = extStr.split(" ");
        if (exts.length > 0) {
            StringBuilder bldr = new StringBuilder(exts[0]);
            for (int i = 1; i < exts.length; i++) {
                if (i % extsPerLine == 0) {
                    logger.info("EXTENSIONS: {}", bldr.toString());
                    bldr.setLength(0);
                } else {
                    bldr.append(" ");
                }
                bldr.append(exts[i]);
            }
            if (bldr.length() > 0) {
                logger.info("EXTENSIONS: {}", bldr.toString());
            }
        }
    }

    @Override
    public void initShaders() {
        defaultShaderProgram = prepareAndStoreShaderProgramInstance("default", new ShaderParametersDefault());
        defaultTexturedShaderProgram = prepareAndStoreShaderProgramInstance("defaultTextured", new ShaderParametersDefault());

        // TODO: Find a better way to do this
        prepareAndStoreShaderProgramInstance("post", new ShaderParametersPost());
        prepareAndStoreShaderProgramInstance("ssao", new ShaderParametersSSAO());
        prepareAndStoreShaderProgramInstance("lightShafts", new ShaderParametersLightShafts());
        prepareAndStoreShaderProgramInstance("sobel", new ShaderParametersSobel());
        prepareAndStoreShaderProgramInstance("initialPost", new ShaderParametersInitialPost());
        prepareAndStoreShaderProgramInstance("prePostComposite", new ShaderParametersPrePostComposite());
        prepareAndStoreShaderProgramInstance("highPass", new ShaderParametersDefault());
        prepareAndStoreShaderProgramInstance("blur", new ShaderParametersDefault());
        prepareAndStoreShaderProgramInstance("downSampler", new ShaderParametersDefault());
        prepareAndStoreShaderProgramInstance("toneMapping", new ShaderParametersToneMapping());
        prepareAndStoreShaderProgramInstance("sky", new ShaderParametersSky());
        prepareAndStoreShaderProgramInstance("chunk", new ShaderParametersChunk());
        prepareAndStoreShaderProgramInstance("particle", new ShaderParametersParticle());
        prepareAndStoreShaderProgramInstance("block", new ShaderParametersBlock());
        prepareAndStoreShaderProgramInstance("shadowMap", new ShaderParametersShadowMap());
        prepareAndStoreShaderProgramInstance("debug", new ShaderParametersDebug());
        prepareAndStoreShaderProgramInstance("ocDistortion", new ShaderParametersOcDistortion());
        prepareAndStoreShaderProgramInstance("lightBufferPass", new ShaderParametersLightBufferPass());
        prepareAndStoreShaderProgramInstance("lightGeometryPass", new ShaderParametersLightGeometryPass());
        prepareAndStoreShaderProgramInstance("simple", new ShaderParametersDefault());
        prepareAndStoreShaderProgramInstance("ssaoBlur", new ShaderParametersDefault());
    }

    @Override
    public void setActiveMaterial(Material material) {
        // TODO: is this the best way to convert the material to the lwjgl version?  Do we need more checks?
        GLSLMaterial glslMaterial = (GLSLMaterial) material;
        if (!glslMaterial.equals(activeMaterial)) {
            activeMaterial = glslMaterial;
        }
    }

    @Override
    public void bindTexture(int slot, Texture texture) {
        if (activeMaterial != null && !activeMaterial.isDisposed()) {
            GL13.glActiveTexture(GL13.GL_TEXTURE0 + slot);
            // TODO: Need to be cubemap aware, only need to clear bind when switching from cubemap to 2D and vice versa,
            // TODO: Don't bind if already bound to the same
            GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getId());
            GL13.glActiveTexture(GL13.GL_TEXTURE0);
        }
    }

    @Override
    public Material getActiveMaterial() {
        return activeMaterial;
    }

    @Override
    public void recompileAllShaders() {
        AssetManager assetManager = CoreRegistry.get(AssetManager.class);
        assetManager.getLoadedAssets(Shader.class).forEach(Shader::recompile);

        assetManager.getLoadedAssets(Material.class).forEach(Material::recompile);

        activeMaterial = null;
    }

    @SuppressWarnings("unused")  // this is actually used, I'm not sure why the Jenkins Static Analyses says it's unused.
    private GLSLMaterial prepareAndStoreShaderProgramInstance(String title, ShaderParameters params) {
        String uri = "engine:" + title;
        Optional<? extends Shader> shader = Assets.getShader(uri);
        checkState(shader.isPresent(), "Failed to resolve %s", uri);
        shader.get().recompile();
        GLSLMaterial material = (GLSLMaterial) Assets.generateAsset(new ResourceUrn("engine:prog." + title), new MaterialData(shader.get()), Material.class);
        material.setShaderParameters(params);
        progamaticShaders.add(material);

        return material;
    }

    /**
     * Enables the default shader program.
     */
    @Override
    public void enableDefault() {
        defaultShaderProgram.enable();
    }

    /**
     * Enables the default shader program.
     */
    @Override
    public void enableDefaultTextured() {
        defaultTexturedShaderProgram.enable();
    }

    @Override
    public void disableShader() {
        GL20.glUseProgram(0);
        activeMaterial = null;
    }

}


text:
#!/usr/bin/env node
'use strict';

var Download = require('./');
var meow = require('meow');
var progress = require('download-status');
var stdin = require('get-stdin');

/**
 * Options
 */

var cli = meow({
	requireInput: process.stdin.isTTY,
	help: [
		'  Usage',
		'    download <url>',
		'    download <url> > <file>',
		'    download --out <directory> <url>',
		'    cat <file> | download --out <directory>',
		'',
		'  Example',
		'    download http://foo.com/file.zip',
		'    download http://foo.com/cat.png > dog.png',
		'    download --extract --strip 1 --out dest http://foo.com/file.zip',
		'    cat urls.txt | download --out dest',
		'',
		'  Options',
		'    -e, --extract           Try decompressing the file',
		'    -o, --out               Where to place the downloaded files',
		'    -s, --strip <number>    Strip leading paths from file names on extraction'
	].join('\n')
}, {
	boolean: [
		'extract'
	],
	string: [
		'out',
		'strip'
	],
	alias: {
		e: 'extract',
		o: 'out',
		s: 'strip'
	}
});

/**
 * Run
 *
 * @param {Array} src
 * @param {String} dest
 * @api private
 */

function run(src, dest) {
	var download = new Download(cli.flags);

	src.forEach(download.get.bind(download));

	if (process.stdout.isTTY) {
		download.use(progress());
		download.dest(dest ? dest : process.cwd());
	}

	download.run(function (err, files) {
		if (err) {
			console.error(err);
			process.exit(1);
		}

		if (!process.stdout.isTTY) {
			files.forEach(function (file) {
				process.stdout.write(file.contents);
			});
		}
	});
}

/**
 * Apply arguments
 */

if (process.stdin.isTTY) {
	var src = cli.input;
	var dest = cli.flags.out;

	run(src, dest);
} else {
	stdin(function (data) {
		var src = cli.input;
		var dest = cli.flags.out;

		[].push.apply(src, data.trim().split('\n'));
		run(src, dest);
	});
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<mapping>
	<class
		name="it.polito.ai.polibox.client.filesystem.config.impl.FolderMonitorConfig">
		<map-to xml="filesystem-setting" />
		<field name="folder" type="java.lang.String">
			<bind-xml name="directory" node="element" />
		</field>

		<field name="schedulePeriod" type="long">
			<bind-xml name="scheduled-period" node="element" />
		</field>
	</class>
	<class name="it.polito.ai.polibox.client.http.config.impl.ServerConfig">
		<map-to xml="server-setting" />
		<field name="host" type="java.lang.String">
			<bind-xml name="host" node="element" />
		</field>

		<field name="user" type="java.lang.String">
			<bind-xml name="user" node="element" />
		</field>

		<field name="device" type="java.lang.String">
			<bind-xml name="device" node="element" />
		</field>

		<field name="passcode" type="java.lang.String">
			<bind-xml name="passcode" node="element" />
		</field>
	</class>
	<class
		name="it.polito.ai.polibox.client.notification.config.impl.NotificationOptions">
		<map-to xml="notification-setting" />
		<field name="notifications"
			type="it.polito.ai.polibox.client.notification.config.impl.NotificationOption"
			collection="arraylist" container="false">
			<bind-xml name="notification-options" node="element"/>
		</field>
		<field name="notificationNumber" type="integer">
			<bind-xml name="number" node="element"/>
		</field>
	</class>
	<class
		name="it.polito.ai.polibox.client.notification.config.impl.NotificationOption">
		<map-to xml="notification-option" />

		<field name="description" type="java.lang.String">
			<bind-xml name="description" node="element" />
		</field>
		<field name="option" type="boolean">
			<bind-xml name="option" node="attribute" />
		</field>

		<field name="id" type="java.lang.String">
			<bind-xml name="id" node="element" />
		</field>
	</class>
	<class name="it.polito.ai.polibox.client.notification.impl.Notifications">
		<map-to xml="notifications"/>
		<field name="notifications"
			type="it.polito.ai.polibox.client.persistency.Notification"
			collection="arraylist"  container="false">
			<bind-xml name="notification" node="element"/>
		</field>
	</class>
	<class name="it.polito.ai.polibox.client.persistency.Notification">
		<field name="id" type="integer">
			<bind-xml name="id" node="attribute"/>
		</field>
		<field name="code" type="integer">
			<bind-xml name="code" node="attribute"/>
		</field>
		<field name="description" type="java.lang.String">
			<bind-xml node="text"/>
		</field>
		<field name="creationTime" type="date">
			<bind-xml name="creation" node="attribute"/>
		</field>
	</class>
	<class name="it.polito.ai.polibox.client.filesystem.impl.FileMap">
		<map-to xml="files"/>
		<field name="myResources"
			type="it.polito.ai.polibox.client.persistency.Resource"
			collection="arraylist" container="false">
			<bind-xml name="my" node="element"/>
		</field>
		<field name="sharedWithMeResources"
			type="it.polito.ai.polibox.client.persistency.Resource"
			collection="arraylist" container="false">
			<bind-xml name="withme" node="element"/>
		</field>
	</class>
	<class name="it.polito.ai.polibox.client.persistency.Resource">
		<field name="id" type="integer">
			<bind-xml name="id" node="attribute"/>
		</field>
		<field name="parent" type="integer">
			<bind-xml name="parent" node="attribute"/>
		</field>
		<field name="version" type="integer">
			<bind-xml name="version" node="attribute"/>
		</field>
		<field name="owner" type="integer">
			<bind-xml name="owner" node="attribute"/>
		</field>
		<field name="directory" type="boolean">
			<bind-xml name="directory" node="attribute"/>
		</field>
		<field name="deleted" type="boolean">
			<bind-xml name="deleted" node="attribute"/>
		</field>
		<field name="writingLock" type="boolean">
			<bind-xml name="writing-lock" node="attribute"/>
		</field>
		<field name="toSynchronize" type="boolean">
			<bind-xml name="to-synchronize" node="attribute"/>
		</field>
		<field name="chunkNumber" type="integer">
			<bind-xml name="chunk-number" node="attribute"/>
		</field>
		<field name="size" type="integer">
			<bind-xml name="size" node="attribute"/>
		</field>
		<field name="name" type="java.lang.String">
			<bind-xml name="name" node="element"/>
		</field>
		<field name="mime" type="java.lang.String">
			<bind-xml name="mime" node="element"/>
		</field>
		<field name="creationTime" type="date">
			<bind-xml name="creation-time" node="element"/>
		</field>
		<field name="hdLastModify" type="date">
			<bind-xml name="last-modify-hd" node="element"/>
		</field>
		<field name="serverLastModify" type="date">
			<bind-xml name="last-modify-server" node="element"/>
		</field>
		<field name="digest" type="java.lang.String">
			<bind-xml name="digest" node="element"/>
		</field>
		<field name="inode" type="java.lang.String">
			<bind-xml name="inode" node="element"/>
		</field>
	</class>
</mapping>


text:
package org.fredy.filerenamer.ui;

/**
 * @author fredy
 */
public class FileRenamerUI {

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FileRenamerFrame().setVisible(true);
            }
        });
    }
}


text:
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('frontend', '0053_add_pcn_model'),
    ]

    operations = [
        migrations.AddField(
            model_name='measurevalue',
            name='pcn',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='frontend.PCN'),
        ),
    ]


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/Users/caominhvu/AndroidStudioProjects/InteractiveJob/facebook/build/intermediates/bundles/debug/res/values-id/values-id.xml -->
    <eat-comment/>
    <string name="com_facebook_image_download_unknown_error">Kesalahan yang tidak diharapkan saat mengunduh gambar.</string>
    <string name="com_facebook_internet_permission_error_message">Masuk WebView memerlukan izin INTERNET</string>
    <string name="com_facebook_internet_permission_error_title">Kesalahan AndroidManifest</string>
    <string name="com_facebook_like_button_liked">Disukai</string>
    <string name="com_facebook_like_button_not_liked">Suka</string>
    <string name="com_facebook_loading">Memuat...</string>
    <string name="com_facebook_loginview_cancel_action">Batal</string>
    <string name="com_facebook_loginview_log_in_button">Masuk</string>
    <string name="com_facebook_loginview_log_in_button_long">Masuk menggunakan Facebook</string>
    <string name="com_facebook_loginview_log_out_action">Keluar</string>
    <string name="com_facebook_loginview_log_out_button">Keluar</string>
    <string name="com_facebook_loginview_logged_in_as">Masuk sebagai: %1$s</string>
    <string name="com_facebook_loginview_logged_in_using_facebook">Masuk menggunakan Facebook</string>
    <string name="com_facebook_send_button_text">Kirim</string>
    <string name="com_facebook_share_button_text">Berbagi</string>
    <string name="com_facebook_tooltip_default">Baru! Anda memegang kendali - pilih info yang ingin Anda bagikan dengan aplikasi.</string>
</resources>


text:
var TrelloToggleButton = (function() {
    'use strict';

    var _board_header_selector     = '.board-header-btns.mod-left';
    var _board_header_btn_class    = 'board-header-btn';
    var _trello_hideable_classes   = ['.card-label','.badges','.list-card-members','.list-card-cover'];
    var _key_to_bind               = 192; // tilde (`)
	var _button_label              = 'Toggle Details';

    var toggleTrigger;

    var createToggleButton = function(buttonLabel) {
        toggleTrigger = document.createElement('a');
        toggleTrigger.appendChild(document.createTextNode(buttonLabel));
        toggleTrigger.setAttribute('href','#');
        toggleTrigger.classList.add(_board_header_btn_class);
        toggleTrigger.setAttribute('style', 'padding-left: 3px; padding-right: 3px;');
        toggleTrigger.addEventListener('click', function(ev){
            toggleItemsCallback(ev);
        });

        var menuButtonsContainer = document.querySelector(_board_header_selector);
        menuButtonsContainer.appendChild(toggleTrigger);
    };

    var toggleItemsCallback = function(ev){
        document.querySelectorAll(_trello_hideable_classes).forEach(function(i,x) {
            i.style.display = i.style.display == 'none' ? 'block' : 'none';
        });
        return;
    };

    var registerKeyBinding = function(key) {
        document.onkeydown = function(e) {
            e = e || window.event;
            switch(e.which || e.keyCode) {
                case key:
                    toggleItemsCallback(e);
                    break;
                default:return; // exit this handler for other keys
            }
            e.preventDefault(); // prevent the default action (scroll / move caret)
        };
    };

    createToggleButton(_button_label);
    registerKeyBinding(_key_to_bind);
})();


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.android.wearable.elizachat.MainActivity$PlaceholderFragment"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/history"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</ScrollView>


text:
import { ModuleWithProviders }  from '@angular/core'
import { Routes, RouterModule } from '@angular/router'

import { DetailProjectComponent, EditProjectComponent, ProjectsComponent } from './projects'
import { DetailReleaseComponent, EditReleaseComponent, ReleasesComponent } from './releases'
import { DetailStoryComponent, EditStoryComponent, StoriesComponent } from './stories'
import { EditValidationComponent, ValidationsComponent } from './validations'
import { ProjectManagementComponent } from './project-management.component'

const routes: Routes = [{
  path: 'project-management',
  component: ProjectManagementComponent,
  children: [
    {path: 'projects', component: ProjectsComponent },
    {path: 'project/:_id', component: EditProjectComponent },
    {path: 'project/detail/:_id', component: DetailProjectComponent },
    {path: 'releases', component: ReleasesComponent },
    {path: 'release/:_id', component: EditReleaseComponent },
    {path: 'release/detail/:_id', component: DetailReleaseComponent },
    {path: 'stories', component: StoriesComponent },
    {path: 'story/:_id', component: EditStoryComponent },
    {path: 'story/detail/:_id', component: DetailStoryComponent },
    {path: 'validations', component: ValidationsComponent },
    {path: 'validation/:_id', component: EditValidationComponent }
  ]
}]

export const routing: ModuleWithProviders = RouterModule.forRoot(routes)


text:
<?php

namespace Pinterest\Api\Exceptions;

use Exception;

final class TooManyScopesGiven extends Exception
{
}


text:
<?php namespace OtherCode\Rest\Modules\Decoders;

/**
 * Class XMLRPCDecoder
 * @author Unay Santisteban <usantisteban@othercode.es>
 * @package OtherCode\Rest\Modules\Decoders
 */
class XMLRPCDecoder extends \OtherCode\Rest\Modules\Decoders\BaseDecoder
{

    /**
     * The content type that trigger the decoder
     * @var string
     */
    protected $contentType = 'text/xml';

    /**
     * Decode the data of a request
     */
    public function decode()
    {
        $response = xmlrpc_decode($this->body);

        if (is_array($response) && xmlrpc_is_fault($response)) {
            throw new \OtherCode\Rest\Exceptions\RestException($response['faultString'], $response['faultCode']);
        }

        $this->body = $response;
    }
}


text:
Difficulty : Medium Community success rate: 80%

https://www.codingame.com/ide/puzzle/the-last-crusade-episode-1

![alt text](screenshots/ScreenShot001.png)

---

## The Goal

Your objective is to write a program capable of predicting the route Indy will take on his way down a tunnel. Indy is not in danger of getting trapped in this first mission.

## Rules

The tunnel consists of a patchwork of square rooms of different types.The rooms can be accessed and activated by computer using an ancient RS232 serial port (because Mayans aren't very technologically advanced, as is to be expected...).

There is a total of 14 room types (6 base shapes extended to 14 through rotations).

Upon entering a room, depending on the type of the room and Indy's entrance point (TOP,LEFT, or RIGHT) he will either exit the room through a specific exit point, suffer a lethal collision or lose momentum and get stuck:

![alt text](screenshots/ScreenShot002.png)

Indy is perpetually drawn downwards: he cannot leave a room through the top.

At the start of the game, you are given the map of the tunnel in the form of a rectangular grid of rooms. Each room is represented by its type.

For this first mission, you will familiarize yourself with the tunnel system, the rooms have all been arranged in such a way that Indy will have a safe continuous route between his starting point (top of the temple) and the exit area (bottom of the temple).

Each game turn:
- You receive Indy's current position
- Then you specify what Indy's position will be next turn.
- Indy will then move from the current room to the next according to the shape of the current room.

### Victory Conditions
Indy reaches the exit

### Lose Conditions
You assert an incorrect position for Indy

## Example

![alt text](screenshots/ScreenShot003.png)

## Note

The tests provided are similar to the validation tests used to compute the final score but remain different.

---

## Game Input

The program must first read the initialization data from standard input. Then, within an infinite loop, read the data from the standard input related to the current position of Indy and provide to the standard output the expected data.

### Initialization input
Line 1: 2 space separated integers W H specifying the width and height of the grid.

Next H lines: each line represents a line in the grid and contains W space separated integers T. T specifies the type of the room.

Last line: 1 integer EX specifying the coordinate along the X axis of the exit (this data is not useful for this first mission, it will be useful for the second level of this puzzle).

### Input for one game turn
Line 1: XI YI POS
- (XI, YI) two integers to indicate Indy's current position on the grid.
- POS a single word indicating Indy's entrance point into the current room: TOP if Indy enters from above, LEFT if Indy enters from the left and RIGHT if Indy enters from the right.

### Output for one game turn
A single line with 2 integers: X Y representing the (X, Y) coordinates of the room in which you believe Indy will be on the next turn.

### Constraints
- 0 < W ≤ 20
- 0 < H ≤ 20
- 0 ≤ T ≤ 13
- 0 ≤ EX < W
- 0 ≤ XI, X < W
- 0 ≤ YI, Y < H

Response time for one game ≤ 150ms

### Example

![alt text](screenshots/ScreenShot004.png)

---

### Determine that Indy will be in room (0,1) on the next turn

And so on until Indy reaches the exit at (1, 3)...
Synopsis

Indy, the greatest adventurer of modern times (except maybe Lara) finds himself once again in a sticky situation!

During his exploration of a Mayan temple, at the very moment he grabbed a relic of the feathered serpent Quetzalcóatl, a concealed hatch opened up beneath his feet plunging him at high speed deep into a dark underground tunnel.

Indy is at risk of slamming into a wall or getting permanently stuck underground at any moment.

Luckily, you - his loyal assistant - are here to get him out of trouble.


text:
bool lireFichier(char *filename, Chainage &chainage)
{
    std::ifstream ifs(filename, std::ifstream::in);
    if(ifs)
    {
        char line[32];
        while(ifs.getline(line,32))
        {
            std::istringstream iss(line);
            ReleveMeteo releveMeteo = creerReleveMeteo();
            iss >> releveMeteo.station;
            iss >> releveMeteo.date.annee;
            iss >> releveMeteo.date.jour;
            iss >> releveMeteo.date.heure;
            iss >> releveMeteo.temperature;
            insererQueue(chainage, releveMeteo);
        }
        return true;
    }
    return false;
}

double calculerTemperatureMoyenne(const Chainage &chainage)
{
    if(chainage.nb < 1)
    {
        throw std::exception();
    }
    else
    {
        double acc = 0;
        Maillon *maillon = chainage.tete;
        while(maillon != 0)
        {
            acc += (*maillon).elt.temperature;
            maillon = (*maillon).suiv;
        }
        return acc/chainage.nb;
    }
}

void retirerDefauts(Chainage &chainage, const double ecartMax)
{
    if(chainage.nb < 1)
    {
        throw std::exception();
    }
    else
    {
        double acc = 0;
        Maillon *maillon = chainage.tete, *maillonPre = 0;
        while(maillon != 0)
        {
            if((maillon != chainage.tete) && (maillon != chainage.queue) &&  (fabs((*maillon).elt.temperature - (*maillonPre).elt.temperature) > ecartMax) && (fabs((*(*maillon).suiv).elt.temperature - (*maillon).elt.temperature) > ecartMax))
            {
                (*maillonPre).suiv = (*maillon).suiv;
                maillonPre = (*maillon).suiv;
                delete maillon;
                maillon = (*maillonPre).suiv;
                chainage.nb--;

            }
            else
            {
                maillonPre = maillon;
                maillon = (*maillon).suiv;
            }
        }
    }
}

double calculerEcartMoyenTemperature(const Chainage &chainage)
{
    if(chainage.nb < 2)
    {
        throw std::exception();
    }
    else
    {
        double acc = 0;
        Maillon *maillon = chainage.tete;
        while((*maillon).suiv != 0)
        {
            acc += fabs(((*((*maillon).suiv)).elt.temperature) - ((*maillon).elt.temperature));
            maillon = (*maillon).suiv;
        }
        return acc/(chainage.nb-1);
    }
}

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        std::cout << "tp3 <nom du fichier à lire>" << std::endl;
        return 1;
    }
    else
    {
        Chainage c = creerChainage();
        if(!lireFichier(argv[1],c))
        {
            std::cout << "fichier incorrect" << std::endl;
            return 1;
        }
        else
        {
            try
            {
                ReleveMeteo rm = creerReleveMeteo();
                std::cout << "nombre de relevés = " << c.nb << std::endl;
                rm = plusPetitElement(c,compReleveMeteo2);
                std::cout << "relevé de la température minimale = ";
                afficherReleveMeteo(rm,std::cout);
                std::cout << std::endl;
                rm = plusPetitElement(c,compReleveMeteo3);
                std::cout << "relevé de la température maximale = ";
                afficherReleveMeteo(rm,std::cout);
                std::cout << std::endl;
                std::cout << "température moyenne = " << calculerTemperatureMoyenne(c) << std::endl;
                std::cout << "écart moyen des températures = " << calculerEcartMoyenTemperature(c) << std::endl;

                std::cout << std::endl;

                std::cout << "suppression des \"défauts\" (écart maximum = 2 * écart moyen)..." << std::endl;
                retirerDefauts(c,calculerEcartMoyenTemperature(c)*2);
                std::cout << "suppression du premier relevé (tête)..." << std::endl;
                retirerTete(c);
                std::cout << "suppression du dernier relevé (queue)..." << std::endl;
                retirerQueue(c);

                std::cout << std::endl;

                std::cout << "nombre de relevés = " << c.nb << std::endl;
                rm = plusPetitElement(c,compReleveMeteo2);
                std::cout << "relevé de la température minimale = ";
                afficherReleveMeteo(rm,std::cout);
                std::cout << std::endl;
                rm = plusPetitElement(c,compReleveMeteo3);
                std::cout << "relevé de la température maximale = ";
                afficherReleveMeteo(rm,std::cout);
                std::cout << std::endl;
                std::cout << "température moyenne = " << calculerTemperatureMoyenne(c) << std::endl;
                std::cout << "écart moyen des températures = " << calculerEcartMoyenTemperature(c) << std::endl;
            }
            catch(std::exception &e)
            {
                std::cout << std::endl << "nombre de relevés insuffisant pour effectuer les opérations" << std::endl;
            }
            reinitialiser(c);//pas de fuite mémoire
            return 0;
        }
    }
}


text:
namespace arrow {
namespace ipc {
namespace json {
namespace internal {

static std::string GetBufferTypeName(BufferType type) {
  switch (type) {
    case BufferType::DATA:
      return "DATA";
    case BufferType::OFFSET:
      return "OFFSET";
    case BufferType::TYPE:
      return "TYPE";
    case BufferType::VALIDITY:
      return "VALIDITY";
    default:
      break;
  }
  return "UNKNOWN";
}

static std::string GetFloatingPrecisionName(FloatingPoint::Precision precision) {
  switch (precision) {
    case FloatingPoint::HALF:
      return "HALF";
    case FloatingPoint::SINGLE:
      return "SINGLE";
    case FloatingPoint::DOUBLE:
      return "DOUBLE";
    default:
      break;
  }
  return "UNKNOWN";
}

static std::string GetTimeUnitName(TimeUnit::type unit) {
  switch (unit) {
    case TimeUnit::SECOND:
      return "SECOND";
    case TimeUnit::MILLI:
      return "MILLISECOND";
    case TimeUnit::MICRO:
      return "MICROSECOND";
    case TimeUnit::NANO:
      return "NANOSECOND";
    default:
      break;
  }
  return "UNKNOWN";
}

class SchemaWriter {
 public:
  explicit SchemaWriter(const Schema& schema, RjWriter* writer)
      : schema_(schema), writer_(writer) {}

  Status Write() {
    writer_->Key("schema");
    writer_->StartObject();
    writer_->Key("fields");
    writer_->StartArray();
    for (const std::shared_ptr<Field>& field : schema_.fields()) {
      RETURN_NOT_OK(VisitField(*field));
    }
    writer_->EndArray();
    writer_->EndObject();

    // Write dictionaries, if any
    if (dictionary_memo_.size() > 0) {
      writer_->Key("dictionaries");
      writer_->StartArray();
      for (const auto& entry : dictionary_memo_.id_to_dictionary()) {
        RETURN_NOT_OK(WriteDictionary(entry.first, entry.second));
      }
      writer_->EndArray();
    }
    return Status::OK();
  }

  Status WriteDictionary(int64_t id, const std::shared_ptr<Array>& dictionary) {
    writer_->StartObject();
    writer_->Key("id");
    writer_->Int(static_cast<int32_t>(id));
    writer_->Key("data");

    // Make a dummy record batch. A bit tedious as we have to make a schema
    auto schema = ::arrow::schema({arrow::field("dictionary", dictionary->type())});
    RecordBatch batch(schema, dictionary->length(), {dictionary});
    RETURN_NOT_OK(WriteRecordBatch(batch, writer_));
    writer_->EndObject();
    return Status::OK();
  }

  Status WriteDictionaryMetadata(const DictionaryType& type) {
    int64_t dictionary_id = dictionary_memo_.GetId(type.dictionary());
    writer_->Key("dictionary");

    // Emulate DictionaryEncoding from Schema.fbs
    writer_->StartObject();
    writer_->Key("id");
    writer_->Int(static_cast<int32_t>(dictionary_id));
    writer_->Key("indexType");

    writer_->StartObject();
    RETURN_NOT_OK(VisitType(*type.index_type()));
    writer_->EndObject();

    writer_->Key("isOrdered");
    writer_->Bool(type.ordered());
    writer_->EndObject();

    return Status::OK();
  }

  Status VisitField(const Field& field) {
    writer_->StartObject();

    writer_->Key("name");
    writer_->String(field.name().c_str());

    writer_->Key("nullable");
    writer_->Bool(field.nullable());

    const DataType& type = *field.type();

    // Visit the type
    writer_->Key("type");
    writer_->StartObject();
    RETURN_NOT_OK(VisitType(type));
    writer_->EndObject();

    if (type.id() == Type::DICTIONARY) {
      const auto& dict_type = static_cast<const DictionaryType&>(type);
      RETURN_NOT_OK(WriteDictionaryMetadata(dict_type));

      const DataType& dictionary_type = *dict_type.dictionary()->type();
      const DataType& index_type = *dict_type.index_type();
      RETURN_NOT_OK(WriteChildren(dictionary_type.children()));
      WriteBufferLayout(index_type.GetBufferLayout());
    } else {
      RETURN_NOT_OK(WriteChildren(type.children()));
      WriteBufferLayout(type.GetBufferLayout());
    }

    writer_->EndObject();

    return Status::OK();
  }

  Status VisitType(const DataType& type);

  template <typename T>
  typename std::enable_if<std::is_base_of<NoExtraMeta, T>::value ||
                              std::is_base_of<ListType, T>::value ||
                              std::is_base_of<StructType, T>::value,
                          void>::type
  WriteTypeMetadata(const T& type) {}

  void WriteTypeMetadata(const Integer& type) {
    writer_->Key("bitWidth");
    writer_->Int(type.bit_width());
    writer_->Key("isSigned");
    writer_->Bool(type.is_signed());
  }

  void WriteTypeMetadata(const FloatingPoint& type) {
    writer_->Key("precision");
    writer_->String(GetFloatingPrecisionName(type.precision()));
  }

  void WriteTypeMetadata(const IntervalType& type) {
    writer_->Key("unit");
    switch (type.unit()) {
      case IntervalType::Unit::YEAR_MONTH:
        writer_->String("YEAR_MONTH");
        break;
      case IntervalType::Unit::DAY_TIME:
        writer_->String("DAY_TIME");
        break;
    }
  }

  void WriteTypeMetadata(const TimestampType& type) {
    writer_->Key("unit");
    writer_->String(GetTimeUnitName(type.unit()));
    if (type.timezone().size() > 0) {
      writer_->Key("timezone");
      writer_->String(type.timezone());
    }
  }

  void WriteTypeMetadata(const TimeType& type) {
    writer_->Key("unit");
    writer_->String(GetTimeUnitName(type.unit()));
    writer_->Key("bitWidth");
    writer_->Int(type.bit_width());
  }

  void WriteTypeMetadata(const DateType& type) {
    writer_->Key("unit");
    switch (type.unit()) {
      case DateUnit::DAY:
        writer_->String("DAY");
        break;
      case DateUnit::MILLI:
        writer_->String("MILLISECOND");
        break;
    }
  }

  void WriteTypeMetadata(const FixedSizeBinaryType& type) {
    writer_->Key("byteWidth");
    writer_->Int(type.byte_width());
  }

  void WriteTypeMetadata(const DecimalType& type) {
    writer_->Key("precision");
    writer_->Int(type.precision());
    writer_->Key("scale");
    writer_->Int(type.scale());
  }

  void WriteTypeMetadata(const UnionType& type) {
    writer_->Key("mode");
    switch (type.mode()) {
      case UnionMode::SPARSE:
        writer_->String("SPARSE");
        break;
      case UnionMode::DENSE:
        writer_->String("DENSE");
        break;
    }

    // Write type ids
    writer_->Key("typeIds");
    writer_->StartArray();
    for (size_t i = 0; i < type.type_codes().size(); ++i) {
      writer_->Uint(type.type_codes()[i]);
    }
    writer_->EndArray();
  }

  // TODO(wesm): Other Type metadata

  template <typename T>
  void WriteName(const std::string& typeclass, const T& type) {
    writer_->Key("name");
    writer_->String(typeclass);
    WriteTypeMetadata(type);
  }

  template <typename T>
  Status WritePrimitive(const std::string& typeclass, const T& type) {
    WriteName(typeclass, type);
    return Status::OK();
  }

  template <typename T>
  Status WriteVarBytes(const std::string& typeclass, const T& type) {
    WriteName(typeclass, type);
    return Status::OK();
  }

  void WriteBufferLayout(const std::vector<BufferDescr>& buffer_layout) {
    writer_->Key("typeLayout");
    writer_->StartObject();
    writer_->Key("vectors");
    writer_->StartArray();

    for (const BufferDescr& buffer : buffer_layout) {
      writer_->StartObject();
      writer_->Key("type");
      writer_->String(GetBufferTypeName(buffer.type()));

      writer_->Key("typeBitWidth");
      writer_->Int(buffer.bit_width());

      writer_->EndObject();
    }
    writer_->EndArray();
    writer_->EndObject();
  }

  Status WriteChildren(const std::vector<std::shared_ptr<Field>>& children) {
    writer_->Key("children");
    writer_->StartArray();
    for (const std::shared_ptr<Field>& field : children) {
      RETURN_NOT_OK(VisitField(*field));
    }
    writer_->EndArray();
    return Status::OK();
  }

  Status Visit(const NullType& type) { return WritePrimitive("null", type); }
  Status Visit(const BooleanType& type) { return WritePrimitive("bool", type); }
  Status Visit(const Integer& type) { return WritePrimitive("int", type); }

  Status Visit(const FloatingPoint& type) {
    return WritePrimitive("floatingpoint", type);
  }

  Status Visit(const DateType& type) { return WritePrimitive("date", type); }
  Status Visit(const TimeType& type) { return WritePrimitive("time", type); }
  Status Visit(const StringType& type) { return WriteVarBytes("utf8", type); }
  Status Visit(const BinaryType& type) { return WriteVarBytes("binary", type); }
  Status Visit(const FixedSizeBinaryType& type) {
    return WritePrimitive("fixedsizebinary", type);
  }

  Status Visit(const DecimalType& type) { return WritePrimitive("decimal", type); }
  Status Visit(const TimestampType& type) { return WritePrimitive("timestamp", type); }
  Status Visit(const IntervalType& type) { return WritePrimitive("interval", type); }

  Status Visit(const ListType& type) {
    WriteName("list", type);
    return Status::OK();
  }

  Status Visit(const StructType& type) {
    WriteName("struct", type);
    return Status::OK();
  }

  Status Visit(const UnionType& type) {
    WriteName("union", type);
    return Status::OK();
  }

  Status Visit(const DictionaryType& type) {
    return VisitType(*type.dictionary()->type());
  }

 private:
  DictionaryMemo dictionary_memo_;

  const Schema& schema_;
  RjWriter* writer_;
};

Status SchemaWriter::VisitType(const DataType& type) {
  return VisitTypeInline(type, this);
}

class ArrayWriter {
 public:
  ArrayWriter(const std::string& name, const Array& array, RjWriter* writer)
      : name_(name), array_(array), writer_(writer) {}

  Status Write() { return VisitArray(name_, array_); }

  Status VisitArrayValues(const Array& arr) { return VisitArrayInline(arr, this); }

  Status VisitArray(const std::string& name, const Array& arr) {
    writer_->StartObject();
    writer_->Key("name");
    writer_->String(name);

    writer_->Key("count");
    writer_->Int(static_cast<int32_t>(arr.length()));

    RETURN_NOT_OK(VisitArrayValues(arr));

    writer_->EndObject();
    return Status::OK();
  }

  template <typename T>
  typename std::enable_if<IsSignedInt<T>::value, void>::type WriteDataValues(
      const T& arr) {
    const auto data = arr.raw_values();
    for (int i = 0; i < arr.length(); ++i) {
      writer_->Int64(data[i]);
    }
  }

  template <typename T>
  typename std::enable_if<IsUnsignedInt<T>::value, void>::type WriteDataValues(
      const T& arr) {
    const auto data = arr.raw_values();
    for (int i = 0; i < arr.length(); ++i) {
      writer_->Uint64(data[i]);
    }
  }

  template <typename T>
  typename std::enable_if<IsFloatingPoint<T>::value, void>::type WriteDataValues(
      const T& arr) {
    const auto data = arr.raw_values();
    for (int i = 0; i < arr.length(); ++i) {
      writer_->Double(data[i]);
    }
  }

  // Binary, encode to hexadecimal. UTF8 string write as is
  template <typename T>
  typename std::enable_if<std::is_base_of<BinaryArray, T>::value, void>::type
  WriteDataValues(const T& arr) {
    for (int64_t i = 0; i < arr.length(); ++i) {
      int32_t length;
      const uint8_t* buf = arr.GetValue(i, &length);

      if (std::is_base_of<StringArray, T>::value) {
        // Presumed UTF-8
        writer_->String(reinterpret_cast<const char*>(buf), length);
      } else {
        writer_->String(HexEncode(buf, length));
      }
    }
  }

  void WriteDataValues(const FixedSizeBinaryArray& arr) {
    int32_t width = arr.byte_width();
    for (int64_t i = 0; i < arr.length(); ++i) {
      const uint8_t* buf = arr.GetValue(i);
      std::string encoded = HexEncode(buf, width);
      writer_->String(encoded);
    }
  }

  void WriteDataValues(const BooleanArray& arr) {
    for (int i = 0; i < arr.length(); ++i) {
      writer_->Bool(arr.Value(i));
    }
  }

  template <typename T>
  void WriteDataField(const T& arr) {
    writer_->Key("DATA");
    writer_->StartArray();
    WriteDataValues(arr);
    writer_->EndArray();
  }

  template <typename T>
  void WriteIntegerField(const char* name, const T* values, int64_t length) {
    writer_->Key(name);
    writer_->StartArray();
    for (int i = 0; i < length; ++i) {
      writer_->Int64(values[i]);
    }
    writer_->EndArray();
  }

  void WriteValidityField(const Array& arr) {
    writer_->Key("VALIDITY");
    writer_->StartArray();
    if (arr.null_count() > 0) {
      for (int i = 0; i < arr.length(); ++i) {
        writer_->Int(arr.IsNull(i) ? 0 : 1);
      }
    } else {
      for (int i = 0; i < arr.length(); ++i) {
        writer_->Int(1);
      }
    }
    writer_->EndArray();
  }

  void SetNoChildren() {
    writer_->Key("children");
    writer_->StartArray();
    writer_->EndArray();
  }

  Status WriteChildren(const std::vector<std::shared_ptr<Field>>& fields,
                       const std::vector<std::shared_ptr<Array>>& arrays) {
    writer_->Key("children");
    writer_->StartArray();
    for (size_t i = 0; i < fields.size(); ++i) {
      RETURN_NOT_OK(VisitArray(fields[i]->name(), *arrays[i]));
    }
    writer_->EndArray();
    return Status::OK();
  }

  Status Visit(const NullArray& array) {
    SetNoChildren();
    return Status::OK();
  }

  template <typename T>
  typename std::enable_if<std::is_base_of<PrimitiveArray, T>::value, Status>::type Visit(
      const T& array) {
    WriteValidityField(array);
    WriteDataField(array);
    SetNoChildren();
    return Status::OK();
  }

  template <typename T>
  typename std::enable_if<std::is_base_of<BinaryArray, T>::value, Status>::type Visit(
      const T& array) {
    WriteValidityField(array);
    WriteIntegerField("OFFSET", array.raw_value_offsets(), array.length() + 1);
    WriteDataField(array);
    SetNoChildren();
    return Status::OK();
  }

  Status Visit(const DictionaryArray& array) {
    return VisitArrayValues(*array.indices());
  }

  Status Visit(const ListArray& array) {
    WriteValidityField(array);
    WriteIntegerField("OFFSET", array.raw_value_offsets(), array.length() + 1);
    const auto& type = static_cast<const ListType&>(*array.type());
    return WriteChildren(type.children(), {array.values()});
  }

  Status Visit(const StructArray& array) {
    WriteValidityField(array);
    const auto& type = static_cast<const StructType&>(*array.type());
    std::vector<std::shared_ptr<Array>> children;
    children.reserve(array.num_fields());
    for (int i = 0; i < array.num_fields(); ++i) {
      children.emplace_back(array.field(i));
    }
    return WriteChildren(type.children(), children);
  }

  Status Visit(const UnionArray& array) {
    WriteValidityField(array);
    const auto& type = static_cast<const UnionType&>(*array.type());

    WriteIntegerField("TYPE_ID", array.raw_type_ids(), array.length());
    if (type.mode() == UnionMode::DENSE) {
      WriteIntegerField("OFFSET", array.raw_value_offsets(), array.length());
    }
    std::vector<std::shared_ptr<Array>> children;
    children.reserve(array.num_fields());
    for (int i = 0; i < array.num_fields(); ++i) {
      children.emplace_back(array.child(i));
    }
    return WriteChildren(type.children(), children);
  }

 private:
  const std::string& name_;
  const Array& array_;
  RjWriter* writer_;
};

static Status GetObjectInt(const RjObject& obj, const std::string& key, int* out) {
  const auto& it = obj.FindMember(key);
  RETURN_NOT_INT(key, it, obj);
  *out = it->value.GetInt();
  return Status::OK();
}

static Status GetObjectBool(const RjObject& obj, const std::string& key, bool* out) {
  const auto& it = obj.FindMember(key);
  RETURN_NOT_BOOL(key, it, obj);
  *out = it->value.GetBool();
  return Status::OK();
}

static Status GetObjectString(const RjObject& obj, const std::string& key,
                              std::string* out) {
  const auto& it = obj.FindMember(key);
  RETURN_NOT_STRING(key, it, obj);
  *out = it->value.GetString();
  return Status::OK();
}

static Status GetInteger(const rj::Value::ConstObject& json_type,
                         std::shared_ptr<DataType>* type) {
  const auto& it_bit_width = json_type.FindMember("bitWidth");
  RETURN_NOT_INT("bitWidth", it_bit_width, json_type);

  const auto& it_is_signed = json_type.FindMember("isSigned");
  RETURN_NOT_BOOL("isSigned", it_is_signed, json_type);

  bool is_signed = it_is_signed->value.GetBool();
  int bit_width = it_bit_width->value.GetInt();

  switch (bit_width) {
    case 8:
      *type = is_signed ? int8() : uint8();
      break;
    case 16:
      *type = is_signed ? int16() : uint16();
      break;
    case 32:
      *type = is_signed ? int32() : uint32();
      break;
    case 64:
      *type = is_signed ? int64() : uint64();
      break;
    default:
      std::stringstream ss;
      ss << "Invalid bit width: " << bit_width;
      return Status::Invalid(ss.str());
  }
  return Status::OK();
}

static Status GetFloatingPoint(const RjObject& json_type,
                               std::shared_ptr<DataType>* type) {
  const auto& it_precision = json_type.FindMember("precision");
  RETURN_NOT_STRING("precision", it_precision, json_type);

  std::string precision = it_precision->value.GetString();

  if (precision == "DOUBLE") {
    *type = float64();
  } else if (precision == "SINGLE") {
    *type = float32();
  } else if (precision == "HALF") {
    *type = float16();
  } else {
    std::stringstream ss;
    ss << "Invalid precision: " << precision;
    return Status::Invalid(ss.str());
  }
  return Status::OK();
}

static Status GetFixedSizeBinary(const RjObject& json_type,
                                 std::shared_ptr<DataType>* type) {
  const auto& it_byte_width = json_type.FindMember("byteWidth");
  RETURN_NOT_INT("byteWidth", it_byte_width, json_type);

  int32_t byte_width = it_byte_width->value.GetInt();
  *type = fixed_size_binary(byte_width);
  return Status::OK();
}

static Status GetDecimal(const RjObject& json_type, std::shared_ptr<DataType>* type) {
  const auto& it_precision = json_type.FindMember("precision");
  const auto& it_scale = json_type.FindMember("scale");

  RETURN_NOT_INT("precision", it_precision, json_type);
  RETURN_NOT_INT("scale", it_scale, json_type);

  *type = decimal(it_precision->value.GetInt(), it_scale->value.GetInt());
  return Status::OK();
}

static Status GetDate(const RjObject& json_type, std::shared_ptr<DataType>* type) {
  const auto& it_unit = json_type.FindMember("unit");
  RETURN_NOT_STRING("unit", it_unit, json_type);

  std::string unit_str = it_unit->value.GetString();

  if (unit_str == "DAY") {
    *type = date32();
  } else if (unit_str == "MILLISECOND") {
    *type = date64();
  } else {
    std::stringstream ss;
    ss << "Invalid date unit: " << unit_str;
    return Status::Invalid(ss.str());
  }
  return Status::OK();
}

static Status GetTime(const RjObject& json_type, std::shared_ptr<DataType>* type) {
  const auto& it_unit = json_type.FindMember("unit");
  RETURN_NOT_STRING("unit", it_unit, json_type);

  const auto& it_bit_width = json_type.FindMember("bitWidth");
  RETURN_NOT_INT("bitWidth", it_bit_width, json_type);

  std::string unit_str = it_unit->value.GetString();

  if (unit_str == "SECOND") {
    *type = time32(TimeUnit::SECOND);
  } else if (unit_str == "MILLISECOND") {
    *type = time32(TimeUnit::MILLI);
  } else if (unit_str == "MICROSECOND") {
    *type = time64(TimeUnit::MICRO);
  } else if (unit_str == "NANOSECOND") {
    *type = time64(TimeUnit::NANO);
  } else {
    std::stringstream ss;
    ss << "Invalid time unit: " << unit_str;
    return Status::Invalid(ss.str());
  }

  const auto& fw_type = static_cast<const FixedWidthType&>(**type);

  int bit_width = it_bit_width->value.GetInt();
  if (bit_width != fw_type.bit_width()) {
    return Status::Invalid("Indicated bit width does not match unit");
  }

  return Status::OK();
}

static Status GetTimestamp(const RjObject& json_type, std::shared_ptr<DataType>* type) {
  const auto& it_unit = json_type.FindMember("unit");
  RETURN_NOT_STRING("unit", it_unit, json_type);

  std::string unit_str = it_unit->value.GetString();

  TimeUnit::type unit;
  if (unit_str == "SECOND") {
    unit = TimeUnit::SECOND;
  } else if (unit_str == "MILLISECOND") {
    unit = TimeUnit::MILLI;
  } else if (unit_str == "MICROSECOND") {
    unit = TimeUnit::MICRO;
  } else if (unit_str == "NANOSECOND") {
    unit = TimeUnit::NANO;
  } else {
    std::stringstream ss;
    ss << "Invalid time unit: " << unit_str;
    return Status::Invalid(ss.str());
  }

  const auto& it_tz = json_type.FindMember("timezone");
  if (it_tz == json_type.MemberEnd()) {
    *type = timestamp(unit);
  } else {
    *type = timestamp(unit, it_tz->value.GetString());
  }

  return Status::OK();
}

static Status GetUnion(const RjObject& json_type,
                       const std::vector<std::shared_ptr<Field>>& children,
                       std::shared_ptr<DataType>* type) {
  const auto& it_mode = json_type.FindMember("mode");
  RETURN_NOT_STRING("mode", it_mode, json_type);

  std::string mode_str = it_mode->value.GetString();
  UnionMode mode;

  if (mode_str == "SPARSE") {
    mode = UnionMode::SPARSE;
  } else if (mode_str == "DENSE") {
    mode = UnionMode::DENSE;
  } else {
    std::stringstream ss;
    ss << "Invalid union mode: " << mode_str;
    return Status::Invalid(ss.str());
  }

  const auto& it_type_codes = json_type.FindMember("typeIds");
  RETURN_NOT_ARRAY("typeIds", it_type_codes, json_type);

  std::vector<uint8_t> type_codes;
  const auto& id_array = it_type_codes->value.GetArray();
  for (const rj::Value& val : id_array) {
    DCHECK(val.IsUint());
    type_codes.push_back(static_cast<uint8_t>(val.GetUint()));
  }

  *type = union_(children, type_codes, mode);

  return Status::OK();
}

static Status GetType(const RjObject& json_type,
                      const std::vector<std::shared_ptr<Field>>& children,
                      std::shared_ptr<DataType>* type) {
  const auto& it_type_name = json_type.FindMember("name");
  RETURN_NOT_STRING("name", it_type_name, json_type);

  std::string type_name = it_type_name->value.GetString();

  if (type_name == "int") {
    return GetInteger(json_type, type);
  } else if (type_name == "floatingpoint") {
    return GetFloatingPoint(json_type, type);
  } else if (type_name == "bool") {
    *type = boolean();
  } else if (type_name == "utf8") {
    *type = utf8();
  } else if (type_name == "binary") {
    *type = binary();
  } else if (type_name == "fixedsizebinary") {
    return GetFixedSizeBinary(json_type, type);
  } else if (type_name == "decimal") {
    return GetDecimal(json_type, type);
  } else if (type_name == "null") {
    *type = null();
  } else if (type_name == "date") {
    return GetDate(json_type, type);
  } else if (type_name == "time") {
    return GetTime(json_type, type);
  } else if (type_name == "timestamp") {
    return GetTimestamp(json_type, type);
  } else if (type_name == "list") {
    if (children.size() != 1) {
      return Status::Invalid("List must have exactly one child");
    }
    *type = list(children[0]);
  } else if (type_name == "struct") {
    *type = struct_(children);
  } else if (type_name == "union") {
    return GetUnion(json_type, children, type);
  } else {
    std::stringstream ss;
    ss << "Unrecognized type name: " << type_name;
    return Status::Invalid(ss.str());
  }
  return Status::OK();
}

static Status GetField(const rj::Value& obj, const DictionaryMemo* dictionary_memo,
                       std::shared_ptr<Field>* field);

static Status GetFieldsFromArray(const rj::Value& obj,
                                 const DictionaryMemo* dictionary_memo,
                                 std::vector<std::shared_ptr<Field>>* fields) {
  const auto& values = obj.GetArray();

  fields->resize(values.Size());
  for (rj::SizeType i = 0; i < fields->size(); ++i) {
    RETURN_NOT_OK(GetField(values[i], dictionary_memo, &(*fields)[i]));
  }
  return Status::OK();
}

static Status ParseDictionary(const RjObject& obj, int64_t* id, bool* is_ordered,
                              std::shared_ptr<DataType>* index_type) {
  int32_t int32_id;
  RETURN_NOT_OK(GetObjectInt(obj, "id", &int32_id));
  *id = int32_id;

  RETURN_NOT_OK(GetObjectBool(obj, "isOrdered", is_ordered));

  const auto& it_index_type = obj.FindMember("indexType");
  RETURN_NOT_OBJECT("indexType", it_index_type, obj);

  const auto& json_index_type = it_index_type->value.GetObject();

  std::string type_name;
  RETURN_NOT_OK(GetObjectString(json_index_type, "name", &type_name));
  if (type_name != "int") {
    return Status::Invalid("Dictionary indices can only be integers");
  }
  return GetInteger(json_index_type, index_type);
}

static Status GetField(const rj::Value& obj, const DictionaryMemo* dictionary_memo,
                       std::shared_ptr<Field>* field) {
  if (!obj.IsObject()) {
    return Status::Invalid("Field was not a JSON object");
  }
  const auto& json_field = obj.GetObject();

  std::string name;
  bool nullable;
  RETURN_NOT_OK(GetObjectString(json_field, "name", &name));
  RETURN_NOT_OK(GetObjectBool(json_field, "nullable", &nullable));

  std::shared_ptr<DataType> type;

  const auto& it_dictionary = json_field.FindMember("dictionary");
  if (dictionary_memo != nullptr && it_dictionary != json_field.MemberEnd()) {
    // Field is dictionary encoded. We must have already
    RETURN_NOT_OBJECT("dictionary", it_dictionary, json_field);
    int64_t dictionary_id;
    bool is_ordered;
    std::shared_ptr<DataType> index_type;
    RETURN_NOT_OK(ParseDictionary(it_dictionary->value.GetObject(), &dictionary_id,
                                  &is_ordered, &index_type));

    std::shared_ptr<Array> dictionary;
    RETURN_NOT_OK(dictionary_memo->GetDictionary(dictionary_id, &dictionary));

    type = std::make_shared<DictionaryType>(index_type, dictionary, is_ordered);
  } else {
    // If the dictionary_memo was not passed, or if the field is not dictionary
    // encoded, we are interested in the complete type including all children

    const auto& it_type = json_field.FindMember("type");
    RETURN_NOT_OBJECT("type", it_type, json_field);

    const auto& it_children = json_field.FindMember("children");
    RETURN_NOT_ARRAY("children", it_children, json_field);

    std::vector<std::shared_ptr<Field>> children;
    RETURN_NOT_OK(GetFieldsFromArray(it_children->value, dictionary_memo, &children));
    RETURN_NOT_OK(GetType(it_type->value.GetObject(), children, &type));
  }

  *field = std::make_shared<Field>(name, type, nullable);
  return Status::OK();
}

template <typename T>
inline typename std::enable_if<IsSignedInt<T>::value, typename T::c_type>::type
UnboxValue(const rj::Value& val) {
  DCHECK(val.IsInt64());
  return static_cast<typename T::c_type>(val.GetInt64());
}

template <typename T>
inline typename std::enable_if<IsUnsignedInt<T>::value, typename T::c_type>::type
UnboxValue(const rj::Value& val) {
  DCHECK(val.IsUint());
  return static_cast<typename T::c_type>(val.GetUint64());
}

template <typename T>
inline typename std::enable_if<IsFloatingPoint<T>::value, typename T::c_type>::type
UnboxValue(const rj::Value& val) {
  DCHECK(val.IsFloat());
  return static_cast<typename T::c_type>(val.GetDouble());
}

template <typename T>
inline typename std::enable_if<std::is_base_of<BooleanType, T>::value, bool>::type
UnboxValue(const rj::Value& val) {
  DCHECK(val.IsBool());
  return val.GetBool();
}

class ArrayReader {
 public:
  explicit ArrayReader(const rj::Value& json_array, const std::shared_ptr<DataType>& type,
                       MemoryPool* pool)
      : json_array_(json_array), type_(type), pool_(pool) {}

  Status ParseTypeValues(const DataType& type);

  Status GetValidityBuffer(const std::vector<bool>& is_valid, int32_t* null_count,
                           std::shared_ptr<Buffer>* validity_buffer) {
    int length = static_cast<int>(is_valid.size());

    std::shared_ptr<Buffer> out_buffer;
    RETURN_NOT_OK(GetEmptyBitmap(pool_, length, &out_buffer));
    uint8_t* bitmap = out_buffer->mutable_data();

    *null_count = 0;
    for (int i = 0; i < length; ++i) {
      if (!is_valid[i]) {
        ++(*null_count);
        continue;
      }
      BitUtil::SetBit(bitmap, i);
    }

    *validity_buffer = out_buffer;
    return Status::OK();
  }

  template <typename T>
  typename std::enable_if<
      std::is_base_of<PrimitiveCType, T>::value || std::is_base_of<DateType, T>::value ||
          std::is_base_of<TimestampType, T>::value ||
          std::is_base_of<TimeType, T>::value || std::is_base_of<BooleanType, T>::value,
      Status>::type
  Visit(const T& type) {
    typename TypeTraits<T>::BuilderType builder(type_, pool_);

    const auto& json_data = obj_->FindMember("DATA");
    RETURN_NOT_ARRAY("DATA", json_data, *obj_);

    const auto& json_data_arr = json_data->value.GetArray();

    DCHECK_EQ(static_cast<int32_t>(json_data_arr.Size()), length_);
    for (int i = 0; i < length_; ++i) {
      if (!is_valid_[i]) {
        RETURN_NOT_OK(builder.AppendNull());
        continue;
      }

      const rj::Value& val = json_data_arr[i];
      RETURN_NOT_OK(builder.Append(UnboxValue<T>(val)));
    }

    return builder.Finish(&result_);
  }

  template <typename T>
  typename std::enable_if<std::is_base_of<BinaryType, T>::value, Status>::type Visit(
      const T& type) {
    typename TypeTraits<T>::BuilderType builder(pool_);

    const auto& json_data = obj_->FindMember("DATA");
    RETURN_NOT_ARRAY("DATA", json_data, *obj_);

    const auto& json_data_arr = json_data->value.GetArray();

    DCHECK_EQ(static_cast<int32_t>(json_data_arr.Size()), length_);

    auto byte_buffer = std::make_shared<PoolBuffer>(pool_);
    for (int i = 0; i < length_; ++i) {
      if (!is_valid_[i]) {
        RETURN_NOT_OK(builder.AppendNull());
        continue;
      }

      const rj::Value& val = json_data_arr[i];
      DCHECK(val.IsString());
      if (std::is_base_of<StringType, T>::value) {
        RETURN_NOT_OK(builder.Append(val.GetString()));
      } else {
        std::string hex_string = val.GetString();

        DCHECK(hex_string.size() % 2 == 0) << "Expected base16 hex string";
        int32_t length = static_cast<int>(hex_string.size()) / 2;

        if (byte_buffer->size() < length) {
          RETURN_NOT_OK(byte_buffer->Resize(length));
        }

        const char* hex_data = hex_string.c_str();
        uint8_t* byte_buffer_data = byte_buffer->mutable_data();
        for (int32_t j = 0; j < length; ++j) {
          RETURN_NOT_OK(ParseHexValue(hex_data + j * 2, &byte_buffer_data[j]));
        }
        RETURN_NOT_OK(builder.Append(byte_buffer_data, length));
      }
    }

    return builder.Finish(&result_);
  }

  template <typename T>
  typename std::enable_if<std::is_base_of<FixedSizeBinaryType, T>::value, Status>::type
  Visit(const T& type) {
    typename TypeTraits<T>::BuilderType builder(type_, pool_);

    const auto& json_data = obj_->FindMember("DATA");
    RETURN_NOT_ARRAY("DATA", json_data, *obj_);

    const auto& json_data_arr = json_data->value.GetArray();

    DCHECK_EQ(static_cast<int32_t>(json_data_arr.Size()), length_);
    int32_t byte_width = type.byte_width();

    // Allocate space for parsed values
    std::shared_ptr<Buffer> byte_buffer;
    RETURN_NOT_OK(AllocateBuffer(pool_, byte_width, &byte_buffer));
    uint8_t* byte_buffer_data = byte_buffer->mutable_data();

    for (int i = 0; i < length_; ++i) {
      if (!is_valid_[i]) {
        RETURN_NOT_OK(builder.AppendNull());
        continue;
      }

      const rj::Value& val = json_data_arr[i];
      DCHECK(val.IsString());
      std::string hex_string = val.GetString();
      if (static_cast<int32_t>(hex_string.size()) != byte_width * 2) {
        DCHECK(false) << "Expected size: " << byte_width * 2
                      << " got: " << hex_string.size();
      }
      const char* hex_data = hex_string.c_str();

      for (int32_t j = 0; j < byte_width; ++j) {
        RETURN_NOT_OK(ParseHexValue(hex_data + j * 2, &byte_buffer_data[j]));
      }
      RETURN_NOT_OK(builder.Append(byte_buffer_data));
    }
    return builder.Finish(&result_);
  }

  template <typename T>
  Status GetIntArray(const RjArray& json_array, const int32_t length,
                     std::shared_ptr<Buffer>* out) {
    std::shared_ptr<Buffer> buffer;
    RETURN_NOT_OK(AllocateBuffer(pool_, length * sizeof(T), &buffer));

    T* values = reinterpret_cast<T*>(buffer->mutable_data());
    for (int i = 0; i < length; ++i) {
      const rj::Value& val = json_array[i];
      DCHECK(val.IsInt());
      values[i] = static_cast<T>(val.GetInt());
    }

    *out = buffer;
    return Status::OK();
  }

  Status Visit(const ListType& type) {
    int32_t null_count = 0;
    std::shared_ptr<Buffer> validity_buffer;
    RETURN_NOT_OK(GetValidityBuffer(is_valid_, &null_count, &validity_buffer));

    const auto& json_offsets = obj_->FindMember("OFFSET");
    RETURN_NOT_ARRAY("OFFSET", json_offsets, *obj_);
    std::shared_ptr<Buffer> offsets_buffer;
    RETURN_NOT_OK(GetIntArray<int32_t>(json_offsets->value.GetArray(), length_ + 1,
                                       &offsets_buffer));

    std::vector<std::shared_ptr<Array>> children;
    RETURN_NOT_OK(GetChildren(*obj_, type, &children));
    DCHECK_EQ(children.size(), 1);

    result_ = std::make_shared<ListArray>(type_, length_, offsets_buffer, children[0],
                                          validity_buffer, null_count);

    return Status::OK();
  }

  Status Visit(const StructType& type) {
    int32_t null_count = 0;
    std::shared_ptr<Buffer> validity_buffer;
    RETURN_NOT_OK(GetValidityBuffer(is_valid_, &null_count, &validity_buffer));

    std::vector<std::shared_ptr<Array>> fields;
    RETURN_NOT_OK(GetChildren(*obj_, type, &fields));

    result_ = std::make_shared<StructArray>(type_, length_, fields, validity_buffer,
                                            null_count);

    return Status::OK();
  }

  Status Visit(const UnionType& type) {
    int32_t null_count = 0;

    std::shared_ptr<Buffer> validity_buffer;
    std::shared_ptr<Buffer> type_id_buffer;
    std::shared_ptr<Buffer> offsets_buffer;

    RETURN_NOT_OK(GetValidityBuffer(is_valid_, &null_count, &validity_buffer));

    const auto& json_type_ids = obj_->FindMember("TYPE_ID");
    RETURN_NOT_ARRAY("TYPE_ID", json_type_ids, *obj_);
    RETURN_NOT_OK(
        GetIntArray<uint8_t>(json_type_ids->value.GetArray(), length_, &type_id_buffer));

    if (type.mode() == UnionMode::DENSE) {
      const auto& json_offsets = obj_->FindMember("OFFSET");
      RETURN_NOT_ARRAY("OFFSET", json_offsets, *obj_);
      RETURN_NOT_OK(
          GetIntArray<int32_t>(json_offsets->value.GetArray(), length_, &offsets_buffer));
    }

    std::vector<std::shared_ptr<Array>> children;
    RETURN_NOT_OK(GetChildren(*obj_, type, &children));

    result_ = std::make_shared<UnionArray>(type_, length_, children, type_id_buffer,
                                           offsets_buffer, validity_buffer, null_count);

    return Status::OK();
  }

  Status Visit(const NullType& type) {
    result_ = std::make_shared<NullArray>(length_);
    return Status::OK();
  }

  Status Visit(const DictionaryType& type) {
    // This stores the indices in result_
    //
    // XXX(wesm): slight hack
    auto dict_type = type_;
    type_ = type.index_type();
    RETURN_NOT_OK(ParseTypeValues(*type_));
    type_ = dict_type;
    result_ = std::make_shared<DictionaryArray>(type_, result_);
    return Status::OK();
  }

  Status GetChildren(const RjObject& obj, const DataType& type,
                     std::vector<std::shared_ptr<Array>>* array) {
    const auto& json_children = obj.FindMember("children");
    RETURN_NOT_ARRAY("children", json_children, obj);
    const auto& json_children_arr = json_children->value.GetArray();

    if (type.num_children() != static_cast<int>(json_children_arr.Size())) {
      std::stringstream ss;
      ss << "Expected " << type.num_children() << " children, but got "
         << json_children_arr.Size();
      return Status::Invalid(ss.str());
    }

    for (int i = 0; i < static_cast<int>(json_children_arr.Size()); ++i) {
      const rj::Value& json_child = json_children_arr[i];
      DCHECK(json_child.IsObject());

      std::shared_ptr<Field> child_field = type.child(i);

      auto it = json_child.FindMember("name");
      RETURN_NOT_STRING("name", it, json_child);

      DCHECK_EQ(it->value.GetString(), child_field->name());
      std::shared_ptr<Array> child;
      RETURN_NOT_OK(ReadArray(pool_, json_children_arr[i], child_field->type(), &child));
      array->emplace_back(child);
    }

    return Status::OK();
  }

  Status GetArray(std::shared_ptr<Array>* out) {
    if (!json_array_.IsObject()) {
      return Status::Invalid("Array element was not a JSON object");
    }

    auto obj = json_array_.GetObject();
    obj_ = &obj;

    RETURN_NOT_OK(GetObjectInt(obj, "count", &length_));

    const auto& json_valid_iter = obj.FindMember("VALIDITY");
    RETURN_NOT_ARRAY("VALIDITY", json_valid_iter, obj);

    const auto& json_validity = json_valid_iter->value.GetArray();
    DCHECK_EQ(static_cast<int>(json_validity.Size()), length_);
    for (const rj::Value& val : json_validity) {
      DCHECK(val.IsInt());
      is_valid_.push_back(val.GetInt() != 0);
    }

    RETURN_NOT_OK(ParseTypeValues(*type_));
    *out = result_;
    return Status::OK();
  }

 private:
  const rj::Value& json_array_;
  const RjObject* obj_;
  std::shared_ptr<DataType> type_;
  MemoryPool* pool_;

  // Parsed common attributes
  std::vector<bool> is_valid_;
  int32_t length_;
  std::shared_ptr<Array> result_;
};

Status ArrayReader::ParseTypeValues(const DataType& type) {
  return VisitTypeInline(type, this);
}

Status WriteSchema(const Schema& schema, RjWriter* json_writer) {
  SchemaWriter converter(schema, json_writer);
  return converter.Write();
}

static Status LookForDictionaries(const rj::Value& obj, DictionaryTypeMap* id_to_field) {
  const auto& json_field = obj.GetObject();

  const auto& it_dictionary = json_field.FindMember("dictionary");
  if (it_dictionary == json_field.MemberEnd()) {
    // Not dictionary-encoded
    return Status::OK();
  }

  // Dictionary encoded. Construct the field and set in the type map
  std::shared_ptr<Field> dictionary_field;
  RETURN_NOT_OK(GetField(obj, nullptr, &dictionary_field));

  int id;
  RETURN_NOT_OK(GetObjectInt(it_dictionary->value.GetObject(), "id", &id));
  (*id_to_field)[id] = dictionary_field;
  return Status::OK();
}

static Status GetDictionaryTypes(const RjArray& fields, DictionaryTypeMap* id_to_field) {
  for (rj::SizeType i = 0; i < fields.Size(); ++i) {
    RETURN_NOT_OK(LookForDictionaries(fields[i], id_to_field));
  }
  return Status::OK();
}

static Status ReadDictionary(const RjObject& obj, const DictionaryTypeMap& id_to_field,
                             MemoryPool* pool, int64_t* dictionary_id,
                             std::shared_ptr<Array>* out) {
  int id;
  RETURN_NOT_OK(GetObjectInt(obj, "id", &id));

  const auto& it_data = obj.FindMember("data");
  RETURN_NOT_OBJECT("data", it_data, obj);

  auto it = id_to_field.find(id);
  if (it == id_to_field.end()) {
    std::stringstream ss;
    ss << "No dictionary with id " << id;
    return Status::Invalid(ss.str());
  }
  std::vector<std::shared_ptr<Field>> fields = {it->second};

  // We need a schema for the record batch
  auto dummy_schema = std::make_shared<Schema>(fields);

  // The dictionary is embedded in a record batch with a single column
  std::shared_ptr<RecordBatch> batch;
  RETURN_NOT_OK(ReadRecordBatch(it_data->value, dummy_schema, pool, &batch));

  if (batch->num_columns() != 1) {
    return Status::Invalid("Dictionary record batch must only contain one field");
  }

  *dictionary_id = id;
  *out = batch->column(0);
  return Status::OK();
}

static Status ReadDictionaries(const rj::Value& doc, const DictionaryTypeMap& id_to_field,
                               MemoryPool* pool, DictionaryMemo* dictionary_memo) {
  auto it = doc.FindMember("dictionaries");
  if (it == doc.MemberEnd()) {
    // No dictionaries
    return Status::OK();
  }

  RETURN_NOT_ARRAY("dictionaries", it, doc);
  const auto& dictionary_array = it->value.GetArray();

  for (const rj::Value& val : dictionary_array) {
    DCHECK(val.IsObject());
    int64_t dictionary_id;
    std::shared_ptr<Array> dictionary;
    RETURN_NOT_OK(
        ReadDictionary(val.GetObject(), id_to_field, pool, &dictionary_id, &dictionary));

    RETURN_NOT_OK(dictionary_memo->AddDictionary(dictionary_id, dictionary));
  }
  return Status::OK();
}

Status ReadSchema(const rj::Value& json_schema, MemoryPool* pool,
                  std::shared_ptr<Schema>* schema) {
  auto it = json_schema.FindMember("schema");
  RETURN_NOT_OBJECT("schema", it, json_schema);
  const auto& obj_schema = it->value.GetObject();

  const auto& it_fields = obj_schema.FindMember("fields");
  RETURN_NOT_ARRAY("fields", it_fields, obj_schema);

  // Determine the dictionary types
  DictionaryTypeMap dictionary_types;
  RETURN_NOT_OK(GetDictionaryTypes(it_fields->value.GetArray(), &dictionary_types));

  // Read the dictionaries (if any) and cache in the memo
  DictionaryMemo dictionary_memo;
  RETURN_NOT_OK(ReadDictionaries(json_schema, dictionary_types, pool, &dictionary_memo));

  std::vector<std::shared_ptr<Field>> fields;
  RETURN_NOT_OK(GetFieldsFromArray(it_fields->value, &dictionary_memo, &fields));

  *schema = std::make_shared<Schema>(fields);
  return Status::OK();
}

Status ReadRecordBatch(const rj::Value& json_obj, const std::shared_ptr<Schema>& schema,
                       MemoryPool* pool, std::shared_ptr<RecordBatch>* batch) {
  DCHECK(json_obj.IsObject());
  const auto& batch_obj = json_obj.GetObject();

  auto it = batch_obj.FindMember("count");
  RETURN_NOT_INT("count", it, batch_obj);
  int32_t num_rows = static_cast<int32_t>(it->value.GetInt());

  it = batch_obj.FindMember("columns");
  RETURN_NOT_ARRAY("columns", it, batch_obj);
  const auto& json_columns = it->value.GetArray();

  std::vector<std::shared_ptr<Array>> columns(json_columns.Size());
  for (int i = 0; i < static_cast<int>(columns.size()); ++i) {
    const std::shared_ptr<DataType>& type = schema->field(i)->type();
    RETURN_NOT_OK(ReadArray(pool, json_columns[i], type, &columns[i]));
  }

  *batch = std::make_shared<RecordBatch>(schema, num_rows, columns);
  return Status::OK();
}

Status WriteRecordBatch(const RecordBatch& batch, RjWriter* writer) {
  writer->StartObject();
  writer->Key("count");
  writer->Int(static_cast<int32_t>(batch.num_rows()));

  writer->Key("columns");
  writer->StartArray();

  for (int i = 0; i < batch.num_columns(); ++i) {
    const std::shared_ptr<Array>& column = batch.column(i);

    DCHECK_EQ(batch.num_rows(), column->length())
        << "Array length did not match record batch length";

    RETURN_NOT_OK(WriteArray(batch.column_name(i), *column, writer));
  }

  writer->EndArray();
  writer->EndObject();
  return Status::OK();
}

Status WriteArray(const std::string& name, const Array& array, RjWriter* json_writer) {
  ArrayWriter converter(name, array, json_writer);
  return converter.Write();
}

Status ReadArray(MemoryPool* pool, const rj::Value& json_array,
                 const std::shared_ptr<DataType>& type, std::shared_ptr<Array>* array) {
  ArrayReader converter(json_array, type, pool);
  return converter.GetArray(array);
}

Status ReadArray(MemoryPool* pool, const rj::Value& json_array, const Schema& schema,
                 std::shared_ptr<Array>* array) {
  if (!json_array.IsObject()) {
    return Status::Invalid("Element was not a JSON object");
  }

  const auto& json_obj = json_array.GetObject();

  const auto& it_name = json_obj.FindMember("name");
  RETURN_NOT_STRING("name", it_name, json_obj);

  std::string name = it_name->value.GetString();

  std::shared_ptr<Field> result = nullptr;
  for (const std::shared_ptr<Field>& field : schema.fields()) {
    if (field->name() == name) {
      result = field;
      break;
    }
  }

  if (result == nullptr) {
    std::stringstream ss;
    ss << "Field named " << name << " not found in schema";
    return Status::KeyError(ss.str());
  }

  return ReadArray(pool, json_array, result->type(), array);
}

}  // namespace internal
}  // namespace json
}  // namespace ipc
}  // namespace arrow


text:
[instagram-private-api](../../README.md) / [feeds](../../modules/feeds.md) / AccountFollowingFeed

# Class: AccountFollowingFeed

[feeds](../../modules/feeds.md).AccountFollowingFeed

## Hierarchy

- [`Feed`](../index/Feed.md)<[`AccountFollowingFeedResponse`](../../interfaces/responses/AccountFollowingFeedResponse.md), [`AccountFollowingFeedResponseUsersItem`](../responses/AccountFollowingFeedResponseUsersItem.md)\>

  ↳ **`AccountFollowingFeed`**

## Table of contents

### Constructors

- [constructor](AccountFollowingFeed.md#constructor)

### Properties

- [attemptOptions](AccountFollowingFeed.md#attemptoptions)
- [enableGroups](AccountFollowingFeed.md#enablegroups)
- [id](AccountFollowingFeed.md#id)
- [includesHashtags](AccountFollowingFeed.md#includeshashtags)
- [nextMaxId](AccountFollowingFeed.md#nextmaxid)
- [order](AccountFollowingFeed.md#order)
- [query](AccountFollowingFeed.md#query)
- [searchSurface](AccountFollowingFeed.md#searchsurface)

### Accessors

- [items$](AccountFollowingFeed.md#items$)
- [state](AccountFollowingFeed.md#state)

### Methods

- [deserialize](AccountFollowingFeed.md#deserialize)
- [isMoreAvailable](AccountFollowingFeed.md#ismoreavailable)
- [items](AccountFollowingFeed.md#items)
- [observable](AccountFollowingFeed.md#observable)
- [request](AccountFollowingFeed.md#request)
- [serialize](AccountFollowingFeed.md#serialize)
- [toPlain](AccountFollowingFeed.md#toplain)

## Constructors

### constructor

• **new AccountFollowingFeed**(`client`)

#### Parameters

| Name | Type |
| :------ | :------ |
| `client` | [`IgApiClient`](../index/IgApiClient.md) |

#### Inherited from

[Feed](../index/Feed.md).[constructor](../index/Feed.md#constructor)

#### Defined in

[src/core/repository.ts:7](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/core/repository.ts#L7)

## Properties

### attemptOptions

• **attemptOptions**: `Partial`<`AttemptOptions`<`any`\>\>

#### Inherited from

[Feed](../index/Feed.md).[attemptOptions](../index/Feed.md#attemptoptions)

#### Defined in

[src/core/feed.ts:10](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/core/feed.ts#L10)

___

### enableGroups

• **enableGroups**: `boolean` = `true`

#### Defined in

[src/feeds/account-following.feed.ts:9](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/feeds/account-following.feed.ts#L9)

___

### id

• **id**: `string` \| `number`

#### Defined in

[src/feeds/account-following.feed.ts:12](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/feeds/account-following.feed.ts#L12)

___

### includesHashtags

• **includesHashtags**: `boolean` = `true`

#### Defined in

[src/feeds/account-following.feed.ts:10](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/feeds/account-following.feed.ts#L10)

___

### nextMaxId

• **nextMaxId**: `string`

#### Defined in

[src/feeds/account-following.feed.ts:14](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/feeds/account-following.feed.ts#L14)

___

### order

• `Optional` **order**: ``"default"`` \| ``"date_followed_latest"`` \| ``"date_followed_earliest"`` = `'default'`

#### Defined in

[src/feeds/account-following.feed.ts:7](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/feeds/account-following.feed.ts#L7)

___

### query

• **query**: `string` = `''`

#### Defined in

[src/feeds/account-following.feed.ts:8](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/feeds/account-following.feed.ts#L8)

___

### searchSurface

• `Optional` **searchSurface**: `string`

#### Defined in

[src/feeds/account-following.feed.ts:6](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/feeds/account-following.feed.ts#L6)

## Accessors

### items$

• `get` **items$**(): `Observable`<`Item`[]\>

#### Returns

`Observable`<`Item`[]\>

#### Defined in

[src/core/feed.ts:18](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/core/feed.ts#L18)

___

### state

• `set` **state**(`body`): `void`

#### Parameters

| Name | Type |
| :------ | :------ |
| `body` | [`AccountFollowingFeedResponse`](../../interfaces/responses/AccountFollowingFeedResponse.md) |

#### Returns

`void`

#### Defined in

[src/feeds/account-following.feed.ts:16](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/feeds/account-following.feed.ts#L16)

## Methods

### deserialize

▸ **deserialize**(`data`): `void`

#### Parameters

| Name | Type |
| :------ | :------ |
| `data` | `string` |

#### Returns

`void`

#### Inherited from

[Feed](../index/Feed.md).[deserialize](../index/Feed.md#deserialize)

#### Defined in

[src/core/feed.ts:79](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/core/feed.ts#L79)

___

### isMoreAvailable

▸ **isMoreAvailable**(): `boolean`

#### Returns

`boolean`

#### Inherited from

[Feed](../index/Feed.md).[isMoreAvailable](../index/Feed.md#ismoreavailable)

#### Defined in

[src/core/feed.ts:87](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/core/feed.ts#L87)

___

### items

▸ **items**(): `Promise`<[`AccountFollowingFeedResponseUsersItem`](../responses/AccountFollowingFeedResponseUsersItem.md)[]\>

#### Returns

`Promise`<[`AccountFollowingFeedResponseUsersItem`](../responses/AccountFollowingFeedResponseUsersItem.md)[]\>

#### Overrides

[Feed](../index/Feed.md).[items](../index/Feed.md#items)

#### Defined in

[src/feeds/account-following.feed.ts:38](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/feeds/account-following.feed.ts#L38)

___

### observable

▸ **observable**(`semaphore?`, `attemptOptions?`): `Observable`<[`AccountFollowingFeedResponseUsersItem`](../responses/AccountFollowingFeedResponseUsersItem.md)[]\>

#### Parameters

| Name | Type |
| :------ | :------ |
| `semaphore?` | () => `Promise`<`any`\> |
| `attemptOptions?` | `Partial`<`AttemptOptions`<`any`\>\> |

#### Returns

`Observable`<[`AccountFollowingFeedResponseUsersItem`](../responses/AccountFollowingFeedResponseUsersItem.md)[]\>

#### Inherited from

[Feed](../index/Feed.md).[observable](../index/Feed.md#observable)

#### Defined in

[src/core/feed.ts:21](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/core/feed.ts#L21)

___

### request

▸ **request**(): `Promise`<[`AccountFollowingFeedResponse`](../../interfaces/responses/AccountFollowingFeedResponse.md)\>

#### Returns

`Promise`<[`AccountFollowingFeedResponse`](../../interfaces/responses/AccountFollowingFeedResponse.md)\>

#### Overrides

[Feed](../index/Feed.md).[request](../index/Feed.md#request)

#### Defined in

[src/feeds/account-following.feed.ts:21](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/feeds/account-following.feed.ts#L21)

___

### serialize

▸ **serialize**(): `string`

#### Returns

`string`

#### Inherited from

[Feed](../index/Feed.md).[serialize](../index/Feed.md#serialize)

#### Defined in

[src/core/feed.ts:75](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/core/feed.ts#L75)

___

### toPlain

▸ **toPlain**(): `Record`<`string`, `any`\>

#### Returns

`Record`<`string`, `any`\>

#### Inherited from

[Feed](../index/Feed.md).[toPlain](../index/Feed.md#toplain)

#### Defined in

[src/core/feed.ts:83](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/core/feed.ts#L83)


text:
//
//  DTViewController.m
//  DTBeaconExample
//

#import "DTBeacon.h"

#import "DTViewController.h"

@interface DTViewController()

- (void)_proximityNotification:(NSNotification*)notification;

@property(nonatomic, strong) IBOutlet UILabel *proximityLabel;

@end

@implementation DTViewController

@synthesize proximityLabel;

#pragma mark - LIFECYCLE

- (void)viewDidLoad {

    /* subscribe to the proximity notification */
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_proximityNotification:)
                                                 name:kBeaconProximityNotification
                                               object:nil];

    /* initialise region detection */
    [[DTBeacon alloc] initRegion];

    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - NOTIFICATION

- (void)_proximityNotification:(NSNotification*)notification {

    NSDictionary *d        = [notification userInfo];
    NSInteger    proximity = [[d objectForKey:kBeaconProximityKey] integerValue];

    if(proximity == CLProximityUnknown) {
        self.proximityLabel.text = @"Unknown Proximity";

    } else if(proximity == CLProximityImmediate) {
        self.proximityLabel.text = @"Immediate";

    } else if(proximity == CLProximityNear) {
        self.proximityLabel.text = @"Near";

    } else if(proximity == CLProximityFar) {

        self.proximityLabel.text = @"Far";
    }
}

@end


text:
package ru.job4j.httpprotocol;

import java.util.Date;

/**
 * Class ru.job4j.httpprotocol.
 *
 * @author edzabarov
 * @since 28.07.2018
 */
public class User {
    private int id;
    private String name;
    private String login;
    private String password;
    private String role;
    private String email;
    private Date createDate;

    public User(int id, String name, String login, String password, String role, String email, Date createDate) {
        this.id = id;
        this.name = name;
        this.login = login;
        this.password = password;
        this.role = role;
        this.email = email;
        this.createDate = createDate;
    }

    public User(String name, String password, String role) {
        this(name.hashCode(), name, name, password, role, "no", new Date());
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getLogin() {
        return login;
    }

    public String getPassword() {
        return password;
    }

    public String getRole() {
        return role;
    }

    public String getEmail() {
        return email;
    }

    public Date getCreateDate() {
        return createDate;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (id != user.id) return false;
        if (!name.equals(user.name)) return false;
        return login.equals(user.login);
    }

    @Override
    public int hashCode() {
        return id;
    }

    @Override
    public String toString() {
        return String.format("%s %s %s %s %s", id, name, login, email, createDate);
    }
}


text:
int threads_tests();

#endif //EVOLUTION_THREADTESTS_H


text:
layout: "docs"
page_title: "Gossip and RPC Encryption"
sidebar_current: "docs-agent-encryption"
description: |-
  Learn how to configure Nomad to encrypt HTTP, RPC, and Serf traffic.
---

# Encryption

The Nomad agent supports encrypting all of its network traffic. There are
two separate encryption systems, one for gossip traffic, and one for HTTP and
RPC.

## Gossip

Enabling gossip encryption only requires that you set an encryption key when
starting the Nomad server. The key can be set via the
[`encrypt`](/docs/agent/configuration/server.html#encrypt) parameter: the value
of this setting is a server configuration file containing the encryption key.

The key must be 16-bytes, base64 encoded. As a convenience, Nomad provides the
[`nomad keygen`](/docs/commands/keygen.html) command to generate a cryptographically suitable key:

```sh
$ nomad keygen
cg8StVXbQJ0gPvMd9o7yrg==
```

With that key, you can enable gossip encryption on the agent.

## HTTP, RPC, and Raft Encryption with TLS

Nomad supports using TLS to verify the authenticity of servers and clients. To
enable this, Nomad requires that all clients and servers have key pairs that are
generated and signed by a Certificate Authority. This can be a private CA.

TLS can be used to verify the authenticity of the servers and clients. The
configuration option [`verify_server_hostname`][tls] causes Nomad to verify that
a certificate is provided that is signed by the Certificate Authority from the
[`ca_file`][tls] for TLS connections.

If `verify_server_hostname` is set, then outgoing connections perform
hostname verification. Unlike traditional HTTPS browser validation, all servers
must have a certificate valid for `server.<region>.nomad` or the client will
reject the handshake. It is also recommended for the certificate to sign
`localhost` such that the CLI can validate the server name.

TLS is used to secure the RPC calls between agents, but gossip between nodes is
done over UDP and is secured using a symmetric key. See above for enabling
gossip encryption.

## Encryption Examples

### TLS Configuration using `cfssl`

While [Vault's PKI backend][vault] is an ideal solution for managing
certificates and other secrets in a production environment, it's useful to use
simpler command line tools when learning how to configure TLS and your [PKI].

[`cfssl`][cfssl] is a tool for working with TLS certificates and certificate
authorities similar to [OpenSSL's][openssl] `x509` command line tool.

Once you have the `cfssl` command line tool installed, the first step to
setting up TLS is to create a Certificate Authority (CA) certificate.  The
following command will generate a suitable example CA CSR, certificate, and
key:

```shell
# Run in the directory where you want to store certificates
$ cfssl print-defaults csr | cfssl gencert -initca - | cfssljson -bare ca
```

Next create a `nomad-csr.json` which contains the configuration for the actual
certificate you'll be using in Nomad:

```json
{
  "CN": "global.nomad",
  "hosts": [
    "server.global.nomad",
    "client.global.nomad",
    "localhost"
  ]
}
```

This will create a certificate suitable for both clients and servers in the
`global` (default) region.

In production Nomad agents should have a certificate valid for the name
`${ROLE}.${REGION}.nomad` where role is either `client` or `server` depending
on the node's role.

Create a certificate signed by your CA:

```shell
$ cfssl gencert -ca ca.pem -ca-key ca-key.pem nomad-csr.json | cfssljson -bare nomad
```

You've now successfully generated self-signed certificates! You should see the
following files:

- `ca.pem` - the CA certificate. This corresponds to the Nomad `ca_file`
  parameter in the Nomad [`tls` stanza][tls].

- `ca-key.pem` - the CA private key. This is used to sign CSRs and should
  **not** be included in the Nomad [`tls` stanza][tls].

- `nomad.pem` - the Nomad certificate for the region. This corresponds to the
  `cert_file` parameter in the Nomad [`tls` stanza][tls].

- `nomad-key.pem` - the Nomad private key. This corresponds to the `key_file`
  parameter in the Nomad [`tls` stanza][tls].

- `*.csr` - the certificate signing request. This is temporary for generating
  certificates and should **not** be included in the Nomad [`tls` stanza][tls].

In your Nomad configuration add the `tls` stanza:

```hcl
tls {
  http = true
  rpc  = true

  ca_file   = "ca.pem"
  cert_file = "nomad.pem"
  key_file  = "nomad-key.pem"

  verify_server_hostname = true
}
```

[vault]: https://www.vaultproject.io/docs/secrets/pki/
[PKI]: https://en.wikipedia.org/wiki/Public_key_infrastructure
[cfssl]: https://cfssl.org/
[openssl]: https://www.openssl.org/
[tls]: /docs/agent/configuration/tls.html "Nomad TLS Configuration"


text:
require.def(
    "antie/devices/mediaplayer/html5seekfinishedemitevent",
    [
        "antie/devices/mediaplayer/seekfinishedemitevent",
        "antie/devices/mediaplayer/html5"
    ],
    function (SeekFinishedEmitEvent, HTML5) {
        "use strict";

        SeekFinishedEmitEvent(HTML5);

        return HTML5;
    }
);


text:
namespace System.Diagnostics
{
	public class ConsoleTimeLogger : TimeLogger
	{
		public static ConsoleTimeLogger Start(string taskTitle)
		{
			return new ConsoleTimeLogger(taskTitle);
		}

		public ConsoleTimeLogger(string taskTitle)
			: base(
				taskTitle,
				x => Console.WriteLine(x.FormatedTime)
			)
		{
		}
	}
}


text:
<?php
/**
 * Elgg OpenDD import action.
 *
 * This action accepts data to import (in OpenDD format) and performs and import. It accepts
 * data as $data.
 *
 * @package Elgg
 * @subpackage Core
 * @deprecated 1.9
 */

$data = get_input('data', '', false);

$return = import($data);

if ($return) {
	system_message(elgg_echo('importsuccess'));
} else {
	register_error(elgg_echo('importfail'));
}

forward(REFERER);


text:
import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { MaterialModule } from '@angular/material';
import 'hammerjs';

@NgModule({
  imports:[
       CommonModule,
       MaterialModule.forRoot()
   ],
  declarations: [
       //TopNavBar,
   ],
  exports:      [],
  providers:    [ ]
})
export class CoreModule {
}


text:
      {{ address.first_name }} {{ address.last_name }}

{{ address.address_line_1 }}

{{ address.address_line_2 }}

        {{ address.city }} - {{ address.zip_code }}

{{ address?.state?.name }}

{{ address.country.name }}

          Mobile:
          {{ address.phone }}

        •
        Cash/Card on Delivery available

        •
        Standard Delivery available


text:
<?php
error_reporting(E_ALL);
date_default_timezone_set('Europe/Prague');

define('FUNCTIONAL_ORCHESTRATOR_API_URL', getenv('ORCHESTRATOR_API_URL'));
define('FUNCTIONAL_ORCHESTRATOR_API_TOKEN', getenv('ORCHESTRATOR_API_TOKEN'));
define('FUNCTIONAL_ERROR_NOTIFICATION_EMAIL', getenv('ERROR_NOTIFICATION_EMAIL'));

require __DIR__ . '/../vendor/autoload.php';


text:
require 'octokit'
require 'sinatra'
require 'sinatra_auth_github'
require 'dotenv'
require 'json'
require 'active_support'
require 'active_support/core_ext/string'
require 'problem_child/version'
require 'problem_child/helpers'

module ProblemChild
  def self.root
    File.expand_path './problem_child', File.dirname(__FILE__)
  end

  def self.views_dir
    @views_dir ||= File.expand_path 'views', ProblemChild.root
  end

  def self.views_dir=(dir)
    @views_dir = dir
  end

  def self.public_dir
    @public_dir ||= File.expand_path 'public', ProblemChild.root
  end

  def self.public_dir=(dir)
    @public_dir = dir
  end

  class App < Sinatra::Base
    include ProblemChild::Helpers

    set :github_options, scopes: 'repo,read:org'

    use Rack::Session::Cookie, http_only: true,
                               secret:    ENV['SESSION_SECRET'] || SecureRandom.hex

    configure :production do
      require 'rack-ssl-enforcer'
      use Rack::SslEnforcer
    end

    ENV['WARDEN_GITHUB_VERIFIER_SECRET'] ||= SecureRandom.hex
    register Sinatra::Auth::Github

    set :views, (proc { ProblemChild.views_dir })
    set :root,  (proc { ProblemChild.root })
    set :public_folder, (proc { ProblemChild.public_dir })

    get '/' do
      flash = nil
      issue = nil
      access = false

      auth!

      halt erb :form, layout: :layout, locals: { repo: repo, anonymous: anonymous_submissions?, flash: flash, issue: issue, access: access }
    end

    post '/' do
      auth! unless anonymous_submissions?

      if issue_title.empty?
        flash = 'Please enter a title.'
      else
        issue = uploads.empty? ? create_issue : create_pull_request
        session[:form_data] = nil
        access = repo_access?
      end

      halt erb :form, layout: :layout, locals: { repo: repo, anonymous: anonymous_submissions?, flash: flash, issue: issue, access: access }
    end
  end
end

Dotenv.load unless ProblemChild::App.production?


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.vaadin</groupId>
	<artifactId>diagram-builder-root</artifactId>
	<packaging>pom</packaging>
	<version>1.3-SNAPSHOT</version>
	<name>DiagramBuilder Add-on Root Project</name>

	<modules>
		<module>diagram-builder</module>
		<module>diagram-builder-demo</module>
	</modules>

</project>


text:
package com.github.onsdigital.data;

import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Created by thomasridd on 19/03/15.
 */
public class DataFuture {
    public String name;
    public String source;

    public HashMap<String, Future<TimeSeriesObject>> timeSeries = new HashMap<>();

    public void addSeries(String taxi, Future<TimeSeriesObject> series) {
        timeSeries.put(taxi, series);
    }

    public TimeSeriesObject getSeries(String taxi)  {
        try {
            return timeSeries.get(taxi).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}