text:
package org.graphwalker.maven.plugin;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Nils Olsson
 */
public abstract class DefaultMojoBase extends AbstractMojo {

  @Component
  private MavenSession session;

  @Component
  private MavenProject mavenProject;

  protected MavenSession getSession() {
    return session;
  }

  protected MavenProject getMavenProject() {
    return mavenProject;
  }

  private String toString(Set<String> set) {
    if (null == set) {
      return "";
    }
    return StringUtils.join(set.toArray(new String[set.size()]), ",");
  }

  protected Set<File> findFiles(Set<String> includes, Set<String> excludes, File... directories) {
    return findFiles(toString(includes), toString(excludes), directories);
  }

  protected Set<File> findFiles(String includes, String excludes, File... directories) {
    Set<File> files = new HashSet<>();
    for (File directory : directories) {
      if (directory.exists()) {
        try {
          for (Object filename : FileUtils.getFileNames(directory, includes, excludes, true, true)) {
            files.add(new File((String) filename));
          }
        } catch (Throwable t) {
          getLog().debug(t);
        }
      }
    }
    return files;
  }
}


text:
<?php

declare(strict_types=1);

namespace Brick\Geo\Tests\IO;

use Brick\Geo\Exception\GeometryIOException;
use Brick\Geo\IO\GeoJSON\Feature;
use Brick\Geo\IO\GeoJSON\FeatureCollection;
use Brick\Geo\IO\GeoJSONReader;
use stdClass;

class GeoJSONReaderTest extends GeoJSONAbstractTest
{
    /**
     * @dataProvider providerReadGeometry
     *
     * @param string $geojson The GeoJSON to read.
     * @param array  $coords  The expected Geometry coordinates.
     * @param bool   $is3D    Whether the resulting Geometry has a Z coordinate.
     * @param bool   $lenient Whether to be lenient about case-sensitivity.
     */
    public function testReadGeometry(string $geojson, array $coords, bool $is3D, bool $lenient) : void
    {
        $geometry = (new GeoJSONReader($lenient))->read($geojson);
        $this->assertGeometryContents($geometry, $coords, $is3D, false, 4326);
    }

    public function providerReadGeometry() : \Generator
    {
        foreach ($this->providerGeometryGeoJSON() as [$geojson, $coords, $is3D]) {
            yield [$geojson, $coords, $is3D, false];
            yield [$this->alterCase($geojson), $coords, $is3D, true];
        }
    }

    /**
     * @dataProvider providerReadFeature
     *
     * @param string        $geojson    The GeoJSON to read.
     * @param stdClass|null $properties The contained properties.
     * @param array|null    $coords     The expected Geometry coordinates, or null if the Feature has no geometry.
     * @param bool          $is3D       Whether the resulting Geometry has a Z coordinate.
     * @param bool          $lenient    Whether to be lenient about case-sensitivity.
     */
    public function testReadFeature(string $geojson, ?stdClass $properties, ?array $coords, bool $is3D, bool $lenient) : void
    {
        $feature = (new GeoJSONReader($lenient))->read($geojson);

        self::assertInstanceOf(Feature::class, $feature);
        self::assertEquals($properties, $feature->getProperties());

        $geometry = $feature->getGeometry();

        if ($coords === null) {
            self::assertNull($geometry);
        } else {
            $this->assertGeometryContents($geometry, $coords, $is3D, false, 4326);
        }
    }

    public function providerReadFeature() : \Generator
    {
        foreach ($this->providerFeatureGeoJSON() as [$geojson, $properties, $coords, $is3D]) {
            yield [$geojson, $properties, $coords, $is3D, false];
            yield [$this->alterCase($geojson), $properties, $coords, $is3D, true];
        }
    }

    /**
     * @dataProvider providerReadFeatureCollection
     *
     * @param string  $geojson The GeoJSON to read.
     * @param array[] $coords  The expected Point coordinates.
     * @param bool[]  $is3D    Whether the resulting Point has a Z coordinate.
     * @param bool    $lenient Whether to be lenient about case-sensitivity.
     */
    public function testReadFeatureCollection(string $geojson, array $properties, array $coords, array $is3D, bool $lenient) : void
    {
        $featureCollection = (new GeoJSONReader($lenient))->read($geojson);

        self::assertInstanceOf(FeatureCollection::class, $featureCollection);

        foreach ($featureCollection->getFeatures() as $key => $feature) {
            self::assertEquals($properties[$key], $feature->getProperties());
            $geometry = $feature->getGeometry();
            $this->assertGeometryContents($geometry, $coords[$key], $is3D[$key], false, 4326);
        }
    }

    public function providerReadFeatureCollection() : \Generator
    {
        foreach ($this->providerFeatureCollectionGeoJSON() as [$geojson, $properties, $coords, $is3D]) {
            yield [$geojson, $properties, $coords, $is3D, false];
            yield [$this->alterCase($geojson), $properties, $coords, $is3D, true];
        }
    }

    /**
     * @dataProvider providerNonLenientReadWrongCaseType
     */
    public function testNonLenientReadWrongCaseType(string $geojson, string $expectedExceptionMessage) : void
    {
        $reader = new GeoJSONReader();

        $this->expectException(GeometryIOException::class);
        $this->expectExceptionMessage($expectedExceptionMessage);

        $reader->read($geojson);
    }

    public function providerNonLenientReadWrongCaseType() : \Generator
    {
        foreach ($this->providerGeometryPointGeoJSON() as [$geojson]) {
            yield [$this->alterCase($geojson), 'Unsupported GeoJSON type: POINT.'];
        }

        foreach ($this->providerFeaturePointGeoJSON() as [$geojson]) {
            yield [$this->alterCase($geojson), 'Unsupported GeoJSON type: FEATURE.'];
        }

        foreach ($this->providerFeatureCollectionGeoJSON() as [$geojson]) {
            yield [$this->alterCase($geojson), 'Unsupported GeoJSON type: FEATURECOLLECTION.'];
        }
    }

    /**
     * Changes the case of type attributes.
     */
    private function alterCase(string $geojson) : string
    {
        $callback = function(array $matches) : string {
            return $matches[1] . strtoupper($matches[2]);
        };

        return preg_replace_callback('/("type"\s*\:\s*)("[^"]+")/', $callback, $geojson);
    }
}

redpajama_set_name: RedPajamaGithub


text:
set names utf8;
CREATE TABLE t1 (name VARCHAR (40), event VARCHAR (30) collate utf8_en_ci, primary key(name,event))
PARTITION BY LIST (event) (
    PARTITION event1 VALUES IN ('A')
);

ALTER TABLE t1 ADD PARTITION (
    PARTITION event2 VALUES IN ('a')
);

ALTER TABLE t1 ADD PARTITION (
    PARTITION event3 VALUES IN ('B')
);

ALTER TABLE t1 ADD PARTITION (
    PARTITION event4 VALUES IN ('b')
);

ALTER TABLE t1 ADD PARTITION (
    PARTITION event5 VALUES IN (_utf8'C')
);

ALTER TABLE t1 ADD PARTITION (
    PARTITION event6 VALUES IN (_iso88591'D')
);

ALTER TABLE t1 ADD PARTITION (
    PARTITION event7 VALUES IN (_euckr'E')
);

ALTER TABLE t1 ADD PARTITION (
    PARTITION event8 VALUES IN ('e')
);

ALTER TABLE t1 ADD PARTITION (
    PARTITION event9 VALUES IN (_iso88591'F'),
    PARTITION event10 VALUES IN (_euckr'F')
);

insert into t1 select '1', 'A';
insert into t1 select '2', 'a';
insert into t1 select '3', 'B';
insert into t1 select '4', 'b';
insert into t1 select '5', 'C';
insert into t1 select '6', 'c';
insert into t1 select '7', 'D';
insert into t1 select '8', 'd';

select * from t1 order by 1,2;

drop table t1;
set names iso88591;


text:
package models

import anorm.SqlParser._
import anorm.{~, _}
import play.api.Play.current
import play.api.db.DB
import securesocial.core._
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.libs.json.Writes._

import scala.concurrent.Future

case class UserLevel(userLevelSeqId: Long, maxActiveUploads: Long, maxActiveUploadBytes: Long)

case class User(userSeqId: Long, userProfile: BasicProfile, userLevel: UserLevel)

case class UserUsage(currentActiveUploads: Option[Long], currentActiveUploadBytes: Option[Long])

  object User {
    val user = {
      get[Long]("seqId") ~
      get[String]("userId") ~
      get[String]("providerId") ~
      get[Option[String]]("firstName") ~
      get[Option[String]]("lastName") ~
      get[Option[String]]("fullName") ~
      get[Option[String]]("email") ~
      get[Option[String]]("avatarUrl") ~
      get[String]("authenticationMethod") ~
      get[Option[String]]("oAuth1Token") ~
      get[Option[String]]("oAuth1Secret") ~
      get[Option[String]]("oAuth2AccessToken") ~
      get[Option[String]]("oAuth2TokenType") ~
      get[Option[Int]]("oAuth2ExpiresIn") ~
      get[Option[String]]("oAuth2RefreshToken") ~
      get[Option[String]]("passwordHasher") ~
      get[Option[String]]("password") ~
      get[Option[String]]("passwordSalt") ~
      get[Long]("userLevelSeqId") ~
        get[Long]("maxActiveUploads")~
        get[Long]("maxActiveUploadBytes") map {
        case seqId ~ userId ~ providerId ~ firstName ~ lastName ~ fullName ~ email ~ avatarUrl ~
          authenticationMethod ~ oAuth1Token ~ oAuth1Secret ~ oAuth2AccessToken ~ oAuth2TokenType ~
          oAuth2ExpiresIn ~ oAuth2RefreshToken ~ passwordHasher ~ password ~ passwordSalt ~
          userLevelSeqId ~ maxActiveUploads ~ maxActiveUploadBytes =>
          User(seqId, BasicProfile(providerId, userId, firstName, lastName, fullName, email, avatarUrl, AuthenticationMethod(authenticationMethod),
            Option(OAuth1Info(oAuth1Token.get, oAuth1Secret.get)), Option(OAuth2Info(oAuth2AccessToken.get, oAuth2TokenType, oAuth2ExpiresIn, oAuth2RefreshToken)),
            Option(PasswordInfo(passwordHasher.get, password.get, passwordSalt))), UserLevel(userLevelSeqId, maxActiveUploads, maxActiveUploadBytes))
      }
    }

    def find(seqId: Long): Future[User] = {
      val result = DB.withConnection { implicit c =>
        SQL("SELECT * FROM p_user_profile JOIN p_user_level ON p_user_profile.seqId = p_user_level.userSeqId WHERE seqId = {seqId}")
          .on('seqId -> seqId).as(user *).headOption
      }

      Future.successful(result.get)
    }

    implicit val userWrites = new Writes[User] {
      def writes(user: User) = Json.obj(
        "id" -> user.userSeqId,
        "firstName" -> user.userProfile.firstName,
        "lastName" -> user.userProfile.lastName,
        "fullName" -> user.userProfile.fullName,
        "email" -> user.userProfile.email,
        "avatarUrl" -> user.userProfile.avatarUrl
      )
    }

  }


text:
<?php

/*
 * This file is part of Sulu.
 *
 * (c) Sulu GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Bundle\ArticleBundle\Builder;

use ONGR\ElasticsearchBundle\Service\Manager;
use Sulu\Bundle\CoreBundle\Build\SuluBuilder;

/**
 * Builder for article-index.
 */
class ArticleIndexBuilder extends SuluBuilder
{
    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'article_index';
    }

    /**
     * {@inheritdoc}
     */
    public function getDependencies()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function build()
    {
        $this->buildForManager($this->container->get('es.manager.live'), $this->input->getOption('destroy'));
        $this->buildForManager($this->container->get('es.manager.default'), $this->input->getOption('destroy'));
    }

    /**
     * Build index for given manager.
     *
     * If index not exists - it will be created.
     * If index exists and destroy flag is true - drop and create index.
     * Else do nothing.
     */
    private function buildForManager(Manager $manager, bool $destroy): void
    {
        $name = $manager->getName();
        if (!$manager->indexExists()) {
            $this->output->writeln(sprintf('Create index for "<comment>%s</comment>" manager.', $name));
            $manager->createIndex();

            return;
        }

        if (!$destroy) {
            return;
        }

        $this->output->writeln(sprintf('Drop and create index for "<comment>%s</comment>" manager.', $name));
        $manager->dropAndCreateIndex();
    }
}


text:
package Networking.Server;

