text:
import numpy as np
from scipy.linalg import eigh_tridiagonal

NODE_TYPES = ['EQUID', 'LEGENDRE', 'CHEBY-1', 'CHEBY-2', 'CHEBY-3', 'CHEBY-4']

QUAD_TYPES = ['GAUSS', 'RADAU-LEFT', 'RADAU-RIGHT', 'LOBATTO']

class NodesError(Exception):
    """Exception class to handle error in NodesGenerator class"""

    pass

class NodesGenerator(object):
    """
    Class that can be used to generate generic distribution of nodes derived
    from Gauss quadrature rule.
    Its implementation is fully inspired from a `book of W. Gautschi <https://doi.org/10.1093/oso/9780198506720.001.0001>`_.

    Attributes
    ----------
    node_type : str
        The type of node distribution
    quad_type : str
        The quadrature type

    """

    def __init__(self, node_type='LEGENDRE', quad_type='LOBATTO'):
        """

        Parameters
        ----------
        node_type : str, optional
            The type of node distribution, can be

            - EQUID : equidistant nodes
            - LEGENDRE : node distribution from Legendre polynomials
            - CHEBY-1 : node distribution from Chebychev polynomials (1st kind)
            - CHEBY-2 : node distribution from Chebychev polynomials (2nd kind)
            - CHEBY-3 : node distribution from Chebychev polynomials (3rd kind)
            - CHEBY-4 : node distribution from Chebychev polynomials (4th kind)

            The default is 'LEGENDRE'.

        quad_type : str, optional
            The quadrature type, can be

            - GAUSS : inner point only, no node at boundary
            - RADAU-LEFT : only left boundary as node
            - RADAU-RIGHT : only right boundary as node
            - LOBATTO : left and right boundary as node

            The default is 'LOBATTO'.
        """

        # Check argument validity
        for arg, vals in zip(['node_type', 'quad_type'], [NODE_TYPES, QUAD_TYPES]):
            val = eval(arg)
            if val not in vals:
                raise NodesError(f"{arg}='{val}' not implemented, must be in {vals}")

        # Store attributes
        self.node_type = node_type
        self.quad_type = quad_type

    def getNodes(self, num_nodes):
        """
        Computes a given number of quadrature nodes.

        Parameters
        ----------
        num_nodes : int
            Number of nodes to compute.

        Returns
        -------
        nodes : np.1darray
            Nodes located in [-1, 1], in increasing order.
        """
        # Check number of nodes
        if self.quad_type in ['LOBATTO', 'RADAU-LEFT'] and num_nodes < 2:
            raise NodesError(f"num_nodes must be larger than 2 for {self.quad_type}, " f"but for {num_nodes}")
        elif num_nodes < 1:
            raise NodesError("you surely want at least one node ;)")

        # Equidistant nodes
        if self.node_type == 'EQUID':
            if self.quad_type == 'GAUSS':
                return np.linspace(-1, 1, num=num_nodes + 2)[1:-1]
            elif self.quad_type == 'LOBATTO':
                return np.linspace(-1, 1, num=num_nodes)
            elif self.quad_type == 'RADAU-RIGHT':
                return np.linspace(-1, 1, num=num_nodes + 1)[1:]
            elif self.quad_type == 'RADAU-LEFT':
                return np.linspace(-1, 1, num=num_nodes + 1)[:-1]

        # Quadrature nodes linked to orthogonal polynomials
        alpha, beta = self.getTridiagCoefficients(num_nodes)
        nodes = eigh_tridiagonal(alpha, np.sqrt(beta[1:]))[0]
        nodes.sort()

        return nodes

    def getOrthogPolyCoefficients(self, num_coeff):
        """
        Produces a given number of analytic three-term recurrence coefficients.

        Parameters
        ----------
        num_coeff : int
            Number of coefficients to compute.

        Returns
        -------
        alpha : np.1darray
            The alpha coefficients of the three-term recurrence.
        beta : np.1darray
            The beta coefficients of the three-term recurrence.
        """
        if self.node_type == 'LEGENDRE':
            k = np.arange(num_coeff, dtype=float)
            alpha = 0 * k
            beta = k**2 / (4 * k**2 - 1)
            beta[0] = 2
        elif self.node_type == 'CHEBY-1':
            alpha = np.zeros(num_coeff)
            beta = np.full(num_coeff, 0.25)
            beta[0] = np.pi
            if num_coeff > 1:
                beta[1] = 0.5
        elif self.node_type == 'CHEBY-2':
            alpha = np.zeros(num_coeff)
            beta = np.full(num_coeff, 0.25)
            beta[0] = np.pi / 2
        elif self.node_type == 'CHEBY-3':
            alpha = np.zeros(num_coeff)
            alpha[0] = 0.5
            beta = np.full(num_coeff, 0.25)
            beta[0] = np.pi
        elif self.node_type == 'CHEBY-4':
            alpha = np.zeros(num_coeff)
            alpha[0] = -0.5
            beta = np.full(num_coeff, 0.25)
            beta[0] = np.pi
        return alpha, beta

    def evalOrthogPoly(self, t, alpha, beta):
        """
        Evaluates the two higher order orthogonal polynomials corresponding
        to the given (alpha,beta) coefficients.

        Parameters
        ----------
        t : float or np.1darray
            The point where to evaluate the orthogonal polynomials.
        alpha : np.1darray
            The alpha coefficients of the three-term recurrence.
        beta : np.1darray
            The beta coefficients of the three-term recurrence.

        Returns
        -------
        pi[0] : float or np.1darray
            The second higher order orthogonal polynomial evaluation.
        pi[1] : float or np.1darray
            The higher oder orthogonal polynomial evaluation.
        """
        t = np.asarray(t, dtype=float)
        pi = np.array([np.zeros_like(t) for i in range(3)])
        pi[1:] += 1
        for alpha_j, beta_j in zip(alpha, beta):
            pi[2] *= t - alpha_j
            pi[0] *= beta_j
            pi[2] -= pi[0]
            pi[0] = pi[1]
            pi[1] = pi[2]
        return pi[0], pi[1]

    def getTridiagCoefficients(self, num_nodes):
        """
        Computes recurrence coefficients for the tridiagonal Jacobian matrix,
        taking into account the quadrature type.

        Parameters
        ----------
        num_nodes : int
            Number of nodes that should be computed from those coefficients.

        Returns
        -------
        alpha : np.1darray
            The modified alpha coefficients of the three-term recurrence.
        beta : np.1darray
            The modified beta coefficients of the three-term recurrence.
        """
        # Coefficients for Gauss quadrature type
        alpha, beta = self.getOrthogPolyCoefficients(num_nodes)

        # If not Gauss quadrature type, modify the alpha/beta coefficients
        if self.quad_type.startswith('RADAU'):
            b = -1.0 if self.quad_type.endswith('LEFT') else 1.0
            b1, b2 = self.evalOrthogPoly(b, alpha[:-1], beta[:-1])[:2]
            alpha[-1] = b - beta[-1] * b1 / b2
        elif self.quad_type == 'LOBATTO':
            a, b = -1.0, 1.0
            a2, a1 = self.evalOrthogPoly(a, alpha[:-1], beta[:-1])[:2]
            b2, b1 = self.evalOrthogPoly(b, alpha[:-1], beta[:-1])[:2]
            alpha[-1], beta[-1] = np.linalg.solve([[a1, a2], [b1, b2]], [a * a1, b * b1])
        return alpha, beta


text:
// <copyright file="EngineManager.cs" company="Kuub Studios">
// Copyright (c) Kuub Studios. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>

using System;
using System.IO;
using NLog;
using OpenTK;

