text:
#pragma once
#include <aws/applicationcostprofiler/ApplicationCostProfiler_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/applicationcostprofiler/model/ReportFrequency.h>
#include <aws/applicationcostprofiler/model/Format.h>
#include <aws/applicationcostprofiler/model/S3Location.h>
#include <aws/core/utils/DateTime.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace ApplicationCostProfiler
{
namespace Model
{

  /**
   *
The configuration of a report in AWS Application Cost Profiler.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_APPLICATIONCOSTPROFILER_API ReportDefinition
  {
  public:
    ReportDefinition();
    ReportDefinition(Aws::Utils::Json::JsonView jsonValue);
    ReportDefinition& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The ID of the report.

     */
    inline const Aws::String& GetReportId() const{ return m_reportId; }

    /**
     *
The ID of the report.

     */
    inline bool ReportIdHasBeenSet() const { return m_reportIdHasBeenSet; }

    /**
     *
The ID of the report.

     */
    inline void SetReportId(const Aws::String& value) { m_reportIdHasBeenSet = true; m_reportId = value; }

    /**
     *
The ID of the report.

     */
    inline void SetReportId(Aws::String&& value) { m_reportIdHasBeenSet = true; m_reportId = std::move(value); }

    /**
     *
The ID of the report.

     */
    inline void SetReportId(const char* value) { m_reportIdHasBeenSet = true; m_reportId.assign(value); }

    /**
     *
The ID of the report.

     */
    inline ReportDefinition& WithReportId(const Aws::String& value) { SetReportId(value); return *this;}

    /**
     *
The ID of the report.

     */
    inline ReportDefinition& WithReportId(Aws::String&& value) { SetReportId(std::move(value)); return *this;}

    /**
     *
The ID of the report.

     */
    inline ReportDefinition& WithReportId(const char* value) { SetReportId(value); return *this;}

    /**
     *
Description of the report

     */
    inline const Aws::String& GetReportDescription() const{ return m_reportDescription; }

    /**
     *
Description of the report

     */
    inline bool ReportDescriptionHasBeenSet() const { return m_reportDescriptionHasBeenSet; }

    /**
     *
Description of the report

     */
    inline void SetReportDescription(const Aws::String& value) { m_reportDescriptionHasBeenSet = true; m_reportDescription = value; }

    /**
     *
Description of the report

     */
    inline void SetReportDescription(Aws::String&& value) { m_reportDescriptionHasBeenSet = true; m_reportDescription = std::move(value); }

    /**
     *
Description of the report

     */
    inline void SetReportDescription(const char* value) { m_reportDescriptionHasBeenSet = true; m_reportDescription.assign(value); }

    /**
     *
Description of the report

     */
    inline ReportDefinition& WithReportDescription(const Aws::String& value) { SetReportDescription(value); return *this;}

    /**
     *
Description of the report

     */
    inline ReportDefinition& WithReportDescription(Aws::String&& value) { SetReportDescription(std::move(value)); return *this;}

    /**
     *
Description of the report

     */
    inline ReportDefinition& WithReportDescription(const char* value) { SetReportDescription(value); return *this;}

    /**
     *
The cadence at which the report is generated.

     */
    inline const ReportFrequency& GetReportFrequency() const{ return m_reportFrequency; }

    /**
     *
The cadence at which the report is generated.

     */
    inline bool ReportFrequencyHasBeenSet() const { return m_reportFrequencyHasBeenSet; }

    /**
     *
The cadence at which the report is generated.

     */
    inline void SetReportFrequency(const ReportFrequency& value) { m_reportFrequencyHasBeenSet = true; m_reportFrequency = value; }

    /**
     *
The cadence at which the report is generated.

     */
    inline void SetReportFrequency(ReportFrequency&& value) { m_reportFrequencyHasBeenSet = true; m_reportFrequency = std::move(value); }

    /**
     *
The cadence at which the report is generated.

     */
    inline ReportDefinition& WithReportFrequency(const ReportFrequency& value) { SetReportFrequency(value); return *this;}

    /**
     *
The cadence at which the report is generated.

     */
    inline ReportDefinition& WithReportFrequency(ReportFrequency&& value) { SetReportFrequency(std::move(value)); return *this;}

    /**
     *
The format used for the generated reports.

     */
    inline const Format& GetFormat() const{ return m_format; }

    /**
     *
The format used for the generated reports.

     */
    inline bool FormatHasBeenSet() const { return m_formatHasBeenSet; }

    /**
     *
The format used for the generated reports.

     */
    inline void SetFormat(const Format& value) { m_formatHasBeenSet = true; m_format = value; }

    /**
     *
The format used for the generated reports.

     */
    inline void SetFormat(Format&& value) { m_formatHasBeenSet = true; m_format = std::move(value); }

    /**
     *
The format used for the generated reports.

     */
    inline ReportDefinition& WithFormat(const Format& value) { SetFormat(value); return *this;}

    /**
     *
The format used for the generated reports.

     */
    inline ReportDefinition& WithFormat(Format&& value) { SetFormat(std::move(value)); return *this;}

    /**
     *
The location in Amazon Simple Storage Service (Amazon S3) the reports should
     * be saved to.

     */
    inline const S3Location& GetDestinationS3Location() const{ return m_destinationS3Location; }

    /**
     *
The location in Amazon Simple Storage Service (Amazon S3) the reports should
     * be saved to.

     */
    inline bool DestinationS3LocationHasBeenSet() const { return m_destinationS3LocationHasBeenSet; }

    /**
     *
The location in Amazon Simple Storage Service (Amazon S3) the reports should
     * be saved to.

     */
    inline void SetDestinationS3Location(const S3Location& value) { m_destinationS3LocationHasBeenSet = true; m_destinationS3Location = value; }

    /**
     *
The location in Amazon Simple Storage Service (Amazon S3) the reports should
     * be saved to.

     */
    inline void SetDestinationS3Location(S3Location&& value) { m_destinationS3LocationHasBeenSet = true; m_destinationS3Location = std::move(value); }

    /**
     *
The location in Amazon Simple Storage Service (Amazon S3) the reports should
     * be saved to.

     */
    inline ReportDefinition& WithDestinationS3Location(const S3Location& value) { SetDestinationS3Location(value); return *this;}

    /**
     *
The location in Amazon Simple Storage Service (Amazon S3) the reports should
     * be saved to.

     */
    inline ReportDefinition& WithDestinationS3Location(S3Location&& value) { SetDestinationS3Location(std::move(value)); return *this;}

    /**
     *
Timestamp (milliseconds) when this report definition was created.

     */
    inline const Aws::Utils::DateTime& GetCreatedAt() const{ return m_createdAt; }

    /**
     *
Timestamp (milliseconds) when this report definition was created.

     */
    inline bool CreatedAtHasBeenSet() const { return m_createdAtHasBeenSet; }

    /**
     *
Timestamp (milliseconds) when this report definition was created.

     */
    inline void SetCreatedAt(const Aws::Utils::DateTime& value) { m_createdAtHasBeenSet = true; m_createdAt = value; }

    /**
     *
Timestamp (milliseconds) when this report definition was created.

     */
    inline void SetCreatedAt(Aws::Utils::DateTime&& value) { m_createdAtHasBeenSet = true; m_createdAt = std::move(value); }

    /**
     *
Timestamp (milliseconds) when this report definition was created.

     */
    inline ReportDefinition& WithCreatedAt(const Aws::Utils::DateTime& value) { SetCreatedAt(value); return *this;}

    /**
     *
Timestamp (milliseconds) when this report definition was created.

     */
    inline ReportDefinition& WithCreatedAt(Aws::Utils::DateTime&& value) { SetCreatedAt(std::move(value)); return *this;}

    /**
     *
Timestamp (milliseconds) when this report definition was last updated.

     */
    inline const Aws::Utils::DateTime& GetLastUpdatedAt() const{ return m_lastUpdatedAt; }

    /**
     *
Timestamp (milliseconds) when this report definition was last updated.

     */
    inline bool LastUpdatedAtHasBeenSet() const { return m_lastUpdatedAtHasBeenSet; }

    /**
     *
Timestamp (milliseconds) when this report definition was last updated.

     */
    inline void SetLastUpdatedAt(const Aws::Utils::DateTime& value) { m_lastUpdatedAtHasBeenSet = true; m_lastUpdatedAt = value; }

    /**
     *
Timestamp (milliseconds) when this report definition was last updated.

     */
    inline void SetLastUpdatedAt(Aws::Utils::DateTime&& value) { m_lastUpdatedAtHasBeenSet = true; m_lastUpdatedAt = std::move(value); }

    /**
     *
Timestamp (milliseconds) when this report definition was last updated.

     */
    inline ReportDefinition& WithLastUpdatedAt(const Aws::Utils::DateTime& value) { SetLastUpdatedAt(value); return *this;}

    /**
     *
Timestamp (milliseconds) when this report definition was last updated.

     */
    inline ReportDefinition& WithLastUpdatedAt(Aws::Utils::DateTime&& value) { SetLastUpdatedAt(std::move(value)); return *this;}

  private:

    Aws::String m_reportId;
    bool m_reportIdHasBeenSet = false;

    Aws::String m_reportDescription;
    bool m_reportDescriptionHasBeenSet = false;

    ReportFrequency m_reportFrequency;
    bool m_reportFrequencyHasBeenSet = false;

    Format m_format;
    bool m_formatHasBeenSet = false;

    S3Location m_destinationS3Location;
    bool m_destinationS3LocationHasBeenSet = false;

    Aws::Utils::DateTime m_createdAt;
    bool m_createdAtHasBeenSet = false;

    Aws::Utils::DateTime m_lastUpdatedAt;
    bool m_lastUpdatedAtHasBeenSet = false;
  };

} // namespace Model
} // namespace ApplicationCostProfiler
} // namespace Aws


text:
import {NewSignal} from 'vega';
import {parseSelector} from 'vega-event-selector';
import {stringValue} from 'vega-util';
import {SelectionComponent} from '.';
import {ScaleChannel, X, Y} from '../../channel';
import {UnitModel} from '../unit';
import {BRUSH as INTERVAL_BRUSH} from './interval';
import {SelectionProjection} from './project';
import {default as scalesCompiler, domain} from './scales';
import {SelectionCompiler} from '.';

const ANCHOR = '_zoom_anchor';
const DELTA = '_zoom_delta';

const zoom: SelectionCompiler<'interval'> = {
  defined: selCmpt => {
    return selCmpt.type === 'interval' && selCmpt.zoom;
  },

  signals: (model, selCmpt, signals) => {
    const name = selCmpt.name;
    const hasScales = scalesCompiler.defined(selCmpt);
    const delta = name + DELTA;
    const {x, y} = selCmpt.project.hasChannel;
    const sx = stringValue(model.scaleName(X));
    const sy = stringValue(model.scaleName(Y));
    let events = parseSelector(selCmpt.zoom, 'scope');

    if (!hasScales) {
      events = events.map(e => ((e.markname = name + INTERVAL_BRUSH), e));
    }

    signals.push(
      {
        name: name + ANCHOR,
        on: [
          {
            events,
            update: !hasScales
              ? `{x: x(unit), y: y(unit)}`
              : '{' +
                [sx ? `x: invert(${sx}, x(unit))` : '', sy ? `y: invert(${sy}, y(unit))` : '']
                  .filter(expr => !!expr)
                  .join(', ') +
                '}'
          }
        ]
      },
      {
        name: delta,
        on: [
          {
            events,
            force: true,
            update: 'pow(1.001, event.deltaY * pow(16, event.deltaMode))'
          }
        ]
      }
    );

    if (x !== undefined) {
      onDelta(model, selCmpt, x, 'width', signals);
    }

    if (y !== undefined) {
      onDelta(model, selCmpt, y, 'height', signals);
    }

    return signals;
  }
};

export default zoom;