import Console.ConsoleFrame;
import Networking.Client.ConnectionHandler;
import Constants.MasterServerConstants;
import Source.Source;
import Interface.MainFrame;
import Networking.Requests.HostMatch;
import Networking.Requests.RegisterActivity;
import Networking.Requests.Request;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ClientServerDispatcher extends ServerDispatcher {

    private volatile Match activeMatch;
    private static ClientServerDispatcher instance;
    private final AbstractMap<String, Source> sourceFiles;

    private ClientServerDispatcher() {
        sourceFiles = new ConcurrentSkipListMap<>();
    }

    public static ClientServerDispatcher getInstance() {
        if (instance == null) {
            instance = new ClientServerDispatcher();
        }

        return instance;
    }

    /**
     * Starts a timer which first sends a HostMatch request to the master
     * server, in order to register the match. After that it sends
     * RegisterActivity requests each MasterServerConstants.Packet_Delay
     * milliseconds which are used by the master server to confirm that this
     * match is still active and therefor continue listing it.
     */
    private void startMasterServerNotifier() {
        Timer masterServerNotifier = new Timer();

        TimerTask notification = new TimerTask() {
            private boolean matchRegistered = false;

            @Override
            public void run() {
                if (!isRunning.get()) {
                    masterServerNotifier.cancel();
                    return;
                }

                try {
                    if (!matchRegistered) {
                        // Register match with the master server
                        ConnectionHandler.getInstance().sendToMasterServer(new HostMatch(activeMatch));
                        matchRegistered = true;
                    }
                    // Confirm activity
                    ConnectionHandler.getInstance().sendToMasterServer(new RegisterActivity());
                } catch (IOException ex) {
                    masterServerNotifier.cancel();
                    Logger.getLogger(ClientServerDispatcher.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        };

        masterServerNotifier.scheduleAtFixedRate(notification, 0, MasterServerConstants.PACKET_DELAY);
    }

    /**
     *
     * @param match The match object associated with this server.
     * @return true if successful, false otherwise.
     */
    public boolean start(Match match) {
        this.activeMatch = match;
        this.port = match.getPort();
        boolean result = this.start(port);
        startMasterServerNotifier();
        return result;
    }

    @Override
    public boolean stop() {
        boolean result = super.stop();
        MainFrame.getInstance().localServerName = null;
        return result;
    }

    /**
     * Starts the loop which handles incoming connections.
     *
     * @param serverSocket The server socket to which the clients will connect
     * to.
     */
    @Override
    protected void listenForConnections(ServerSocket serverSocket) {
        while (isRunning.get()) {
            try {
                Socket clientSocket = serverSocket.accept();
                clientSocket.setTcpNoDelay(MasterServerConstants.TCP_NO_DELAY);
                PlayerConnection playerConnection = new PlayerConnection(clientSocket);
                THREAD_POOL.execute(playerConnection);
                activeConnections.add(playerConnection);
            } catch (IOException ex) {
                //Logger.getLogger(ServerDispatcher.class.getName()).log(Level.SEVERE, null, ex);
                ConsoleFrame.sendMessage(this.getClass().getSimpleName(), ex.getMessage());
            }
        }
    }

    @Override
    public void run() {
        startConnectionCleaner();
        listenForConnections(serverSocket);
    }

    /**
     * Send a request to all clients connected to this match.
     *
     * @param request The request which will be broadcasted to all connected
     * players.
     */
    public synchronized void broadcast(Request request) {
        for (Connection i : activeConnections) {
            try {
                i.getOutputStream().reset();
                i.getOutputStream().writeObject(request);
                i.getOutputStream().flush();
            } catch (IOException ex) {
                Logger.getLogger(ClientServerDispatcher.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Send a request to all clients connected to this match except the host.
     *
     * @param request The request which will be broadcasted to all connected
     * players.
     */
    public synchronized void broadcastToAllExceptHost(Request request) {
        for (Connection i : activeConnections) {
            if (!((PlayerConnection) i).getUsername().equals(Player.getInstance().getUsername())) {
                try {
                    i.getOutputStream().reset();
                    i.getOutputStream().writeObject(request);
                    i.getOutputStream().flush();
                } catch (IOException ex) {
                    Logger.getLogger(ClientServerDispatcher.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    /**
     * @return The active match associated with this server.
     */
    public Match getActiveMatch() {
        return activeMatch;
    }

    public AbstractMap getSourceFilesMap() {
        return sourceFiles;
    }

    public List<String> getPlayerStateList() {
        List<String> playerStates = new ArrayList<>();
        for (String player : activeMatch.getPlayerList()) {
            String entry = player;
            Source sourceName = sourceFiles.get(player);
            if (sourceName != null) {
                entry += "/" + sourceName.getName();
            }
            playerStates.add(entry);
        }

        return playerStates;
    }
}


text:
var ApiGen = ApiGen || {};
ApiGen.elements = [["c","controllerProcessExcel"],["c","excelProcessor"],["f","is_date()"],["f","is_time()"],["c","modelProcessExcel"],["c","previewSheet"]];


text:
/*
 * @Author: 卓文理
 * @Email: 531840344@qq.com
 * @Date: 2017-08-08 11:17:25
 */

'use strict';

import ReactDOM from 'react-dom';
import socket from 'app/composition/socket';
import { store, Main } from './main';

debug.enable(process.env.DEBUG);

const log = debug('entry');

log(`Running in [${process.env.NODE_ENV}] environment`);
log('Environment', process.env);

socket.on('connect', () => {
    log('Client connected to socket');

    store.dispatch({
        type: 'NEW_SOCKET_SESSION',
        payload: { data: Math.random() },
        meta: { broadcast: true, next: false },
    });
});

socket.open();

ReactDOM.render(
    Main, document.getElementById('app-container')
);


text:
/// @example cpu_cnn_inference_f32.c
/// @copybrief cpu_cnn_inference_f32_c
/// > Annotated version: @ref cpu_cnn_inference_f32_c

/// @page cpu_cnn_inference_f32_c CNN f32 inference example
/// This C API example demonstrates how to build an AlexNet neural
/// network topology for forward-pass inference.
///
/// > Example code: @ref cpu_cnn_inference_f32.c
///
/// Some key take-aways include:
///
/// * How tensors are implemented and submitted to primitives.
/// * How primitives are created.
/// * How primitives are sequentially submitted to the network, where the
///   output from primitives is passed as input to the next primitive.
///   The latter specifies a dependency between the primitive input and output
///   data.
/// * Specific 'inference-only' configurations.
/// * Limiting the number of reorders performed that are detrimental
///   to performance.
///
/// The example implements the AlexNet layers
/// as numbered primitives (for example, conv1, pool1, conv2).
///
/// @include cpu_cnn_inference_f32.c

// Required for posix_memalign
#define _POSIX_C_SOURCE 200112L

#include "mkldnn.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BATCH 8
#define IC 3
#define OC 96
#define CONV_IH 227
#define CONV_IW 227
#define CONV_OH 55
#define CONV_OW 55
#define CONV_STRIDE 4
#define CONV_PAD 0
#define POOL_OH 27
#define POOL_OW 27
#define POOL_STRIDE 2
#define POOL_PAD 0

#define CHECK(f)                                                             \
    do {                                                                     \
        mkldnn_status_t s = f;                                               \
        if (s != mkldnn_success) {                                           \
            printf("[%s:%d] error: %s returns %d\n", __FILE__, __LINE__, #f, \
                    s);                                                      \
            exit(2);                                                         \
        }                                                                    \
    } while (0)

#define CHECK_TRUE(expr)                                              \
    do {                                                              \
        int e_ = expr;                                                \
        if (!e_) {                                                    \
            printf("[%s:%d] %s failed\n", __FILE__, __LINE__, #expr); \
            exit(2);                                                  \
        }                                                             \
    } while (0)

static size_t product(mkldnn_dim_t *arr, size_t size) {
    size_t prod = 1;
    for (size_t i = 0; i < size; ++i)
        prod *= arr[i];
    return prod;
}

typedef struct {
    int nargs;
    mkldnn_exec_arg_t *args;
} args_t;

static void prepare_arg_node(args_t *node, int nargs) {
    node->args = (mkldnn_exec_arg_t *)malloc(sizeof(mkldnn_exec_arg_t) * nargs);
    node->nargs = nargs;
}
static void free_arg_node(args_t *node) {
    free(node->args);
}

static void set_arg(
        mkldnn_exec_arg_t *arg, int arg_idx, mkldnn_memory_t memory) {
    arg->arg = arg_idx;
    arg->memory = memory;
}

static void init_data_memory(uint32_t dim, const mkldnn_dim_t *dims,
        mkldnn_format_tag_t user_tag, mkldnn_data_type_t mkldnn_f32,
        mkldnn_engine_t engine, float *data, mkldnn_memory_t *memory) {
    mkldnn_memory_desc_t user_md;
    CHECK(mkldnn_memory_desc_init_by_tag(
            &user_md, dim, dims, mkldnn_f32, user_tag));
    CHECK(mkldnn_memory_create(memory, &user_md, engine, data));
}

mkldnn_status_t prepare_reorder(mkldnn_memory_t *user_memory, // in
        const mkldnn_memory_desc_t *prim_memory_md, // in
        mkldnn_engine_t prim_engine, // in: primitive's engine
        int dir_is_user_to_prim, // in: user -> prim or prim -> user
        mkldnn_memory_t *prim_memory, // out: primitive's memory created
        mkldnn_primitive_t *reorder, // out: reorder primitive created
        uint32_t *net_index, // primitive index in net (inc if reorder created)
        mkldnn_primitive_t *net, args_t *net_args) {  // net params
    const mkldnn_memory_desc_t *user_memory_md;
    mkldnn_memory_get_memory_desc(*user_memory, &user_memory_md);

    mkldnn_engine_t user_mem_engine;
    mkldnn_memory_get_engine(*user_memory, &user_mem_engine);

    if (!mkldnn_memory_desc_equal(user_memory_md, prim_memory_md)) {
        // memory_create(&p, m, NULL) means allocate memory
        CHECK(mkldnn_memory_create(prim_memory, prim_memory_md, prim_engine,
                MKLDNN_MEMORY_ALLOCATE));
        mkldnn_primitive_desc_t reorder_pd;
        if (dir_is_user_to_prim) {
            CHECK(mkldnn_reorder_primitive_desc_create(&reorder_pd,
                    user_memory_md, user_mem_engine, prim_memory_md,
                    prim_engine, NULL));
        } else {
            CHECK(mkldnn_reorder_primitive_desc_create(&reorder_pd,
                    prim_memory_md, prim_engine, user_memory_md,
                    user_mem_engine, NULL));
        }
        CHECK(mkldnn_primitive_create(reorder, reorder_pd));
        CHECK(mkldnn_primitive_desc_destroy(reorder_pd));

        net[*net_index] = *reorder;
        prepare_arg_node(&net_args[*net_index], 2);
        set_arg(&net_args[*net_index].args[0], MKLDNN_ARG_FROM,
                dir_is_user_to_prim ? *user_memory : *prim_memory);
        set_arg(&net_args[*net_index].args[1], MKLDNN_ARG_TO,
                dir_is_user_to_prim ? *prim_memory : *user_memory);
        (*net_index)++;
    } else {
        *prim_memory = NULL;
        *reorder = NULL;
    }

    return mkldnn_success;
}

mkldnn_status_t simple_net() {

    mkldnn_engine_t engine;
    CHECK(mkldnn_engine_create(&engine, mkldnn_cpu, 0));

    // build a simple net
    uint32_t n = 0;
    mkldnn_primitive_t net[10];
    args_t net_args[10];

    float *net_src
            = (float *)malloc(BATCH * IC * CONV_IH * CONV_IW * sizeof(float));
    float *net_dst
            = (float *)malloc(BATCH * OC * POOL_OH * POOL_OW * sizeof(float));

    // AlexNet: conv
    // {BATCH, IC, CONV_IH, CONV_IW} (x) {OC, IC, CONV_KH, CONV_KW} ->
    // {BATCH, OC, CONV_OH, CONV_OW}
    // strides: {CONV_STRIDE, CONV_STRIDE}
    mkldnn_dim_t conv_user_src_sizes[4] = { BATCH, IC, CONV_IH, CONV_IW };
    mkldnn_dim_t conv_user_weights_sizes[4] = { OC, IC, 11, 11 };
    mkldnn_dim_t conv_bias_sizes[4] = { OC };
    mkldnn_dim_t conv_user_dst_sizes[4] = { BATCH, OC, CONV_OH, CONV_OW };
    mkldnn_dim_t conv_strides[2] = { CONV_STRIDE, CONV_STRIDE };
    mkldnn_dim_t conv_padding[2] = { CONV_PAD, CONV_PAD };

    float *conv_src = net_src;
    float *conv_weights = (float *)malloc(
            product(conv_user_weights_sizes, 4) * sizeof(float));
    float *conv_bias
            = (float *)malloc(product(conv_bias_sizes, 1) * sizeof(float));

    // create memory for user data
    mkldnn_memory_t conv_user_src_memory, conv_user_weights_memory,
            conv_user_bias_memory;
    init_data_memory(4, conv_user_src_sizes, mkldnn_nchw, mkldnn_f32, engine,
            conv_src, &conv_user_src_memory);
    init_data_memory(4, conv_user_weights_sizes, mkldnn_oihw, mkldnn_f32,
            engine, conv_weights, &conv_user_weights_memory);
    init_data_memory(1, conv_bias_sizes, mkldnn_x, mkldnn_f32, engine,
            conv_bias, &conv_user_bias_memory);

    // create data descriptors for convolution w/ no specified format

    mkldnn_memory_desc_t conv_src_md, conv_weights_md, conv_bias_md,
            conv_dst_md;
    CHECK(mkldnn_memory_desc_init_by_tag(&conv_src_md, 4, conv_user_src_sizes,
            mkldnn_f32, mkldnn_format_tag_any));
    CHECK(mkldnn_memory_desc_init_by_tag(&conv_weights_md, 4,
            conv_user_weights_sizes, mkldnn_f32, mkldnn_format_tag_any));
    CHECK(mkldnn_memory_desc_init_by_tag(
            &conv_bias_md, 1, conv_bias_sizes, mkldnn_f32, mkldnn_x));
    CHECK(mkldnn_memory_desc_init_by_tag(&conv_dst_md, 4, conv_user_dst_sizes,
            mkldnn_f32, mkldnn_format_tag_any));

    // create a convolution
    mkldnn_convolution_desc_t conv_any_desc;
    CHECK(mkldnn_convolution_forward_desc_init(&conv_any_desc, mkldnn_forward,
            mkldnn_convolution_direct, &conv_src_md, &conv_weights_md,
            &conv_bias_md, &conv_dst_md, conv_strides, conv_padding,
            conv_padding));

    mkldnn_primitive_desc_t conv_pd;
    CHECK(mkldnn_primitive_desc_create(
            &conv_pd, &conv_any_desc, NULL, engine, NULL));

    mkldnn_memory_t conv_internal_src_memory, conv_internal_weights_memory,
            conv_internal_dst_memory;

    // create memory for dst data, we don't need reorder it to user data
    const mkldnn_memory_desc_t *dst_md
            = mkldnn_primitive_desc_query_md(conv_pd, mkldnn_query_dst_md, 0);
    CHECK(mkldnn_memory_create(&conv_internal_dst_memory, dst_md, engine,
            MKLDNN_MEMORY_ALLOCATE));

    // create reorder primitives between user data and convolution srcs
    // if required
    mkldnn_primitive_t conv_reorder_src, conv_reorder_weights;

    const mkldnn_memory_desc_t *src_md
            = mkldnn_primitive_desc_query_md(conv_pd, mkldnn_query_src_md, 0);
    CHECK(prepare_reorder(&conv_user_src_memory, src_md, engine, 1,
            &conv_internal_src_memory, &conv_reorder_src, &n, net, net_args));

    const mkldnn_memory_desc_t *weights_md = mkldnn_primitive_desc_query_md(
            conv_pd, mkldnn_query_weights_md, 0);
    CHECK(prepare_reorder(&conv_user_weights_memory, weights_md, engine, 1,
            &conv_internal_weights_memory, &conv_reorder_weights, &n, net,
            net_args));

    mkldnn_memory_t conv_src_memory = conv_internal_src_memory ?
            conv_internal_src_memory :
            conv_user_src_memory;
    mkldnn_memory_t conv_weights_memory = conv_internal_weights_memory ?
            conv_internal_weights_memory :
            conv_user_weights_memory;

    // finally create a convolution primitive
    mkldnn_primitive_t conv;
    CHECK(mkldnn_primitive_create(&conv, conv_pd));
    net[n] = conv;
    prepare_arg_node(&net_args[n], 4);
    set_arg(&net_args[n].args[0], MKLDNN_ARG_SRC, conv_src_memory);
    set_arg(&net_args[n].args[1], MKLDNN_ARG_WEIGHTS, conv_weights_memory);
    set_arg(&net_args[n].args[2], MKLDNN_ARG_BIAS, conv_user_bias_memory);
    set_arg(&net_args[n].args[3], MKLDNN_ARG_DST, conv_internal_dst_memory);
    n++;

    // AlexNet: relu
    // {BATCH, OC, CONV_OH, CONV_OW} -> {BATCH, OC, CONV_OH, CONV_OW}
    float negative_slope = 1.0f;

    // create relu memory descriptor on dst memory descriptor
    // from previous primitive
    const mkldnn_memory_desc_t *relu_src_md
            = mkldnn_primitive_desc_query_md(conv_pd, mkldnn_query_dst_md, 0);

    // create a relu
    mkldnn_eltwise_desc_t relu_desc;
    CHECK(mkldnn_eltwise_forward_desc_init(&relu_desc, mkldnn_forward,
            mkldnn_eltwise_relu, relu_src_md, negative_slope, 0));

    mkldnn_primitive_desc_t relu_pd;
    CHECK(mkldnn_primitive_desc_create(
            &relu_pd, &relu_desc, NULL, engine, NULL));

    mkldnn_memory_t relu_dst_memory;
    const mkldnn_memory_desc_t *relu_dst_md
            = mkldnn_primitive_desc_query_md(relu_pd, mkldnn_query_dst_md, 0);
    CHECK(mkldnn_memory_create(&relu_dst_memory, relu_dst_md, engine,
            MKLDNN_MEMORY_ALLOCATE));

    // finally create a relu primitive
    mkldnn_primitive_t relu;
    CHECK(mkldnn_primitive_create(&relu, relu_pd));
    net[n] = relu;
    prepare_arg_node(&net_args[n], 2);
    set_arg(&net_args[n].args[0], MKLDNN_ARG_SRC, conv_internal_dst_memory);
    set_arg(&net_args[n].args[1], MKLDNN_ARG_DST, relu_dst_memory);
    n++;

    // AlexNet: lrn
    // {BATCH, OC, CONV_OH, CONV_OW} -> {BATCH, OC, CONV_OH, CONV_OW}
    // local size: 5
    // alpha: 0.0001
    // beta: 0.75
    uint32_t local_size = 5;
    float alpha = 0.0001f;
    float beta = 0.75f;
    float k = 1.0f;

    // create lrn memory descriptor on dst memory descriptor
    //  from previous primitive
    const mkldnn_memory_desc_t *lrn_src_md = relu_dst_md;

    // create a lrn
    mkldnn_lrn_desc_t lrn_desc;
    CHECK(mkldnn_lrn_forward_desc_init(&lrn_desc, mkldnn_forward,
            mkldnn_lrn_across_channels, lrn_src_md, local_size, alpha, beta,
            k));

    mkldnn_primitive_desc_t lrn_pd;
    CHECK(mkldnn_primitive_desc_create(&lrn_pd, &lrn_desc, NULL, engine, NULL));

    mkldnn_memory_t lrn_dst_memory;
    const mkldnn_memory_desc_t *lrn_dst_md
            = mkldnn_primitive_desc_query_md(lrn_pd, mkldnn_query_dst_md, 0);
    CHECK(mkldnn_memory_create(&lrn_dst_memory, lrn_dst_md, engine,
            MKLDNN_MEMORY_ALLOCATE));

    mkldnn_memory_t lrn_ws_memory;
    const mkldnn_memory_desc_t *lrn_ws_md = mkldnn_primitive_desc_query_md(
            lrn_pd, mkldnn_query_workspace_md, 0);
    CHECK(mkldnn_memory_create(
            &lrn_ws_memory, lrn_ws_md, engine, MKLDNN_MEMORY_ALLOCATE));

    // finally create a lrn primitive
    mkldnn_primitive_t lrn;
    CHECK(mkldnn_primitive_create(&lrn, lrn_pd));
    net[n] = lrn;
    prepare_arg_node(&net_args[n], 3);
    set_arg(&net_args[n].args[0], MKLDNN_ARG_SRC, relu_dst_memory);
    set_arg(&net_args[n].args[1], MKLDNN_ARG_DST, lrn_dst_memory);
    set_arg(&net_args[n].args[2], MKLDNN_ARG_WORKSPACE, lrn_ws_memory);
    n++;

    // AlexNet: pool
    // {BATCH, OC, CONV_OH, CONV_OW} -> {BATCH, OC, POOL_OH, POOL_OW}
    // kernel: {3, 3}
    // strides: {POOL_STRIDE, POOL_STRIDE}
    mkldnn_dim_t pool_dst_sizes[4] = { BATCH, OC, POOL_OH, POOL_OW };
    mkldnn_dim_t pool_kernel[2] = { 3, 3 };
    mkldnn_dim_t pool_strides[2] = { POOL_STRIDE, POOL_STRIDE };
    mkldnn_dim_t pool_padding[2] = { POOL_PAD, POOL_PAD };

    // create pooling memory descriptor on dst descriptor
    //  from previous primitive
    const mkldnn_memory_desc_t *pool_src_md = lrn_dst_md;

    // create descriptors for dst pooling data
    mkldnn_memory_desc_t pool_dst_any_md;
    CHECK(mkldnn_memory_desc_init_by_tag(&pool_dst_any_md, 4, pool_dst_sizes,
            mkldnn_f32, mkldnn_format_tag_any));

    // create memory for user data
    mkldnn_memory_t pool_user_dst_memory;
    init_data_memory(4, pool_dst_sizes, mkldnn_nchw, mkldnn_f32, engine,
            net_dst, &pool_user_dst_memory);

    // create a pooling
    mkldnn_pooling_desc_t pool_desc;
    CHECK(mkldnn_pooling_forward_desc_init(&pool_desc, mkldnn_forward,
            mkldnn_pooling_max, pool_src_md, &pool_dst_any_md, pool_strides,
            pool_kernel, pool_padding, pool_padding));

    mkldnn_primitive_desc_t pool_pd;
    CHECK(mkldnn_primitive_desc_create(
            &pool_pd, &pool_desc, NULL, engine, NULL));

    // create memory for workspace
    mkldnn_memory_t pool_ws_memory;
    const mkldnn_memory_desc_t *pool_ws_md = mkldnn_primitive_desc_query_md(
            pool_pd, mkldnn_query_workspace_md, 0);
    CHECK(mkldnn_memory_create(&pool_ws_memory, pool_ws_md, engine,
            MKLDNN_MEMORY_ALLOCATE));

    mkldnn_memory_t pool_dst_memory;

    // create reorder primitives between user data and pooling dsts
    // if required
    mkldnn_primitive_t pool_reorder_dst;
    mkldnn_memory_t pool_internal_dst_memory;
    const mkldnn_memory_desc_t *pool_dst_md
            = mkldnn_primitive_desc_query_md(pool_pd, mkldnn_query_dst_md, 0);
    n += 1; // tentative workaround: preserve space for pooling that should
            // happen before the reorder
    CHECK(prepare_reorder(&pool_user_dst_memory, pool_dst_md, engine, 0,
            &pool_internal_dst_memory, &pool_reorder_dst, &n, net, net_args));
    n -= pool_reorder_dst ? 2 : 1;

    pool_dst_memory = pool_internal_dst_memory ? pool_internal_dst_memory :
                                                 pool_user_dst_memory;

    // finally create a pooling primitive
    mkldnn_primitive_t pool;
    CHECK(mkldnn_primitive_create(&pool, pool_pd));
    net[n] = pool;
    prepare_arg_node(&net_args[n], 3);
    set_arg(&net_args[n].args[0], MKLDNN_ARG_SRC, lrn_dst_memory);
    set_arg(&net_args[n].args[1], MKLDNN_ARG_DST, pool_dst_memory);
    set_arg(&net_args[n].args[2], MKLDNN_ARG_WORKSPACE, pool_ws_memory);
    n++;

    if (pool_reorder_dst)
        n += 1;

    mkldnn_stream_t stream;
    CHECK(mkldnn_stream_create(&stream, engine, mkldnn_stream_default_flags));
    for (uint32_t i = 0; i < n; ++i) {
        CHECK(mkldnn_primitive_execute(
                net[i], stream, net_args[i].nargs, net_args[i].args));
    }

    CHECK(mkldnn_stream_wait(stream));

    // clean-up
    for (uint32_t i = 0; i < n; ++i)
        free_arg_node(&net_args[i]);

    CHECK(mkldnn_primitive_desc_destroy(conv_pd));
    CHECK(mkldnn_primitive_desc_destroy(relu_pd));
    CHECK(mkldnn_primitive_desc_destroy(lrn_pd));
    CHECK(mkldnn_primitive_desc_destroy(pool_pd));

    mkldnn_stream_destroy(stream);

    free(net_src);
    free(net_dst);

    mkldnn_memory_destroy(conv_user_src_memory);
    mkldnn_memory_destroy(conv_user_weights_memory);
    mkldnn_memory_destroy(conv_user_bias_memory);
    mkldnn_memory_destroy(conv_internal_src_memory);
    mkldnn_memory_destroy(conv_internal_weights_memory);
    mkldnn_memory_destroy(conv_internal_dst_memory);
    mkldnn_primitive_destroy(conv_reorder_src);
    mkldnn_primitive_destroy(conv_reorder_weights);
    mkldnn_primitive_destroy(conv);

    free(conv_weights);
    free(conv_bias);

    mkldnn_memory_destroy(relu_dst_memory);
    mkldnn_primitive_destroy(relu);

    mkldnn_memory_destroy(lrn_ws_memory);
    mkldnn_memory_destroy(lrn_dst_memory);
    mkldnn_primitive_destroy(lrn);

    mkldnn_memory_destroy(pool_user_dst_memory);
    mkldnn_memory_destroy(pool_internal_dst_memory);
    mkldnn_memory_destroy(pool_ws_memory);
    mkldnn_primitive_destroy(pool_reorder_dst);
    mkldnn_primitive_destroy(pool);

    mkldnn_engine_destroy(engine);

    return mkldnn_success;
}

int main(int argc, char **argv) {
    mkldnn_status_t result = simple_net();
    printf("%s\n", (result == mkldnn_success) ? "passed" : "failed");
    return result;
}


text:
import type { ICoordinates } from "./ICoordinates";
export interface IMouseData {
    clickPosition?: ICoordinates;
    position?: ICoordinates;
    clickTime?: number;
}


text:
//============================================================================
// Name        : LOD_Example.h
// Author      : Duarte Peixinho
// Version     :
// Copyright   : ;)
// Description : LOD Example
//============================================================================

#ifndef LOD_EXAMPLE_H
#define	LOD_EXAMPLE_H

#define TEAPOTS 10000

#include "../BaseExample/BaseExample.h"
#include <Pyros3D/Rendering/Renderer/ForwardRenderer/ForwardRenderer.h>
#include <Pyros3D/Utils/Colors/Colors.h>
#include <Pyros3D/Rendering/Components/Rendering/RenderingComponent.h>
#include <Pyros3D/Rendering/Components/Lights/DirectionalLight/DirectionalLight.h>
#include <Pyros3D/Assets/Renderable/Primitives/Shapes/Sphere.h>
#include <Pyros3D/Rendering/Components/Rendering/RenderingComponent.h>
#include <Pyros3D/Core/Octree/Octree.h>
using namespace p3d;

class LOD_Example : public BaseExample
{

public:

	LOD_Example();
	virtual ~LOD_Example();

	virtual void Init();
	virtual void Update();
	virtual void Shutdown();
	virtual void OnResize(const uint32 width, const uint32 height);

private:

	// Renderer
	ForwardRenderer* Renderer;
	// Projection
	Projection projection;
	// Light
	std::vector<GameObject*> Lights;
	std::vector<PointLight*> pLights;

	// Objects List
	std::vector<GameObject*> Teapots;
	std::vector<RenderingComponent*> rTeapots;
	std::vector<GenericShaderMaterial*> mTeapots;
	Renderable* teapotLOD1Handle;
	Renderable* teapotLOD2Handle;
	Renderable* teapotLOD3Handle;

	Octree* octree;
	bool generatedOctree;
};

#endif	/* LOD_EXAMPLE_H */


text:
package org.geometrycommands;

import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import java.io.Reader;
import java.io.Writer;
import org.geometrycommands.GridCommand.GridOptions;
import org.kohsuke.args4j.Option;

/**
 * A Command to create a vector grid
 * @author Jared Erickson
 */
public class GridCommand extends GeometryCommand<GridOptions> {

    /**
     * Get the command name
     * @return The command name
     */
    @Override
    public String getName() {
        return "grid";
    }

    /**
     * Get the description of what the Command does
     * @return The description of what the Command does
     */
    @Override
    public String getDescription() {
        return "Calculate a grid around the input geometry.";
    }

    /**
     * Get the GridOptions
     * @return The GridOptions
     */
    @Override
    public GridOptions getOptions() {
        return new GridOptions();
    }

    /**
     * Create a vector grid
     * @param geometry The input Geometry
     * @param options The GeometryOptions
     * @param reader The java.io.Reader
     * @param writer The java.io.Writer
     * @throws Exception if an error occurs
     */
    @Override
    protected void processGeometry(Geometry geometry, GridOptions options, Reader reader, Writer writer) throws Exception {

        // Get the input Geometry's Envelope
        Envelope env = geometry.getEnvelopeInternal();

        // Extract the min X and Y
        double minX = env.getMinX();
        double minY = env.getMinY();

        // Calculate hte envelop's width and height
        double w = env.getWidth();
        double h = env.getHeight();

        // Get the number of columns and rows
        int numberOfColumns = options.getNumberOfColumns();
        int numberOfRows = options.getNumberOfRows();

        // Calculate the cell width and height
        double cellWidth = w / options.getNumberOfColumns();
        double cellHeight = h / options.getNumberOfRows();

        // Create the cells
        GeometryFactory geometryFactory = new GeometryFactory();
        Geometry[] geoms = new Geometry[numberOfRows * numberOfColumns];
        int i = 0;
        for (int r = 0; r < numberOfRows; r++) {
            for (int c = 0; c < numberOfColumns; c++) {
                double x = minX + (c * cellWidth);
                double y = minY + (r * cellHeight);
                Envelope e = new Envelope(x, x + cellWidth, y, y + cellHeight);
                geoms[i] = geometryFactory.toGeometry(e);
                i++;
            }
        }

        // Create the Geometry grid
        Geometry grid = geometryFactory.createGeometryCollection(geoms);

        // Write the Geometry grid
        writer.write(writeGeometry(grid, options));
    }

    /**
     * The GridOptions
     */
    public static class GridOptions extends GeometryOptions {

        /**
         * The number of columns
         */
        @Option(name = "-c", aliases = "--columns", usage = "The number of columns", required = true)
        private int numberOfColumns;

        /**
         * The number of rows
         */
        @Option(name = "-r", aliases = "--rows", usage = "The number of rows", required = true)
        private int numberOfRows;

        /**
         * Get the number of columns
         * @return The number of columns
         */
        public int getNumberOfColumns() {
            return numberOfColumns;
        }

        /**
         * Set the number of columns
         * @param numberOfColumns The number of columns
         */
        public void setNumberOfColumns(int numberOfColumns) {
            this.numberOfColumns = numberOfColumns;
        }

        /**
         * Get the number of rows
         * @return The number of rows
         */
        public int getNumberOfRows() {
            return numberOfRows;
        }

        /**
         * Set the number of rows
         * @param numberOfRows The number of rows
         */
        public void setNumberOfRows(int numberOfRows) {
            this.numberOfRows = numberOfRows;
        }
    }
}


text:
package arms

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// GetRecordingRule invokes the arms.GetRecordingRule API synchronously
func (client *Client) GetRecordingRule(request *GetRecordingRuleRequest) (response *GetRecordingRuleResponse, err error) {
	response = CreateGetRecordingRuleResponse()
	err = client.DoAction(request, response)
	return
}

// GetRecordingRuleWithChan invokes the arms.GetRecordingRule API asynchronously
func (client *Client) GetRecordingRuleWithChan(request *GetRecordingRuleRequest) (<-chan *GetRecordingRuleResponse, <-chan error) {
	responseChan := make(chan *GetRecordingRuleResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.GetRecordingRule(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// GetRecordingRuleWithCallback invokes the arms.GetRecordingRule API asynchronously
func (client *Client) GetRecordingRuleWithCallback(request *GetRecordingRuleRequest, callback func(response *GetRecordingRuleResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *GetRecordingRuleResponse
		var err error
		defer close(result)
		response, err = client.GetRecordingRule(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// GetRecordingRuleRequest is the request struct for api GetRecordingRule
type GetRecordingRuleRequest struct {
	*requests.RpcRequest
	ClusterId string `position:"Query" name:"ClusterId"`
}

// GetRecordingRuleResponse is the response struct for api GetRecordingRule
type GetRecordingRuleResponse struct {
	*responses.BaseResponse
	RequestId string `json:"RequestId" xml:"RequestId"`
	Data      string `json:"Data" xml:"Data"`
}

// CreateGetRecordingRuleRequest creates a request to invoke GetRecordingRule API
func CreateGetRecordingRuleRequest() (request *GetRecordingRuleRequest) {
	request = &GetRecordingRuleRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("ARMS", "2019-08-08", "GetRecordingRule", "arms", "openAPI")
	request.Method = requests.POST
	return
}

// CreateGetRecordingRuleResponse creates a response to parse from GetRecordingRule response
func CreateGetRecordingRuleResponse() (response *GetRecordingRuleResponse) {
	response = &GetRecordingRuleResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
package com.google.android.imaging.pixelvisualcorecamera.api2;

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.Matrix.ScaleToFit;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Size;
import android.view.Surface;
import android.view.TextureView;

/**
 * A {@link TextureView} that can be adjusted to a specified aspect ratio.
 */
public final class AutoFitTextureView extends TextureView {

  private int mRatioWidth = 0;
  private int mRatioHeight = 0;

  public AutoFitTextureView(Context context) {
    this(context, null);
  }

  public AutoFitTextureView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public AutoFitTextureView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  /**
   * Sets the aspect ratio for this view. The size of the view will be measured based on the ratio
   * calculated from the parameters. Note that the actual sizes of parameters don't matter, that
   * is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result.
   *
   * @param width  Relative horizontal size
   * @param height Relative vertical size
   */
  public void setAspectRatio(int width, int height) {
    if (width < 0 || height < 0) {
      throw new IllegalArgumentException("Size cannot be negative.");
    }
    mRatioWidth = width;
    mRatioHeight = height;
    requestLayout();
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
    if (0 == mRatioWidth || 0 == mRatioHeight) {
      setMeasuredDimension(width, height);
    } else {
      if (width < height * mRatioWidth / mRatioHeight) {
        setMeasuredDimension(width, width * mRatioHeight / mRatioWidth);
      } else {
        setMeasuredDimension(height * mRatioWidth / mRatioHeight, height);
      }
    }
  }

  /**
   * Configures the necessary {@link Matrix} transformation.
   * This method should be called after the camera preview size is determined.
   *
   * @param displayRotation current rotation of default display
   * @param viewWidth  The width of `mTextureView`
   * @param viewHeight The height of `mTextureView`
   */
  void configureTransform(
      int displayRotation, int viewWidth, int viewHeight, Size previewSize) {
    Matrix matrix = new Matrix();
    RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
    RectF bufferRect = new RectF(0, 0, previewSize.getHeight(), previewSize.getWidth());
    float centerX = viewRect.centerX();
    float centerY = viewRect.centerY();
    if (Surface.ROTATION_90 == displayRotation || Surface.ROTATION_270 == displayRotation) {
      bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
      matrix.setRectToRect(viewRect, bufferRect, ScaleToFit.FILL);
      float scale = Math.max(
          (float) viewHeight / previewSize.getHeight(),
          (float) viewWidth / previewSize.getWidth());
      matrix.postScale(scale, scale, centerX, centerY);
      matrix.postRotate(90 * (displayRotation - 2), centerX, centerY);
    } else if (Surface.ROTATION_180 == displayRotation) {
      matrix.postRotate(180, centerX, centerY);
    }
    setTransform(matrix);
  }
}


text:
import Hapi = require('hapi');

// Create a server with a host and port
var server = Hapi.createServer('localhost', 8000);

// Add plugins
var plugin: any = {
	register: function (plugin: Object, options: Object, next: Function) {
		next();
	}
};

plugin.register.attributes = {
	name: 'test',
	version: '1.0.0'
};

server.pack.register(plugin, (err: Object) => {
	if (err) { throw err; }
});

server.pack.register([plugin], (err: Object) => {
	if (err) { throw err; }
});

// Add server method
var add = function (a: number, b: number, next: (err: any, result?: any, ttl?: number) => void) {
	next(null, a + b);
};

server.method('sum', add, { cache: { expiresIn: 2000 } });

server.methods.sum(4, 5, (err: any, result: any) => {
	console.log(result);
});

var addArray = function (array: Array<number>, next: (err: any, result?: any, ttl?: number) => void) {
	var sum: number = 0;
	array.forEach((item: number) => {
		sum += item;
	});
	next(null, sum);
};

server.method('sumObj', addArray, {
	cache: { expiresIn: 2000 },
	generateKey: (array: Array<number>) => {
		return array.join(',');
	}
});

server.methods.sumObj([5, 6], (err: any, result: any) => {
	console.log(result);
});

// Add the route
server.route({
	method: 'GET',
	path: '/hello',
	handler: function (request: Hapi.Request, reply: Function) {
		reply('hello world');
	}
});

server.route([{
	method: 'GET',
	path: '/hello2',
	handler: function (request: Hapi.Request, reply: Function) {
		reply('hello world2');
	}
}]);

// Start the server
server.start();


text:
<?xml version="1.0" encoding="UTF-8"?>
<thresholds>
   <threshold branchcount="6" branchrate="80" branchsexecuted="0"
              class="gov.hhs.fha.nhinc.docquery._20.entity.EntityDocQueryImpl"
              linecount="41"
              linerate="80"
              linesexecuted="0"/>
   <threshold branchcount="2" branchrate="80" branchsexecuted="0"
              class="gov.hhs.fha.nhinc.docquery._20.entity.EntityDocQuerySecured"
              linecount="8"
              linerate="80"
              linesexecuted="0"/>
   <threshold branchcount="2" branchrate="80" branchsexecuted="0"
              class="gov.hhs.fha.nhinc.docquery._20.entity.EntityDocQueryUnsecured"
              linecount="8"
              linerate="80"
              linesexecuted="0"/>
   <threshold branchcount="0" branchrate="80" branchsexecuted="0"
              class="gov.hhs.fha.nhinc.docquery._20.nhin.DocQuery"
              linecount="2"
              linerate="80"
              linesexecuted="0"/>
   <threshold branchcount="2" branchrate="80" branchsexecuted="0"
              class="gov.hhs.fha.nhinc.docquery._20.nhin.DocQueryImpl"
              linecount="12"
              linerate="80"
              linesexecuted="0"/>
   <threshold branchcount="4" branchrate="80" branchsexecuted="0"
              class="gov.hhs.fha.nhinc.docquery._20.passthru.NhincProxyDocQueryImpl"
              linecount="14"
              linerate="80"
              linesexecuted="0"/>
   <threshold branchcount="0" branchrate="80" branchsexecuted="0"
              class="gov.hhs.fha.nhinc.docquery._20.passthru.NhincProxyDocQuerySecured"
              linecount="2"
              linerate="80"
              linesexecuted="0"/>
   <threshold branchcount="0" branchrate="80" branchsexecuted="0"
              class="gov.hhs.fha.nhinc.docquery._20.passthru.NhincProxyDocQueryUnsecured"
              linecount="2"
              linerate="80"
              linesexecuted="0"/>
   <threshold branchcount="4" branchrate="80" branchsexecuted="0"
              class="gov.hhs.fha.nhinc.gateway.servlet.InitServlet"
              linecount="19"
              linerate="80"
              linesexecuted="0"/>
</thresholds>


text:
package ws.ament.hammock.web.tomcat;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

import org.jboss.arquillian.core.spi.LoadableExtension;

public class SecureTomcatArquillianExtension implements LoadableExtension {
    @Override
    public void register(ExtensionBuilder extensionBuilder) {
        File baseDir = new File("target/tomcat-work");
        if (!baseDir.exists()) {
            baseDir.mkdir(); // only auto create work folder.
        }
        File keystore = new File(baseDir, "keystore.jks");
        if (keystore.exists()) {
            return; // already copyed
        }

        File keystoreSource = new File("src/test/keystore.jks");
        try {
            Files.copy(keystoreSource.toPath(), keystore.toPath());
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Nabu-asr: data.py File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Nabu-asr

nabu

scripts

Functions |
Variables

data.py File Reference

does the data preperation
More...

Functions

def 	nabu.scripts.data.main (expdir)

 	main function

Variables

 	nabu.scripts.data.FLAGS = tf.app.flags.FLAGS

Detailed Description

does the data preperation

<address class="footer">
Generated by

 1.8.12
</address>


text:
package com.asakusafw.operation.tools.directio.file;

import static com.asakusafw.operation.tools.directio.file.Util.*;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.hadoop.conf.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.asakusafw.operation.tools.directio.BasePath;
import com.asakusafw.operation.tools.directio.DataSourceInfo;
import com.asakusafw.operation.tools.directio.DirectIoPath;
import com.asakusafw.operation.tools.directio.common.ConfigurationParameter;
import com.asakusafw.runtime.directio.DirectDataSource;
import com.asakusafw.runtime.directio.DirectDataSourceRepository;
import com.asakusafw.runtime.directio.hadoop.HadoopDataSourceCore;
import com.asakusafw.runtime.directio.hadoop.HadoopDataSourceUtil;
import com.asakusafw.utils.jcommander.CommandConfigurationException;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.ParametersDelegate;

/**
 * Handles parameters about Direct I/O data source.
 * @since 0.10.0
 */
@Parameters(resourceBundle = "com.asakusafw.operation.tools.directio.jcommander")
public class DataSourceParameter {

    static final Logger LOG = LoggerFactory.getLogger(DataSourceParameter.class);

    @ParametersDelegate
    final ConfigurationParameter configurationParameter = new ConfigurationParameter();

    private DirectDataSourceRepository repository;

    @Parameter(
            names = { "-s", "--data-source", },
            descriptionKey = "parameter.data-source",
            required = false
    )
    String id;

    private List<IdAndPath> declared;

    private DataSourceInfo resolved;

    /**
     * Returns the Hadoop configuration.
     * @return the Hadoop configuration
     */
    public Configuration getConfiguration() {
        return configurationParameter.getConfiguration();
    }

    /**
     * Returns the repository.
     * @return the repository
     */
    public DirectDataSourceRepository getRepository() {
        if (repository == null) {
            LOG.debug("loading data source repository");
            this.repository = HadoopDataSourceUtil.loadRepository(getConfiguration());
        }
        return repository;
    }

    /**
     * Returns the data source information.
     * @return the data source information, or {@code empty} if it is not specified.
     */
    public Optional<DataSourceInfo> getDataSourceInfo() {
        if (id == null) {
            return Optional.empty();
        }
        if (resolved == null) {
            resolved = resolve();
        }
        return Optional.of(resolved);
    }

    /**
     * Returns the data source information for the path.
     * @param path the target path
     * @return the data source information
     */
    public DataSourceInfo getDataSourceInfo(BasePath path) {
        DataSourceInfo info = getDataSourceInfo().orElse(null);
        if (info != null) {
            if (info.getPath().isPrefixOf(path) == false) {
                throw new CommandConfigurationException(MessageFormat.format(
                        "Direct I/O data source \"{0}\" (on \"{1}\") cannot accept the path \"{2}\"",
                        info.getId(),
                        info.getPath(),
                        path));
            }
            return info;
        } else {
            DirectDataSourceRepository repo = getRepository();
            try {
                String container = repo.getContainerPath(path.toString());
                String dsId = repo.getRelatedId(container);
                DirectDataSource source = repo.getRelatedDataSource(container);
                return new DataSourceInfo(dsId, source, BasePath.of(container));
            } catch (IOException | InterruptedException e) {
                throw new CommandConfigurationException(MessageFormat.format(
                        "there is no available Direct I/O data source for the path: {0}",
                        path), e);
            }
        }
    }

    /**
     * Returns the all available Direct I/O data sources.
     * @return the data sources
     */
    public List<DataSourceInfo> getAllDataSourceInfo() {
        DirectDataSourceRepository repo = getRepository();
        return getDeclared().stream()
                .flatMap(pair -> {
                    try {
                        DirectDataSource source = repo.getRelatedDataSource(pair.path);
                        return Stream.of(new DataSourceInfo(pair.id, source, BasePath.of(pair.path)));
                    } catch (IOException | InterruptedException e) {
                        LOG.warn("error occurred while loading Direct I/O data source: {}", pair.id, e);
                        return Stream.empty();
                    }
                })
                .collect(Collectors.toList());
    }

    /**
     * Resolves the given path.
     * @param path the path string
     * @return the corresponded Direct I/O path
     */
    public DirectIoPath resolve(String path) {
        LOG.debug("resolving path: {}", path);

        BasePath basePath = BasePath.headOf(path);
        LOG.debug("base path candidate: {}", basePath);

        DataSourceInfo info = getDataSourceInfo(basePath);
        LOG.debug("data source: {} ({})", info.getId(), info.getPath());

        return new DirectIoPath(info, basePath, basePath.restOf(path).orElse(null));
    }

    /**
     * Resolves the given path as Hadoop file system path.
     * @param path the Direct I/O path string
     * @return the corresponded Hadoop file system path
     */
    public org.apache.hadoop.fs.Path resolveAsHadoopPath(String path) {
        DirectIoPath result = resolve(path);
        if (result.getSource().getEntity().findProperty(HadoopDataSourceCore.class).isPresent() == false) {
            throw new CommandConfigurationException(MessageFormat.format(
                    "unsupported target path \"{0}\" (type: {1}): {2}",
                    result.getSource().getId(),
                    result.getSource().getEntity().getClass().getName(),
                    result));
        }
        if (result.getResourcePattern().isPresent()) {
            throw new CommandConfigurationException(MessageFormat.format(
                    "target path must not contain any meta-characters: {0}",
                    result));
        }
        return asHadoopPath(result.getBarePath());
    }

    /**
     * Returns the Hadoop file system for the path.
     * @param path the target path
     * @return the corresponded file system object
     */
    public org.apache.hadoop.fs.FileSystem getHadoopFileSystem(org.apache.hadoop.fs.Path path) {
        try {
            return path.getFileSystem(getConfiguration());
        } catch (IOException e) {
            throw new CommandConfigurationException(MessageFormat.format(
                    "error occurred while resolving Hadoop path: {0} ({1})",
                    path,
                    Optional.ofNullable(e.getMessage()).orElseGet(() -> e.toString())), e);
        }
    }

    private List<IdAndPath> getDeclared() {
        DirectDataSourceRepository repo = getRepository();
        if (declared == null) {
            try {
                declared = repo.getContainerPaths().stream()
                        .flatMap(path -> {
                            try {
                                return Stream.of(new IdAndPath(repo.getRelatedId(path), path));
                            } catch (IOException e) {
                                LOG.warn("error occurred while resolving data source: {}", path, e);
                            }
                            return Stream.empty();
                        })
                        .collect(Collectors.toList());
            } catch (IOException | InterruptedException e) {
                throw new CommandConfigurationException(
                        "error occurred while collecting Direct I/O data sources", e);
            }
        }
        return declared;
    }

    private DataSourceInfo resolve() {
        String path = getDeclared().stream()
                .filter(it -> it.id.equals(id))
                .map(it -> it.path)
                .findFirst()
                .orElseThrow(() -> new CommandConfigurationException(MessageFormat.format(
                        "Direct I/O data source \"{0}\" is not defined (available IDs: {1})",
                        id,
                        getDeclared().stream()
                                .map(it -> it.id)
                                .sorted()
                                .collect(Collectors.joining(", ")))));

        DirectDataSourceRepository repo = getRepository();
        try {
            DirectDataSource source = repo.getRelatedDataSource(path);
            return new DataSourceInfo(id, source, BasePath.of(path));
        } catch (IOException | InterruptedException e) {
            throw new CommandConfigurationException(MessageFormat.format(
                    "error occurred while loading Direct I/O data source \"{0}\"",
                    id), e);
        }
    }

    private static class IdAndPath {

        final String id;

        final String path;

        IdAndPath(String id, String path) {
            this.id = id;
            this.path = path;
        }
    }
}


text:
namespace djinni_generated {

class NativePrimitiveList final {
public:
    using CppType = ::PrimitiveList;
    using JniType = jobject;

    using Boxed = NativePrimitiveList;

    ~NativePrimitiveList();

    static CppType toCpp(JNIEnv* jniEnv, JniType j);
    static ::djinni::LocalRef<JniType> fromCpp(JNIEnv* jniEnv, const CppType& c);

private:
    NativePrimitiveList();
    friend ::djinni::JniClass<NativePrimitiveList>;

    const ::djinni::GlobalRef<jclass> clazz { ::djinni::jniFindClass("com/dropbox/djinni/test/PrimitiveList") };
    const jmethodID jconstructor { ::djinni::jniGetMethodID(clazz.get(), "<init>", "(Ljava/util/ArrayList;)V") };
    const jfieldID field_mList { ::djinni::jniGetFieldID(clazz.get(), "mList", "Ljava/util/ArrayList;") };
};

}  // namespace djinni_generated


text:
\documentclass[10pt,sigconf]{acmart}
\newcommand{\be}{\begin{enumerate}}
\newcommand{\ee}{\end{enumerate}}
\newcommand{\bi}{\begin{itemize}}
\newcommand{\ei}{\end{itemize}}
\newcommand{\Q}{\(\mathcal{Q}\)}
\usepackage{verbatim}

\usepackage{booktabs} % For formal tables

% Copyright
%\setcopyright{none}
%\setcopyright{acmcopyright}
%\setcopyright{acmlicensed}
%\setcopyright{rightsretained}
%\setcopyright{usgov}
%\setcopyright{usgovmixed}
%\setcopyright{cagov}
%\setcopyright{cagovmixed}

%% % DOI
%% \acmDOI{10.475/123_4}
%%
%% % ISBN
%% \acmISBN{123-4567-24-567/08/06}
%%
%% %Conference
%% \acmConference[WOODSTOCK'97]{ACM Woodstock conference}{July 1997}{El
%%   Paso, Texas USA}
%% \acmYear{1997}
%% \copyrightyear{2016}
%%
%% \acmPrice{15.00}

\begin{document}
% \title{Why (analytical) databases should come in manual transmission}
\title{Small is Beautiful: A Contrarian Approach to Big Data}
% \titlenote{Produces the permission block, and copyright information}
% \subtitle{Extended Abstract}
% \subtitlenote{inspired by Schumacher's classic, ``Small is Beautiful ---
% Economics as if People Mattered''}

\author{Ramesh Subramonian}
\affiliation{%
  \institution{NerdWallet}
}
% \email{rsubramonian@nerdwallet.com}

\author{Indrajeet Singh}
\affiliation{%
  \institution{NerdWallet}
}
% \email{isingh@nerdwallet.com}

\author{Krushnakant Mardikar}
\affiliation{%
 \institution{GS Labs}
}
% \email{krushnakant.mardikar@gslab.com}

\author{Tara Mirmira}
\affiliation{%
  \institution{UC Berkeley}
}
% \email{tmirmira@berkeley.edu}

\author{Srinath Krishnamurthy}
\affiliation{
  \institution{GS Labs}
}
% \email{srinath.krishnamurthy@gslab.com}

% The default list of authors is too long for headers
  \renewcommand{\shortauthors}{R. Subramonian et al}

% \begin{abstract}
% some abstract
% \end{abstract}
\input{abstract}

%
% The code below should be generated by the tool at
% http://dl.acm.org/ccs.cfm
% Please copy and paste the code instead of the example below.
%
%% \begin{CCSXML}
%% <ccs2012>
%%  <concept>
%%   <concept_id>10010520.10010553.10010562</concept_id>
%%   <concept_desc>Computer systems organization~Embedded systems</concept_desc>
%%   <concept_significance>500</concept_significance>
%%  </concept>
%%  <concept>
%%   <concept_id>10010520.10010575.10010755</concept_id>
%%   <concept_desc>Computer systems organization~Redundancy</concept_desc>
%%   <concept_significance>300</concept_significance>
%%  </concept>
%%  <concept>
%%   <concept_id>10010520.10010553.10010554</concept_id>
%%   <concept_desc>Computer systems organization~Robotics</concept_desc>
%%   <concept_significance>100</concept_significance>
%%  </concept>
%%  <concept>
%%   <concept_id>10003033.10003083.10003095</concept_id>
%%   <concept_desc>Networks~Network reliability</concept_desc>
%%   <concept_significance>100</concept_significance>
%%  </concept>
%% </ccs2012>
%% \end{CCSXML}
%%
%% \ccsdesc[500]{Computer systems organization~Embedded systems}
%% \ccsdesc[300]{Computer systems organization~Redundancy}
%% \ccsdesc{Computer systems organization~Robotics}
%% \ccsdesc[100]{Networks~Network reliability}
%%
%% % We no longer use \terms command
%% %\terms{Theory}
%%
%% \keywords{ACM proceedings, \LaTeX, text tagging}

\maketitle

\input{samplebody-conf}

% \bibliographystyle{ACM-Reference-Format}
\newpage
\bibliographystyle{alpha}
\bibliography{../ref}

\end{document}


text:
trim_method="trim" 	# Can be {trim or roll).
max_len=40		# Trim output to this length.
roll_speed=2		# Roll speed in chraacters per second.

segment_path=$(dirname $0)
source "$segment_path/../lib.sh"

# Check if audacious is playing and print that song.
audacious_pid=$(pidof audacious)
if [ -n "$audacious_pid" ]; then
    if $(audtool playback-playing); then
        np=$(audtool current-song)
        case "$trim_method" in
            "roll")
        	np=$(roll_stuff "${np}" ${max_len} ${roll_speed})
        	;;
            "trim")
		np=$(echo "${np}" | cut -c1-"$max_len")
		;;
	esac
	echo "♫ ${np}"
    fi
fi


text:
/**
 *   Here's where everything gets included. You don't need
 *   to change anything here, and doing so might break
 *   stuff. Here be dragons and all that.
 */
/**
 *   Default variables
 *
 *   While these can be set with JavaScript, it's probably
 *   better and faster to just set them here, compile to
 *   CSS and include that instead to use some of that
 *   hardware-accelerated goodness.
 */
.unslider-nav ol {
  list-style: none;
  text-align: center;
}
.unslider-nav ol li {
  display: inline-block;
  width: 6px;
  height: 6px;
  margin: 0 4px;
  background: transparent;
  border-radius: 5px;
  overflow: hidden;
  text-indent: -999em;
  border: 2px solid #14275E;
  cursor: pointer;
}
.unslider-nav ol li.unslider-active {
  background: #FFFFE5;
  cursor: default;
}


text:
var TestEvents = (function () {
    function TestEvents() {
    }
    TestEvents.TestSingleRequest = 'TestTestSingleRequest';
    TestEvents.TestSingleResponse = 'TestTestSingleResponse';
    TestEvents.TestFailedRequest = 'TestTestFailedRequest';
    TestEvents.TestFailedResponse = 'TestTestFailedResponse';
    TestEvents.TestUnauthorizedRequest = 'TestTestUnauthorizedRequest';
    TestEvents.TestUnauthorizedResponse = 'TestTestUnauthorizedResponse';
    TestEvents.TestSingleLegacyRequest = 'TestTestSingleLegacyRequest';
    TestEvents.TestSingleLegacyResponse = 'TestTestSingleLegacyResponse';
    TestEvents.TestDoubleARequest = 'TestTestDoubleARequest';
    TestEvents.TestDoubleAResponse = 'TestTestDoubleAResponse';
    TestEvents.TestDoubleBRequest = 'TestTestDoubleBRequest';
    TestEvents.TestDoubleBResponse = 'TestTestDoubleBResponse';
    return TestEvents;
}());
var ServerEvents = {
    OnError: "ServerOnError",
    OnWarn: "ServerOnWarn",
    OnNotification: "ServerOnNotification",
};
//# sourceMappingURL=TypeScriptEvents.js.map


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package parallelvalidator;

import java.io.RandomAccessFile;
import java.nio.CharBuffer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import parallelvalidator.exception.MalformedException;

public class ChunkReaderTest {

    private static final String FIXTURE_FOLDER = "fixture/";
    private static final String FIXTURE = FIXTURE_FOLDER + "utf8sequence";

    private static final String EXPECTED = "123456789€123456789";
    private BufferProcessorImpl proc = new BufferProcessorImpl();

    public ChunkReaderTest() {
    }

    @Before
    public void setUp() {
         proc.reset();
    }

    @After
    public void tearDown() {
    }

    class BufferProcessorImpl implements BufferProcessor{

            private String fullString = new String();

            @Override
            public void process(CharBuffer cbuf) {
                fullString = fullString.concat(cbuf.toString());
            }

            public String getResult(){
                return fullString;
            }

            public void reset(){
                fullString = new String();
            }
        }

    @Test
    public void canReadWholeFileSegment() {

        try (RandomAccessFile fis = new RandomAccessFile(FIXTURE, "r")) {

            Segment whole = new Segment(0, fis.length());
            ChunkReader reader = new ChunkReader(fis.getChannel(), whole,
                    proc, 10, 30);
            reader.readNext();
            assertEquals(EXPECTED, proc.getResult());

        } catch (Exception ex) {
            fail(ex.getMessage());
        }
    }

    @Test
    public void throwsExceptionIfUnderflowBytesInSegmentEnd(){

        try (RandomAccessFile fis = new RandomAccessFile(FIXTURE, "r")) {

            Segment s = new Segment(5, 5);
            ChunkReader reader = new ChunkReader(fis.getChannel(), s,
                    proc, 8, 10);
            reader.readNext();
            fail();

        } catch (MalformedException e) {
            assertEquals(e.getLength(), 1);
            assertEquals(e.getRelativeStart(), 4);
        } catch (Exception ex){
            fail(ex.getMessage());
        }
    }

    @Test
    public void throwsExceptionIfUnderflowBytesInSegmentStart(){

        try (RandomAccessFile fis = new RandomAccessFile(FIXTURE, "r")) {

            Segment s = new Segment(11, 5);
            ChunkReader reader = new ChunkReader(fis.getChannel(), s, proc, 5, 10);
            reader.readNext();
            fail();

        } catch (MalformedException e) {
            assertEquals(e.getLength(), 1);
            assertEquals(e.getRelativeStart(), 0);
        } catch (Exception ex){
            fail(ex.getMessage());
        }
    }

    @Test
    @SuppressWarnings("empty-statement")
    public void canReadWithSmallCharBuffer(){

        try(RandomAccessFile fis = new RandomAccessFile(FIXTURE, "r")) {

            Segment s = new Segment(0, fis.length());
            ChunkReader reader = new ChunkReader(fis.getChannel(), s, proc, 8, 8);
            while(reader.readNext());

        }catch(Exception ex){
            fail(ex.getMessage());
        }

        assertEquals(EXPECTED, proc.getResult());
    }
}


text:
<?php

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \frontend\models\SignupForm */

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
//use kartik\date\DatePicker;
//use yii\jui\DatePicker;

$this->title = 'Create Admin ';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

veuillez remplir les champs suivant pour enregistrement:

    <?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>

        <?= $form->field($model, 'username')->textInput()->label('pseudo')?>

        <?= $form->field($model, 'name')->textInput()->label('non')?>

        <?= $form->field($model, 'password')->passwordInput()->label('mot de passe') ?>

        <?= $form->field($model, 'pwd_re')->passwordInput()->label('Retapez votre mot de passe') ?>

        <?= $form->field($model, 'email')->textInput() ?>

        <?= $form->field($model, 'sexe')->dropDownList(
					['H'=>'Homme', 'F'=>'Femme'])?>

        <?= $form->field($model, 'role')->dropDownList(
					['member'=>'Member','admin'=>'Admin'])?>

        <?= Html::submitButton('Create',['class'=> 'btn btn-success','name'=> 'signup-button']) ?>

    <?php ActiveForm::end(); ?>


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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<relativePath>../../../pom.xml</relativePath>
		<groupId>anttoolkit</groupId>
		<artifactId>anttoolkit-root</artifactId>
		<version>1.0</version>
	</parent>

	<name>jsch</name>
	<description>Jsch third party module, providing tasks to work with SSH</description>
	<url>http://www.jcraft.com/jsch/</url>
	<artifactId>anttoolkit-jsch</artifactId>
	<version>0.1.45</version>

	<properties>
		<module.taskdef>com/anttoolkit/jsch/antlib.xml</module.taskdef>
	</properties>

	<dependencies>
		<!-- Jsch -->
		<dependency>
			<groupId>com.jcraft</groupId>
			<artifactId>jsch</artifactId>
			<version>${project.version}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-antrun-plugin</artifactId>
				<executions>
					<execution>
						<id>package-module</id>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

</project>


text:
var fs = require('fs');
var builder = require('xmlbuilder');
var xml2js = require ('xml2js');
var Firebird = require('node-firebird');
var request = require('request');
var titleCase = require('title-case');
var data = new Date();
var dia =data.getDate();
var FBoptions = {};
var xx = null;
FBoptions.host = 'localhost';
FBoptions.port = 3050;
FBoptions.database = 'c:\\bessani softwares\\florestal\\base\\florestal.fdb';
FBoptions.user = 'SYSDBA';
FBoptions.password = 'masterkey';
  process.stdin.resume();
  process.stdin.setEncoding('utf8');
  var util = require('util');

  process.stdin.on('data', function (text) {
  function envia (data) {
      options = {
    	  method:'POST',
    	  url: "https://www.rumo.com.br/sistema/adm/APILogon.asp",
    	  headers: {
    		'User-Agent': 'FastCommerce API Interface',
    		'Content-type': 'application/x-www-form-urlencoded',
    		'Charset':'UTF-8'
    	  }	,
    	  form: {
    		StoreName: 'Localdecor',
    		StoreID: 11058,
    		Username:'API',
    		Password:'5hj08*V3z',
    		method:'ProductManagement',
        OutputFormat: 3,
    		XMLRecords: data
    	  }
    	};

    var parser = new xml2js.Parser();
   request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
      console.log(body);

  }
  else {console.log(body);};
   });
    };
  	Firebird.attach(FBoptions, function(err, db) {
      var root = builder.create('Records');
  		if (err)
  			throw err;
  		db.sequentially('select p.codigo,p.idsite,(select first 1 skip (cast((select ((count(*)-1)/2) from produto where id_produtopai=p.codigo)as integer)) prvenda from produto where id_produtopai=p.codigo) from produtopai p',function(row, index) {
        root.ele('Record')
            .ele('Field', {'Name': 'Comando','Value': "A"}).up()
            .ele('Field', {'Name': 'IDProduto','Value': row.IDSITE}).up()
            .ele('Field', {'Name': 'Preco','Value': row.PRVENDA});
  		}, function(err) {
				db.detach();
        envia(root.toString({ pretty: true }));

      });
  	});
  console.log('iniciando processo');

  });


text:
package v1.pyroteck.com.pyroteck.receiver;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.parse.ParsePushBroadcastReceiver;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import v1.pyroteck.com.pyroteck.MainActivity;

/**
 * Created by Nilesh on 27/05/15.
 */
public class CustomParsePushBroadcastReceiver extends ParsePushBroadcastReceiver {

    private static final String TAG = "CustomBroadcastReceiver";

    @Override
    protected void onPushReceive(Context context, Intent intent) {
        super.onPushReceive(context, intent);
        JSONObject json = null;
        Log.d(TAG,"onPushReceive");
        try {
            String action = intent.getAction();
            String channel = intent.getExtras().getString("com.parse.Channel");
            json = new JSONObject(intent.getExtras().getString("com.parse.Data"));

            Log.d(TAG, "got action " + action + " on channel " + channel + " with:"+"JSON Object "+json.toString());
            Iterator itr = json.keys();
            while (itr.hasNext()) {
                String key = (String) itr.next();
                Log.d(TAG, "..." + key + " => " + json.getString(key));
            }
        } catch (JSONException e) {
            //Log.d(TAG, "JSONException: " + e.getMessage());
        }
    }

    @Override
    protected Class<? extends Activity> getActivity(Context context, Intent intent) {

        //return super.getActivity(context, intent);
        return MainActivity.class;
    }
}


text:
#include <yael/ivf.h>
#include <yael/hamming.h>
#include "mex.h"
#include <string.h>

/* The different possible functions */
#define IVF_FUNCTION_STATUS            0
#define IVF_FUNCTION_NEW               1
#define IVF_FUNCTION_FREE              2
#define IVF_FUNCTION_ADD               3
#define IVF_FUNCTION_LOAD              4
#define IVF_FUNCTION_SAVE              5
#define IVF_FUNCTION_GETIDS            6
#define IVF_FUNCTION_GETBINSIG         7
#define IVF_FUNCTION_QUERYHE           8
#define IVF_FUNCTION_IMBFACTOR         9
#define IVF_FUNCTION_QUERYHEW          10
#define IVF_FUNCTION_FINDBS  		       12
#define IVF_FUNCTION_CROSSMATCH        20
#define IVF_FUNCTION_CROSSMATCH_ALT    22
#define IVF_FUNCTION_CROSSMATCH_COUNT  25

static ivf_t * ivf = NULL;

/* the buffers associated with the voting area (matches).
   This size will be expanded using geometric re-allocation so that it fits
   the maximum amount of memory needed after a few queries */
#define DEFAULT_NB_MATCHES (1 << 20);
static int bufmatch_size = DEFAULT_NB_MATCHES;

int ivfmex_status (int verbose)
{
  int i, j;

  if (ivf == NULL) return 0;

  mexPrintf("k=%d lists\n", ivf->k);
  mexPrintf("elem_size=%d\n", ivf->elem_size);
  mexPrintf("n=%d vectors stored\n\n", ivf->n);

  if (verbose >= 1) {
    mexPrintf("Inverted lists:nbelems/nballocs\n");
    for (i = 0 ; i < ivf->k ; i++)
      mexPrintf("%d/%d  ", ivf->nbelems[i], ivf->seg_size[i]);
    mexPrintf("\n");
  }
  if (verbose >= 2) {
    for (i = 0 ; i < ivf->k ; i++) {
      mexPrintf("List %-7d -> ", i);
      for (j = 0 ; j < ivf->nbelems[i] ; j++)
        mexPrintf("%d  ", ivf->ids[i][j]);
      mexPrintf("\n");
    }
  }
  return ivf->n;
}

/* Check empirically if the inverted file start at 0.
   Return */

#define IVF_MATLAB    1    /* likely to be matlab */
#define IVF_FROM0     0    /* should be C (idx at 0) */
int ivfmex_offsetidx()
{
  if (ivf->nbelems[0] == 0 && ivf->nbelems[1] > 0)
    return IVF_MATLAB;

  return IVF_FROM0;
}

void mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray*prhs[])

{
  long i;
  int operation = 0;
  char varname[256];
  int verbose = 0;

  /* First select which operation is to be performed */
  if (nrhs < 1 || mxGetClassID(prhs[0]) != mxCHAR_CLASS)
    mexErrMsgTxt ("First argument must be defined and be a string (new|add|query)");
  if (mxGetString (prhs[0], varname, 256) != 0)
    mexErrMsgTxt ("Could not convert string data");

  if (!strcmp(varname, "status"))
    operation = IVF_FUNCTION_STATUS;
  else if (!strcmp(varname, "queryhe"))
    operation = IVF_FUNCTION_QUERYHE;
  else if (!strcmp(varname, "queryhew"))
    operation = IVF_FUNCTION_QUERYHEW;
  else if (!strcmp(varname, "new"))
    operation = IVF_FUNCTION_NEW;
  else if (!strcmp(varname, "free"))
    operation = IVF_FUNCTION_FREE;
  else if (!strcmp(varname, "add"))
    operation = IVF_FUNCTION_ADD;
  else if (!strcmp(varname, "load"))
    operation = IVF_FUNCTION_LOAD;
  else if (!strcmp(varname, "save"))
    operation = IVF_FUNCTION_SAVE;
  else if (!strcmp(varname, "getids"))
    operation = IVF_FUNCTION_GETIDS;
  else if (!strcmp(varname, "imbfactor"))
    operation = IVF_FUNCTION_IMBFACTOR;
  else if (!strcmp(varname, "findbs"))
    operation = IVF_FUNCTION_FINDBS;
  else if (!strcmp(varname, "crossmatch"))
    operation = IVF_FUNCTION_CROSSMATCH;
  else if (!strcmp(varname, "crossmatchalt"))
    operation = IVF_FUNCTION_CROSSMATCH_ALT;
  else if (!strcmp(varname, "crossmatchcount"))
    operation = IVF_FUNCTION_CROSSMATCH_COUNT;
  else mexErrMsgTxt("Unknown operation for this inverted file");

  switch (operation) {
  case IVF_FUNCTION_STATUS: {
    if (nrhs > 1)
      verbose = (int) mxGetScalar (prhs[1]);

    plhs[0] = mxCreateNumericMatrix (1, 1, mxUINT64_CLASS, mxREAL);
    long long * retptr = (long long *) mxGetPr (plhs[0]);
    * retptr = ivfmex_status (verbose);
  }
    break;

  case IVF_FUNCTION_NEW:

    if (nlhs != 0)
      mexErrMsgTxt ("This function returns no value (just allocated the IVF)");
    if (nrhs != 3 && nrhs != 4)
      mexErrMsgTxt ("Invalid number of input arguments");
    if (ivf != NULL)
      mexErrMsgTxt ("Inverted file already allocated.\n"
		    "It should be free before being invoking new.");

    int coarsek = (int) mxGetScalar (prhs[1]);
    int elemsize = (int) mxGetScalar (prhs[2]);
    int segsize = DEFAULT_SEG_SIZE;
    if (nrhs == 4)
      segsize = (int) mxGetScalar (prhs[3]);

    /* Produce an inverted file */
#ifndef __SSE4_2__
    #warning No SSE4 -> code will not be ultimately optimized
#endif
    ivf = ivf_new (coarsek, elemsize, segsize);

    /* Give default value to the size of the voting buffer */
    bufmatch_size = DEFAULT_NB_MATCHES;
    return;

  case IVF_FUNCTION_FREE:
    if (nlhs != 0 || nrhs != 1)
      mexErrMsgTxt ("Usage: ivfmex('free')");
    ivf_delete (ivf);
    ivf = NULL;
    return;

  case IVF_FUNCTION_ADD: {
    if (nlhs != 0)
      mexErrMsgTxt ("Usage: ivfmex ('queryhe', ids, keys, codes, ht)\n"
		    "This function outputs no argument");
    if (nrhs != 4)
      mexErrMsgTxt ("Usage: ivfmex ('queryhe', ids, keys, codes, ht)\n");

    if (mxGetClassID(prhs[1]) != mxINT32_CLASS || mxGetM (prhs[1]) != 1)
      mexErrMsgTxt ("Argument 2 should a vector of int32 ids");
    int n = mxGetN (prhs[1]);
    int * ids = (int *) mxGetPr (prhs[1]);

    if (mxGetClassID(prhs[2]) != mxINT32_CLASS)
      mexErrMsgTxt ("Argument 3 is be the set of indexes (visual words), of type int32");
    if (mxGetN (prhs[2])!= n || mxGetM(prhs[2]) != 1)
      mexErrMsgTxt ("Problem with Argument 3");
    int * keys = (int *) mxGetPr (prhs[2]);

    if (mxGetClassID(prhs[3]) != mxUINT8_CLASS)
      mexErrMsgTxt ("Argument 4 should be the set of codes (nbytes_per_codes * n)");
    if (mxGetN (prhs[3])!= n || mxGetM(prhs[3]) != ivf->elem_size)
      mexErrMsgTxt ("Problem with Argument 4");
    uint8 * codes = (uint8 *) mxGetPr (prhs[3]);

    ivf_addn (ivf, ids, keys, codes, n);
  }
    return;

  case IVF_FUNCTION_SAVE: {
    if (nlhs != 0 || nrhs != 2)
      mexErrMsgTxt ("Usage: ivfmex('save', filename)");
    if (ivf == NULL)
      mexErrMsgTxt ("ivfmex/save: IVFADC structured not initialized");

    char fname[512];
    if (mxGetClassID(prhs[1]) != mxCHAR_CLASS)
      mexErrMsgTxt ("Argument 2 (filename) should be a string");

    if (mxGetString (prhs[1], fname, 256) != 0)
      mexErrMsgTxt ("Could not convert string data");

    ivf_save (fname, ivf);
    }
    break;

  case IVF_FUNCTION_LOAD: {
    if (nlhs != 0 || nrhs != 2)
      mexErrMsgTxt ("Usage: ivfmex('load', filename)");
    if (ivf != NULL)
      mexErrMsgTxt ("ivfmex/load: free the structure before loading a new one from disk");

    char fname[512];
    if (mxGetClassID(prhs[1]) != mxCHAR_CLASS)
      mexErrMsgTxt ("Argument 2 (filename) should be a string");

    if (mxGetString (prhs[1], fname, 256) != 0)
      mexErrMsgTxt ("Could not convert string data");

    ivf = ivf_load (fname);
    }
    break;

  case IVF_FUNCTION_GETIDS:
    if (nlhs != 1)
      mexErrMsgTxt ("This function outputs 1 argument");
    if (nrhs != 2)
      mexErrMsgTxt ("Usage: ids = ivfmex('getids', listid)");
    {
      int listno = (int) mxGetScalar (prhs[1]);
      int listlength = ivf_get_nb_elems (ivf, listno);

      /* mexPrintf ("listno=%d  listlength=%d\n", listno, listlength); */

      plhs[0] = mxCreateNumericMatrix (1, listlength, mxINT32_CLASS, mxREAL);
      int * ids = (int *) mxGetPr (plhs[0]);
      memcpy (ids, ivf_get_ids (ivf, listno), sizeof(int) * listlength);
    }
    break;

  case IVF_FUNCTION_IMBFACTOR:
    if (nlhs != 1)
      mexErrMsgTxt ("This function outputs 1 argument");
    if (nrhs != 1)
      mexErrMsgTxt ("Usage: imbf = ivfmex('imbfactor')");
    if (ivf == NULL)
      mexErrMsgTxt ("Inverted file is not defined\n Use ivfmex('new',...).");
    {
      plhs[0] = mxCreateDoubleMatrix(1,1, mxREAL);
      double *imbf = mxGetPr(plhs[0]);
      *imbf = ivf_imbalance_factor (ivf);
    }
    break;

  case IVF_FUNCTION_FINDBS:
    if (nlhs != 1)
      mexErrMsgTxt ("This function outputs 1 argument");
    if (nrhs != 3)
      mexErrMsgTxt ("Usage: bs = ivfmex('findbs', key, ids)");
    if (ivf == NULL)
      mexErrMsgTxt ("Inverted file is not defined\n Use ivfmex('new',...).");
    {
			int * keys = (int *) mxGetPr (prhs[1]);
			int * ids = (int *) mxGetPr (prhs[2]);
			int n = mxGetM (prhs[2]);

			uint8 * bs_ = ivf_find_vals (ivf, keys, ids, n);

			if (!bs_)
				mexErrMsgTxt ("Wrong pairs of keys and ids...");

			plhs[0] = mxCreateNumericMatrix (ivf->elem_size, n, mxUINT8_CLASS, mxREAL);
      uint8 * bs = (uint8 *) mxGetPr (plhs[0]);
      memcpy (bs, bs_, sizeof(uint8) * ivf->elem_size *n);

   		free (bs_);
    }
    break;

  case IVF_FUNCTION_QUERYHE:

    if (nlhs != 1 || nrhs != 5)
      mexErrMsgTxt ("Usage: matches = ivfmex ('queryhe', ids, keys, codes, ht)");

    if (mxGetClassID(prhs[1]) != mxINT32_CLASS || mxGetM (prhs[1]) != 1)
      mexErrMsgTxt ("Argument 2 should a vector of int32 ids");

    if (ivf == NULL)
      mexErrMsgTxt ("Inverted file is not defined\n Use ivfmex('new',...).");
    {
    int nq = mxGetN (prhs[1]);
    int * qids = (int *) mxGetPr (prhs[1]);

    if (mxGetClassID(prhs[2]) != mxINT32_CLASS)
      mexErrMsgTxt ("Argument 3 is be the set of indexes (visual words), of type int32");
    if (mxGetN (prhs[2])!= nq || mxGetM(prhs[2]) != 1)
      mexErrMsgTxt ("Problem with Argument 3");
    int * keys = (int *) mxGetPr (prhs[2]);

    if (mxGetClassID(prhs[3]) != mxUINT8_CLASS)
      mexErrMsgTxt ("Argument 4 should be the set of codes (nbytes_per_codes * n)");
    if (mxGetN (prhs[3])!= nq || mxGetM(prhs[3]) != ivf->elem_size)
      mexErrMsgTxt ("Problem with Argument 4");
    uint8 * codes = (uint8 *) mxGetPr (prhs[3]);

    /* Hamming threshold for Hamming Embedding */
    int ht = (int) mxGetScalar (prhs[4]);

    int nmatches = bufmatch_size;  /* a priori on the maximum number of matches */
    ivfmatch_t * matches = ivf_hequery (ivf, qids, keys, codes, nq, &nmatches, ht);

    /* Update the buffer matching size if needed */
    if (nmatches > bufmatch_size)
      bufmatch_size = nmatches;

    /* Cast the match structure into matlab vectors */
    plhs[0] = mxCreateNumericMatrix (3, nmatches, mxINT32_CLASS, mxREAL);

    int * matchinfo = (int *) mxGetPr (plhs[0]);
    int i;
    for (i = 0 ; i < nmatches ; i++) {
      matchinfo[i*3] = matches[i].qid;
      matchinfo[i*3+1] = matches[i].bid;
      matchinfo[i*3+2] = matches[i].score;
    }

    free (matches);
    }
    break;

  case IVF_FUNCTION_QUERYHEW: {
    if (nlhs != 2 || (nrhs != 5 && nrhs != 6 && nrhs != 7))
      mexErrMsgTxt ("Usage: [ids, scores] = ivfmex ('queryhe', ids, keys, codes, ht [,scoremap, listw])");

    if (mxGetClassID(prhs[1]) != mxINT32_CLASS || mxGetM (prhs[1]) != 1)
      mexErrMsgTxt ("Argument 2 should a vector of int32 ids");

    if (ivf == NULL)
      mexErrMsgTxt ("Inverted file is not defined\n Use ivfmex('new',...).");

      int nq = mxGetN (prhs[1]);
    int * qids = (int *) mxGetPr (prhs[1]);

    if (mxGetClassID(prhs[2]) != mxINT32_CLASS)
      mexErrMsgTxt ("Argument 3 is be the set of indexes (visual words), of type int32");
    if (mxGetN (prhs[2])!= nq || mxGetM(prhs[2]) != 1)
      mexErrMsgTxt ("Problem with Argument 3");
    int * keys = (int *) mxGetPr (prhs[2]);

    if (mxGetClassID(prhs[3]) != mxUINT8_CLASS)
      mexErrMsgTxt ("Argument 4 should be the set of codes (nbytes_per_codes * n)");
    if (mxGetN (prhs[3])!= nq || mxGetM(prhs[3]) != ivf->elem_size)
      mexErrMsgTxt ("Problem with Argument 4");
    uint8 * codes = (uint8 *) mxGetPr (prhs[3]);

    /* Hamming threshold for Hamming Embedding */
    int ht = (int) mxGetScalar (prhs[4]);

    /* Optionally, use a mapping function for scores and a weighting function for lists */
    float * score_map = NULL;
    float * list_w = NULL;

    if (nrhs >= 6) {
      if (mxGetClassID(prhs[5]) != mxSINGLE_CLASS)
        mexErrMsgTxt ("Argument 5 should be a single array to weight Hamming distances");
      score_map = (float *) mxGetPr (prhs[5]);
    }

    if (nrhs >= 7) {
      if (mxGetClassID(prhs[6]) != mxSINGLE_CLASS)
        mexErrMsgTxt ("Argument 6 should be a single array to weights the lists");

      if ( (mxGetN (prhs[6])==1 && mxGetM (prhs[6])==(ivf->k-1))
           || (mxGetN (prhs[6])==(ivf->k-1) && mxGetM (prhs[6])==1) ) {

        list_w = (float *) malloc (ivf->k * sizeof (*list_w));
        list_w[0] = 0;
        memcpy (list_w+1, (float *) mxGetPr (prhs[6]), (ivf->k-1) * sizeof(*list_w));
      }
      else mexErrMsgTxt ("Length of argument 6 should be equal to the number of inverted lists");
    }

    size_t nmatches;
    ivfmatch_t * matches = ivf_hequeryw (ivf, qids, keys, codes, nq, ht, &nmatches, score_map, list_w);

    fprintf (stderr, "Found %ld matches\n", nmatches);

    /* Cast the match structure into matlab vectors */
    plhs[0] = mxCreateNumericMatrix (2, nmatches, mxINT32_CLASS, mxREAL);
    plhs[1] = mxCreateNumericMatrix (1, nmatches, mxSINGLE_CLASS, mxREAL);

    int32_T * matchids = (int32_T *) mxGetPr (plhs[0]);
    float * matchscores = (float *) mxGetPr (plhs[1]);
    size_t i;

    for (i = 0 ; i < nmatches ; i++) {
      *(matchids++) = matches[i].qid;
      *(matchids++) = matches[i].bid;
      *(matchscores++) = matches[i].score;
    }

    free (matches);
    free (list_w);
    }
    break;

    case IVF_FUNCTION_CROSSMATCH: {
      if (nlhs != 2 || nrhs != 2)
         mexErrMsgTxt ("Usage: [matches, nmatches] = ivfmex ('crossmatch', ht)");

      if (ivf == NULL)
        mexErrMsgTxt ("Inverted file is not defined\n Use ivfmex('new',...).");

      int off = ivfmex_offsetidx();

      /* Hamming threshold for Hamming Embedding */
      int ht = (int) mxGetScalar (prhs[1]);

      size_t * nmatches = (size_t *) malloc (sizeof(*nmatches) * ivf->k);
      hammatch_t ** hmlist = ivf_he_collect_crossmatches (ivf, ht, nmatches);

      /* compute the cumulative number of matches */
      size_t * cumnmatches = (size_t *) malloc (sizeof (*cumnmatches) * (ivf->k+1));
      cumnmatches[0] = 0;
      for (i = 0 ; i < ivf->k ; i++)
        cumnmatches[i+1] = nmatches[i] + cumnmatches[i];
      size_t totmatches = cumnmatches[ivf->k];

      /* Cast the match structure into matlab vectors */
      plhs[0] = mxCreateNumericMatrix (3, totmatches, mxINT32_CLASS, mxREAL);
      plhs[1] = mxCreateNumericMatrix (1, ivf->k-1, mxINT64_CLASS, mxREAL);

      memcpy (mxGetPr(plhs[1]), nmatches + off, sizeof (*nmatches) * (ivf->k-1));

      int * matchinfo = (int *) mxGetPr (plhs[0]);
      int i, j;

      for (j = off ; j < ivf->k - 1 + off ; j++)
        for (i = 0 ; i < nmatches[j] ; i++) {
          *(matchinfo++) = hmlist[j][i].qid;
          *(matchinfo++) = hmlist[j][i].bid;
          *(matchinfo++) = hmlist[j][i].score;
        }

      for (i = 0 ; i < ivf->k ; i++)
        free (hmlist[i]);
      free (hmlist);
      free (cumnmatches);
      free (nmatches);
    }
      break;

    case IVF_FUNCTION_CROSSMATCH_ALT: {
      if ((nlhs != 3 && nlhs != 4) || nrhs != 2)
         mexErrMsgTxt ("Usage: [idx, hamdis, keys] = ivfmex ('crossmatchalt', ht)");
      if (ivf == NULL)
        mexErrMsgTxt ("Inverted file is not defined\n Use ivfmex('new',...).");

      int off = ivfmex_offsetidx();

      /* Count the number of matches */
      int ht = (int) mxGetScalar (prhs[1]);

      size_t * nmatches = (size_t *) malloc (sizeof(*nmatches) * ivf->k);
      ivf_he_count_crossmatches (ivf, ht, nmatches);

      /* compute the cumulative number of matches */
      size_t * cumnmatches = (size_t *) malloc (sizeof (*cumnmatches) * (ivf->k+1));
      cumnmatches[0] = 0;
      for (i = 0 ; i < ivf->k ; i++)
        cumnmatches[i+1] = nmatches[i] + cumnmatches[i];
      size_t totmatches = cumnmatches[ivf->k];

      plhs[0] = mxCreateNumericMatrix (2, totmatches, mxINT32_CLASS, mxREAL);
      plhs[1] = mxCreateNumericMatrix (1, totmatches, mxUINT16_CLASS, mxREAL);
      plhs[2] = mxCreateNumericMatrix (1, ivf->k-1, mxINT64_CLASS, mxREAL);

      ivf_he_crossmatches_prealloc (ivf, ht, (int *) mxGetPr(plhs[0]),
                                    (uint16 *) mxGetPr(plhs[1]), cumnmatches);

      memcpy (mxGetPr(plhs[2]), nmatches + off, sizeof (*nmatches) * (ivf->k-1));

      if (nlhs == 4) {
        plhs[3] = mxCreateNumericMatrix (1, totmatches, mxINT32_CLASS, mxREAL);
        int * key = (int *) mxGetPr(plhs[3]);
        long j;
        for (i = 0 ; i < ivf->k ; i++)
          for (j = cumnmatches[i] ; j < cumnmatches[i+1] ; j++) {
            key[j] = i;
          }
      }

      free (nmatches);
      free (cumnmatches);
    }
      break;

    case IVF_FUNCTION_CROSSMATCH_COUNT: {
      if (nlhs != 1 || nrhs != 2)
        mexErrMsgTxt ("Usage: nmatches = ivfmex ('crossmatchcount', ht)");

      if (ivf == NULL)
        mexErrMsgTxt ("Inverted file is not defined\n Use ivfmex('new',...).");

      int off = ivfmex_offsetidx();

      /* Hamming threshold for Hamming Embedding */
      int ht = (int) mxGetScalar (prhs[1]);

      size_t * nmatches = (size_t *) malloc (sizeof(*nmatches) * ivf->k);

      ivf_he_count_crossmatches (ivf, ht, nmatches);

      plhs[0] = mxCreateNumericMatrix (1, ivf->k-1, mxINT64_CLASS, mxREAL);
      memcpy (mxGetPr(plhs[0]), nmatches + off, sizeof (*nmatches) * (ivf->k-1));
      free (nmatches);
    }
      break;

  }
}