namespace KuubEngine.Core
{
    /// <summary>
    /// Helper class to start game instances
    /// </summary>
    public static class EngineManager
    {
        private static Logger log = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// Starts a new game instance and runs it
        /// </summary>
        /// <typeparam name="T"><see cref="Game"/> to start</typeparam>
        /// <param name="args">Command line arguments</param>
        /// <param name="catchErrors">Catch unhandled exceptions and show the crash reporter</param>
        public static void Start<T>(string[] args, bool catchErrors = true) where T : Game, new()
        {
            if (catchErrors)
            {
                AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
                {
                    log.Fatal((Exception)eventArgs.ExceptionObject, "Unhandled exception in game");
                    File.WriteAllText("crash.txt", eventArgs.ExceptionObject.ToString());
                    Environment.Exit(1);
                };
            }

            using (Toolkit.Init())
            {
                using (T game = new T())
                {
                    game.Run(args);
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import {Model}                from 'arva-ds/core/Model';

export default class Invite extends Model {

    /**
     * received from
     */
    get player1() { }

    /**
     * received from
     */
    get player2() { }

}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>Module Hierarchy</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

[hide private]

[frames] | no frames]

 [ Module Hierarchy
 | Class Hierarchy ]

Module Hierarchy

 csbuild: CSBuild main module

 csbuild._shared_globals: Defines shared globals used by the application.

 csbuild.log: Logging Module

 csbuild.projectSettings: ProjectSettings module

 csbuild.project_generator: Project Generator Module

 csbuild.project_generator_qtcreator

 csbuild.project_generator_slickedit

 csbuild.terminfo: Provides info about the terminal the makefile's being run in

 csbuild.toolchain: Toolchain Module

 csbuild.toolchain_android: Contains a plugin class for interfacing with GCC

 csbuild.toolchain_gcc: Contains a plugin class for interfacing with GCC

 csbuild.toolchain_msvc: Contains a plugin class for interfacing with MSVC

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Thu Apr 10 22:15:45 2014

      http://epydoc.sourceforge.net


text:
import React from 'react';

import legends from '../legends';

import Tag from './Tag';

const renderTags = (tags) => {
  // check if there is some tags
  if (tags.length === 0) return undefined;

  return tags.map((tag, i) => {
    let legend = (legends.indexOf(tag) !== -1);

    return <Tag legend={legend} index={i} tag={tag} />
  })

  // CODE FROM BEFORE REACT KEEPING AS A REMINDER THAT I GOT ADD IT BACK
  // add a click event for the tags
  // document.getElementById(('z' + z)).setAttribute('onclick', 'tag("'+ tagsArray[z] + '")');
}

const Tags = (props) => {
  return (
    <div className='tags'>
      {renderTags(props.quote.tags)}
    </div>
  )
}

export default Tags;


text:
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/cloud_viewer.h>
#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <pcl/point_types.h>

#define GLFW_NO_GLU

#include <GL/glew.h>
#include <GL/glfw.h>

#include "miroir_manager.h"
#include "gpu_manager.h"

#include <pcl/io/openni_grabber.h>
#include <pcl/io/oni_grabber.h>
//#ifdef _WIN32
//	#define sleep(x) Sleep((x)*1000)
//#endif

bool stop = false;
GLuint vao;
GLuint quad_vertexbuffer;

void GLFWCALL onWindowResized( int width, int height )
{
	MiroirManager::getSingleton().setWindowDimensions(width, height);
}

void keyboardCallback(const pcl::visualization::KeyboardEvent &evt, void *)
{
	if(evt.getKeySym() == "F1")
    {
		MiroirManager::setShowMode(DEPTH_MAP_RAW);
	}
	else if(evt.getKeySym() == "F2")
	{
		MiroirManager::setShowMode(DEPTH_MAP_BIL);
	}
	else if(evt.getKeySym() == "F3")
	{
		MiroirManager::setShowMode(TSDF);
	}
	else if(evt.getKeySym() == "F4")
	{
		MiroirManager::setShowMode(RAYCAST);
	}
	else if(evt.getKeySym() == "F5")
	{
		MiroirManager::setShowMode(CORRESP);
	}
	else if(evt.getKeySym() == "t" && evt.keyDown())
	{
		MiroirManager::setRunTSDF(!MiroirManager::isTSDFRunning());
	}
	else if(evt.getKeySym() == "a" && evt.keyDown())
	{
		//MiroirManager::setRunTSDF(!MiroirManager::isTSDFRunning());
	}
}

void GLFWCALL keyboardCallback(int key, int action)
{
	/*if(key == GLFW_KEY_F1)
    {
		MiroirManager::setShowMode(DEPTH_MAP);
	}
	else if(key == GLFW_KEY_F2)
	{
		MiroirManager::setShowMode(TSDF);
	}
	else if(key == GLFW_KEY_F3)
	{
		MiroirManager::setShowMode(RAYCAST);
	}*/

	if(key == 84 && action)	// t
    {
		MiroirManager::setRunTSDF(!MiroirManager::isTSDFRunning());
	}
}

void draw()
{
	glFinish();
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // Clear required buffers

	glBindVertexArray(vao);

	glDrawArrays(GL_TRIANGLES, 0, 6); // Starting from vertex 0; 3 vertices total -> 1 triangle

	glBindVertexArray(0);

	glfwSwapBuffers();
}

bool initGL()
{
	if(!glfwInit())
	{
		std::cerr << "Failed to initialize GLFW\n";
		return false;
	}

	glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); // 4x antialiasing
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); // We want OpenGL 3.3
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL
	glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
	// Open a window and create its OpenGL context
	if( !glfwOpenWindow( 640, 480, 0,0,0,0, 32,0, GLFW_WINDOW ) )
	{
		std::cerr <<  "Failed to open GLFW window\n";
		glfwTerminate();
		return false;
	}

	GLenum err = glGetError();
	assert(err == GL_NO_ERROR);

	glfwSetWindowTitle("MIROIR");
	glfwEnable( GLFW_STICKY_KEYS );
	glfwSetWindowSizeCallback( onWindowResized );
	glfwSetKeyCallback(keyboardCallback);
	err = glGetError();
	assert(err == GL_NO_ERROR);

	glewExperimental = GL_TRUE;
	if(glewInit() != GLEW_OK)
	{
		std::cerr <<  "Failed to open GLEW\n";
		return false;
	}
	glGetError();

	// background color
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

	// fullscreen quad
	static const GLfloat g_quad_vertex_buffer_data[] = {
		-1.0f, -1.0f, 0.0f,
		1.0f, -1.0f, 0.0f,
		-1.0f,  1.0f, 0.0f,
		-1.0f,  1.0f, 0.0f,
		1.0f, -1.0f, 0.0f,
		1.0f,  1.0f, 0.0f,
	};

	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	glGenBuffers(1, &quad_vertexbuffer);
	glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW);
	glVertexAttribPointer(
	   0,                  // attribute 0. No particular reason for 0, but must match the layout in the shader.
	   3,                  // size
	   GL_FLOAT,           // type
	   GL_FALSE,           // normalized?
	   0,                  // stride
	   (void*)0            // array buffer offset
	);

	glEnableVertexAttribArray(0); // Disable our Vertex Array Object
	glBindVertexArray(0); // Disable our Vertex Buffer Object

	// shaders
	GLuint vshader, fshader;
	GLuint program = GpuManager::createProgram("../src/Shaders/vert.glsl", "../src/Shaders/frag.glsl", vshader, fshader);

	glUseProgram(program);
	GLint texLoc = glGetUniformLocation(fshader, "texture");
	glUniform1i(texLoc, 0);	// TODO pass texture!

	int isValid;
	glValidateProgram(vshader);
	glGetProgramiv(vshader, GL_VALIDATE_STATUS, &isValid);
	assert(isValid);

	return true;
}

int main( int argc, char ** argv )
{
#ifdef MIROIR_GL_INTEROP
	if(!initGL())
		return -1;
#endif
	bool recompile_kernel = (argc == 2)&&(!strcmp(argv[1],"-kc"));

	GpuManager::initCL(recompile_kernel);

	MiroirManager& miroir = MiroirManager::getSingleton();

	miroir.initGlobalBuffers();
	miroir.buildMiroir();

#ifdef MIROIR_GL_INTEROP
	miroir.getGrabber()->start();
	do
	{
		draw();

		miroir.step();

	} while(glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS && glfwGetWindowParam( GLFW_OPENED ));

#else
	boost::thread miroir_t( &MiroirManager::run, &miroir );
	boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("MIROIR"));
	viewer->setBackgroundColor (0, 0, 0);
	viewer->addCoordinateSystem (1.0);
	viewer->initCameraParameters();

	viewer->registerKeyboardCallback(&keyboardCallback);
	viewer->setCameraPosition(0.0, 0.0, -1.0, 0.0, -1.0, 0.0);

	miroir.setWindowDimensions(640, 480);

	//camera visualization
	//viewer->addCube(-0.05, 0.05, -0.05, 0.05, -0.05, 0.05);

	while(!viewer->wasStopped() || (glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS && glfwGetWindowParam( GLFW_OPENED )))
	{
		pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr cloud = miroir.getOutputCloud();
		if( cloud != NULL )
		{
			//viewer.showCloud(cloud);
			if(!viewer->updatePointCloud(cloud))
			{
				viewer->addPointCloud(cloud);
				viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1);
			}
			viewer->spinOnce (100);
		}

		cl_float4* camPose = miroir.getCameraPose();
		//viewer->addCube(camPose[3].s[0]*0.001-0.05, camPose[3].s[0]*0.001+0.05, camPose[3].s[1]*0.001-0.05, camPose[3].s[1]*0.001+0.05, camPose[3].s[2]*0.001-0.05, camPose[3].s[2]*0.001+0.05);

		pcl::ModelCoefficients coeffs;
		// translation
		coeffs.values.push_back (camPose[3].s[0]*0.001);
		coeffs.values.push_back (camPose[3].s[1]*0.001);
		coeffs.values.push_back (camPose[3].s[2]*0.001);
		// rotation
		float b1 = 0.5f * std::sqrt(1.0f + camPose[0].s[0] + camPose[1].s[1] + camPose[2].s[2]);
		coeffs.values.push_back (b1);
		coeffs.values.push_back ((camPose[2].s[1] - camPose[1].s[2]) / (4.0f*b1));
		coeffs.values.push_back ((camPose[0].s[2] - camPose[2].s[0]) / (4.0f*b1));
		coeffs.values.push_back ((camPose[1].s[0] - camPose[0].s[1]) / (4.0f*b1));
		// size
		coeffs.values.push_back (0.05);
		coeffs.values.push_back (0.05);
		coeffs.values.push_back (0.05);
		viewer->removeShape ("cube");
		viewer->addCube (coeffs, "cube");
		//boost::this_thread::sleep (boost::posix_time::microseconds (100000));
		//sleep(1);
	}

	MiroirManager::stop();
	miroir_t.join();
#endif

	GpuManager::cleanCL();

	return 0;
}


text:
<?php

namespace AntiMattr\ETL\Extract\MongoDB;

/**
 * @author Matthew Fitzgerald <matthewfitz@gmail.com>
 */
class PDOMaximumColumnEmbedManyExtractor extends PDOMaximumColumnExtractor
{
    /** @var string */
    protected $embedManyField;

    public function __construct(
        \MongoDB $db,
        $collection,
        $field,
        \PDO $connection,
        $table,
        $column,
        $criteria = '',
        $defaultValue = null,
        array $projection = [],
        array $sort = [],
        $embedManyField,
        $batchSize = null,
        $timeout = 30000)
    {
        $this->collection = $collection;
        $this->column = $column;
        $this->connection = $connection;
        $this->criteria = $criteria;
        $this->db = $db;
        $this->defaultValue = $defaultValue;
        $this->field = $field;
        $this->projection = $projection;
        $this->sort = $sort;
        $this->table = $table;
        $this->embedManyField = $embedManyField;
        $this->timeout = $timeout;
        $this->batchIterator = new MongoDBEmbedManyBatchIterator($embedManyField, $batchSize);
    }