function onDelta(
  model: UnitModel,
  selCmpt: SelectionComponent,
  proj: SelectionProjection,
  size: 'width' | 'height',
  signals: NewSignal[]
) {
  const name = selCmpt.name;
  const channel = proj.channel as ScaleChannel;
  const hasScales = scalesCompiler.defined(selCmpt);
  const signal = signals.filter(s => s.name === proj.signals[hasScales ? 'data' : 'visual'])[0];
  const sizeSg = model.getSizeSignalRef(size).signal;
  const scaleCmpt = model.getScaleComponent(channel);
  const scaleType = scaleCmpt.get('type');
  const base = hasScales ? domain(model, channel) : signal.name;
  const delta = name + DELTA;
  const anchor = `${name}${ANCHOR}.${channel}`;
  const zoomFn = !hasScales
    ? 'zoomLinear'
    : scaleType === 'log'
    ? 'zoomLog'
    : scaleType === 'symlog'
    ? 'zoomSymlog'
    : scaleType === 'pow'
    ? 'zoomPow'
    : 'zoomLinear';
  const arg = !hasScales
    ? ''
    : scaleType === 'pow'
    ? `, ${scaleCmpt.get('exponent') ?? 1}`
    : scaleType === 'symlog'
    ? `, ${scaleCmpt.get('constant') ?? 1}`
    : '';
  const update = `${zoomFn}(${base}, ${anchor}, ${delta}${arg})`;

  signal.on.push({
    events: {signal: delta},
    update: hasScales ? update : `clampRange(${update}, 0, ${sizeSg})`
  });
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import PropTypes from 'prop-types';

import './content-header.css';

function ContentHeader({section, title}) {
  return (

{section} /

{title}

  );
}

ContentHeader.propTypes = {
  section: PropTypes.string.isRequired,
  title: PropTypes.string.isRequired
};

export default ContentHeader;


text:
/*
 * header_file_scope.cpp
 *
 *  Created on: 10.11.2014
 *      Author: Marius
 */

#include "header_file_scope.hpp"
#include <boost/algorithm/string.hpp>

header_file_scope::header_file_scope(
	const std::string& filename,
	const std::vector<std::string>& inclusions,
	const std::vector<std::string>& namespaces,
	std::ostream& out)
	: namespaces{namespaces.size()}, out(out)
{
	std::string guard;
	std::string tmp;

	for(const std::string& namespace_ : namespaces)
	{
		tmp = namespace_;
		boost::algorithm::to_upper(tmp);
		guard += tmp;
		guard += '_';
	}

	tmp = filename;
	boost::algorithm::to_upper(tmp);
	guard += tmp;
	guard += "_HPP_";

	out << "#ifndef " << guard << "\n#define " << guard << "\n\n";

	for(const std::string& inclusion: inclusions)
	{
		out << "#include <" << inclusion << ">\n";
	}

	for(const std::string& namespace_: namespaces)
	{
		out << "namespace " << namespace_ << "\n{\n";
	}

}

header_file_scope::~header_file_scope()
{
	for(;namespaces; --namespaces)
	{
		out << "}\n";
	}
	out << "#endif\n";
}


text:
<?php

/**
 * sfRichTextEditorFCK implements the FCK rich text editor.
 *
 * Options:
 *  - tool   - Sets the FCKEditor toolbar style
 *  - config - Sets custom path to the FCKEditor configuration file
 *
 * @package    symfony
 * @subpackage helper
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: sfRichTextEditorFCK.class.php 17860 2009-05-01 22:33:31Z FabianLange $
 */
class sfRichTextEditorFCK extends sfRichTextEditor
{
  /**
   * Returns the rich text editor as HTML.
   *
   * @return string Rich text editor HTML representation
   */
  public function toHTML()
  {
    $options = $this->options;

    // we need to know the id for things the rich text editor
    // in advance of building the tag
    $id = _get_option($options, 'id', $this->name);

    $php_file = sfConfig::get('sf_rich_text_fck_js_dir').DIRECTORY_SEPARATOR.'fckeditor.php';

    if (!is_readable(sfConfig::get('sf_web_dir').DIRECTORY_SEPARATOR.$php_file))
    {
      throw new sfConfigurationException('You must install FCKEditor to use this helper (see rich_text_fck_js_dir settings).');
    }

    // FCKEditor.php class is written with backward compatibility of PHP4.
    // This reportings are to turn off errors with public properties and already declared constructor
    $error_reporting = error_reporting(E_ALL);

    require_once(sfConfig::get('sf_web_dir').DIRECTORY_SEPARATOR.$php_file);

    // turn error reporting back to your settings
    error_reporting($error_reporting);

    $fckeditor           = new FCKeditor($this->name);
    $fckeditor->BasePath = sfContext::getInstance()->getRequest()->getRelativeUrlRoot().'/'.sfConfig::get('sf_rich_text_fck_js_dir').'/';
    $fckeditor->Value    = $this->content;

    if (isset($options['width']))
    {
      $fckeditor->Width = $options['width'];
    }
    elseif (isset($options['cols']))
    {
      $fckeditor->Width = (string)((int) $options['cols'] * 10).'px';
    }

    if (isset($options['height']))
    {
      $fckeditor->Height = $options['height'];
    }
    elseif (isset($options['rows']))
    {
      $fckeditor->Height = (string)((int) $options['rows'] * 10).'px';
    }

    if (isset($options['tool']))
    {
      $fckeditor->ToolbarSet = $options['tool'];
    }

    if (isset($options['config']))
    {
      $fckeditor->Config['CustomConfigurationsPath'] = javascript_path($options['config']);
    }

    $content = $fckeditor->CreateHtml();

    if (sfConfig::get('sf_compat_10'))
    {
      // fix for http://trac.symfony-project.com/ticket/732
      // fields need to be of type text to be picked up by fillin. they are hidden by inline css anyway:
      // <input type="hidden" id="name" name="name" style="display:none" value="
default
">
      $content = str_replace('type="hidden"','type="text"',$content);
    }

    return $content;
  }
}


text:
import random
from ananas import PineappleBot, ConfigurationError, hourly, reply

def make_gram(word_array):
    return " ".join(word_array)

class NGramTextModel():
    def __init__(self, n, lines):
        self.n = n
        self.gram_dictionary = dict()
        self.build_from_lines(lines)

    def build_from_lines(self, lines):
        for line in lines:
            line = line.replace("\r", " ")
            line = line.replace("\n", " ")
            line_arr = ["^"] * self.n + [word.strip() for word in line.split()] + ["$"] * self.n

            for i in range(self.n, len(line_arr)):
                gram = make_gram(line_arr[i - self.n : i])
                word = line_arr[i]
                if (gram not in self.gram_dictionary):
                    self.gram_dictionary[gram] = []
                self.gram_dictionary[gram].append(word)

    def generate_sentence(self):
        sentence = self.n*["^"]
        next_gram = sentence[-self.n : ]
        while(next_gram != ["$"]*self.n):
            try:
                word_suggestion = random.choice(self.gram_dictionary[make_gram(next_gram)])
                sentence += [word_suggestion]
            except IndexError:
                break
            next_gram = sentence[-self.n : ]
        return " ".join(sentence[self.n : -self.n])

class MarkovBot(PineappleBot):
    def init():
        self.config.n = 2
    def start():
        if "corpus" not in self.config: raise ConfigurationError("MarkovBot requires a 'corpus'")
        with open(self.config.grammar_file, "r") as f:
            if f: self.model = NGramTextModel(self.config.n, f.lines())
            else: raise ConfigurationError("Couldn't open corpus file")

    @reply
    def reply(self, mention, user):
        self.mastodon.status_post("@{} {}".format(user["acct"],
                self.model.generate_sentence()),
                in_reply_to_id = mention["id"],
                visibility = mention["visibility"])

    @hourly()
    def post(self):
        self.mastodon.toot(self.model.generate_sentence())


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../../" />

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

Testare con NPM ([name])

			Questo articolo mostra come inserire three.js in un ambiente
			[link:https://nodejs.org/en/ node.js] così che tu possa eseguire test
			automatici. I test possono essere eseguiti da linea di comando o da
			strumenti CI automatici come [link:https://travis-ci.org/ Travis].

Versione breve

			Se sei a tuo agio con node e npm, installa npm
			 $ npm install three --save-dev
			e aggiungi
			 const THREE = require('three');
			al tuo test.

Creare un progetto testabile da zero

			Se non sei familiare con questi strumenti, ecco una guida rapida per
			linux (il processo di installazione sarà leggermente diverso usando
			Windows, ma i comandi NPM saranno uguali).

Configurazione di base

					Installa [link:https://www.npmjs.org/ npm] e nodejs. Il percorso più
					breve in genere assomiglia a qualcosa del simile:

$ sudo apt-get install -y npm nodejs-legacy
# fix any problems with SSL in the default registry URL
$ npm config set registry http://registry.npmjs.org/

					Crea una nuova cartella per il progetto
					 $ mkdir test-example; cd test-example

					Crea un nuovo file di progetto tramite npm:
					 $ npm init
					e accetta tutti i valori suggeriti premendo Enter per ogni richiesta.
					Con queste richieste si creerà il file package.json.

					Prova ad avviare la funzione di test con:
					 $ npm test
					fallirà, come ci aspettiamo. Se controlli nel file package.json la
					definizione dello script di test è:
					 "test": "echo \"Error: no test specified\" && exit 1"

Aggiungere mocha

			Utilizzeremo [link:https://mochajs.org/ mocha].

					Installare mocha con:
					 $ npm install mocha --save-dev
					Si noti che è stata creata la cartella node_modules/ e le tue
					dipendenze sono state installate al suo interno. Inoltre, si noti che
					il file package.json è stato aggiornato: è stata aggiunta la proprietà
					devDependencies, aggiornata dal comando --save-dev.

					Modificare il file package.json per usare mocha per i test. Quando
					viene invocato il test, vogliamo eseguire mocha e specificare un
					reporter dettagliato. Per impostazione predefinita questo eseguirà
					qualsiasi cosa nella cartella test/ (non avendo una cartella test/ si può
					incorrere in un npm ERR!, bisogna crearla con il comando mkdir test)
					 "test": "mocha --reporter list"

					Rilanciare il test con:
					 $ npm test

					Adesso il test dovrebbe essere eseguito con successo, riportando "0 passing (1ms) or
					similar".

Aggiungere three.js

					Inseriamo la nostra dipendenza three.js con il comando:
					 $ npm install three --save-dev

							Se hai bisogno di una versione di three.js diversa, usa
							 $ npm show three versions
							per vedere quali sono le versioni disponibili. Per dire ad npm la versione
							scelta, usa
							 $ npm install three@0.84.0 --save
							(0.84.0 nell'esempio). --save fa sì che sia una dipendenza del
							progetto piuttosto che una devDependecy. Per maggiori informazioni
							consulta il documento
							[link:https://docs.npmjs.com/cli/v8/configuring-npm/package-json qui].

					Mocha cercherà i test nella cartella test/, quindi creiamola
					 $ mkdir test

					Infine abbiamo effettivamente bisogno di un test JS per l'esecuzione.
					Aggiungiamo un semplice test il quale verificherà che l'oggetto
					three.js sia disponibile e funzionante. Crea il file
					test/verify-three.js contenente:

const THREE = require('three');
const assert = require('assert');

describe('The THREE object', function() {
  it('should have a defined BasicShadowMap constant', function() {
    assert.notEqual('undefined', THREE.BasicShadowMap);
  }),

  it('should be able to construct a Vector3 with default of x=0', function() {
    const vec3 = new THREE.Vector3();
    assert.equal(0, vec3.x);
  })
})

          Adesso rieseguiamo il test con il comando $ npm test. Questo dovrebbe
          eseguire i test sopra definiti e terminare con successo, mostrando qualcosa del tipo:

The THREE object should have a defined BasicShadowMap constant: 0ms
The THREE object should be able to construct a Vector3 with default of x=0: 0ms
2 passing (8ms)

Aggiungere il tuo codice

      Hai bisogno di fare tre cose:

          Scrivere un test per il comportamento che di aspetti dal tuo codice, e
          metterlo all'interno della cartella test/.
					[link:https://github.com/air/encounter/blob/master/test/Physics-test.js Qui] un esempio di un progetto reale.

          Esportare il tuo codice funzionale in modo tale che nodejs possa vederlo
          per usarlo insieme a require. Controlla
					[link:https://github.com/air/encounter/blob/master/js/Physics.js qui].

          Richiamare il tuo codice nel file di test, allo stesso modo in cui
          abbiamo fatto per richiamare three nell'esempio sopra `require('three')`

        Il punto 2 e 3 saranno molto dipendenti da come hai gestito il tuo codice.
        Nell'esempio di Physics.js fornito sopra, la parte di esportazione si trova giustamente
        alla fine. Assegniamo un oggetto a module.exports:

//=============================================================================
// make available in nodejs
//=============================================================================
if (typeof exports !== 'undefined') { module.exports = Physics; }

Affrontare le dipendenze

        Se stai già utilizzando qualcosa di smart come require.js o browserify,
        salta questa parte.

        Tipicamente un progetto three.js verrà eseguito nel browser. Il caricamento
        del modulo viene quindi eseguito dal browser che esegue una serie di tag
        di script. I tuo singoli file non si devono preoccupare per le dipendenze.
        Tuttavia, in un contesto nodejs non è presente il file index.html che lega tutto
        insieme, quindi devi essere esplicito.

        Se stai esportando un modulo che dipende da altri file, dovrai dire a node
        di caricarli. Di seguito un approccio:

          All'inizio del tuo  modulo, controlla se ti trovi in un ambiente nodejs.

Se è così, dichiara esplicitamente le tue dipendenze.

          In caso contrario, probabilmente sei in un browser e quindi non devi fare
          nient'altro.

			Esempio di codice da Physics.js:

//=============================================================================
// setup for server-side testing
//=============================================================================
if (typeof require === 'function') // test for nodejs environment {
  const THREE = require('three'); const MY3 = require('./MY3.js'); }


text:
#include "ServiceHandler.h"
#include "Policy.h"

const char* ServiceHandler::gpcCategory = "ServiceHandler";
const char* ServiceHandler::gpcConfigPath = "ServiceHandlers";

ServiceHandler::ServiceHandler(const char *ServiceHandlerName) :
	HierarchConfNamed(ServiceHandlerName) {
	StatTrace(ServiceHandler.Ctor, ServiceHandlerName, coast::storage::Current());
}

bool ServiceHandler::HandleService(std::ostream &os, Context &ctx) {
	StartTrace(ServiceHandler.HandleService);
	Trace("Service [" << fName << "]");
	String strKey("ServiceHandler");
	ctx.Push(strKey, this);
	bool status = DoHandleService(os, ctx);
	ctx.Pop(strKey); //!@FIXME: use PushPopEntry for LookupInterfaces too
	return status;
}

RegCacheImpl(ServiceHandler);
RegisterModule(ServiceHandlersModule);

bool ServiceHandlersModule::Init(const ROAnything config) {
	ROAnything roaHandlerConfig;
	if (config.LookupPath(roaHandlerConfig, ServiceHandler::gpcConfigPath)) {
		HierarchyInstaller ai(ServiceHandler::gpcCategory);
		return RegisterableObject::Install(roaHandlerConfig, ServiceHandler::gpcCategory, &ai);
	}
	return false;
}

bool ServiceHandlersModule::ResetFinis(const ROAnything config) {
	AliasTerminator at(ServiceHandler::gpcCategory);
	return RegisterableObject::ResetTerminate(ServiceHandler::gpcCategory, &at);
}

bool ServiceHandlersModule::Finis() {
	return StdFinis(ServiceHandler::gpcCategory, ServiceHandler::gpcConfigPath);
}


text:
RSpec.describe FipExtractor::Vehicle do
  subject { described_class.new(params) }
  let(:params) do
    {
      reference_table_id: 1,
      brand_id: 1,
      model_id: 1,
      year: 1999,
      fuel: 1,
      vehicle_type: :car
    }
  end

  describe '#route' do
    it do
      expect(subject.route).to eq('ConsultarValorComTodosParametros')
    end
  end

  describe '#params' do
    it do
      expect(subject.params).to eq({
        codigoTipoVeiculo: 1,
        codigoTabelaReferencia: 1,
        codigoModelo: 1,
        codigoMarca: 1,
        anoModelo: 1999,
        codigoTipoCombustivel: 1,
        tipoConsulta: 'tradicional'
      })
    end
  end
end


text:
	<title>Smack Documentation - Jive Software</title>
	<link rel="stylesheet" type="text/css" href="style.css" />

Smack Documentation

Contents:

Overview

Getting Started Guide

Managing Connections

Messaging Basics

Roster and Presence

Processing Incoming Packets

Provider Architecture

Packet Properties

Debugging with Smack

Privacy

Smack Extensions Manual

Copyright © Jive Software 2002-2008


text:
// Copyright (C) 2014 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 14.5
description: >
    class super in static setter
---*/
class B {
  static method() {
    return 1;
  }
  static get x() {
    return 2;
  }
}
class C extends B {
  static set x(v) {
    assert.sameValue(v, 3, "The value of `v` is `3`");
    assert.sameValue(super.x, 2, "The value of `super.x` is `2`");
    assert.sameValue(super.method(), 1, "`super.method()` returns `1`");
  }
}
assert.sameValue(C.x = 3, 3, "`C.x = 3` is `3`");


text:
  Random Stats from the last few months

  <canvas baseChart width="400" height="400"
          [datasets]="lineChartData"
          [labels]="lineChartLabels"
          [options]="lineChartOptions"
          [colors]="lineChartColors"
          [legend]="lineChartLegend"
          [chartType]="lineChartType"
          (chartHover)="chartHovered($event)"
          (chartClick)="chartClicked($event)"></canvas>

  <button md-button (click)="randomize()">Update</button>

      <canvas baseChart
              [datasets]="barChartData"
              [labels]="barChartLabels"
              [options]="barChartOptions"
              [legend]="barChartLegend"
              [chartType]="barChartType"
              (chartHover)="chartHovered($event)"
              (chartClick)="chartClicked($event)"></canvas>


text:
<!DOCTYPE html>

  <meta charset="utf-8" />

  <meta name="viewport" content="width=device-width" />

  <title>Welcome to Foundation</title>

  <link rel="stylesheet" href="stylesheets/app.css">

Link 1

Link 2

Link 3

Link 4

Link 5

Link 6

Link 7

This is a content section.

Bacon ipsum dolor sit amet nulla ham qui sint exercitation eiusmod commodo, chuck duis velit. Aute in reprehenderit, dolore aliqua non est magna in labore pig pork biltong. Eiusmod swine spare ribs reprehenderit culpa. Boudin aliqua adipisicing rump corned beef.

Bacon ipsum dolor sit amet nulla ham qui sint exercitation eiusmod commodo, chuck duis velit. Aute in reprehenderit, dolore aliqua non est magna in labore pig pork biltong. Eiusmod swine spare ribs reprehenderit culpa. Boudin aliqua adipisicing rump corned beef.

Next Page →

Get in touch!

We'd love to hear from you, you attractive person you.

            Contact Us

© Copyright no one at all. Go to town.

Link 1

Link 2

Link 3

Link 4

Link 5

Link 6

Link 7


text:
using Newtonsoft.Json;
using RongCloudNetCore.Models;
using RongCloudNetCore.Util;
using System;
using System.Net;
using System.Threading.Tasks;

namespace RongCloudNetCore.Methods
{
    public class Wordfilter
    {
        private string appKey;
        private string appSecret;

        public Wordfilter(string appKey, string appSecret)
        {
            this.appKey = appKey;
            this.appSecret = appSecret;
        }

        /// <summary>
        /// 添加敏感词方法(设置敏感词后,App 中用户不会收到含有敏感词的消息内容,默认最多设置 50 个敏感词。)
        /// </summary>
        /// <param name="word">敏感词,最长不超过 32 个字符(必传)</param>
        public async Task<CodeSuccessReslut> Add(string word)
        {
            if (string.IsNullOrEmpty(word))
                throw new ArgumentNullException(nameof(word));

            string postStr = "";
            postStr += "word=" + WebUtility.UrlEncode(word == null ? "" : word) + "&";
            postStr = postStr.Substring(0, postStr.LastIndexOf('&'));

            return JsonConvert.DeserializeObject<CodeSuccessReslut>(await RongHttpClient.ExecutePost(appKey, appSecret, RongCloud.RONGCLOUDURI + "/wordfilter/add.json", postStr, "application/x-www-form-urlencoded"));
        }

        /// <summary>
        /// 查询敏感词列表方法
        /// </summary>
        public async Task<ListWordfilterReslut> GetList()
        {

            string postStr = "";
            return JsonConvert.DeserializeObject<ListWordfilterReslut>(await RongHttpClient.ExecutePost(appKey, appSecret, RongCloud.RONGCLOUDURI + "/wordfilter/list.json", postStr, "application/x-www-form-urlencoded"));
        }

        /// <summary>
        /// 移除敏感词方法(从敏感词列表中,移除某一敏感词。)
        /// </summary>
        /// <param name="word">敏感词,最长不超过 32 个字符(必传)</param>
        public async Task<CodeSuccessReslut> Delete(string word)
        {
            if (string.IsNullOrEmpty(word))
                throw new ArgumentNullException(nameof(word));

            string postStr = "";
            postStr += "word=" + WebUtility.UrlEncode(word == null ? "" : word) + "&";
            postStr = postStr.Substring(0, postStr.LastIndexOf('&'));

            return JsonConvert.DeserializeObject<CodeSuccessReslut>(await RongHttpClient.ExecutePost(appKey, appSecret, RongCloud.RONGCLOUDURI + "/wordfilter/delete.json", postStr, "application/x-www-form-urlencoded"));
        }
    }
}


text:
package org.mifos.test.acceptance.framework.loan;

public class CreateMultipleLoanAccountSelectParameters {
    public String getBranch() {
        return this.branch;
    }
    public void setBranch(String branch) {
        this.branch = branch;
    }
    public String getLoanOfficer() {
        return this.loanOfficer;
    }
    public void setLoanOfficer(String loanOfficer) {
        this.loanOfficer = loanOfficer;
    }
    public String getCenter() {
        return this.center;
    }
    public void setCenter(String center) {
        this.center = center;
    }
    public String getLoanProduct() {
        return this.loanProduct;
    }
    public void setLoanProduct(String loanProduct) {
        this.loanProduct = loanProduct;
    }

    private String branch;
    private String loanOfficer;
    private String center;
    private String loanProduct;
}


text:
import json
import csv
import codecs
from collections import OrderedDict
#from pm.comm.log import *
from pm.items import PmItem
from pm.spiders.pmData import *
class PmPipeline(object):
    def process_item(self, item, spider):
        return item
def trimsignal(str):
    return str.replace("\n","").replace(" ","")
def changeOneData(item):
    it = item
    it["monitortime"]=it["monitortime"].replace(u"数据更新时间:", "")
    if it["iscity"] == 2:
        it["primarypollutant"] = trimsignal(it["primarypollutant"])
        pass
    elif it["iscity"] == 1:
        it["aqi"] = trimsignal(it["aqi"])
        it["pm25"] = trimsignal(it["pm25"])
        it["pm10"] = trimsignal(it["pm10"])
        it["co"] = trimsignal(it["co"])
        it["pm25"] = trimsignal(it["aqi"])
        it["no2"] = trimsignal(it["no2"])
        it["o3"] = trimsignal(it["o3"])
        it["o3_8h"] = trimsignal(it["o3_8h"])
        it["so2"] = trimsignal(it["so2"])
        it["pollutantlevel"] = re.findall(r".*((.+?)).*", it["pollutantlevel"])[0]
        it["primarypollutant"] = trimsignal(it["primarypollutant"]).replace("首要污染物:", "")
class JsonWithEncodingPipeline(object):
    def __init__(self):
        #info("."*300)
        self.file = codecs.open('data_utf8.json', 'w', encoding='utf-8')
        self.file.write("[\n")
        self.isfirst=True

    def process_item(self, item, spider):
        changeOneData(item)
        if self.isfirst:
            line =json.dumps(dict(item), ensure_ascii=False, sort_keys=False)
            self.isfirst=False
        else:
            line = ",\n" +json.dumps( dict(item), ensure_ascii=False, sort_keys=False)
        self.file.write(line)
        return item
    def close_spider(self, spider):
        self.file.write("]")
        self.file.close()

class CsvPipeline(object):
    def open_spider(self, spider):
        self.file = open(r'data_utf8.csv', 'w', encoding='utf-8')
        fieldnames = list(PmItem.fields.keys())
        #self.writer = csv.DictWriter(self.file, fieldnames=fieldnames, dialect='excel')
        self.writer = csv.DictWriter(self.file, fieldnames=fieldnames)
        self.writer.writeheader()

    def close_spider(self, spider):
        self.file.close()
    def process_item(self, item, spider):
        changeOneData(item)
        if not item.get("city", None) is None:
            self.writer.writerow(dict(item))
<<<<<<< HEAD

class OraclePipeline(object):
    def open_spider(self, spider):
        self.tool = databaseTool()
        self.tool.start()
        self.info=list(self.tool.getStationInfo())
        self.file = open(r'data_utf8.log', 'w', encoding='utf-8')
    def close_spider(self, spider):
        self.tool.close()

    def process_item(self, item, spider):
        changeOneData(item)
        hour = T_BUS_AIR_QUALITY_HOUR()
        #hour = T_BUS_AIR_QUALITY_HOUR(**item)
        keys=list(PmItem.fields.keys())
        for key in keys:
            try:
                setattr(hour,key,item[key])
            except:
                pass
        code = [ it  for it in self.info if it[1]==item["city"] and it[2]==item["positionname"]]
        if len(code) >0:
            setattr(hour, "stationcode",code[0][0] )
        else:
            self.file.write(item["city"]+"," +item["positionname"] +"\n")
        self.tool.addobj(hour)
=======
            return item
>>>>>>> 4f91f40a29983efdc691d5cfcaf3592745ff8f6c


text:
local octree = {}

octree.__index = octree

function new()
  local t = {
		root = {
			size = 1,

			x = 0,
			y = 0,
			z = 0
		}
	}
	setmetatable(t, octree)
	return t
end

-- Tree metatable
function octree:expand_if_needed(x, y, z)
	local root = self.root

	local size = root.size

	-- Relative coordinates
	local rX = x - root.x
	local rY = y - root.y
	local rZ = z - root.z

	-- Out of bounds marks
	local xPos = rX >= size
	local xNeg = rX < -size

	local yPos = rY >= size
	local yNeg = rY < -size

	local zPos = rZ >= size
	local zNeg = rZ < -size

	-- Check if the point is in the bounds
	if xPos or xNeg or
		yPos or yNeg or
		zPos or zNeg then

		-- Change the root node to fit
		local node = {
			size = size * 2,

			x = 0,
			y = 0,
			z = 0
		}

		local index = 0

		-- Offset the new root, and place the old into it
		if rX >= 0 then node.x = root.x + size end
		if rY >= 0 then node.y = root.y + size end
		if rZ >= 0 then node.z = root.z + size end

		if rX < 0 then
			node.x = root.x - size
			index = index + 1
		end
		if rY < 0 then
			node.y = root.y - size
			index = index + 2
		end
		if rZ < 0 then
			node.z = root.z - size
			index = index + 4
		end

		node[index] = root

		-- Erase previous root information
		root.size = nil
		root.x = nil
		root.y = nil
		root.z = nil

		-- Set the new root
		self.root = node

		-- Repeat until the size is sufficient
		self:expand_if_needed(x, y, z)
	end
end

function octree:get(x, y, z)
	self:expand_if_needed(x, y, z)

	-- Convert the coordinates relative to the root
	local node = self.root
	local size = node.size

	local rX = x - node.x
	local rY = y - node.y
	local rZ = z - node.z

	while true do
		size = size / 2

		local index = 0

		-- Seek, and offset the point for the next node
		if rX >= 0 then
			index = index + 1
			rX = rX - size
		else
			rX = rX + size
		end

		if rY >= 0 then
			index = index + 2
			rY = rY - size
		else
			rY = rY + size
		end

		if rZ >= 0 then
			index = index + 4
			rZ = rZ - size
		else
			rZ = rZ + size
		end

		-- Get the node/value at the calculated index
		local child = node[index]

		if type(child) ~= "table" then
			return child
		end

		-- We must go deeper!
		node = child
	end
end

local function merge_if_possible(stack, path, ref)

	for i = #stack, 1, -1 do
		local node = stack[i]

		-- Check if every value is the same in the node
		for x = 0, 7, 1 do
			if ref ~= node[x] then
				-- Break if any is not
				return
			end
		end

		-- Successful merge
		stack[i -1][path[i]] = ref
	end

end

function octree:set(x, y, z, value)
	self:expand_if_needed(x, y, z)

	-- Convert the coordinates relative to the root
	local node = self.root
	local size = node.size

	local rX = x - node.x
	local rY = y - node.y
	local rZ = z - node.z

	local stack = {}
	local path = {}

	while true do
		size = size / 2

		local index = 0

		if rX >= 0 then
			index = index + 1
			rX = rX - size
		else
			rX = rX + size
		end

		if rY >= 0 then
			index = index + 2
			rY = rY - size
		else
			rY = rY + size
		end

		if rZ >= 0 then
			index = index + 4
			rZ = rZ - size
		else
			rZ = rZ + size
		end

		table.insert(stack, node)
		table.insert(path, index)

		-- Get the node/value at the calculated index
		local child = node[index]

		if type(child) ~= "table" then
			if (child ~= value) then
				-- No node/value present
				if child == nil then
					-- If the size is not 1, it needs further populating,
					-- Otherwise, it just needs a value
					if size ~= 0.5 then
						child = {}
						node[index] = child
					else
						node[index] = value

						merge_if_possible(stack, path, value)
						return
					end
				else
					-- There is a node, but its value does not match, divide it
					-- If the size is over 1, otherwise, just set the value
					if size ~= 0.5 then
						local split = {
							child, child, child, child,
							child, child, child, child
						}

						child = split
						node[index] = split
					else
						-- Hit a real leaf, set the value and walk away
						node[index] = value

						merge_if_possible(stack, path, value)
						return
					end
				end
			else
				-- This treenode already has the same value, nothing to do
				return
			end
		end

		node = child
	end
end

return setmetatable(
	{ new = new },
	{ __call = function(_, ...) return new(...) end }
)


text:
{% extends extends_tmpl %}
{% load i18n %}

{% block title %}{% trans "Waiting list" %} - {{ tournament.name }}{% endblock %}

{% block endbody %}

{% if is_tournament_admin %}

{% endif %}
{% endblock %}

{% block content %}

{% trans "Waiting list" %}

{% trans "Players signed up" %}

        {{ tournament.get_player_list_count }}
        /
        {{ tournament.max_players }}

{% trans "Wildcard spots" %}

            {{ tournament.wildcard_spots }}

{% trans "Available spots" %}

        {{ tournament.get_available_spots }}

        {% if tournament.get_waiting_list_count > 0 %}
        ({{ tournament.get_waiting_list_count }} {% trans "on waiting list" %})
        {% endif %}

            #
            {% trans "Name" %}
            {% trans "Country" %}
            {% trans "Division" %}
            {% trans "PDGA" %}
            {% trans "Rating" %}
            {% trans "Paid" %}

            {% if is_tournament_admin %}
            {% trans "Actions" %}
            {% endif %}

        {% for tp in players %}

                {{ forloop.counter }}

                    {{ tp.player.name }}

                {{ tp.player_class.name }}

                    {% if tp.player.pdga_number %}

                        {{ tp.player.pdga_number }}

                    {% else %}
                        {% trans "N/A" %}
                    {% endif %}

                    {% if tp.player.pdga_rating %}{{ tp.player.pdga_rating }}{% endif %}

                    {% if tp.is_paid %}
                        {% trans "Yes" %}
                    {% else %}
                        {% trans "No" %}
                    {% endif %}

                {% if is_tournament_admin %}

                                {% trans "Edit this registration" %}

                                {% trans "Edit this player" %}

                                {% trans "Delete from tournament" %}

                                {% trans "Accept into tournament" %}

                {% endif %}

        {% endfor %}

{% endblock %}


text:
namespace llvm {

/// HexagonII - This namespace holds all of the target specific flags that
/// instruction info tracks.
///
namespace HexagonII {
  // *** The code below must match HexagonInstrFormat*.td *** //

  // Insn types.
  // *** Must match HexagonInstrFormat*.td ***
  enum Type {
    TypePSEUDO = 0,
    TypeALU32  = 1,
    TypeCR     = 2,
    TypeJR     = 3,
    TypeJ      = 4,
    TypeLD     = 5,
    TypeST     = 6,
    TypeSYSTEM = 7,
    TypeXTYPE  = 8,
    TypeMEMOP  = 9,
    TypeNV     = 10,
    TypePREFIX = 30, // Such as extenders.
    TypeMARKER = 31  // Such as end of a HW loop.
  };

  // MCInstrDesc TSFlags
  // *** Must match HexagonInstrFormat*.td ***
  enum {
    // This 5-bit field describes the insn type.
    TypePos  = 0,
    TypeMask = 0x1f,

    // Solo instructions.
    SoloPos  = 5,
    SoloMask = 0x1,

    // Predicated instructions.
    PredicatedPos  = 6,
    PredicatedMask = 0x1
  };

  // *** The code above must match HexagonInstrFormat*.td *** //

} // End namespace HexagonII.

} // End namespace llvm.

#endif


text:
using System;
using System.Linq;
using FluentAssertions;
using LinqToDB;
using LinqToDB.Data;
using LinqToDB.Mapping;
using NUnit.Framework;

namespace Tests.UserTests
{
	[TestFixture]
	public class Issue3161Tests : TestBase
	{
		[Table("TABLE1")]
		public partial class Table1
		{
			[Column("ID1"), PrimaryKey, NotNull] public int Id1 { get; set; }
			[Column("NAME1"), Nullable] public string? Name1 { get; set; }
		}

		[Table("TABLE2")]
		public partial class Table2
		{
			[Column("ID2"), PrimaryKey, NotNull] public int Id2 { get; set; }
			[Column("PARENTID2"), NotNull] public int ParentId2 { get; set; }
			[Column("NAME2"), Nullable] public string? Name2 { get; set; }
		}

		[Table("TABLE3")]
		public partial class Table3
		{
			[Column("ID3"), PrimaryKey, NotNull] public int Id3 { get; set; }
			[Column("PARENTID3"), NotNull] public int ParentId3 { get; set; }
			[Column("NAME3"), Nullable] public string? Name3 { get; set; }
		}

		[Test]
		public void CrossApplyOnce([IncludeDataSources(TestProvName.AllSqlServer2008Plus, TestProvName.AllClickHouse)] string context)
		{
			using var db = GetDataContext(context);
			using var tbl1 = db.CreateLocalTable(new[]
			{
				new Table1 { Id1 = 1, Name1 = "Some1" },
				new Table1 { Id1 = 2, Name1 = "Some2" },
			});
			using var tbl2 = db.CreateLocalTable(new[]
			{
				new Table2 { Id2 = 11, ParentId2 = 1, Name2 = "Child11" },
				new Table2 { Id2 = 12, ParentId2 = 1, Name2 = "Child12" },
				new Table2 { Id2 = 13, ParentId2 = 2, Name2 = "Child13" },
			});
			var ret = db.GetTable<Table1>()
				.Select(t1 => new
				{
					Name1 = t1.Name1,
					Value1 = db.GetTable<Table2>()
						.Where(x => x.ParentId2 == t1.Id1)
						.Select(t2 => new
						{
							//cross apply
							Name2 = t2.Name2,
							Value2 = t2.Id2
						})
						.FirstOrDefault()
				})
				.ToList();

			ret.Should().HaveCount(2);
		}

		[Test]
		public void CrossApplyTwice([IncludeDataSources(TestProvName.AllSqlServer2008Plus)] string context)
		{
			using var db = GetDataContext(context);
			using var tbl1 = db.CreateLocalTable(new[]
			{
				new Table1 { Id1 = 1, Name1 = "Some1" },
				new Table1 { Id1 = 2, Name1 = "Some2" },
			});
			using var tbl2 = db.CreateLocalTable(new[]
			{
				new Table2 { Id2 = 11, ParentId2 = 1, Name2 = "Child11" },
				new Table2 { Id2 = 12, ParentId2 = 1, Name2 = "Child12" },
				new Table2 { Id2 = 13, ParentId2 = 2, Name2 = "Child13" },
			});
			using var tbl3 = db.CreateLocalTable(new[]
			{
				new Table3 { Id3 = 21, ParentId3 = 11, Name3 = "Child21" },
				new Table3 { Id3 = 22, ParentId3 = 11, Name3 = "Child22" },
				new Table3 { Id3 = 23, ParentId3 = 12, Name3 = "Child23" },
			});
			var ret = db.GetTable<Table1>()
				.Select(t1 => new
				{
					Name1 = t1.Name1,
					Value1 = db.GetTable<Table2>()
						.Where(x => x.ParentId2 == t1.Id1)
						.Select(t2 => new
						{
							//first cross apply
							Name2 = t2.Name2,
							Value2 = db.GetTable<Table3>()
								.Where(x => x.ParentId3 == t2.Id2)
								.Select(t3 => new
								{
									//nested cross apply
									Name3 = t3.Name3,
									Value3 = t3.Id3
								})
								.FirstOrDefault()
						})
						.FirstOrDefault()
				})
				.ToList();
			Assert.That(ret.Count, Is.EqualTo(2));

			// validate that the prior statement executed as a single query, not two distinct queries
			var baselines = GetCurrentBaselines();
			baselines.Should().Contain("SELECT", Exactly.Times(3));
			baselines.Should().Contain("SELECT TOP", Exactly.Twice());

			// LastQuery will only return a single query, so if it was split into two queries, not all name fields would be present
			var lastQuery = ((DataConnection)db).LastQuery;
			lastQuery.Should().Contain("NAME1", Exactly.Once());
			lastQuery.Should().Contain("NAME2", Exactly.Once());
			lastQuery.Should().Contain("NAME3", Exactly.Once());
		}
	}
}


text:
package com.gabstudios.validate;

/**
 * This is a int validator. After this class is created, call the testXXXX()
 * methods to perform tests when the validate() method is called.
 *
 *      Validate.defineInteger(int).testNotNull().validate();
 *
 * If the throwValidationExceptionOnFail() method has been called and if the validate fails
 * then a ValidateException will be thrown.
 *
 *      Validate.defineInteger(int).testEquals(int)
 *          .throwValidationExceptionOnFail().validate();
 *
 * If no test method is called, validate() returns a false.
 *
 * @author Gregory Brown (sysdevone)
 *
 */
public class IntegerValidator extends NumberValidator<Integer>
{

    /**
     * Protected constructor. Use Validate static method to create validator.
     *
     * @param value
     *            The value that will be validated.
     */
    protected IntegerValidator(final int value)
    {
        super( value, Integer.MIN_VALUE, Integer.MAX_VALUE );
    }

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return String.format(
				"IntegerValidator [_isTestMaxValue=%s, _isTestMinValue=%s, _maxValue=%s, _minValue=%s, _isValidationExceptionThrownOnFail=%s, _equalsValue=%s, _isTestEquals=%s, _isTestNotNull=%s, _isTested=%s, _value=%s]",
				_isTestMaxValue, _isTestMinValue, _maxValue, _minValue, _isValidationExceptionThrownOnFail,
				_equalsValue, _isTestEquals, _isTestNotNull, _isTested, _value);
	}

}


text:
/*
 * Module Name: Kdc main
 *
 * Filename: includes.h
 *
 * Abstract:
 *
 * Kdc main module include file
 *
 */

#ifndef _WIN32/* ============= LINUX ONLY ================ */
#include <config.h>
#include <vmkdcsys.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <lwrpcrt/lwrpcrt.h>
#include <reg/lwreg.h>
#include <reg/regutil.h>

#include <net/if.h>
#include <ifaddrs.h>

#else
/* ========================= WIN32 ONLY ======================== */

#pragma once
#include <errno.h>
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>
#include <tchar.h>
#include <winsvc.h>
#include <Winreg.h>
#include <assert.h>
#include <Ws2tcpip.h>
#endif

//SUNG vmkdc merge,
#include <topdefines.h>
#include <vmdir.h>
#include <vmdirtypes.h>
#include <vmdirdefines.h>
#include <vmdircommon.h>
#include "srvcommon.h"
#include "vmdirserver.h"
#include "ldaphead.h"
#include "middlelayer.h"
#include <dce/rpc.h>
#include <pthread.h>

/* Common include between Linux and Windows */
#include <vmkdc.h>
#include <vmkdctypes.h>
#include <vmkdcdefines.h>
#include <vmkdcerrorcode.h>
#include <vmkdccommon.h>
#include <kdcsrvcommon.h>
#include <vmkdcserver.h>

#include "defines.h"
#include "structs.h"
#include "prototypes.h"
#include "externs.h"

#include <kdckrb5/types.h>
#include <kdckrb5/structs.h>
#include <kdckrb5/prototypes.h>

#include "directory.h"
#include "networking.h"
#include "process.h"
#include "parsekt.h"
#include "princtok.h"
#include "fgetsl.h"

#include <krb5-crypto/includes.h>


text:
a=5
b=10
x=6

echo "use round brackets"
if (( $a < $x && $x < $b )); then
    echo "x=$x is between a=$a and b=$b"
else
    echo "x=$x is not between a=$a and b=$b"
fi

echo "use square brackets"
if [[ $a < $x && $x < $b ]]; then
    echo "x=$x is between a=$a and b=$b"
else
    echo "x=$x is not between a=$a and b=$b"
fi

# [[...]] will recognize variables as string
# [[ $a < $x && $x < $b ]] is equivalent to [[ "5" < "6" && "6" < "10" ]]

# (()) will recognize variables as number

daytime=morning
fruit=peach

if [[ $daytime == "morning" && ( $fruit == "apple" || $fruit == "banana" ) ]]; then
    echo "fruit is my favorite"
else
    echo "fruit is not my favorite"
fi

echo "test short circuit and"
head -n1 andor.sh && echo "1: echo reached" # will output "echo reached"
head -n1 notexistfile && echo "2: echo reached" # will not output "echo reached"

echo "test short circuit or"
head -n1 andor.sh || echo "1: echo reached" # will not output "echo reached"
head -n1 notexistfile || echo "2: echo reached" # will output "echo reached"

echo "combine and or"
(( $a < $x && $x < $b )) && echo "true" || echo "false"


text:
var definitions, handler, path, utils;

definitions = {
  config: {
    type: 'object',
    required: ['target']
  }
};

// This action honors all the config from "nikita.file.ini".

// ## Handler
handler = async function({config}) {
  // Set the target directory to yum's default path if target is a file name
  config.target = path.resolve('/etc/yum.repos.d', config.target);
  return (await this.file.ini({
    parse: utils.ini.parse_multi_brackets,
    escape: false
  }, config));
};

// ## Exports
module.exports = {
  handler: handler,
  metadata: {
    definitions: definitions
  }
};

// ## Dependencies
path = require('path');

utils = require('../utils');


text:
package nl.gridline.zieook.model;

import java.io.Serializable;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * [purpose]
 *

 * Project zieook-api-data

 * PopularityTypes.java created 13 dec. 2011
 *

 * Copyright, all rights reserved 2011 GridLine Amsterdam
 * @author Job
 * @version $Revision:$, $Date:$
 */
@XmlRootElement(name = "popularity-types")
@XmlAccessorType(XmlAccessType.FIELD)
public class PopularityTypes implements Serializable
{
	/**
	 *
	 */
	private static final long serialVersionUID = -5850595265758644903L;

	private final List<String> types;

	public PopularityTypes()
	{
		types = null;
	}

	public PopularityTypes(List<String> types)
	{
		this.types = types;
	}

	/**
	 * @return The types.
	 */
	public List<String> getTypes()
	{
		return types;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode()
	{
		final int prime = 31;
		int result = 1;
		result = prime * result + ((types == null) ? 0 : types.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj)
	{
		if (this == obj)
		{
			return true;
		}
		if (obj == null)
		{
			return false;
		}
		if (getClass() != obj.getClass())
		{
			return false;
		}
		PopularityTypes other = (PopularityTypes) obj;
		if (types == null)
		{
			if (other.types != null)
			{
				return false;
			}
		}
		else if (!types.equals(other.types))
		{
			return false;
		}
		return true;
	}

}


text:
OC.L10N.register(
    "core",
    {
    "Couldn't send mail to following users: %s " : "On non pote inviar message de e-posta a le usatores sequente: %s",
    "Turned on maintenance mode" : "Activate modo de mantenentia",
    "Turned off maintenance mode" : "De-activar modo de mantenentia",
    "Updated database" : "Base de datos actualisate",
    "Checked database schema update" : "Il ha verificate actualisation de schema de base de datos",
    "Checked database schema update for apps" : "Il ha verificate actualisation de schema de base de datos pro apps",
    "Updated \"%s\" to %s" : "Actualisava \"%s\" a %s",
    "Disabled incompatible apps: %s" : "Apps non compatibile ha essite dishabilitate: %s",
    "No image or file provided" : "Il forniva necun imagine o file",
    "Unknown filetype" : "Typo de file incognite",
    "Invalid image" : "Imagine invalide",
    "No temporary profile picture available, try again" : "Necun photo de profilo temporanee disponibile, essaya novemente",
    "Sunday" : "Dominica",
    "Monday" : "Lunedi",
    "Tuesday" : "Martedi",
    "Wednesday" : "Mercuridi",
    "Thursday" : "Jovedi",
    "Friday" : "Venerdi",
    "Saturday" : "Sabbato",
    "January" : "januario",
    "February" : "Februario",
    "March" : "Martio",
    "April" : "April",
    "May" : "Mai",
    "June" : "Junio",
    "July" : "Julio",
    "August" : "Augusto",
    "September" : "Septembre",
    "October" : "Octobre",
    "November" : "Novembre",
    "December" : "Decembre",
    "Settings" : "Configurationes",
    "Saving..." : "Salveguardante...",
    "Couldn't send reset email. Please contact your administrator." : "On non pote inviar message de configurar ex novo. Pro favor continge tu administrator.",
    "I know what I'm doing" : "Io sape lo que io es facente",
    "Password can not be changed. Please contact your administrator." : "Contrasigno non pote esser modificate. Pro favor continge tu administrator.",
    "No" : "No",
    "Yes" : "Si",
    "Choose" : "Seliger",
    "Ok" : "Ok",
    "_{count} file conflict_::_{count} file conflicts_" : ["{count} conflicto de file","{count} conflictos de file"],
    "One file conflict" : "Un conflicto de file",
    "New Files" : "Nove files",
    "Already existing files" : "Files jam existente",
    "Which files do you want to keep?" : "Qual files tu vole mantener?",
    "Cancel" : "Cancellar",
    "Continue" : "Continuar",
    "Error loading file exists template" : "Error quando on incargava patrono de file existente",
    "Very weak password" : "Contrasigno multo debile",
    "Weak password" : "Contrasigno debile",
    "So-so password" : "Contrasigno passabile",
    "Good password" : "Contrasigno bon",
    "Strong password" : "Contrasigno forte",
    "Error occurred while checking server setup" : "Un error occurreva quando on verificava le configuration de le servitor.",
    "Shared" : "Compartite",
    "Shared with {recipients}" : "Compatite con {recipients}",
    "Share" : "Compartir",
    "Error" : "Error",
    "Error while sharing" : "Error quando on compartiva",
    "Error while unsharing" : "Error quando on levava le compartir",
    "Error while changing permissions" : "Error quando on modificava permissiones",
    "Shared with you and the group {group} by {owner}" : "Compartite con te e le gruppo {group} per {owner}",
    "Shared with you by {owner}" : "Compartite con te per {owner} ",
    "Share with user or group …" : "Compartir con usator o gruppo ...",
    "Share link" : "Compartir ligamine",
    "Password protect" : "Protegite per contrasigno",
    "Password" : "Contrasigno",
    "Choose a password for the public link" : "Selige un contrasigno pro le ligamine public",
    "Email link to person" : "Ligamine de e-posta a persona",
    "Send" : "Invia",
    "Set expiration date" : "Fixa data de expiration",
    "Expiration date" : "Data de expiration",
    "Adding user..." : "Addente usator...",
    "group" : "gruppo",
    "Resharing is not allowed" : "Il non es permittite compartir plus que un vice",
    "Shared in {item} with {user}" : "Compartite in  {item} con {user}",
    "Unshare" : "Leva compartir",
    "notify by email" : "notificar per message de e-posta",
    "can share" : "pote compartir",
    "can edit" : "pote modificar",
    "access control" : "controlo de accesso",
    "create" : "crear",
    "delete" : "deler",
    "Password protected" : "Proteger con contrasigno",
    "Error unsetting expiration date" : "Error quando on levava le data de expiration",
    "Error setting expiration date" : "Error quando on fixava le data de expiration",
    "Sending ..." : "Inviante ...",
    "Email sent" : "Message de e-posta inviate",
    "Warning" : "Aviso",
    "The object type is not specified." : "Le typo de objecto non es specificate",
    "Enter new" : "Inserta nove",
    "Delete" : "Deler",
    "Add" : "Adder",
    "Edit tags" : "Modifica etiquettas",
    "_download %n file_::_download %n files_" : ["",""],
    "Please reload the page." : "Pro favor recarga le pagina.",
    "The update was successful. Redirecting you to ownCloud now." : "Le actualisation terminava con successo. On redirige nunc a tu ownCloud.",
    "%s password reset" : "%s contrasigno re-fixate",
    "Use the following link to reset your password: {link}" : "Usa le ligamine sequente pro re-fixar tu contrasigno: {link}",
    "New password" : "Nove contrasigno",
    "New Password" : "Nove contrasigno",
    "Reset password" : "Reinitialisar contrasigno",
    "_{count} search result in other places_::_{count} search results in other places_" : ["",""],
    "For the best results, please consider using a GNU/Linux server instead." : "Pro le exitos melior, pro favor tu considera usar in loco un servitor GNU/Linux.",
    "Personal" : "Personal",
    "Users" : "Usatores",
    "Apps" : "Applicationes",
    "Admin" : "Administration",
    "Help" : "Adjuta",
    "Error loading tags" : "Error quando on cargava etiquettas",
    "Tag already exists" : "Etiquetta ja existe",
    "Access forbidden" : "Accesso prohibite",
    "File not found" : "File non trovate",
    "The specified document has not been found on the server." : "Le documento specificate non ha essite trovate sur le servitor.",
    "The share will expire on %s." : "Le compartir expirara le %s.",
    "Cheers!" : "Acclamationes!",
    "Technical details" : "Detalios technic",
    "Remote Address: %s" : "Adresse remote: %s",
    "Request ID: %s" : "ID de requesta: %s",
    "Code: %s" : "Codice: %s",
    "Message: %s" : "Message: %s",
    "File: %s" : "File: %s",
    "Line: %s" : "Rango: %s",
    "Trace" : "Tracia",
    "Security Warning" : "Aviso de securitate",
    "Please update your PHP installation to use %s securely." : "Pro favor actualisa tu installation de PHP pro usar %s con securitate.",
    "Create an admin account" : "Crear un conto de administration",
    "Username" : "Nomine de usator",
    "Storage & database" : "Immagazinage & base de datos",
    "Data folder" : "Dossier de datos",
    "Configure the database" : "Configurar le base de datos",
    "Only %s is available." : "Solmente %s es disponibile",
    "Database user" : "Usator de base de datos",
    "Database password" : "Contrasigno de base de datos",
    "Database name" : "Nomine de base de datos",
    "Database tablespace" : "Spatio de tabella de base de datos",
    "Database host" : "Hospite de base de datos",
    "Finish setup" : "Terminar configuration",
    "Finishing …" : "Terminante ...",
    "Log out" : "Clauder le session",
    "Search" : "Cercar",
    "Server side authentication failed!" : "Il falleva authentication de latere servitor!",
    "Please contact your administrator." : "Pro favor continge tu administrator.",
    "Forgot your password? Reset it!" : "Tu oblidava tu contrasigno? Re-configura lo!",
    "remember" : "memora",
    "Log in" : "Aperir session",
    "Alternative Logins" : "Accessos de autorisation alternative",
    "Thank you for your patience." : "Gratias pro tu patientia.",
    "Start update" : "Initia actualisation"
},
"nplurals=2; plural=(n != 1);");


text:
layout: post
title: "Benchmarking BLAS&LAPACK implementation for use with R, Python and Julia"
description: "Some benchmarking of numerical linear algebra libraries with R, Python, and Julia"
category:
tags:  [r, statistics, machine-learning, python]
---

__Guest post by [Guy Barel](guybare@post.bgu.ac.il).__

__Disclaimer:__ This project spanned a long period, and we were not as tidy as we should have been. This means that we are unable to provide the code used to produce the plots. If you decide to reproduce these results, and find similar/contradicting findings, please share with us.

Linear algebra libraries contain essential methods for statistical software.
Machine learning and AI use numeric linear algebra operations on data sets represented as matrices and vectors, making numerical linear algebra a core component in the field.
In recent years, the HPC community has attracted considerable research attention on obtaining high performances in matrix computations.
In addition, the growth of database dimensions brings an urgent need for analyzing the data sets in a reasonable time.
Therefore, knowing what the optimal libraries are in computing speed is crucial for any user interested in the field.

The following is a benchmark I conducted during my 4-th year engineering project at BGU with the guidance of Dr. Jonathan Rosenblatt.
The benchmark evaluates the performances of some matrix operations, in terms of execution time, for a wide range of linear algebra libraries - Basic Linear Algebra Subprograms [(BLAS)]( http://www.netlib.org/blas/), Linear Algebra Package [(LAPACK)](  http://www.netlib.org/lapack/), and high-performance libraries ([OpenBLAS]( https://www.openblas.net), [ATLAS]( http://math-atlas.sourceforge.net/), and [IntelMKL]( https://software.intel.com/content/www/us/en/develop/tools/oneapi/components/onemkl.html#gs.btl752)).
Moreover, the libraries evaluation  is combined with three programming languages, R, Python, and Julia, offering extended analysis compared to related publications.

In order to reach optimized performance time, the combination of two main parameters are examined, $$(i)$$ the selection of a linear algebra library and $$(ii)$$ the preferred programming language.

For benchmarking purposes, it is necessary to replace the underlying BLAS implementation of a programming language, where the replacement process has been proven particularly challenging.
For this purpose, I use a novel framework called [FlexiBLAS](https://www.mpi-magdeburg.mpg.de/projects/flexiblas) to exchange the BLAS implementation at run-time via an environment variable.
This approach uses a wrapper library called FlexiBLAS, which neither requires relinkage nor recompilation.
FlexiBLAS concept is a lightweight wrapper library around all BLAS and LAPACK subroutines using a plugin framework on top of the POSIX features for load, unload, and search for functions or symbols inside elf-files at runtime.
The major advantage of this approach is the relatively simple process of exchanging the BLAS library; besides, numerical experiments show no significant overhead introduced by this approach [MartinK¨ohler2013].

For benchmarking linear algebra libraries, hardware and software aspects significantly matter for the overall results.
The use of different CPUs, programming languages, or operating systems will generate distinct performance profiles.
This benchmark were carried out on a 64-bit machine featuring four 16-core Intel Xeon E7-4850v4 processors at 2.1GHz 115W, 1M L1, 4M L2, and 40M 20-way set associative shared cache, a total of 64 core/ 128 threads.
All tests will be performed on Linux OS Ubuntu 18.04, Using R, Julia, and Python programming languages.

### Benchmark

Each benchmark experiment consists of 10 runs for a matrix of size $$2^7 , 2^9 , 2^{11} , 2^{12}$$ , and $$2^{13}$$, rows/columns, using the chosen benchmark— *Matrix-Multiplication, Singular Value Decomposition(SVD), Cholesky decomposition* and a matrix sizes of $$2^{15} , 2^{17} , 2^{19} , 2^{20}$$ , and $$2^{21}$$ for *Dot-Product* —over all the optimized BLAS implementations mentioned.
For each test, I generated a random matrix for representing a matrix object.
Then, I ran each operation ten times, recorded the elapsed running time, and computed an average time.
Below are the results of the tests.

### Results

I choose to present the results in two different forms- $$(1)$$ Programming Languages oriented and $$(2)$$ Libraries oriented.
This way, we can better understand the influences of the programming languages and the libraries, individually, on the computation time.
Each of these plots displays results for all the available BLAS implementations, with the matrix dimension on the horizontal axis and the elapsed time in seconds on the vertical axis.

#### **Programming Languages oriented results**

#### Dot-Product results

![](../images/Dot-product.JPG)
*Figure 1 Dot-product results*

#### Matrix multiplication results

![](../images/Matrix multiplication.JPG)
*Figure 2 Matrix multiplication results*

#### SVD results

![](../images/SVD.JPG)
*Figure 3 SVD results*

#### Cholskey results

![](../images/Cholesky.JPG)
*Figure 4 Cholskey results*

#### **Libraries oriented results**

![](../images/BLAS&LAPACK.JPG "BLAS&LAPACK results")
*Figure 5 BLAS&LAPACK results*

![](../images/MKL.JPG "MKL results")
*Figure 6 MKL results*

![](../images/ATLAS.JPG "ATLAS results")
*Figure 7 ATLAS results*

![](../images/OpenBLAS.JPG "OpenBLAS results")
*Figure 8 OpenBLAS results*

### Conclusion

Unsurprisingly, the standard BLAS and LAPACK are dominated by all other alternatives.
Atlas is improving on the standard BLAS and LAPACK but is dominated by the libraries MKL and OpenBLAS that have relatively similar performance.
Python and Julia are essentially indistinguishable and ahead of R for most of the tests.
Surprisingly, R obtains much better results under OpenBLAS for most numerical tests and performs better computation time than Python and Julia.

This benchmark shows that greater performances can be achieved by wisely choosing the programming languages and the linear algebra libraries, significantly improving performances for linear algebra computation.

### References

[MartinK¨ohler2013] Martin K¨ohler, J. S. (2013). FlexiBLAS - A flexible BLAS library with runtime exchangeable backends.


text:
function Test()
	local pattern = [[
ab ad be cd be f0 12
ab cd f0 12
]]

	TestPattern(pattern, RunJam())
end


text:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/include/autoprepend.php');
require_once "includes/header.php";
require_once "includes/navbar.php";
require_once "sections/Home.php";
require_once "includes/footer.php";
?>


text:
package client

import (
	"log"
	"os"
	"strings"
	"time"

	Cli "github.com/get3w/get3w/cli"
	flag "github.com/get3w/get3w/pkg/mflag"
	"github.com/get3w/get3w/storage"
	"github.com/go-fsnotify/fsnotify"
)

// CmdWatch builds a new image from the source code at a given path.
//
// If '-' is provided instead of a path or URL, Docker will build an image from either a Dockerfile or tar archive read from STDIN.
//
// Usage: get3w run [OPTIONS] PATH | URL | -
func (cli *Get3WCli) CmdWatch(args ...string) error {
	cmd := Cli.Subcmd("watch", []string{"", "DIR"}, Cli.Get3WCommands["watch"].Description, true)
	cmd.Require(flag.Max, 1)
	cmd.ParseFlags(args, true)

	dir := cmd.Arg(0)

	return cli.watch(dir)
}

func (cli *Get3WCli) watch(dir string) error {
	parser, err := storage.NewLocalParser(cli.config.AuthConfig.Username, dir)
	if err != nil {
		return err
	}

	err = parser.Build(true)
	if err != nil {
		return err
	}

	sourcePath := parser.Storage.GetSourcePrefix("")
	destinationPath := strings.TrimRight(strings.ToLower(parser.Storage.GetDestinationPrefix("")), string(os.PathSeparator))
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	done := make(chan bool)
	go func() {
		lastTime := time.Now()
		for {
			select {
			case event := <-watcher.Events:
				if !strings.HasPrefix(strings.ToLower(event.Name), destinationPath) {
					now := time.Now()
					d := now.Sub(lastTime)
					if d.Seconds() > 1 {
						log.Println("build done.")

						parser, err := storage.NewLocalParser(cli.config.AuthConfig.Username, dir)
						if err != nil {
							log.Println("error:", err)
						}

						err = parser.Build(false)
						if err != nil {
							log.Println("error:", err)
						}

						lastTime = time.Now()
					}
				}

				// if event.Op&fsnotify.Write == fsnotify.Write {
				// 	log.Println("modified file:", event.Name)
				// }
			case err := <-watcher.Errors:
				log.Println("error:", err)
			}
		}
	}()

	err = watcher.Add(sourcePath)
	if err != nil {
		log.Fatal(err)
	}

	<-done

	return nil
}


text:
package com.lovping.curl;

public class Curl
{
    public static final int CURLINFO_STRING   = 0x100000;
    public static final int CURLINFO_LONG     = 0x200000;
    public static final int CURLINFO_DOUBLE   = 0x300000;
    public static final int CURLINFO_SLIST    = 0x400000;
    public static final int CURLINFO_EFFECTIVE_URL    = CURLINFO_STRING + 1;
    public static final int CURLINFO_RESPONSE_CODE    = CURLINFO_LONG   + 2;
    public static final int CURLINFO_TOTAL_TIME       = CURLINFO_DOUBLE + 3;
    public static final int CURLINFO_NAMELOOKUP_TIME  = CURLINFO_DOUBLE + 4;
    public static final int CURLINFO_CONNECT_TIME     = CURLINFO_DOUBLE + 5;
    public static final int CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6;
    public static final int CURLINFO_SIZE_UPLOAD      = CURLINFO_DOUBLE + 7;
    public static final int CURLINFO_SIZE_DOWNLOAD    = CURLINFO_DOUBLE + 8;
    public static final int CURLINFO_SPEED_DOWNLOAD   = CURLINFO_DOUBLE + 9;
    public static final int CURLINFO_SPEED_UPLOAD     = CURLINFO_DOUBLE + 10;
    public static final int CURLINFO_HEADER_SIZE      = CURLINFO_LONG   + 11;
    public static final int CURLINFO_REQUEST_SIZE     = CURLINFO_LONG   + 12;
    public static final int CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG   + 13;
    public static final int CURLINFO_FILETIME         = CURLINFO_LONG   + 14;
    public static final int CURLINFO_CONTENT_LENGTH_DOWNLOAD   = CURLINFO_DOUBLE + 15;
    public static final int CURLINFO_CONTENT_LENGTH_UPLOAD     = CURLINFO_DOUBLE + 16;
    public static final int CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17;
    public static final int CURLINFO_CONTENT_TYPE     = CURLINFO_STRING + 18;
    public static final int CURLINFO_REDIRECT_TIME    = CURLINFO_DOUBLE + 19;
    public static final int CURLINFO_REDIRECT_COUNT   = CURLINFO_LONG   + 20;
    public static final int CURLINFO_PRIVATE          = CURLINFO_STRING + 21;
    public static final int CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG   + 22;
    public static final int CURLINFO_HTTPAUTH_AVAIL   = CURLINFO_LONG   + 23;
    public static final int CURLINFO_PROXYAUTH_AVAIL  = CURLINFO_LONG   + 24;
    public static final int CURLINFO_OS_ERRNO         = CURLINFO_LONG   + 25;
    public static final int CURLINFO_NUM_CONNECTS     = CURLINFO_LONG   + 26;
    public static final int CURLINFO_SSL_ENGINES      = CURLINFO_SLIST  + 27;
    public static final int CURLINFO_COOKIELIST       = CURLINFO_SLIST  + 28;
    public static final int CURLINFO_LASTSOCKET       = CURLINFO_LONG   + 29;
    public static final int CURLINFO_FTP_ENTRY_PATH   = CURLINFO_STRING + 30;
    public static final int CURLINFO_REDIRECT_URL     = CURLINFO_STRING + 31;
    public static final int CURLINFO_PRIMARY_IP       = CURLINFO_STRING + 32;
    public static final int CURLINFO_APPCONNECT_TIME  = CURLINFO_DOUBLE + 33;
    public static final int CURLINFO_CERTINFO         = CURLINFO_SLIST  + 34;
    public static final int CURLINFO_CONDITION_UNMET  = CURLINFO_LONG   + 35;
    public static final int CURLINFO_RTSP_SESSION_ID  = CURLINFO_STRING + 36;
    public static final int CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG   + 37;
    public static final int CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG   + 38;
    public static final int CURLINFO_RTSP_CSEQ_RECV   = CURLINFO_LONG   + 39;
    public static final int CURLINFO_PRIMARY_PORT     = CURLINFO_LONG   + 40;
    public static final int CURLINFO_LOCAL_IP         = CURLINFO_STRING + 41;
    public static final int CURLINFO_LOCAL_PORT       = CURLINFO_LONG   + 42;

    public static final int LONG          = 0;
    public static final int OBJECTPOINT   = 10000;
    public static final int FUNCTIONPOINT = 20000;
    public static final int OFF_T         = 30000;
    public static final int CURLOPT_FILE = OBJECTPOINT + 1;
    public static final int CURLOPT_URL =  OBJECTPOINT + 2;
    public static final int CURLOPT_PORT = LONG + 3;
    public static final int CURLOPT_PROXY = OBJECTPOINT + 4;
    public static final int CURLOPT_USERPWD = OBJECTPOINT + 5;
    public static final int CURLOPT_PROXYUSERPWD = OBJECTPOINT + 6;
    public static final int CURLOPT_RANGE = OBJECTPOINT + 7;
    public static final int CURLOPT_INFILE = OBJECTPOINT + 9;
    public static final int CURLOPT_ERRORBUFFER = OBJECTPOINT + 10;
    public static final int CURLOPT_WRITEFUNCTION = FUNCTIONPOINT + 11;
    public static final int CURLOPT_READFUNCTION = FUNCTIONPOINT + 12;
    public static final int CURLOPT_TIMEOUT = LONG + 13;
    public static final int CURLOPT_INFILESIZE = LONG + 14;
    public static final int CURLOPT_POSTFIELDS = OBJECTPOINT + 15;
    public static final int CURLOPT_REFERER = OBJECTPOINT + 16;
    public static final int CURLOPT_FTPPORT = OBJECTPOINT + 17;
    public static final int CURLOPT_USERAGENT = OBJECTPOINT + 18;
    public static final int CURLOPT_LOW_SPEED_LIMIT = LONG + 19;
    public static final int CURLOPT_LOW_SPEED_TIME = LONG + 20;
    public static final int CURLOPT_RESUME_FROM = LONG + 21;
    public static final int CURLOPT_COOKIE = OBJECTPOINT + 22;
    public static final int CURLOPT_HTTPHEADER = OBJECTPOINT + 23;
    public static final int CURLOPT_HTTPPOST = OBJECTPOINT + 24;
    public static final int CURLOPT_SSLCERT = OBJECTPOINT + 25;
    public static final int CURLOPT_KEYPASSWD = OBJECTPOINT + 26;
    public static final int CURLOPT_CRLF = LONG + 27;
    public static final int CURLOPT_QUOTE = OBJECTPOINT + 28;
    public static final int CURLOPT_WRITEHEADER = OBJECTPOINT + 29;
    public static final int CURLOPT_COOKIEFILE = OBJECTPOINT + 31;
    public static final int CURLOPT_SSLVERSION = LONG + 32;
    public static final int CURLOPT_TIMECONDITION = LONG + 33;
    public static final int CURLOPT_TIMEVALUE = LONG + 34;
    public static final int CURLOPT_CUSTOMREQUEST = OBJECTPOINT + 36;
    public static final int CURLOPT_STDERR = OBJECTPOINT + 37;
    public static final int CURLOPT_POSTQUOTE = OBJECTPOINT + 39;
    public static final int CURLOPT_WRITEINFO = OBJECTPOINT + 40;
    public static final int CURLOPT_VERBOSE = LONG + 41;
    public static final int CURLOPT_HEADER = LONG + 42;
    public static final int CURLOPT_NOPROGRESS = LONG + 43;
    public static final int CURLOPT_NOBODY = LONG + 44;
    public static final int CURLOPT_FAILONERROR = LONG + 45;
    public static final int CURLOPT_UPLOAD = LONG + 46;
    public static final int CURLOPT_POST = LONG + 47;
    public static final int CURLOPT_DIRLISTONLY = LONG + 48;
    public static final int CURLOPT_APPEND = LONG + 50;
    public static final int CURLOPT_NETRC = LONG + 51;
    public static final int CURLOPT_FOLLOWLOCATION = LONG + 52;
    public static final int CURLOPT_TRANSFERTEXT = LONG + 53;
    public static final int CURLOPT_PUT = LONG + 54;
    public static final int CURLOPT_PROGRESSFUNCTION = FUNCTIONPOINT + 56;
    public static final int CURLOPT_PROGRESSDATA = OBJECTPOINT + 57;
    public static final int CURLOPT_AUTOREFERER = LONG + 58;
    public static final int CURLOPT_PROXYPORT = LONG + 59;
    public static final int CURLOPT_POSTFIELDSIZE = LONG + 60;
    public static final int CURLOPT_HTTPPROXYTUNNEL = LONG + 61;
    public static final int CURLOPT_INTERFACE = OBJECTPOINT + 62;
    public static final int CURLOPT_KRBLEVEL = OBJECTPOINT + 63;
    public static final int CURLOPT_SSL_VERIFYPEER = LONG + 64;
    public static final int CURLOPT_CAINFO = OBJECTPOINT + 65;
    public static final int CURLOPT_MAXREDIRS = LONG + 68;
    public static final int CURLOPT_FILETIME = LONG + 69;
    public static final int CURLOPT_TELNETOPTIONS = OBJECTPOINT + 70;
    public static final int CURLOPT_MAXCONNECTS = LONG + 71;
    public static final int CURLOPT_CLOSEPOLICY = LONG + 72;
    public static final int CURLOPT_FRESH_CONNECT = LONG + 74;
    public static final int CURLOPT_FORBID_REUSE = LONG + 75;
    public static final int CURLOPT_RANDOM_FILE = OBJECTPOINT + 76;
    public static final int CURLOPT_EGDSOCKET = OBJECTPOINT + 77;
    public static final int CURLOPT_CONNECTTIMEOUT = LONG + 78;
    public static final int CURLOPT_HEADERFUNCTION = FUNCTIONPOINT + 79;
    public static final int CURLOPT_HTTPGET = LONG + 80;
    public static final int CURLOPT_SSL_VERIFYHOST = LONG + 81;
    public static final int CURLOPT_COOKIEJAR = OBJECTPOINT + 82;
    public static final int CURLOPT_SSL_CIPHER_LIST = OBJECTPOINT + 83;
    public static final int CURLOPT_HTTP_VERSION = LONG + 84;
    public static final int CURLOPT_FTP_USE_EPSV = LONG + 85;
    public static final int CURLOPT_SSLCERTTYPE = OBJECTPOINT + 86;
    public static final int CURLOPT_SSLKEY = OBJECTPOINT + 87;
    public static final int CURLOPT_SSLKEYTYPE = OBJECTPOINT + 88;
    public static final int CURLOPT_SSLENGINE = OBJECTPOINT + 89;
    public static final int CURLOPT_SSLENGINE_DEFAULT = LONG + 90;
    public static final int CURLOPT_DNS_USE_GLOBAL_CACHE = LONG + 91;
    public static final int CURLOPT_DNS_CACHE_TIMEOUT = LONG + 92;
    public static final int CURLOPT_PREQUOTE = OBJECTPOINT + 93;
    public static final int CURLOPT_DEBUGFUNCTION = FUNCTIONPOINT + 94;
    public static final int CURLOPT_DEBUGDATA = OBJECTPOINT + 95;
    public static final int CURLOPT_COOKIESESSION = LONG + 96;
    public static final int CURLOPT_CAPATH = OBJECTPOINT + 97;
    public static final int CURLOPT_BUFFERSIZE = LONG + 98;
    public static final int CURLOPT_NOSIGNAL = LONG + 99;
    public static final int CURLOPT_SHARE = OBJECTPOINT + 100;
    public static final int CURLOPT_PROXYTYPE = LONG + 101;
    public static final int CURLOPT_ACCEPT_ENCODING = OBJECTPOINT + 102;
    public static final int CURLOPT_PRIVATE = OBJECTPOINT + 103;
    public static final int CURLOPT_HTTP200ALIASES = OBJECTPOINT + 104;
    public static final int CURLOPT_UNRESTRICTED_AUTH = LONG + 105;
    public static final int CURLOPT_FTP_USE_EPRT = LONG + 106;
    public static final int CURLOPT_HTTPAUTH = LONG + 107;
    public static final int CURLOPT_SSL_CTX_FUNCTION = FUNCTIONPOINT + 108;
    public static final int CURLOPT_SSL_CTX_DATA = OBJECTPOINT + 109;
    public static final int CURLOPT_FTP_CREATE_MISSING_DIRS = LONG + 110;
    public static final int CURLOPT_PROXYAUTH = LONG + 111;
    public static final int CURLOPT_FTP_RESPONSE_TIMEOUT = LONG + 112;
    public static final int CURLOPT_IPRESOLVE = LONG + 113;
    public static final int CURLOPT_MAXFILESIZE = LONG + 114;
    public static final int CURLOPT_INFILESIZE_LARGE = OFF_T + 115;
    public static final int CURLOPT_RESUME_FROM_LARGE = OFF_T + 116;
    public static final int CURLOPT_MAXFILESIZE_LARGE = OFF_T + 117;
    public static final int CURLOPT_NETRC_FILE = OBJECTPOINT + 118;
    public static final int CURLOPT_USE_SSL = LONG + 119;
    public static final int CURLOPT_POSTFIELDSIZE_LARGE = OFF_T + 120;
    public static final int CURLOPT_TCP_NODELAY = LONG + 121;
    public static final int CURLOPT_FTPSSLAUTH = LONG + 129;
    public static final int CURLOPT_IOCTLFUNCTION = FUNCTIONPOINT + 130;
    public static final int CURLOPT_IOCTLDATA = OBJECTPOINT + 131;
    public static final int CURLOPT_FTP_ACCOUNT = OBJECTPOINT + 134;
    public static final int CURLOPT_COOKIELIST = OBJECTPOINT + 135;
    public static final int CURLOPT_IGNORE_CONTENT_LENGTH = LONG + 136;
    public static final int CURLOPT_FTP_SKIP_PASV_IP = LONG + 137;
    public static final int CURLOPT_FTP_FILEMETHOD = LONG + 138;
    public static final int CURLOPT_LOCALPORT = LONG + 139;
    public static final int CURLOPT_LOCALPORTRANGE = LONG + 140;
    public static final int CURLOPT_CONNECT_ONLY = LONG + 141;
    public static final int CURLOPT_CONV_FROM_NETWORK_FUNCTION = FUNCTIONPOINT + 142;
    public static final int CURLOPT_CONV_TO_NETWORK_FUNCTION = FUNCTIONPOINT + 143;
    public static final int CURLOPT_CONV_FROM_UTF8_FUNCTION = FUNCTIONPOINT + 144;
    public static final int CURLOPT_MAX_SEND_SPEED_LARGE = OFF_T + 145;
    public static final int CURLOPT_MAX_RECV_SPEED_LARGE = OFF_T + 146;
    public static final int CURLOPT_FTP_ALTERNATIVE_TO_USER = OBJECTPOINT + 147;
    public static final int CURLOPT_SOCKOPTFUNCTION = FUNCTIONPOINT + 148;
    public static final int CURLOPT_SOCKOPTDATA = OBJECTPOINT + 149;
    public static final int CURLOPT_SSL_SESSIONID_CACHE = LONG + 150;
    public static final int CURLOPT_SSH_AUTH_TYPES = LONG + 151;
    public static final int CURLOPT_SSH_PUBLIC_KEYFILE = OBJECTPOINT + 152;
    public static final int CURLOPT_SSH_PRIVATE_KEYFILE = OBJECTPOINT + 153;
    public static final int CURLOPT_FTP_SSL_CCC = LONG + 154;
    public static final int CURLOPT_TIMEOUT_MS = LONG + 155;
    public static final int CURLOPT_CONNECTTIMEOUT_MS = LONG + 156;
    public static final int CURLOPT_HTTP_TRANSFER_DECODING = LONG + 157;
    public static final int CURLOPT_HTTP_CONTENT_DECODING = LONG + 158;
    public static final int CURLOPT_NEW_FILE_PERMS = LONG + 159;
    public static final int CURLOPT_NEW_DIRECTORY_PERMS = LONG + 160;
    public static final int CURLOPT_POSTREDIR = LONG + 161;
    public static final int CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 = OBJECTPOINT + 162;
    public static final int CURLOPT_OPENSOCKETFUNCTION = FUNCTIONPOINT + 163;
    public static final int CURLOPT_OPENSOCKETDATA = OBJECTPOINT + 164;
    public static final int CURLOPT_COPYPOSTFIELDS = OBJECTPOINT + 165;
    public static final int CURLOPT_PROXY_TRANSFER_MODE = LONG + 166;
    public static final int CURLOPT_SEEKFUNCTION = FUNCTIONPOINT + 167;
    public static final int CURLOPT_SEEKDATA = OBJECTPOINT + 168;
    public static final int CURLOPT_CRLFILE = OBJECTPOINT + 169;
    public static final int CURLOPT_ISSUERCERT = OBJECTPOINT + 170;
    public static final int CURLOPT_ADDRESS_SCOPE = LONG + 171;
    public static final int CURLOPT_CERTINFO = LONG + 172;
    public static final int CURLOPT_USERNAME = OBJECTPOINT + 173;
    public static final int CURLOPT_PASSWORD = OBJECTPOINT + 174;
    public static final int CURLOPT_PROXYUSERNAME = OBJECTPOINT + 175;
    public static final int CURLOPT_PROXYPASSWORD = OBJECTPOINT + 176;
    public static final int CURLOPT_NOPROXY = OBJECTPOINT + 177;
    public static final int CURLOPT_TFTP_BLKSIZE = LONG + 178;
    public static final int CURLOPT_SOCKS5_GSSAPI_SERVICE = OBJECTPOINT + 179;
    public static final int CURLOPT_SOCKS5_GSSAPI_NEC = LONG + 180;
    public static final int CURLOPT_PROTOCOLS = LONG + 181;
    public static final int CURLOPT_REDIR_PROTOCOLS = LONG + 182;
    public static final int CURLOPT_SSH_KNOWNHOSTS = OBJECTPOINT + 183;
    public static final int CURLOPT_SSH_KEYFUNCTION = FUNCTIONPOINT + 184;
    public static final int CURLOPT_SSH_KEYDATA = OBJECTPOINT + 185;
    public static final int CURLOPT_MAIL_FROM = OBJECTPOINT + 186;
    public static final int CURLOPT_MAIL_RCPT = OBJECTPOINT + 187;
    public static final int CURLOPT_FTP_USE_PRET = LONG + 188;
    public static final int CURLOPT_RTSP_REQUEST = LONG + 189;
    public static final int CURLOPT_RTSP_SESSION_ID = OBJECTPOINT + 190;
    public static final int CURLOPT_RTSP_STREAM_URI = OBJECTPOINT + 191;
    public static final int CURLOPT_RTSP_TRANSPORT = OBJECTPOINT + 192;
    public static final int CURLOPT_RTSP_CLIENT_CSEQ = LONG + 193;
    public static final int CURLOPT_RTSP_SERVER_CSEQ = LONG + 194;
    public static final int CURLOPT_INTERLEAVEDATA = OBJECTPOINT + 195;
    public static final int CURLOPT_INTERLEAVEFUNCTION = FUNCTIONPOINT + 196;
    public static final int CURLOPT_WILDCARDMATCH = LONG + 197;
    public static final int CURLOPT_CHUNK_BGN_FUNCTION = FUNCTIONPOINT + 198;
    public static final int CURLOPT_CHUNK_END_FUNCTION = FUNCTIONPOINT + 199;
    public static final int CURLOPT_FNMATCH_FUNCTION = FUNCTIONPOINT + 200;
    public static final int CURLOPT_CHUNK_DATA = OBJECTPOINT + 201;
    public static final int CURLOPT_FNMATCH_DATA = OBJECTPOINT + 202;
    public static final int CURLOPT_RESOLVE = OBJECTPOINT + 203;
    public static final int CURLOPT_TLSAUTH_USERNAME = OBJECTPOINT + 204;
    public static final int CURLOPT_TLSAUTH_PASSWORD = OBJECTPOINT + 205;
    public static final int CURLOPT_TLSAUTH_TYPE = OBJECTPOINT + 206;
    public static final int CURLOPT_TRANSFER_ENCODING = LONG + 207;
    public static final int CURLOPT_CLOSESOCKETFUNCTION = FUNCTIONPOINT + 208;
    public static final int CURLOPT_CLOSESOCKETDATA = OBJECTPOINT + 209;
    public static final int CURLOPT_GSSAPI_DELEGATION = LONG + 210;
    public static final int CURLOPT_DNS_SERVERS = OBJECTPOINT + 211;
    public static final int CURLOPT_ACCEPTTIMEOUT_MS = LONG + 212;
    public static final int CURLOPT_TCP_KEEPALIVE = LONG + 213;
    public static final int CURLOPT_TCP_KEEPIDLE = LONG + 214;
    public static final int CURLOPT_TCP_KEEPINTVL = LONG + 215;
    public static final int CURLOPT_SSL_OPTIONS = LONG + 216;
    public static final int CURLOPT_MAIL_AUTH = OBJECTPOINT + 217;
    public static final int CURLOPT_WRITEDATA = CURLOPT_FILE;
    public static final int CURLOPT_READDATA = CURLOPT_INFILE;

    public static final int CURL_IPRESOLVE_WHATEVER = 0;
    public static final int CURL_IPRESOLVE_V4 = 1;
    public static final int CURL_IPRESOLVE_V6 = 2;

    public static native int curl_init();
    public static native int curl_errno();
    public static native String curl_error();
    // curl_easy_setopt with long, unsigned long, curl_off_t
    public static native boolean curl_setopt(int curl, int option, long value);
    // curl_easy_setopt with char *
    public static native boolean curl_setopt(int curl, int option, String value);
    // curl_easy_setopt with curl_slit
    public static native boolean curl_setopt(int curl, int option, String[] value);
    // curl_easy_setopt with void *
    public static native boolean curl_setopt(int curl, int option, byte[] value);
    // curl_easy_setopt with callback, Object is a class implements callback
    public static native boolean curl_setopt(int curl, int option, Object value);
    public static native boolean curl_perform(int curl);
    // curl_easy_getinfo with long
    public static native long curl_getinfo_long(int curl, int info);
    // curl_easy_getinfo with double
    public static native double curl_getinfo_double(int curl, int info);
    // curl_easy_getinfo with curl_slist
    public static native String[] curl_getinfo_list(int curl, int info);
    // curl_easy_getinfo with certinfo, certinfo is set of curl_slist
    // Object[] is equal String[][]
    public static native Object[] curl_getinfo_certinfo(int curl, int info);
    // curl_easy_getinfo with string, including long and double
    public static native String curl_getinfo(int curl, int info);
    public static native void curl_cleanup(int curl);

    /*
     * CURLOPT_WRITEFUNCTION
     * CURLOPT_HEADERFUNCTION
     * size_t function(void *ptr, size_t size, size_t nmemb, void *userdata);
     */
    public interface Write
    {
        public int callback(byte[] ptr);
    }

    /*
     * CURLOPT_READFUNCTION
     * size_t function(void *ptr, size_t size, size_t nmemb, void *userdata);
     */
    public interface Read
    {
        public int callback(byte[] ptr);
    }

    /*
     * CURLOPT_DEBUGFUNCTION
     * int curl_debug_callback(CURL *, curl_infotype, char *, size_t, void *);
     */
    public interface Debug
    {
        public int callback(int type, byte[] ptr);

        public final int CURLINFO_TEXT = 0;
        public final int CURLINFO_HEADER_IN = 1;
        public final int CURLINFO_HEADER_OUT = 2;
        public final int CURLINFO_DATA_IN = 3;
        public final int CURLINFO_DATA_OUT = 4;
        public final int CURLINFO_SSL_DATA_IN = 5;
        public final int CURLINFO_SSL_DATA_OUT = 6;
        public final String[] CURLINFO = {
            "TEXT",
            "HEADER_IN",
            "HEADER_OUT",
            "DATA_IN",
            "DATA_OUT",
            "SSL_DATA_IN",
            "SSL_DATA_OUT",
            "END",
        };
    }

    /*
     * CURLOPT_PROGRESSFUNCTION
     * typedef int (*curl_progress_callback)(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow);
     */
    public interface Progress
    {
        public int callback(double dltotal, double dlnow, double ultotal, double ulnow);
    }

    static {
        try {
            System.loadLibrary("curl");
        } catch (UnsatisfiedLinkError e) {
            throw new UnsatisfiedLinkError();
		}
	}

}


text:
@interface TLExpressionViewController : TLViewController

@end


text:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "golib.h"

#define ROUND(x, n) (((x) + (n) - 1) & ~(uintptr)((n) - 1))

typedef _Bool bool;
enum {
	false	= 0,
	true	= 1,
};

// libgo symbols that we don't need to export in golib.h
extern bool runtime_isarchive;
extern bool runtime_isstarted;
extern bool runtime_iscgo;
extern void runtime_cpuinit();
extern void setncpu(int32) __asm__("runtime.setncpu");
extern void setpagesize(uintptr) __asm__("runtime.setpagesize");
extern void* runtime_sched;
extern void* runtime_getsched() __asm__("runtime.getsched");
extern void runtime_check() __asm__("runtime.check");
extern void runtime_args(int32, char **) __asm__("runtime.args");
extern void runtime_osinit();
extern void runtime_schedinit()
#if GCC_VERSION >= 80100 // 8.1.0
	__asm__("runtime.schedinit")
#endif
;
extern void runtime_main()
#if GCC_VERSION >= 80100 // 8.1.0
	__asm__("runtime.main")
#endif
;
extern void runtime_mstart(void *);
extern void* runtime_m() __attribute__((noinline, no_split_stack));
extern void runtime_gosched()
#if GCC_VERSION >= 80100 // 8.1.0
	__asm__("runtime.Gosched")
#endif
;
#if GCC_VERSION >= 80100 // 8.1.0
extern void runtime_gc() __asm__("runtime.GC");
#else
extern void runtime_gc(int32);
#endif
extern void runtime_pollServerInit()
#if GCC_VERSION >= 80100 // 8.1.0
	__asm__("internal_poll.runtime_pollServerInit")
#else
	__asm__("net.runtime_pollServerInit")
#endif
;
extern void runtime_setIsCgo() __asm__("runtime.setIsCgo");
// partial struct head from gcc/libgo/go/reflect/type.go
typedef struct rtype {
	uintptr size;
	uintptr ptrdata;	// size of memory prefix holding all pointers
	uint32  hash;		// hash of type; avoids computation in hash tables
	uint8   kind;		// enumeration for C
	int8	align;		// alignment of variable with this type
	uint8	fieldAlign;	// alignment of struct field with this type
	uint8	_;		// unused/padding

	uintptr hashfn;		// hash function
	uintptr equalfn;	// equality function

	uint8	*gcdata ;	// garbage collection data
} rtype;
extern void runtime_typedmemmove(rtype *typ, void *dest, void *src) __asm__("runtime.typedmemmove");
extern void* allocate_array_of_pointers(uintptr num) __asm__("main.Allocate_array_of_pointers");

// golib.go symbols that we don't need to export in golib.h
extern mem_stats get_mem_stats() __asm__("main.Get_mem_stats");

// have the GC scan the BSS
extern char edata, end;
extern char **environ;
extern uint8 _end[];
uintptr __go_end;
struct root_list {
	struct root_list *next;
#if GCC_VERSION >= 80100 // 8.1.0
	int count;
#endif
	struct root {
		void *decl;
		size_t size;
#if GCC_VERSION >= 80100 // 8.1.0
		size_t ptrdata;
		unsigned int *gcdata;
#endif
	} roots[2];
};
extern void __go_register_gc_roots (struct root_list* r)
#if GCC_VERSION >= 80100 // 8.1.0
	__asm__("runtime.registerGCRoots")
#endif
;
static struct root_list bss_roots = {
	NULL,
#if GCC_VERSION >= 80100 // 8.1.0
	1,
#endif
	{
		{
			NULL,
			0,
#if GCC_VERSION >= 80100 // 8.1.0
			0,
			NULL,
#endif
		},
		{
			NULL,
			0,
#if GCC_VERSION >= 80100 // 8.1.0
			0,
			NULL,
#endif
		},
	},
};

// from GCC's libgo/runtime/go-main.c
int golib_main(int argc, char **argv)
{
	runtime_isarchive = false;
	if (runtime_isstarted)
		return 0;
	runtime_isstarted = true;

	if (runtime_iscgo)
		runtime_setIsCgo();

	__go_end = (uintptr)_end;
	/*printf("_end=%p\n", _end);*/
	runtime_cpuinit();
	runtime_check();
	/*printf("edata=%p, end=%p, end-edata=%ld\n", &edata, &end, &end - &edata);*/
	bss_roots.roots[0].decl = &edata;
	bss_roots.roots[0].size = &end - &edata;
	__go_register_gc_roots(&bss_roots);
	runtime_args(argc, argv);
#if GCC_VERSION >= 80000 // 8.0.0
	setncpu(getproccount());
	setpagesize(getpagesize());
#else
	runtime_osinit();
#endif
	runtime_sched = runtime_getsched();
	runtime_schedinit();
	runtime_pollServerInit();
	__go_go((void (*)(void *))runtime_main, NULL);
	runtime_mstart(runtime_m());
	abort();
}

void* go_malloc(uintptr size)
{
	return allocate_array_of_pointers(ROUND(size, sizeof(void*)) / sizeof(void*));
}

void go_run_finalizer(void (*f)(void *), void *obj)
{
	f(obj);
}

// wrappers to handle GCC's constant naming changes from Nim code

// yield execution to another goroutine
void go_yield()
{
	runtime_gosched();
}

// run the garbage collector
void go_gc()
{
#if GCC_VERSION >= 80100 // 8.1.0
	runtime_gc();
#else
	runtime_gc(2);
#endif
}

// memory statistics
mem_stats go_mem_stats()
{
	return get_mem_stats();
}

void typedmemmove(void *dest, void *src, uintptr size)
{
	// round it down to pointer size
	uintptr new_size = size & ~(sizeof(void*) - 1);

	if(new_size) {
		// check the pointer alignment of dest and src
		if ((((uintptr)dest|(uintptr)src) & (sizeof(void*) - 1)) == 0) {
			rtype typ;
			typ.kind = 0;
			typ.size = new_size;
			runtime_typedmemmove(&typ, dest, src);
		} else {
			// the pointers are missaligned, so let memmove() do all the copying
			new_size = 0;
		}
	}
	if(size > new_size) {
		memmove(dest + new_size, src + new_size, size - new_size);
	}
}


text:
OUTDIR=examples/deep-activity-rec/ibrahim16-cvpr-simple/p4-network2
GPU_ID=0
ITER=10000

echo "Resuming Caffe using GPU" $GPU "In Directory " $OUTDIR "Starting from iteration " $ITER

./build/tools/caffe train 2> $OUTDIR/z_trainval-test-log-resume.txt \
  --solver $OUTDIR/trainval-test-solver.prototxt --snapshot=$OUTDIR/z_snapshot_iter_$ITER.solverstate  --gpu $GPU_ID