    /**
     * @return \Iterator
     */
    public function getIterator()
    {
        $sql = sprintf(
            "select max(%s) as 'minimum' from %s %s;",
            $this->column,
            $this->table,
            $this->criteria
        );
        $statement = $this->connection->query($sql);
        $collection = $this->db->{$this->collection};
        $minValue = $this->getMinimumValue($statement);
        $sort = (empty($this->sort)) ? [ $this->field => 1 ] : $this->sort;

        if ($minValue) {

            $fieldCriteria = [ '$gt' => $minValue ];
            $maxValue = $this->getMaximumValue($statement);
            if ($maxValue) {
                $fieldCriteria['$lte'] = $maxValue;
            }

            $cursor = $collection
                ->find([$this->field => $fieldCriteria ], $this->projection)
                ->sort($sort)
                ->timeout($this->timeout);
        } else {
            $cursor = $collection->find([], $this->projection)->sort($sort)->timeout($this->timeout);
        }

        $this->batchIterator->setInnerIterator($cursor);
        return $this->batchIterator;
    }
}


text:
package main

import (
	"fmt"

	"github.com/hashicorp/hcl2/ext/userfunc"
	"github.com/hashicorp/hcl2/gohcl"
	"github.com/hashicorp/hcl2/hcl"
	"github.com/hashicorp/hcl2/hcldec"
	"github.com/zclconf/go-cty/cty"
	"github.com/zclconf/go-cty/cty/function"
)

type specFileContent struct {
	Variables map[string]cty.Value
	Functions map[string]function.Function
	RootSpec  hcldec.Spec
}

var specCtx = &hcl.EvalContext{
	Functions: specFuncs,
}

func loadSpecFile(filename string) (specFileContent, hcl.Diagnostics) {
	file, diags := parser.ParseHCLFile(filename)
	if diags.HasErrors() {
		return specFileContent{RootSpec: errSpec}, diags
	}

	vars, funcs, specBody, declDiags := decodeSpecDecls(file.Body)
	diags = append(diags, declDiags...)

	spec, specDiags := decodeSpecRoot(specBody)
	diags = append(diags, specDiags...)

	return specFileContent{
		Variables: vars,
		Functions: funcs,
		RootSpec:  spec,
	}, diags
}

func decodeSpecDecls(body hcl.Body) (map[string]cty.Value, map[string]function.Function, hcl.Body, hcl.Diagnostics) {
	funcs, body, diags := userfunc.DecodeUserFunctions(body, "function", func() *hcl.EvalContext {
		return specCtx
	})

	content, body, moreDiags := body.PartialContent(&hcl.BodySchema{
		Blocks: []hcl.BlockHeaderSchema{
			{
				Type: "variables",
			},
		},
	})
	diags = append(diags, moreDiags...)

	vars := make(map[string]cty.Value)
	for _, block := range content.Blocks {
		// We only have one block type in our schema, so we can assume all
		// blocks are of that type.
		attrs, moreDiags := block.Body.JustAttributes()
		diags = append(diags, moreDiags...)

		for name, attr := range attrs {
			val, moreDiags := attr.Expr.Value(specCtx)
			diags = append(diags, moreDiags...)
			vars[name] = val
		}
	}

	return vars, funcs, body, diags
}

func decodeSpecRoot(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	content, diags := body.Content(specSchemaUnlabelled)

	if len(content.Blocks) == 0 {
		if diags.HasErrors() {
			// If we already have errors then they probably explain
			// why we have no blocks, so we'll skip our additional
			// error message added below.
			return errSpec, diags
		}

		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing spec block",
			Detail:   "A spec file must have exactly one root block specifying how to map to a JSON value.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	if len(content.Blocks) > 1 {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Extraneous spec block",
			Detail:   "A spec file must have exactly one root block specifying how to map to a JSON value.",
			Subject:  &content.Blocks[1].DefRange,
		})
		return errSpec, diags
	}

	spec, specDiags := decodeSpecBlock(content.Blocks[0])
	diags = append(diags, specDiags...)
	return spec, diags
}

func decodeSpecBlock(block *hcl.Block) (hcldec.Spec, hcl.Diagnostics) {
	var impliedName string
	if len(block.Labels) > 0 {
		impliedName = block.Labels[0]
	}

	switch block.Type {

	case "object":
		return decodeObjectSpec(block.Body)

	case "array":
		return decodeArraySpec(block.Body)

	case "attr":
		return decodeAttrSpec(block.Body, impliedName)

	case "block":
		return decodeBlockSpec(block.Body, impliedName)

	case "block_list":
		return decodeBlockListSpec(block.Body, impliedName)

	case "block_set":
		return decodeBlockSetSpec(block.Body, impliedName)

	case "block_map":
		return decodeBlockMapSpec(block.Body, impliedName)

	case "block_attrs":
		return decodeBlockAttrsSpec(block.Body, impliedName)

	case "default":
		return decodeDefaultSpec(block.Body)

	case "transform":
		return decodeTransformSpec(block.Body)

	case "literal":
		return decodeLiteralSpec(block.Body)

	default:
		// Should never happen, because the above cases should be exhaustive
		// for our schema.
		var diags hcl.Diagnostics
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Invalid spec block",
			Detail:   fmt.Sprintf("Blocks of type %q are not expected here.", block.Type),
			Subject:  &block.TypeRange,
		})
		return errSpec, diags
	}
}

func decodeObjectSpec(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	content, diags := body.Content(specSchemaLabelled)

	spec := make(hcldec.ObjectSpec)
	for _, block := range content.Blocks {
		propSpec, propDiags := decodeSpecBlock(block)
		diags = append(diags, propDiags...)
		spec[block.Labels[0]] = propSpec
	}

	return spec, diags
}

func decodeArraySpec(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	content, diags := body.Content(specSchemaUnlabelled)

	spec := make(hcldec.TupleSpec, 0, len(content.Blocks))
	for _, block := range content.Blocks {
		elemSpec, elemDiags := decodeSpecBlock(block)
		diags = append(diags, elemDiags...)
		spec = append(spec, elemSpec)
	}

	return spec, diags
}

func decodeAttrSpec(body hcl.Body, impliedName string) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		Name     *string        `hcl:"name"`
		Type     hcl.Expression `hcl:"type"`
		Required *bool          `hcl:"required"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.AttrSpec{
		Name: impliedName,
	}

	if args.Required != nil {
		spec.Required = *args.Required
	}
	if args.Name != nil {
		spec.Name = *args.Name
	}

	var typeDiags hcl.Diagnostics
	spec.Type, typeDiags = evalTypeExpr(args.Type)
	diags = append(diags, typeDiags...)

	if spec.Name == "" {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing name in attribute spec",
			Detail:   "The name attribute is required, to specify the attribute name that is expected in an input HCL file.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	return spec, diags
}

func decodeBlockSpec(body hcl.Body, impliedName string) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		TypeName *string  `hcl:"block_type"`
		Required *bool    `hcl:"required"`
		Nested   hcl.Body `hcl:",remain"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.BlockSpec{
		TypeName: impliedName,
	}

	if args.Required != nil {
		spec.Required = *args.Required
	}
	if args.TypeName != nil {
		spec.TypeName = *args.TypeName
	}

	nested, nestedDiags := decodeBlockNestedSpec(args.Nested)
	diags = append(diags, nestedDiags...)
	spec.Nested = nested

	return spec, diags
}

func decodeBlockListSpec(body hcl.Body, impliedName string) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		TypeName *string  `hcl:"block_type"`
		MinItems *int     `hcl:"min_items"`
		MaxItems *int     `hcl:"max_items"`
		Nested   hcl.Body `hcl:",remain"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.BlockListSpec{
		TypeName: impliedName,
	}

	if args.MinItems != nil {
		spec.MinItems = *args.MinItems
	}
	if args.MaxItems != nil {
		spec.MaxItems = *args.MaxItems
	}
	if args.TypeName != nil {
		spec.TypeName = *args.TypeName
	}

	nested, nestedDiags := decodeBlockNestedSpec(args.Nested)
	diags = append(diags, nestedDiags...)
	spec.Nested = nested

	if spec.TypeName == "" {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing block_type in block_list spec",
			Detail:   "The block_type attribute is required, to specify the block type name that is expected in an input HCL file.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	return spec, diags
}

func decodeBlockSetSpec(body hcl.Body, impliedName string) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		TypeName *string  `hcl:"block_type"`
		MinItems *int     `hcl:"min_items"`
		MaxItems *int     `hcl:"max_items"`
		Nested   hcl.Body `hcl:",remain"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.BlockSetSpec{
		TypeName: impliedName,
	}

	if args.MinItems != nil {
		spec.MinItems = *args.MinItems
	}
	if args.MaxItems != nil {
		spec.MaxItems = *args.MaxItems
	}
	if args.TypeName != nil {
		spec.TypeName = *args.TypeName
	}

	nested, nestedDiags := decodeBlockNestedSpec(args.Nested)
	diags = append(diags, nestedDiags...)
	spec.Nested = nested

	if spec.TypeName == "" {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing block_type in block_set spec",
			Detail:   "The block_type attribute is required, to specify the block type name that is expected in an input HCL file.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	return spec, diags
}

func decodeBlockMapSpec(body hcl.Body, impliedName string) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		TypeName *string  `hcl:"block_type"`
		Labels   []string `hcl:"labels"`
		Nested   hcl.Body `hcl:",remain"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.BlockMapSpec{
		TypeName: impliedName,
	}

	if args.TypeName != nil {
		spec.TypeName = *args.TypeName
	}
	spec.LabelNames = args.Labels

	nested, nestedDiags := decodeBlockNestedSpec(args.Nested)
	diags = append(diags, nestedDiags...)
	spec.Nested = nested

	if spec.TypeName == "" {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing block_type in block_map spec",
			Detail:   "The block_type attribute is required, to specify the block type name that is expected in an input HCL file.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}
	if len(spec.LabelNames) < 1 {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Invalid block label name list",
			Detail:   "A block_map must have at least one label specified.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	if hcldec.ImpliedType(spec).HasDynamicTypes() {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Invalid block_map spec",
			Detail:   "A block_map spec may not contain attributes with type 'any'.",
			Subject:  body.MissingItemRange().Ptr(),
		})
	}

	return spec, diags
}

func decodeBlockNestedSpec(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	content, diags := body.Content(specSchemaUnlabelled)

	if len(content.Blocks) == 0 {
		if diags.HasErrors() {
			// If we already have errors then they probably explain
			// why we have no blocks, so we'll skip our additional
			// error message added below.
			return errSpec, diags
		}

		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing spec block",
			Detail:   "A block spec must have exactly one child spec specifying how to decode block contents.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	if len(content.Blocks) > 1 {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Extraneous spec block",
			Detail:   "A block spec must have exactly one child spec specifying how to decode block contents.",
			Subject:  &content.Blocks[1].DefRange,
		})
		return errSpec, diags
	}

	spec, specDiags := decodeSpecBlock(content.Blocks[0])
	diags = append(diags, specDiags...)
	return spec, diags
}

func decodeBlockAttrsSpec(body hcl.Body, impliedName string) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		TypeName    *string        `hcl:"block_type"`
		ElementType hcl.Expression `hcl:"element_type"`
		Required    *bool          `hcl:"required"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.BlockAttrsSpec{
		TypeName: impliedName,
	}

	if args.Required != nil {
		spec.Required = *args.Required
	}
	if args.TypeName != nil {
		spec.TypeName = *args.TypeName
	}

	var typeDiags hcl.Diagnostics
	spec.ElementType, typeDiags = evalTypeExpr(args.ElementType)
	diags = append(diags, typeDiags...)

	if spec.TypeName == "" {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing block_type in block_attrs spec",
			Detail:   "The block_type attribute is required, to specify the block type name that is expected in an input HCL file.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	return spec, diags
}

func decodeLiteralSpec(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		Value cty.Value `hcl:"value"`
	}

	var args content
	diags := gohcl.DecodeBody(body, specCtx, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	return &hcldec.LiteralSpec{
		Value: args.Value,
	}, diags
}

func decodeDefaultSpec(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	content, diags := body.Content(specSchemaUnlabelled)

	if len(content.Blocks) == 0 {
		if diags.HasErrors() {
			// If we already have errors then they probably explain
			// why we have no blocks, so we'll skip our additional
			// error message added below.
			return errSpec, diags
		}

		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing spec block",
			Detail:   "A default block must have at least one nested spec, each specifying a possible outcome.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	if len(content.Blocks) == 1 && !diags.HasErrors() {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagWarning,
			Summary:  "Useless default block",
			Detail:   "A default block with only one spec is equivalent to using that spec alone.",
			Subject:  &content.Blocks[1].DefRange,
		})
	}

	var spec hcldec.Spec
	for _, block := range content.Blocks {
		candidateSpec, candidateDiags := decodeSpecBlock(block)
		diags = append(diags, candidateDiags...)
		if candidateDiags.HasErrors() {
			continue
		}

		if spec == nil {
			spec = candidateSpec
		} else {
			spec = &hcldec.DefaultSpec{
				Primary: spec,
				Default: candidateSpec,
			}
		}
	}

	return spec, diags
}

func decodeTransformSpec(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		Result hcl.Expression `hcl:"result"`
		Nested hcl.Body       `hcl:",remain"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.TransformExprSpec{
		Expr:         args.Result,
		VarName:      "nested",
		TransformCtx: specCtx,
	}

	nestedContent, nestedDiags := args.Nested.Content(specSchemaUnlabelled)
	diags = append(diags, nestedDiags...)

	if len(nestedContent.Blocks) != 1 {
		if nestedDiags.HasErrors() {
			// If we already have errors then they probably explain
			// why we have the wrong number of blocks, so we'll skip our
			// additional error message added below.
			return errSpec, diags
		}

		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Invalid transform spec",
			Detail:   "A transform spec block must have exactly one nested spec block.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	nestedSpec, nestedDiags := decodeSpecBlock(nestedContent.Blocks[0])
	diags = append(diags, nestedDiags...)
	spec.Wrapped = nestedSpec

	return spec, diags
}

var errSpec = &hcldec.LiteralSpec{
	Value: cty.NullVal(cty.DynamicPseudoType),
}

var specBlockTypes = []string{
	"object",
	"array",

	"literal",

	"attr",

	"block",
	"block_list",
	"block_map",
	"block_set",

	"default",
	"transform",
}

var specSchemaUnlabelled *hcl.BodySchema
var specSchemaLabelled *hcl.BodySchema

var specSchemaLabelledLabels = []string{"key"}

func init() {
	specSchemaLabelled = &hcl.BodySchema{
		Blocks: make([]hcl.BlockHeaderSchema, 0, len(specBlockTypes)),
	}
	specSchemaUnlabelled = &hcl.BodySchema{
		Blocks: make([]hcl.BlockHeaderSchema, 0, len(specBlockTypes)),
	}

	for _, name := range specBlockTypes {
		specSchemaLabelled.Blocks = append(
			specSchemaLabelled.Blocks,
			hcl.BlockHeaderSchema{
				Type:       name,
				LabelNames: specSchemaLabelledLabels,
			},
		)
		specSchemaUnlabelled.Blocks = append(
			specSchemaUnlabelled.Blocks,
			hcl.BlockHeaderSchema{
				Type: name,
			},
		)
	}
}


text:
import './RenameButton';
import './EditableText';


text:
You often need the script to work other way when it is executed from command line.
Imagine, you create an administrative tool to do its job when the system administrator
use it from his/her favorite terminal and you want it to be working from web browser with
a friendly GUI. You need to pass two argument to
[Phar::createDefaultStub()](http://php.net/manual/en/phar.createdefaultstub.php).
The first is the file which will run from command line and the second is the index file where
the browser will redirect to. It still let you load the cli version from the browser,
so you have to protect it yourself.

[code:index.php](index.php)

[code:src/cli-index.php](src/cli-index.php)

[code:src/web-index.php](src/web-index.php)

When you open it from the web browser (as web application), you will be redirected to
the web-index.php. In case you run it included in other script or from command line,
it shows you the output of phpinfo() (cli-index.php). Note that your cli-index.php
is not protected yet!


text:
<handler class="org.wso2.carbon.registry.extensions.handlers.ServiceMediaTypeHandler">
	<filter class="org.wso2.carbon.registry.core.jdbc.handlers.filters.MediaTypeMatcher">
		<property name="mediaType">application/vnd.wso2-service+xml</property>
	</filter>
</handler>


text:
#pragma once

#include <memory>

#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/gzip_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/message_lite.h>

namespace paddle {

/**
 * ProtoReader/ProtoWriter are used to read/write a sequence of protobuf
 * messages from/to i/ostream.
 */
class ProtoReader {
 public:
  explicit ProtoReader(std::istream* s, bool dataCompression = false) {
    CHECK(s) << "istream pointer is nullptr";
    istreamInput_.reset(new google::protobuf::io::IstreamInputStream(s));
    if (dataCompression) {
      gzipInput_.reset(
          new google::protobuf::io::GzipInputStream(istreamInput_.get()));
      codedInput_.reset(
          new google::protobuf::io::CodedInputStream(gzipInput_.get()));
    } else {
      codedInput_.reset(
          new google::protobuf::io::CodedInputStream(istreamInput_.get()));
    }
    dataCompression_ = dataCompression;
    approximateReadedBytes_ = 0;
    codedInput_->SetTotalBytesLimit(kDefaultTotalBytesLimit,
                                    kDefaultTotalBytesLimit);
  }

  /**
   * read one message
   */
  bool read(google::protobuf::MessageLite* msg) {
    if (approximateReadedBytes_ >= kMaxLimitBytes) {
      // Once bytes we read get close to 64MB(larger than 55MB),
      // we re-intialize the codedInputStream object.
      approximateReadedBytes_ = 0;

      /**
       * Explicitly destroys the object owned by unique_ptr at first and then
       * construct an new object.
       *
       * 1.reset()
       *
       * 2.reset(new ...)   <-- such sequence is EXTREAMLY important!
       *
       * Reason: (!!!Read me before you modify the following 2 lines of
       * codes!!!)
       *
       * Otherwise, reset() method will ask the CodedInputStream constructor
       * to construct the new object at first forcing the IstreamInputStream
       * object to move its underlying pointer to the next 8192 bytes.
       *
       * Then the old object will be destroied calling
       * IstreamInputStream::BackUp() to move the underlying pointer back.
       * This means that the InstreamInputStream object is referenced by
       * 2 different CodedInputStream object at the same time which "confuses"
       * the position of istreamInput_'s underlying pointer. Such fatal
       * confusion will lead to undefined behaviour when 'codedInput_' is
       * used to read new data.
       *
       */
      codedInput_.reset();
      if (dataCompression_) {
        codedInput_.reset(
            new google::protobuf::io::CodedInputStream(gzipInput_.get()));
      } else {
        codedInput_.reset(
            new google::protobuf::io::CodedInputStream(istreamInput_.get()));
      }
      codedInput_->SetTotalBytesLimit(kDefaultTotalBytesLimit,
                                      kDefaultTotalBytesLimit);
    }

    uint32_t size;
    if (!codedInput_->ReadVarint32(&size)) {
      return false;
    }
    google::protobuf::io::CodedInputStream::Limit limit =
        codedInput_->PushLimit(size);
    CHECK(msg->ParseFromCodedStream(codedInput_.get()));
    codedInput_->PopLimit(limit);

    /**
     * size is varint in the data file, we don't know the length.
     * We assume every size takes 4 bytes in the data file.
     */
    approximateReadedBytes_ += 4 + size;
    return true;
  }

 protected:
  std::unique_ptr<google::protobuf::io::ZeroCopyInputStream> istreamInput_;
  std::unique_ptr<google::protobuf::io::GzipInputStream> gzipInput_;
  std::unique_ptr<google::protobuf::io::CodedInputStream> codedInput_;
  bool dataCompression_;

  /**
   * This is the maximum number of bytes that this CodedInputStream will read
   * before refusing to continue.
   */
  static const int kDefaultTotalBytesLimit = 64 << 20;  // 64MB

  /**
   * If data readed by the reader is more than 55MB( << 64MB),
   * we reset the CodedInputStream object.
   * This can help avoid 64MB warning which will cause the ParseFromCodedStream
   * to fail.
   */
  static const int kMaxLimitBytes = 55 << 20;

  /**
   * This variable dosen't store the exact bytes readed by CodedInputStream
   * object since which is constructed. Instead, it store the approximate bytes
   * because we can't tell how many bytes are readed by the object with the
   * help of API.
   *
   * @note this code depends on protobuf 2.4.0. There is nothing like
   * CodedInputStream::CurrentPosition() in protobuf 2.5.0 to tell us how many
   * bytes has the object readed so far. Therefore, we calculated bytes
   * ourselves.
   */
  int approximateReadedBytes_;
};

class ProtoWriter {
 public:
  explicit ProtoWriter(std::ostream* s, bool dataCompression = false) {
    CHECK(s) << "ostream pointer is nullptr";
    ostreamOutput_.reset(new google::protobuf::io::OstreamOutputStream(s));
    if (dataCompression) {
      gzipOutput_.reset(
          new google::protobuf::io::GzipOutputStream(ostreamOutput_.get()));
      codedOutput_.reset(
          new google::protobuf::io::CodedOutputStream(gzipOutput_.get()));
    } else {
      codedOutput_.reset(
          new google::protobuf::io::CodedOutputStream(ostreamOutput_.get()));
    }
  }

  /**
   * write one message.
   */
  bool write(const google::protobuf::MessageLite& msg) {
    codedOutput_->WriteVarint32(msg.ByteSize());
    bool ret = msg.SerializeToCodedStream(codedOutput_.get());
    return ret;
  }

 protected:
  std::unique_ptr<google::protobuf::io::ZeroCopyOutputStream> ostreamOutput_;
  std::unique_ptr<google::protobuf::io::GzipOutputStream> gzipOutput_;
  std::unique_ptr<google::protobuf::io::CodedOutputStream> codedOutput_;
};

}  // namespace paddle


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    StarRateView *starView = [[StarRateView alloc] initWithFrame:CGRectMake(0, 100, 200, 40) finish:^(CGFloat currentScore) {
        NSLog(@"%f", currentScore);
    }];
    [self.view addSubview:starView];
}

@end


text:
<?php

namespace Oro\Bundle\ImportExportBundle\Processor;

use Oro\Bundle\ImportExportBundle\Context\ContextAwareInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerInterface;

use Oro\Bundle\ImportExportBundle\Context\ContextInterface;
use Oro\Bundle\ImportExportBundle\Processor\ContextAwareProcessor;
use Oro\Bundle\ImportExportBundle\Converter\DataConverterInterface;
use Oro\Bundle\ImportExportBundle\Strategy\StrategyInterface;

class ImportProcessor implements ProcessorInterface, ContextAwareProcessor, SerializerAwareInterface
{
    /**
     * @var ContextInterface
     */
    protected $context;

    /**
     * @var SerializerInterface
     */
    protected $serializer;

    /**
     * @var DataConverterInterface
     */
    protected $dataConverter;

    /**
     * @var StrategyInterface
     */
    protected $strategy;

    /**
     * {@inheritdoc}
     */
    public function setImportExportContext(ContextInterface $context)
    {
        $this->context = $context;

        if ($this->strategy && $this->strategy instanceof ContextAwareInterface) {
            $this->strategy->setImportExportContext($this->context);
        }

        if ($this->dataConverter && $this->dataConverter instanceof ContextAwareInterface) {
            $this->dataConverter->setImportExportContext($context);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function setSerializer(SerializerInterface $serializer)
    {
        $this->serializer = $serializer;
    }

    /**
     * @param DataConverterInterface $dataConverter
     */
    public function setDataConverter(DataConverterInterface $dataConverter)
    {
        $this->dataConverter = $dataConverter;
    }

    /**
     * @param StrategyInterface $strategy
     */
    public function setStrategy(StrategyInterface $strategy)
    {
        $this->strategy = $strategy;
    }

    /**
     * {@inheritdoc}
     */
    public function process($item)
    {
        if ($this->dataConverter) {
            $item = $this->dataConverter->convertToImportFormat($item);
        }

        $object = $this->serializer->deserialize(
            $item,
            $this->context->getOption('entityName'),
            null,
            $this->context->getConfiguration()
        );

        if ($this->strategy) {
            $object = $this->strategy->process($object);
        }

        return $object ?: null;
    }
}


text:
import React from 'react'
import '../../styles/global.styles'

export const CoreLayout = ({ children }) => (

      {children}

)

CoreLayout.propTypes = {
  children: React.PropTypes.element.isRequired
}

export default CoreLayout


text:
**On the Map** is simple application that lets Udacity students log in either with email and password or through Facebook and then they can access pins that other students have placed on a map at their location. The pins point to an interesting resource that the student wants to share with other students.

It showcases how to use **web APIs** and **authentication**, how to **geocode a location** based on a description and display that information on a map or a table view. Being able to access information through a web API and present it either in a table view or other method (here a map) is a basic skill. This can help others learn this.

#### Documentation

The code is well documented. More information can be found on the [project's page](http://hexaedre.com/apps/on-the-map/).

#### Install

1. Fork the repo (press the `Fork` button near the top right) to your account.
2. Clone the repo on your computer. You find the link in your own github repo then type `git clone <github link>`
3. Open the Xcode project file and run.

#### Swift and Xcode versions

This project is for **Swift version 2.2** and **Xcode version 7.3**.

#### More information

More information and screenshots can be found on the [project's page](http://hexaedre.com/apps/on-the-map/). If you have questions I'd be happy to help. Contact information can be found below or on the project's page.

#### How to contribute

I'm always happy to improve code and learn, so if you find thigs to improve please submit a pull request.

##### Here are some ways you can contribute:

* by reporting bugs
* by writing or editing documentation
* by writing code ( no patch is too small : fix typos, add comments, clean up * inconsistent whitespace )
* by refactoring code
* by closing issues
* by reviewing patches
* Submitting an Issue

I use the GitHub issue tracker to track bugs and features. Before submitting a bug report or feature request, check to make sure it hasn't already been submitted. When submitting a bug report, please include a Gist that includes a stack trace and any details that may be necessary to reproduce the bug, including your Swift and Xcode version, and operating system. Ideally, a bug report should include a pull request with failing specs.

##### Submitting a Pull Request

1. Fork the repository.
1. Create a topic branch.
1. Implement your feature or bug fix.
1. Add, commit, and push your changes.
1. Submit a pull request.

This is based on [https://github.com/middleman/middleman-heroku/blob/master/CONTRIBUTING.md](https://github.com/middleman/middleman-heroku/blob/master/CONTRIBUTING.md)

#### License

On the Map is Copyright © 2016 Denis Ricard. It is free software, and may be redistributed under the terms specified in the LICENSE file.

#### About

I'm an iOS developer. You can find my web site at [hexaedre.com](http://hexaedre.com), find me on Twitter under [@hexaedre](http://twitter.com/hexaedre), or [contact me](http://hexaedre.com/contact/).


text:
package org.onlab.util;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * A {@link CompletableFuture} that tracks whether the future or one of its descendants has been blocked on
 * a {@link CompletableFuture#get()} or {@link CompletableFuture#join()} call.
 */
public class BlockingAwareFuture<T> extends CompletableFuture<T> {
    private final AtomicBoolean blocked;

    public BlockingAwareFuture() {
        this(new AtomicBoolean());
    }

    private BlockingAwareFuture(AtomicBoolean blocked) {
        this.blocked = blocked;
    }

    /**
     * Returns a boolean indicating whether the future is blocked.
     *
     * @return indicates whether the future is blocked
     */
    public boolean isBlocked() {
        return blocked.get();
    }

    @Override
    public T get() throws InterruptedException, ExecutionException {
        blocked.set(true);
        try {
            return super.get();
        } finally {
            blocked.set(false);
        }
    }

    @Override
    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        blocked.set(true);
        try {
            return super.get(timeout, unit);
        } finally {
            blocked.set(false);
        }
    }

    @Override
    public synchronized T join() {
        blocked.set(true);
        try {
            return super.join();
        } finally {
            blocked.set(false);
        }
    }

    /**
     * Wraps the given future in a new blockable future.
     *
     * @param future the future to wrap
     * @param <U> the future value type
     * @return a new blockable future
     */
    private <U> CompletableFuture<U> wrap(CompletableFuture<U> future) {
        BlockingAwareFuture<U> blockingFuture = new BlockingAwareFuture<U>(blocked);
        future.whenComplete((result, error) -> {
            if (error == null) {
                blockingFuture.complete(result);
            } else {
                blockingFuture.completeExceptionally(error);
            }
        });
        return blockingFuture;
    }

    @Override
    public <U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> fn) {
        return wrap(super.thenApply(fn));
    }

    @Override
    public <U> CompletableFuture<U> thenApplyAsync(Function<? super T, ? extends U> fn) {
        return wrap(super.thenApplyAsync(fn));
    }

    @Override
    public <U> CompletableFuture<U> thenApplyAsync(Function<? super T, ? extends U> fn, Executor executor) {
        return wrap(super.thenApplyAsync(fn, executor));
    }

    @Override
    public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
        return wrap(super.thenAccept(action));
    }

    @Override
    public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
        return wrap(super.thenAcceptAsync(action));
    }

    @Override
    public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor) {
        return wrap(super.thenAcceptAsync(action, executor));
    }

    @Override
    public CompletableFuture<Void> thenRun(Runnable action) {
        return wrap(super.thenRun(action));
    }

    @Override
    public CompletableFuture<Void> thenRunAsync(Runnable action) {
        return wrap(super.thenRunAsync(action));
    }

    @Override
    public CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor) {
        return wrap(super.thenRunAsync(action, executor));
    }

    @Override
    public <U, V> CompletableFuture<V> thenCombine(
            CompletionStage<? extends U> other, BiFunction<? super T, ? super U, ? extends V> fn) {
        return wrap(super.thenCombine(other, fn));
    }

    @Override
    public <U, V> CompletableFuture<V> thenCombineAsync(
            CompletionStage<? extends U> other, BiFunction<? super T, ? super U, ? extends V> fn) {
        return wrap(super.thenCombineAsync(other, fn));
    }

    @Override
    public <U, V> CompletableFuture<V> thenCombineAsync(
            CompletionStage<? extends U> other, BiFunction<? super T, ? super U, ? extends V> fn, Executor executor) {
        return wrap(super.thenCombineAsync(other, fn, executor));
    }

    @Override
    public <U> CompletableFuture<Void> thenAcceptBoth(
            CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action) {
        return wrap(super.thenAcceptBoth(other, action));
    }

    @Override
    public <U> CompletableFuture<Void> thenAcceptBothAsync(
            CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action) {
        return wrap(super.thenAcceptBothAsync(other, action));
    }

    @Override
    public <U> CompletableFuture<Void> thenAcceptBothAsync(
            CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action, Executor executor) {
        return wrap(super.thenAcceptBothAsync(other, action, executor));
    }

    @Override
    public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action) {
        return wrap(super.runAfterBoth(other, action));
    }

    @Override
    public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action) {
        return wrap(super.runAfterBothAsync(other, action));
    }

    @Override
    public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor) {
        return wrap(super.runAfterBothAsync(other, action, executor));
    }

    @Override
    public <U> CompletableFuture<U> applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn) {
        return wrap(super.applyToEither(other, fn));
    }

    @Override
    public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn) {
        return wrap(super.applyToEitherAsync(other, fn));
    }

    @Override
    public <U> CompletableFuture<U> applyToEitherAsync(
            CompletionStage<? extends T> other, Function<? super T, U> fn, Executor executor) {
        return wrap(super.applyToEitherAsync(other, fn, executor));
    }

    @Override
    public CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action) {
        return wrap(super.acceptEither(other, action));
    }

    @Override
    public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action) {
        return wrap(super.acceptEitherAsync(other, action));
    }

    @Override
    public CompletableFuture<Void> acceptEitherAsync(
            CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor) {
        return wrap(super.acceptEitherAsync(other, action, executor));
    }

    @Override
    public CompletableFuture<Void> runAfterEither(CompletionStage<?> other, Runnable action) {
        return wrap(super.runAfterEither(other, action));
    }

    @Override
    public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action) {
        return wrap(super.runAfterEitherAsync(other, action));
    }

    @Override
    public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action, Executor executor) {
        return wrap(super.runAfterEitherAsync(other, action, executor));
    }

    @Override
    public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn) {
        return wrap(super.thenCompose(fn));
    }

    @Override
    public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn) {
        return wrap(super.thenComposeAsync(fn));
    }

    @Override
    public <U> CompletableFuture<U> thenComposeAsync(
            Function<? super T, ? extends CompletionStage<U>> fn, Executor executor) {
        return wrap(super.thenComposeAsync(fn, executor));
    }

    @Override
    public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) {
        return wrap(super.whenComplete(action));
    }

    @Override
    public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action) {
        return wrap(super.whenCompleteAsync(action));
    }

    @Override
    public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action, Executor executor) {
        return wrap(super.whenCompleteAsync(action, executor));
    }

    @Override
    public <U> CompletableFuture<U> handle(BiFunction<? super T, Throwable, ? extends U> fn) {
        return wrap(super.handle(fn));
    }

    @Override
    public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn) {
        return wrap(super.handleAsync(fn));
    }

    @Override
    public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, Executor executor) {
        return wrap(super.handleAsync(fn, executor));
    }
}


text:
from django import template
from socialregistration.templatetags import button

register = template.Library()

register.tag('instagram_button', button('socialregistration/instagram/instagram_button.html'))


text:
<?php

namespace Frontend\OrderBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * MesOrder
 *
 * @ORM\Table(name="mes_order", indexes={@ORM\Index(name="fk_order_order_state1_idx", columns={"order_state_id"})})
 * @ORM\Entity
 */
class MesOrder
{
    const PRZ = 'Poczta Polska Paczka24 / Extra24 przelew';
    const POB = 'Poczta Polska Paczka24 / Extra24 za pobraniem';

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date_created", type="datetime", nullable=false)
     */
    private $dateCreated;

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

    /**
     * @var string
     *
     * @ORM\Column(name="shiping_number", type="string", length=255, nullable=true)
     */
    private $shipingNumber;

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

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

    /**
     * @var string
     *
     * @ORM\Column(name="building", type="string", length=45, nullable=false)
     */
    private $building;

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

    /**
     * @var string
     *
     * @ORM\Column(name="postal_code", type="string", length=100, nullable=false)
     */
    private $postalCode;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=255, nullable=false)
     */
    private $email;

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

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

    /**
     * @var string
     *
     * @ORM\Column(name="company", type="array", nullable=true)
     */
    private $company;

    /**
     * @var \OrderState
     *
     * @ORM\ManyToOne(targetEntity="OrderState")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="order_state_id", referencedColumnName="id")
     * })
     */
    private $orderState;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="MES\UserBundle\Entity\MesUser", mappedBy="mesUserOrder")
     */
    private $mesUser;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="OrderProducts", inversedBy="order", cascade={"persist"})
     * @ORM\JoinTable(name="order_has_order_products",
     *   joinColumns={
     *     @ORM\JoinColumn(name="order_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="order_products_id", referencedColumnName="id")
     *   }
     * )
     */
    private $orderProducts;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->mesUser = new \Doctrine\Common\Collections\ArrayCollection();
        $this->orderProducts = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set dateCreated
     *
     * @param \DateTime $dateCreated
     * @return MesOrder
     */
    public function setDateCreated($dateCreated)
    {
        $this->dateCreated = $dateCreated;

        return $this;
    }

    /**
     * Get dateCreated
     *
     * @return \DateTime
     */
    public function getDateCreated()
    {
        return $this->dateCreated;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return MesOrder
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set shipingNumber
     *
     * @param string $shipingNumber
     * @return MesOrder
     */
    public function setShipingNumber($shipingNumber)
    {
        $this->shipingNumber = $shipingNumber;

        return $this;
    }

    /**
     * Get shipingNumber
     *
     * @return string
     */
    public function getShipingNumber()
    {
        return $this->shipingNumber;
    }

    /**
     * Set surname
     *
     * @param string $surname
     * @return MesOrder
     */
    public function setSurname($surname)
    {
        $this->surname = $surname;

        return $this;
    }

    /**
     * Get surname
     *
     * @return string
     */
    public function getSurname()
    {
        return $this->surname;
    }

    /**
     * Set street
     *
     * @param string $street
     * @return MesOrder
     */
    public function setStreet($street)
    {
        $this->street = $street;

        return $this;
    }

    /**
     * Get street
     *
     * @return string
     */
    public function getStreet()
    {
        return $this->street;
    }

    /**
     * Set building
     *
     * @param string $building
     * @return MesOrder
     */
    public function setBuilding($building)
    {
        $this->building = $building;

        return $this;
    }

    /**
     * Get building
     *
     * @return string
     */
    public function getBuilding()
    {
        return $this->building;
    }

    /**
     * Set town
     *
     * @param string $town
     * @return MesOrder
     */
    public function setTown($town)
    {
        $this->town = $town;

        return $this;
    }

    /**
     * Get town
     *
     * @return string
     */
    public function getTown()
    {
        return $this->town;
    }

    /**
     * Set postalCode
     *
     * @param string $postalCode
     * @return MesOrder
     */
    public function setPostalCode($postalCode)
    {
        $this->postalCode = $postalCode;

        return $this;
    }

    /**
     * Get postalCode
     *
     * @return string
     */
    public function getPostalCode()
    {
        return $this->postalCode;
    }

    /**
     * Set email
     *
     * @param string $email
     * @return MesOrder
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set phone
     *
     * @param string $phone
     * @return MesOrder
     */
    public function setPhone($phone)
    {
        $this->phone = $phone;

        return $this;
    }

    /**
     * Get phone
     *
     * @return string
     */
    public function getPhone()
    {
        return $this->phone;
    }

    /**
     * Set shipping
     *
     * @param string $shipping
     * @return MesOrder
     */
    public function setShipping($shipping)
    {
        $this->shipping = $shipping;

        return $this;
    }

    /**
     * Get shipping
     *
     * @return string
     */
    public function getShipping()
    {
        return $this->shipping;
    }

    /**
     * Set company
     *
     * @param array $company
     * @return MesOrder
     */
    public function setCompany($company)
    {
        $this->company = $company;

        return $this;
    }

    /**
     * Get company
     *
     * @return array
     */
    public function getCompany()
    {
        return $this->company;
    }

    /**
     * Set orderState
     *
     * @param \Frontend\OrderBundle\Entity\OrderState $orderState
     * @return MesOrder
     */
    public function setOrderState(\Frontend\OrderBundle\Entity\OrderState $orderState = null)
    {
        $this->orderState = $orderState;

        return $this;
    }

    /**
     * Get orderState
     *
     * @return \Frontend\OrderBundle\Entity\OrderState
     */
    public function getOrderState()
    {
        return $this->orderState;
    }

    /**
     * Add mesUser
     *
     * @param \MES\UserBundle\Entity\MesUser $mesUser
     * @return MesOrder
     */
    public function addMesUser(\MES\UserBundle\Entity\MesUser $mesUser)
    {
        $this->mesUser[] = $mesUser;

        return $this;
    }

    /**
     * Remove mesUser
     *
     * @param \MES\UserBundle\Entity\MesUser $mesUser
     */
    public function removeMesUser(\MES\UserBundle\Entity\MesUser $mesUser)
    {
        $this->mesUser->removeElement($mesUser);
    }

    /**
     * Get mesUser
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getMesUser()
    {
        return $this->mesUser;
    }

    /**
     * Add orderProducts
     *
     * @param \Frontend\OrderBundle\Entity\OrderProducts $orderProducts
     * @return MesOrder
     */
    public function addOrderProduct(\Frontend\OrderBundle\Entity\OrderProducts $orderProducts)
    {
        $this->orderProducts[] = $orderProducts;

        return $this;
    }

    /**
     * Remove orderProducts
     *
     * @param \Frontend\OrderBundle\Entity\OrderProducts $orderProducts
     */
    public function removeOrderProduct(\Frontend\OrderBundle\Entity\OrderProducts $orderProducts)
    {
        $this->orderProducts->removeElement($orderProducts);
    }

    /**
     * Get orderProducts
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getOrderProducts()
    {
        return $this->orderProducts;
    }
}


text:
import {createSelector} from 'reselect'

import groupsSelector from 'groupsSelector'

const selectedGroupIdSelector = (state) => state.selectedGroupId

export default createSelector(
  [groupsSelector, selectedGroupIdSelector],
  (groups, selectedGroupId) => groups.get(selectedGroupId)
)


text:
#include "tensorflow/compiler/mlir/tensorflow/transforms/lower_tf.h"

#include <numeric>

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "mlir/IR/Attributes.h"  // TF:llvm-project
#include "mlir/IR/Diagnostics.h"  // TF:llvm-project
#include "mlir/IR/MLIRContext.h"  // TF:llvm-project
#include "mlir/IR/PatternMatch.h"  // TF:llvm-project
#include "mlir/IR/StandardTypes.h"  // TF:llvm-project
#include "mlir/IR/TypeUtilities.h"  // TF:llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_types.h"
#include "tensorflow/core/util/tensor_format.h"

namespace mlir {
namespace TF {
namespace {

// Returns 1D 64-bit dense elements attribute with the given values.
static DenseIntElementsAttr GetI64ElementsAttr(ArrayRef<int64_t> values,
                                               Builder *builder) {
  RankedTensorType ty = RankedTensorType::get(
      {static_cast<int64_t>(values.size())}, builder->getIntegerType(64));
  return DenseIntElementsAttr::get(ty, values);
}

// Returns a 1-d i64 elements attribute populated with numbers from start to
// end, excluding.
static DenseIntElementsAttr GetI64ElementsAttrForSeq(int start, int end,
                                                     Builder *builder) {
  int size = end - start;

  SmallVector<int64_t, 4> vals;
  vals.resize(size);
  std::iota(vals.begin(), vals.end(), start);

  TensorType ty = RankedTensorType::get({size}, builder->getIntegerType(64));
  return DenseIntElementsAttr::get(ty, vals);
}

// Returns int or float DenseElementsAttr with scalar shape with the given
// element type and the integer value.
static DenseElementsAttr GetScalarOfType(Type ty, int64_t raw_value) {
  RankedTensorType scalar_ty = RankedTensorType::get({}, ty);
  if (auto float_ty = ty.dyn_cast_or_null<FloatType>()) {
    FloatAttr attr = FloatAttr::get(float_ty, raw_value);
    return DenseElementsAttr::get(scalar_ty, attr);
  }

  auto int_ty = ty.cast<IntegerType>();
  IntegerAttr attr = IntegerAttr::get(int_ty, raw_value);
  return DenseElementsAttr::get(scalar_ty, attr);
}

// Returns float DenseElementsAttr with scalar shape with the specified value.
static DenseElementsAttr GetScalarOfFloatType(Type ty, double raw_value) {
  auto float_ty = ty.cast<FloatType>();
  FloatAttr attr = FloatAttr::get(float_ty, raw_value);
  RankedTensorType scalar_ty = RankedTensorType::get({}, ty);
  return DenseElementsAttr::get(scalar_ty, attr);
}

// Returns reduction indices to use while lowering tf.BiasAddGrad op to tf.Sum
// op.
DenseIntElementsAttr GetBiasAddGradReductionIndices(int64_t rank,
                                                    StringAttr data_format,
                                                    Builder *builder) {
  tensorflow::TensorFormat format;
  if (!FormatFromString(data_format.getValue().str(), &format)) return {};

  // Reduce along all dimensions except the feature dimension.
  int64_t feature_dim = GetTensorFeatureDimIndex(rank, format);
  llvm::SmallVector<int64_t, 4> dims_to_reduce(rank - 1);
  std::iota(dims_to_reduce.begin(), dims_to_reduce.begin() + feature_dim, 0);
  std::iota(dims_to_reduce.begin() + feature_dim, dims_to_reduce.end(),
            feature_dim + 1);
  return GetI64ElementsAttr(dims_to_reduce, builder);
}

#include "tensorflow/compiler/mlir/tensorflow/transforms/generated_lower_tf.inc"

// Infers ExpandDims op output type for the given input type `ty` and dimension
// to expand at the given `axis`.
Type InferExpandDimsType(Type ty, int64_t axis, Builder *builder) {
  auto ranked_ty = ty.dyn_cast<RankedTensorType>();

  // Unranked type.
  if (!ranked_ty) return ty;

  auto shape = llvm::to_vector<4>(ranked_ty.getShape());
  if (axis < 0) axis += ranked_ty.getRank() + 1;

  shape.insert(shape.begin() + axis, 1);
  return RankedTensorType::get(shape, ranked_ty.getElementType());
}

// Lowers AddN op to a sequence of AddV2 ops to accumulate operands.
//
//   %result = "tf.AddN"(%0, %1, %2)
//
// is lowered to:
//
//   %sum_0 = "tf.AddV2"(%0, %1)
//   %result = "tf.AddV2"(%sum_0, %2)
//
class LowerAddNOp : public OpRewritePattern<TF::AddNOp> {
 public:
  explicit LowerAddNOp(MLIRContext *context)
      : OpRewritePattern<TF::AddNOp>(context) {}

  PatternMatchResult matchAndRewrite(TF::AddNOp op,
                                     PatternRewriter &rewriter) const override {
    // TODO(hinsu): Support variant with TensorList type. tf.AddV2 doesn't
    // support variant type so variant types require special handling.
    if (getElementTypeOrSelf(op.getType()).isa<VariantType>())
      return matchFailure();

    // TODO(hinsu): Improve parallelism by splitting operands in two halves and
    // accumulating them first.
    Value result = *op.inputs().begin();
    for (Value operand : llvm::drop_begin(op.inputs(), 1)) {
      result = rewriter.create<TF::AddV2Op>(op.getLoc(), result, operand);
    }

    rewriter.replaceOp(op, result);
    return matchSuccess();
  }
};

// Lowers DynamicStitch op with constant indices and with static input and
// output shapes using Reshape, UnPack and ConcatV2 op.
//
//   %indices0 = "tf.Const"() {value = dense<4> : tensor<i32>}
//   %indices1 = "tf.Const"() {value = dense<[[3, 2], [1, 0]]> :
//   tensor<2x2xi32>} %0 = "tf.DynamicStitch"(%indices0, %indices1, %arg0,
//   %arg1)
//     : (tensor<i32>, tensor<2x2xi32>, tensor<2xf32>, tensor<2x2x2xf32>)
//     -> tensor<5x2xf32>
//
// is lowered to
//
//   %shape = "tf.Const"() {value = dense<[-1, 2]> : tensor<2xi64>}
//   %inp0 = "tf.Reshape"(%arg0, %shape)
//     : (tensor<2xf32>, tensor<2xi64>) -> tensor<1x2xf32>
//   %inp1 = "tf.Reshape"(%arg1, %shape)
//     : (tensor<2x2x2xf32>, tensor<2xi64>) -> tensor<4x2xf32>
//   %items0 = "tf.Unpack"(%[[INP0]]) {axis = 0 : i64}
//     : (tensor<1x2xf32>) -> tensor<2xf32>
//   %items1:4 = "tf.Unpack"(%[[INP1]]) {axis = 0 : i64}
//     : (tensor<4x2xf32>) -> (tensor<2xf32>, tensor<2xf32>, tensor<2xf32>,
//     tensor<2xf32>)
//   %axis = "tf.Const"() {value = dense<0> : tensor<i64>}
//   %0 = "tf.ConcatV2"(items1#3, items1#2, items1#1, items1#0, %items0, %axis)
//     : (tensor<2xf32>, tensor<2xf32>, tensor<2xf32>, tensor<2xf32>,
//        tensor<2xf32>, tensor<i64>) -> tensor<5x2xf32>
//
class LowerDynamicStitchOp : public OpRewritePattern<TF::DynamicStitchOp> {
 public:
  explicit LowerDynamicStitchOp(MLIRContext *context)
      : OpRewritePattern<TF::DynamicStitchOp>(context) {}

  PatternMatchResult matchAndRewrite(DynamicStitchOp op,
                                     PatternRewriter &rewriter) const override {
    // Static output type is used to compute intermediate values. Note that the
    // output type doesn't have to be static but if input types and indices are
    // constant, then the output type can be statically determined.
    RankedTensorType out_ty = op.getType().dyn_cast<RankedTensorType>();
    if (!out_ty || !out_ty.hasStaticShape()) return matchFailure();

    // Extract out all the constant indices' attributes and verify that data
    // types are static.
    SmallVector<DenseIntElementsAttr, 4> indices;
    indices.reserve(op.N());
    for (auto it : llvm::zip(op.indices(), op.data())) {
      Value index = std::get<0>(it);
      Value data = std::get<1>(it);

      DenseIntElementsAttr index_attr;
      if (!matchPattern(index, m_Constant(&index_attr))) return matchFailure();
      indices.push_back(index_attr);

      RankedTensorType data_ty = data.getType().dyn_cast<RankedTensorType>();
      if (!data_ty || !data_ty.hasStaticShape()) return matchFailure();
    }

    // Compute type of each of the items and shape to use while reshaping inputs
    // so that they can be unpacked to extract out individual items.
    ArrayRef<int64_t> item_shape = out_ty.getShape().drop_front(1);
    auto item_ty = RankedTensorType::get(item_shape, out_ty.getElementType());

    SmallVector<int64_t, 4> packed_shape;
    packed_shape.push_back(-1);
    packed_shape.append(item_shape.begin(), item_shape.end());
    Location loc = op.getLoc();
    auto packed_shape_val = rewriter.create<ConstOp>(
        loc, GetI64ElementsAttr(packed_shape, &rewriter));

    // Prepare each of the output item by unpacking data and then putting it to
    // the specified index.
    SmallVector<Value, 8> values(out_ty.getDimSize(0));
    for (auto it : llvm::zip(indices, op.data())) {
      DenseIntElementsAttr index_attr = std::get<0>(it);
      Value data = std::get<1>(it);

      auto reshaped_data =
          rewriter.create<ReshapeOp>(loc, data, packed_shape_val);
      auto num_items =
          reshaped_data.getType().cast<RankedTensorType>().getShape()[0];
      auto items = rewriter.create<UnpackOp>(
          loc, SmallVector<Type, 4>(num_items, item_ty), reshaped_data,
          /*axis=*/APInt(64, 0));
      for (auto index_item : llvm::zip(index_attr, items.getResults())) {
        int64_t output_index = std::get<0>(index_item).getSExtValue();
        Value item = std::get<1>(index_item);
        values[output_index] = item;
      }
    }

    auto axis = rewriter.create<ConstOp>(loc, rewriter.getI64IntegerAttr(0));
    rewriter.replaceOpWithNewOp<ConcatV2Op>(op, op.getType(), values, axis);
    return matchSuccess();
  }
};

// Lowers InvertPermutation op to TensorScatterUpdate op.
//
// Example:
//
//   %x = "tf.Const"() {value = dense<[3, 4, 0, 1, 2]> : tensor<5xi32>}
//   "tf.InvertPermutation"(%x) : (tensor<5xi32>) -> tensor<5xi32>
//
// is lowered to
//
//   %x = "tf.Const"() {value = dense<[3, 4, 0, 1, 2]> : tensor<5xi32>}
//   %start = "tf.Const"() {value = dense<0> : tensor<i32>}
//   %limit = "tf.Const"() {value = dense<5> : tensor<i32>}
//   %delta = "tf.Const"() {value = dense<1> : tensor<i32>}
//   %updates = "tf.Range"(%start, %limit, %delta) :
//     (tensor<i32>, tensor<i32>, tensor<i32>) -> tensor<5xi32>
//   %perm = "tf.Const"() {value = dense<[1, 0]> : tensor<2xi32>}
//   %indices = "tf.Transpose"(%x, %perm) : (tensor<5xi32, tensor<2xi32) ->
//     tensor<5x1xi32>
//   "tf.TensorScatterUpdate"(%x, %indices, %updates) :
//     (tensor<5xi32>, tensor<5x1xi32>, tensor<5xi32>) -> tensor<5xi32>
//
class LowerInvertPermutationOp
    : public OpRewritePattern<TF::InvertPermutationOp> {
 public:
  explicit LowerInvertPermutationOp(MLIRContext *context)
      : OpRewritePattern<TF::InvertPermutationOp>(context) {}

  PatternMatchResult matchAndRewrite(TF::InvertPermutationOp op,
                                     PatternRewriter &rewriter) const override {
    Location loc = op.getLoc();
    auto x_type = op.x().getType().cast<TensorType>();
    Type int_type = x_type.getElementType();  // Could be i32 or i64.

    // x input must have static shape.
    if (!x_type.hasStaticShape()) {
      return matchFailure();
    }

    auto result_type = x_type;
    auto start =
        rewriter.create<TF::ConstOp>(loc, GetScalarOfType(int_type, 0));
    Value limit = rewriter.create<TF::ConstOp>(
        loc, GetScalarOfType(int_type, x_type.getShape()[0]));
    auto delta =
        rewriter.create<TF::ConstOp>(loc, GetScalarOfType(int_type, 1));
    // Construct a sequence of numbers [0, 1, ... len(x)-1].
    auto updates =
        rewriter.create<TF::RangeOp>(loc, result_type, start, limit, delta);

    auto perm_type = RankedTensorType::get({2}, int_type);
    auto perm = rewriter.create<TF::ConstOp>(
        loc, DenseElementsAttr::get(perm_type, {1, 0}));
    auto transposed_x_type =
        RankedTensorType::get({x_type.getShape()[0], 1}, int_type);
    auto indices =
        rewriter.create<TF::TransposeOp>(loc, transposed_x_type, op.x(), perm);

    rewriter.replaceOpWithNewOp<TF::TensorScatterUpdateOp>(
        op, result_type, op.x(), indices, updates);
    return matchSuccess();
  }
};

// Lowers Pack op to ConcatV2 op after changing shape of the inputs with
// ExpandDims op.
//
// Sample result with 2 inputs to pack:
//
//   %axis = "tf.Const"() {value = dense<1> : tensor<i64>}
//   %inp0 = "tf.ExpandDims"(%operand0, %axis): tensor<2xf32> -> tensor<2x1xf32>
//   %inp1 = "tf.ExpandDims"(%operand1, %axis): tensor<2xf32> -> tensor<2x1xf32>
//   %result = "tf.ConcatV2"(%operand0, %operand1, %axis) { N = 2 : i64 }:
//
class LowerPackOp : public OpRewritePattern<TF::PackOp> {
 public:
  explicit LowerPackOp(MLIRContext *context)
      : OpRewritePattern<TF::PackOp>(context) {}

  PatternMatchResult matchAndRewrite(TF::PackOp op,
                                     PatternRewriter &rewriter) const override {
    Location loc = op.getLoc();
    auto axis_value = rewriter.create<TF::ConstOp>(
        loc,
        DenseElementsAttr::get(
            RankedTensorType::get({}, rewriter.getIntegerType(64)), op.axis()));
    int64_t axis = op.axis().getSExtValue();

    Type prev_input_ty, inferred_ty;
    SmallVector<Value, 4> expanded_inputs;
    expanded_inputs.reserve(op.N());
    for (Value input : op.values()) {
      // If input type is different than the previous input type, infer the
      // output type. Otherwise, use the already inferred output type from the
      // previous iteration.
      Type input_ty = input.getType();
      if (input_ty != prev_input_ty) {
        inferred_ty = InferExpandDimsType(input_ty, axis, &rewriter);
        prev_input_ty = input_ty;
      }
      expanded_inputs.push_back(rewriter.create<TF::ExpandDimsOp>(
          loc, inferred_ty, input, axis_value));
    }

    rewriter.replaceOpWithNewOp<TF::ConcatV2Op>(op, op.getType(),
                                                expanded_inputs, axis_value);
    return matchSuccess();
  }
};

}  // namespace

void PopulateLoweringTFPatterns(MLIRContext *context,
                                OwningRewritePatternList *patterns) {
  patterns->insert<LowerAddNOp, LowerDynamicStitchOp, LowerInvertPermutationOp,
                   LowerPackOp>(context);
  populateWithGenerated(context, patterns);
}

}  // namespace TF
}  // namespace mlir


text:
#ifndef GRAPH_H_
#define GRAPH_H_

#include<list>
#include<vector>
using namespace std;

template<typename T>
struct Node {
	T value;
	list<T> neighbours;
	Node(T v = T(), list<T> n = list<T>()) :
			value(v), neighbours(n) {}
};

template<typename T>
struct Rib {
	Node<T> from;
	Node<T> to;
	Rib(Node<T> _from, Node<T> _to) :
			from(_from), to(_to) {}
};

template<typename T>
class Graph {
public:
	virtual bool areNeighbor(Node<T> firstVertex, Node<T> secondVertex) = 0;
	bool isPath(list<Node<T> > path);
	bool isPath(vector<Node<T> > path);
	virtual void print() = 0;
	virtual ~Graph() {}
};

#endif /* GRAPH_H_ */